v4.3.5: gateway 폴더 구조 정리 — routes/channels/mocks/errors/tasks/automation 서브디렉토리 분리

- src/gateway/ 76개 .ts 파일 중 55개를 종류별 서브디렉토리로 이동
  (routes/ 35, channels/ 4, mocks/ 3, errors/ 5, tasks/ 8, automation/ 3)
- 루트엔 server.ts(server-v2.ts에서 개명) 포함 21개 핵심 인프라 파일만 유지
- gateway 내부 상대경로 import 101곳 + 외부 참조 5곳(cli/index.ts,
  tools/kakao.ts, tools/pptx.ts, tools/shell.ts, tools/task-control.ts)을
  스크립트로 재계산, 빌드/재시작/26개 엔드포인트 스모크테스트로 검증

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
This commit is contained in:
kimandClaude Sonnet 5 committed 2026-07-25 17:02:54 +09:00
1 parent a1cfeb7710
commit db7260ac46
62 files changed
+446 -165

No files matched your search

+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "smallclaw",
"version": "4.3.4",
"version": "4.3.5",
"description": "Local AI agent framework powered by Ollama - OpenClaw alternative",
"main": "dist/index.js",
"bin": {
+1 -1
View File
@@ -412,7 +412,7 @@ gateway
return;
}
} catch {}
require('../gateway/server-v2');
require('../gateway/server');
});
gateway
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
@@ -19,8 +19,8 @@
import fs from 'fs';
import path from 'path';
import { getConfig } from '../config/config';
import { loadPendingRepair, listPendingRepairs, applyApprovedRepair, deletePendingRepair, formatRepairProposal } from '../tools/self-repair';
import { getConfig } from '../../config/config';
import { loadPendingRepair, listPendingRepairs, applyApprovedRepair, deletePendingRepair, formatRepairProposal } from '../../tools/self-repair';
// ─── Types ─────────────────────────────────────────────────────────────────────
@@ -614,7 +614,7 @@ export class TelegramChannel {
}
if (text === '/clear') {
try {
const { clearHistory } = await import('./session');
const { clearHistory } = await import('../session');
clearHistory(`telegram_${userId}`);
} catch {}
await this.sendMessage(chatId, 'Chat history cleared.');
@@ -762,7 +762,7 @@ export class TelegramChannel {
const sessionVoiceMode = this.voiceSessions.get(sessionId);
if (sessionVoiceMode && voiceConfig?.enabled && responseText.length > 0) {
try {
const { synthesizeSpeech } = await import('../tools/tts.js');
const { synthesizeSpeech } = await import('../../tools/tts.js');
const audioBuffer = await synthesizeSpeech(responseText);
const formData = new FormData();
formData.append('chat_id', String(chatId));
@@ -830,7 +830,7 @@ export class TelegramChannel {
private async sendVoiceResponse(chatId: number, text: string): Promise<void> {
try {
const { synthesizeSpeech } = await import('../tools/tts.js');
const { synthesizeSpeech } = await import('../../tools/tts.js');
const audioBuffer = await synthesizeSpeech(text);
const caption = text.length > 1024 ? text.slice(0, 1024) : undefined;
await this.sendVoice(chatId, audioBuffer, caption);
@@ -876,7 +876,7 @@ export class TelegramChannel {
const fileInfo = await this.getFile(voice.file_id);
const audioBuffer = await this.downloadFile(fileInfo.file_path);
const { transcribeAudio } = await import('../tools/stt.js');
const { transcribeAudio } = await import('../../tools/stt.js');
const { text } = await transcribeAudio(audioBuffer, 'ogg');
if (!text || !text.trim()) {
@@ -19,7 +19,7 @@
*/
import express from 'express';
import { getConfig } from '../config/config.js';
import { getConfig } from '../../config/config.js';
// ─── Types ────────────────────────────────────────────────────────────────────
File renamed without changes.
File renamed without changes.
File renamed without changes.
@@ -4,14 +4,14 @@
import type { Express, Request, Response } from 'express';
import { errorCategorizer } from './error-categorizer';
import { getErrorTemplate } from './error-templates';
import { getVerificationFlowManager } from './verification-flow';
import { getCredentialHandler } from '../security/credential-handler';
import { getVerificationFlowManager } from '../verification-flow';
import { getCredentialHandler } from '../../security/credential-handler';
import { getErrorAnalyzer } from './error-analyzer';
import { getErrorHistory } from './error-history';
import { getRetryStrategy } from './retry-strategy';
import { getVisualErrorDetector } from './visual-error-detection';
import { getErrorAudit } from '../security/error-audit';
import { getContextInjectionManager } from './context-injection';
import { getRetryStrategy } from '../retry-strategy';
import { getVisualErrorDetector } from '../visual-error-detection';
import { getErrorAudit } from '../../security/error-audit';
import { getContextInjectionManager } from '../context-injection';
// In-memory store for pending error responses awaiting user input
const pendingErrors: Map<string, {
File renamed without changes.
@@ -18,6 +18,7 @@ export const _WIFI_NATIVE_BRIDGE_H = `#pragma once
#include <fcntl.h>
#include <sys/ioctl.h>
#include <poll.h>
#include <functional>
typedef uint8_t byte;
typedef uint8_t boolean;
#define HIGH 1
@@ -403,6 +404,63 @@ public:
#define _HTTPUPDATE_DEFINED
HTTPUpdateClass httpUpdate;
#endif
// Update stub (Update.h) — 실제 플래시에 쓰는 대신 바이트 카운트만 흉내낸다. 이 에뮬레이터는
// 네이티브 x86 바이너리로 컴파일되므로(WiFi 스케치는 전부 이 경로) 진짜 OTA 자체가 불가능—
// 목표는 "esp_ota_ops.h를 직접 include하지 말고 Update를 쓰라"는 안내를 따라도 최소한
// 컴파일·실행은 되게 하는 것(2026-07-21, "ESP32 OTA가 에뮬레이터에서 에러난다" 리포트).
#define UPDATE_SIZE_UNKNOWN 0xFFFFFFFF
#define U_FLASH 0
#define U_SPIFFS 100
#define U_AUTH 200
class UpdateClass {
size_t _size=0, _written=0; bool _running=false; int _err=0;
public:
bool begin(size_t size=UPDATE_SIZE_UNKNOWN, int command=U_FLASH, int ledPin=-1, uint8_t ledOn=LOW, const char* label=nullptr) {
(void)command;(void)ledPin;(void)ledOn;(void)label;
_size=size; _written=0; _running=true; _err=0; return true;
}
size_t write(uint8_t* data, size_t len) { (void)data; if(!_running) return 0; _written+=len; return len; }
size_t write(Stream& data, size_t len=0) { (void)data;(void)len; return 0; }
bool end(bool evenIfRemaining=false) { (void)evenIfRemaining; _running=false; return true; }
void abort() { _running=false; }
bool isRunning() { return _running; }
bool hasError() { return _err!=0; }
int getError() { return _err; }
String errorString() { return String("no error"); }
size_t size() { return _size; }
size_t progress() { return _written; }
size_t remaining() { return _size==UPDATE_SIZE_UNKNOWN?0:(_size>_written?_size-_written:0); }
void onProgress(std::function<void(size_t,size_t)> fn) { if(fn) fn(0,_size); }
};
#ifndef _UPDATE_DEFINED
#define _UPDATE_DEFINED
UpdateClass Update;
#endif
// ArduinoOTA stub (ArduinoOTA.h) — begin/handle은 아무것도 안 함(진짜 네트워크 OTA 리스너가
// 없으므로 트리거될 이벤트 자체가 없음). 콜백은 등록만 되고 호출되지 않는다 — 컴파일·링크
// 통과가 목적이라 실제 OTA 시나리오를 시뮬레이션하진 않는다.
typedef enum { OTA_AUTH_ERROR=900, OTA_BEGIN_ERROR=901, OTA_CONNECT_ERROR=902, OTA_RECEIVE_ERROR=903, OTA_END_ERROR=904 } ota_error_t;
class ArduinoOTAClass {
public:
ArduinoOTAClass& setPort(uint16_t) { return *this; }
ArduinoOTAClass& setHostname(const char*) { return *this; }
ArduinoOTAClass& setPassword(const char*) { return *this; }
ArduinoOTAClass& setPasswordHash(const char*) { return *this; }
ArduinoOTAClass& setRebootOnSuccess(bool) { return *this; }
ArduinoOTAClass& setMdnsEnabled(bool) { return *this; }
void onStart(std::function<void()>) {}
void onEnd(std::function<void()>) {}
void onProgress(std::function<void(unsigned int,unsigned int)>) {}
void onError(std::function<void(ota_error_t)>) {}
void begin() {}
void end() {}
void handle() {}
int getCommand() { return U_FLASH; }
};
#ifndef _ARDUINOOTA_DEFINED
#define _ARDUINOOTA_DEFINED
ArduinoOTAClass ArduinoOTA;
#endif
#endif
`;
@@ -1208,3 +1266,114 @@ public:
#endif
`;
// esp_camera.h 목 — ESP32-CAM(esp32:esp32:esp32cam) 스케치용(2026-07-21, "esp_camera.h 없음"
// 컴파일 에러 대응). 실제 카메라 하드웨어가 없는 네이티브 x86 에뮬레이션이라 진짜 영상은 못
// 찍는다 — esp_camera_fb_get()은 항상 작은 더미 JPEG 버퍼를 반환해 웹서버 스트리밍 코드가
// 널 포인터로 죽지 않게만 해준다. sensor_t의 set_* 함수들은 전부 no-op(항상 성공 반환).
export const _ESP32CAM_MOCK_H = `#pragma once
#ifndef _EMU_ESP32CAM_MOCK_H
#define _EMU_ESP32CAM_MOCK_H
#include <cstdint>
#include <cstdlib>
#include <cstring>
#include <sys/time.h>
typedef int esp_err_t;
#ifndef ESP_OK
#define ESP_OK 0
#endif
#ifndef ESP_FAIL
#define ESP_FAIL -1
#endif
typedef enum {
PIXFORMAT_RGB565=0, PIXFORMAT_YUV422, PIXFORMAT_YUV420, PIXFORMAT_GRAYSCALE,
PIXFORMAT_JPEG, PIXFORMAT_RGB888, PIXFORMAT_RAW, PIXFORMAT_RGB444, PIXFORMAT_RGB555,
} pixformat_t;
typedef enum {
FRAMESIZE_96X96=0, FRAMESIZE_QQVGA, FRAMESIZE_QCIF, FRAMESIZE_HQVGA, FRAMESIZE_240X240,
FRAMESIZE_QVGA, FRAMESIZE_CIF, FRAMESIZE_HVGA, FRAMESIZE_VGA, FRAMESIZE_SVGA,
FRAMESIZE_XGA, FRAMESIZE_HD, FRAMESIZE_SXGA, FRAMESIZE_UXGA, FRAMESIZE_FHD,
FRAMESIZE_P_HD, FRAMESIZE_P_3MP, FRAMESIZE_QXGA, FRAMESIZE_QHD, FRAMESIZE_WQXGA,
FRAMESIZE_P_FHD, FRAMESIZE_QSXGA, FRAMESIZE_INVALID,
} framesize_t;
typedef enum { CAMERA_GRAB_WHEN_EMPTY=0, CAMERA_GRAB_LATEST } camera_grab_mode_t;
typedef enum { CAMERA_FB_IN_PSRAM=0, CAMERA_FB_IN_DRAM } camera_fb_location_t;
typedef struct {
int pin_pwdn, pin_reset, pin_xclk;
int pin_sccb_sda, pin_sccb_scl;
int pin_sscb_sda, pin_sscb_scl; // 구버전 예제 호환용 별칭
int pin_d7, pin_d6, pin_d5, pin_d4, pin_d3, pin_d2, pin_d1, pin_d0;
int pin_vsync, pin_href, pin_pclk;
int xclk_freq_hz;
int ledc_timer, ledc_channel;
pixformat_t pixel_format;
framesize_t frame_size;
int jpeg_quality;
int fb_count;
camera_grab_mode_t grab_mode;
camera_fb_location_t fb_location;
} camera_config_t;
typedef struct {
uint8_t* buf;
size_t len;
size_t width, height;
pixformat_t format;
struct timeval timestamp;
} camera_fb_t;
struct sensor_t;
typedef int (*_cam_set1_fn)(sensor_t*, int);
struct sensor_t {
camera_config_t* dummy;
int id, status_dummy;
_cam_set1_fn set_framesize, set_quality, set_contrast, set_brightness, set_saturation,
set_sharpness, set_denoise, set_gainceiling, set_colorbar, set_whitebal, set_gain_ctrl,
set_exposure_ctrl, set_hmirror, set_vflip, set_aec2, set_awb_gain, set_agc_gain,
set_aec_value, set_special_effect, set_wb_mode, set_ae_level, set_dcw, set_bpc,
set_wpc, set_raw_gma, set_lenc;
};
inline int _emu_cam_noop(sensor_t*, int) { return 0; }
inline esp_err_t esp_camera_init(const camera_config_t* config) { (void)config; return ESP_OK; }
inline esp_err_t esp_camera_deinit() { return ESP_OK; }
inline camera_fb_t* esp_camera_fb_get() {
// 진짜 카메라가 없으므로 디코딩 가능한 실제 영상은 만들 수 없음 — 널 체크·길이 체크
// 정도만 하는 코드가 안 죽게 작은 더미 버퍼를 채워 반환.
static const size_t len = 4096;
camera_fb_t* fb = new camera_fb_t();
fb->buf = (uint8_t*)malloc(len);
memset(fb->buf, 0, len);
fb->len = len;
fb->width = 640; fb->height = 480;
fb->format = PIXFORMAT_JPEG;
gettimeofday(&fb->timestamp, nullptr);
return fb;
}
inline void esp_camera_fb_return(camera_fb_t* fb) {
if (!fb) return;
if (fb->buf) free(fb->buf);
delete fb;
}
inline sensor_t* esp_camera_sensor_get() {
static sensor_t s;
s.set_framesize=_emu_cam_noop; s.set_quality=_emu_cam_noop; s.set_contrast=_emu_cam_noop;
s.set_brightness=_emu_cam_noop; s.set_saturation=_emu_cam_noop; s.set_sharpness=_emu_cam_noop;
s.set_denoise=_emu_cam_noop; s.set_gainceiling=_emu_cam_noop; s.set_colorbar=_emu_cam_noop;
s.set_whitebal=_emu_cam_noop; s.set_gain_ctrl=_emu_cam_noop; s.set_exposure_ctrl=_emu_cam_noop;
s.set_hmirror=_emu_cam_noop; s.set_vflip=_emu_cam_noop; s.set_aec2=_emu_cam_noop;
s.set_awb_gain=_emu_cam_noop; s.set_agc_gain=_emu_cam_noop; s.set_aec_value=_emu_cam_noop;
s.set_special_effect=_emu_cam_noop; s.set_wb_mode=_emu_cam_noop; s.set_ae_level=_emu_cam_noop;
s.set_dcw=_emu_cam_noop; s.set_bpc=_emu_cam_noop; s.set_wpc=_emu_cam_noop;
s.set_raw_gma=_emu_cam_noop; s.set_lenc=_emu_cam_noop;
return &s;
}
#endif
`;
File renamed without changes.
File renamed without changes.
@@ -2,8 +2,8 @@ import express from 'express';
import fs from 'fs';
import fsp from 'fs/promises';
import path from 'path';
import { getConfig } from '../config/config';
import { listAllSessions } from './session';
import { getConfig } from '../../config/config';
import { listAllSessions } from '../session';
// activeSessions is the module-level token→SessionInfo map in server-v2.ts
// (21 other read/write sites there), so it's threaded in as a dep rather
@@ -6,9 +6,9 @@ import {
getAgentById,
ensureAgentWorkspace,
resolveAgentWorkspace,
} from '../config/config';
import { getAgentRunHistory, getAgentLastRun, recordAgentRun, reloadAgentSchedules } from '../scheduler';
import { spawnAgent } from '../agents/spawner';
} from '../../config/config';
import { getAgentRunHistory, getAgentLastRun, recordAgentRun, reloadAgentSchedules } from '../../scheduler';
import { spawnAgent } from '../../agents/spawner';
type AgentToolProfile = 'minimal' | 'coding' | 'web' | 'full';
File renamed without changes.
@@ -6,13 +6,13 @@ import {
_MPU6050_MOCK_ESP8266_H,_BME280_MOCK_ESP8266_H,_ONEWIRE_MOCK_ESP8266_H,_DALLASTEMP_MOCK_ESP8266_H,
_RELAY_MOCK_ESP8266_H,_L298N_MOCK_ESP8266_H,_CRYPTO_H,_TYPECONVERSION_H,
_ESP8266_WIFI_H,_ESP8266_HTTP_H,_ESP8266_MAIN_CPP,_TFT_MOCK_ESP8266_H,
} from './mocks-esp8266';
} from '../mocks/mocks-esp8266';
import {
_WIFI_NATIVE_BRIDGE_H,_GPIO_BRIDGE_H,_DHT_MOCK_H,_SERVO_MOCK_H,
_WIRE_MOCK_H,_MPU6050_MOCK_H,_BME280_MOCK_H,_ONEWIRE_MOCK_H,_DALLASTEMP_MOCK_H,
_RELAY_MOCK_H,_L298N_MOCK_H,_SPI_MOCK_H,_TFT_MOCK_H,
} from './mocks-esp32';
import { _RN_ILI9341_MOCK_H, _RN_SSD1306_MOCK_H } from './mocks-stm32';
_RELAY_MOCK_H,_L298N_MOCK_H,_SPI_MOCK_H,_TFT_MOCK_H,_ESP32CAM_MOCK_H,
} from '../mocks/mocks-esp32';
import { _RN_ILI9341_MOCK_H, _RN_SSD1306_MOCK_H } from '../mocks/mocks-stm32';
export function registerArduinoRoutes(app: express.Application, getSessionUser: (req: express.Request) => any): void {
@@ -1095,6 +1095,11 @@ app.post('/api/arduino/qemu/start', async (req, res) => {
sketchCode = sketchCode.replace(new RegExp('#include\\s*<' + n.replace('.', '\\.') + '>', 'g'), `#include "${n}"`);
}
}
// ESP32-CAM(esp_camera.h) — 실제 카메라가 없으니 더미 프레임만 반환(2026-07-21,
// "esp_camera.h 없음" 컴파일 에러 대응). AI Thinker ESP32-CAM 등 웹캠 예제가 대상.
if (code.includes('esp_camera.h')) {
require('fs').writeFileSync(sketchDir + '/esp_camera.h', _ESP32CAM_MOCK_H);
}
// ── WiFi 스케치: 네이티브 Linux 컴파일 (실제 소켓 사용) ──────────────────
if (usesWifi) {
require('fs').writeFileSync(sketchDir + '/wifi_native_bridge.h', _WIFI_NATIVE_BRIDGE_H);
@@ -1102,6 +1107,10 @@ app.post('/api/arduino/qemu/start', async (req, res) => {
const _wstub = (name: string) => require('fs').writeFileSync(sketchDir + '/' + name, `#pragma once\n#include "wifi_native_bridge.h"\n`);
_wstub('WiFi.h'); _wstub('WiFiMulti.h'); _wstub('HTTPClient.h'); _wstub('HTTPUpdate.h');
_wstub('WiFiClientSecure.h'); _wstub('NetworkClient.h');
// Update.h/ArduinoOTA.h — OTA 스케치용 스텁(2026-07-21). esp_ota_ops.h는 ESP-IDF
// 저수준 헤더라 이 네이티브 브릿지 환경에선 스텁 안 함(AI 힌트가 이미 Update 사용을
// 안내하므로 그쪽만 받쳐주면 됨).
_wstub('Update.h'); _wstub('ArduinoOTA.h');
require('fs').writeFileSync(sketchDir + '/Arduino.h', '#pragma once\n#include "wifi_native_bridge.h"\n');
// Replace angle-bracket includes with local-quote includes for all WiFi-related headers
sketchCode = sketchCode
@@ -1109,7 +1118,9 @@ app.post('/api/arduino/qemu/start', async (req, res) => {
.replace(/#include\s*<HTTPClient\.h>/g, '#include "HTTPClient.h"')
.replace(/#include\s*<HTTPUpdate\.h>/g, '#include "HTTPUpdate.h"')
.replace(/#include\s*<WiFiClientSecure\.h>/g, '#include "WiFiClientSecure.h"')
.replace(/#include\s*<NetworkClient\.h>/g, '#include "NetworkClient.h"');
.replace(/#include\s*<NetworkClient\.h>/g, '#include "NetworkClient.h"')
.replace(/#include\s*<Update\.h>/g, '#include "Update.h"')
.replace(/#include\s*<ArduinoOTA\.h>/g, '#include "ArduinoOTA.h"');
require('fs').writeFileSync(sketchDir + '/native_main.cpp',
'#include "wifi_native_bridge.h"\nHardwareSerial Serial;\nHardwareSerial Serial1;\nWiFiClass WiFi;\n'
+ '#include "sketch.ino"\n'
@@ -1,5 +1,5 @@
import express from 'express';
import { startOAuthFlow, isConnected, clearTokens, loadTokens, exchangeManualCodeFromPending } from '../auth/openai-oauth';
import { startOAuthFlow, isConnected, clearTokens, loadTokens, exchangeManualCodeFromPending } from '../../auth/openai-oauth';
// OpenAI OAuth connect/disconnect — distinct from the core login/session
// /api/auth/* routes (status/setup/login/logout/change-password), which stay
@@ -1,8 +1,8 @@
import express from 'express';
import path from 'path';
import fs from 'fs';
import { getConfig, ensureUserWorkspace } from '../config/config';
import { getSession, addMessage, getWorkspace } from './session';
import { getConfig, ensureUserWorkspace } from '../../config/config';
import { getSession, addMessage, getWorkspace } from '../session';
import {
createTask,
loadTask,
@@ -12,11 +12,11 @@ import {
listTasks,
deleteTask,
type TaskStatus,
} from './task-store';
import { BackgroundTaskRunner } from './background-task-runner';
import { hookBus } from './hooks';
import { getCredentialHandler } from '../security/credential-handler';
import { getErrorAudit } from '../security/error-audit';
} from '../tasks/task-store';
import { BackgroundTaskRunner } from '../tasks/background-task-runner';
import { hookBus } from '../hooks';
import { getCredentialHandler } from '../../security/credential-handler';
import { getErrorAudit } from '../../security/error-audit';
// Module-level (not nested in registerBgTasksRoutes) because scheduleTaskHeartbeat()
// and the boot-log line in server-v2.ts also need these, outside the route cluster.
@@ -1,7 +1,7 @@
import express from 'express';
import fs from 'fs';
import path from 'path';
import { getConfig } from '../config/config';
import { getConfig } from '../../config/config';
const CANVAS_EXEC_EXT: Record<string, string> = {
'.py': 'python3', '.js': 'node', '.ts': 'npx tsx', '.mjs': 'node',
@@ -1,6 +1,6 @@
import express from 'express';
import { getVault } from '../security/vault';
import { KakaoNotify } from './kakao-notify';
import { getVault } from '../../security/vault';
import { KakaoNotify } from '../channels/kakao-notify';
// Local structural mirrors of the private Telegram/Discord/WhatsApp config
// shapes in server-v2.ts — those types (and normalizeXConfig, which
@@ -2,7 +2,7 @@ import express from 'express';
import fs from 'fs';
import fsp from 'fs/promises';
import path from 'path';
import { getConfig } from '../config/config';
import { getConfig } from '../../config/config';
// Session-file browsing for the main chat sidebar. The POST /api/chat handler
// itself (the actual message/tool-execution loop) stays in server-v2.ts —
@@ -1,7 +1,7 @@
import express from 'express';
import fs from 'fs';
import path from 'path';
import { getConfig } from '../config/config';
import { getConfig } from '../../config/config';
// /api/code/round (Ollama streaming) is deliberately NOT part of this file —
// it mutates the module-level isModelBusy/isModelBusySince flags that are
File renamed without changes.
@@ -10,8 +10,8 @@ import path from 'path';
import fs from 'fs';
import { spawn } from 'child_process';
import iconv from 'iconv-lite';
import { getUserWorkspace } from '../config/config';
import { getOllamaClient } from '../agents/ollama-client';
import { getUserWorkspace } from '../../config/config';
import { getOllamaClient } from '../../agents/ollama-client';
const PHOTO_EXTS = new Set(['jpg', 'jpeg', 'png', 'gif', 'webp', 'heic', 'heif', 'bmp', 'tiff']);
const TEXT_DOC_EXTS = new Set(['txt', 'md', 'csv']);
@@ -1,7 +1,7 @@
import express from 'express';
import fs from 'fs';
import path from 'path';
import { getUserWorkspace } from '../config/config';
import { getUserWorkspace } from '../../config/config';
// ─── Per-user Detective Cases ─────────────────────────────────────────────────
// Stored at <user-workspace>/.smallclaw/detective-cases.json
@@ -1,8 +1,8 @@
import express from 'express';
import fs from 'fs';
import path from 'path';
import { KakaoNotify, resolveKakaoImageToken } from './kakao-notify';
import { getVault } from '../security/vault';
import { KakaoNotify, resolveKakaoImageToken } from '../channels/kakao-notify';
import { getVault } from '../../security/vault';
// kakaoChannel/kakaoNotify/resolveChannelsConfig/IMAGE_TYPES/CONFIG_DIR_PATH all
// stay defined in server-v2.ts (module-level state and helpers used well beyond
@@ -3,8 +3,8 @@ import path from 'path';
import fs from 'fs';
import os from 'os';
import { spawn } from 'child_process';
import { getConfig, getUserWorkspace } from '../config/config';
import { getOllamaClient } from '../agents/ollama-client';
import { getConfig, getUserWorkspace } from '../../config/config';
import { getOllamaClient } from '../../agents/ollama-client';
function getWorkspacePath(userId?: string): string {
if (userId) {
@@ -170,6 +170,53 @@ ${info.orthographyNote}`;
}
});
// AI로 생성한 플래시카드 영구 저장 — /api/language/generate-flashcards 자체는 무상태라
// (LLM 호출 결과만 응답) 프론트가 받은 카드를 여기로 다시 보내야 실제로 저장된다
// (2026-07-21, "새 카드가 새로고침하면 사라진다" 리포트 대응). progress.json과 같은
// 패턴: 유저 워크스페이스에 언어별로 키를 나눠 저장, word로 중복 제거.
app.get('/api/language/custom-cards/:userId', (req: express.Request, res: express.Response) => {
try {
const sessionUser = (req as any).user;
if (!sessionUser) { res.status(401).json({ success: false, error: 'Unauthorized' }); return; }
const lang = LANG_INFO[String(req.query.lang)] ? String(req.query.lang) : 'uz';
const workspace = getWorkspacePath(sessionUser.username);
const cardsPath = path.join(workspace, 'language', 'custom-cards.json');
if (!fs.existsSync(cardsPath)) { res.json({ success: true, cards: [] }); return; }
const all = JSON.parse(fs.readFileSync(cardsPath, 'utf-8'));
res.json({ success: true, cards: Array.isArray(all[lang]) ? all[lang] : [] });
} catch (err: any) {
res.status(500).json({ success: false, error: String(err?.message || err) });
}
});
app.post('/api/language/custom-cards/:userId', (req: express.Request, res: express.Response) => {
try {
const sessionUser = (req as any).user;
if (!sessionUser) { res.status(401).json({ success: false, error: 'Unauthorized' }); return; }
const body = req.body;
const lang = LANG_INFO[body?.lang] ? String(body.lang) : 'uz';
const newCards = Array.isArray(body?.cards) ? body.cards : [];
const workspace = getWorkspacePath(sessionUser.username);
const langDir = path.join(workspace, 'language');
fs.mkdirSync(langDir, { recursive: true });
const cardsPath = path.join(langDir, 'custom-cards.json');
let all: any = {};
try { all = JSON.parse(fs.readFileSync(cardsPath, 'utf-8')); } catch {}
const existing: any[] = Array.isArray(all[lang]) ? all[lang] : [];
const seen = new Set(existing.map((c: any) => c.word));
for (const c of newCards) {
if (!c?.word || !c?.ko || seen.has(c.word)) continue;
seen.add(c.word);
existing.push({ word: String(c.word), rom: String(c.rom || ''), ko: String(c.ko), cat: String(c.cat || '') });
}
all[lang] = existing;
fs.writeFileSync(cardsPath, JSON.stringify(all, null, 2), 'utf-8');
res.json({ success: true, cards: existing });
} catch (err: any) {
res.status(500).json({ success: false, error: String(err?.message || err) });
}
});
// POST /api/language/interpret — 실시간 한국어↔타겟언어 통역 (언어 자동 판별)
app.post('/api/language/interpret', async (req: express.Request, res: express.Response) => {
try {
@@ -1,5 +1,5 @@
import express from 'express';
import { getMCPManager } from './mcp-manager';
import { getMCPManager } from '../mcp-manager';
export function registerMCPRoutes(app: express.Application): void {
@@ -1,9 +1,9 @@
import express from 'express';
import fs from 'fs';
import path from 'path';
import { getConfig, getUserWorkspace } from '../config/config';
import { getVault } from '../security/vault';
import type { HeartbeatRunner } from './heartbeat-runner';
import { getConfig, getUserWorkspace } from '../../config/config';
import { getVault } from '../../security/vault';
import type { HeartbeatRunner } from '../tasks/heartbeat-runner';
// Grab-bag of small, self-contained route pairs that don't warrant their own
// file: investor watchlist, heartbeat config, credentials introspection,
@@ -109,7 +109,7 @@ export function registerMiscRoutes(app: express.Application, deps: MiscRouteDeps
}
pendingApprovals.delete(String(req.params.id));
// Security audit: log every approval action (action name only, no payload)
import('../security/log-scrubber').then(({ log }) => {
import('../../security/log-scrubber').then(({ log }) => {
log.security('[approvals]', decision.toUpperCase(), 'approval-id:', req.params.id, 'action:', approval.action);
}).catch(() => {});
res.json({ success: true, decision });
@@ -126,11 +126,11 @@ export function registerMiscRoutes(app: express.Application, deps: MiscRouteDeps
const lang = String(req.query.lang || 'ko'); // 'ko' or 'us'
try {
if (lang === 'us') {
const { usCaseSearchTool } = await import('../tools/legal.js');
const { usCaseSearchTool } = await import('../../tools/legal.js');
const result = await usCaseSearchTool.execute({ query: q, max_results: n });
res.json(result);
} else {
const { koreanLawSearchTool } = await import('../tools/legal.js');
const { koreanLawSearchTool } = await import('../../tools/legal.js');
const result = await koreanLawSearchTool.execute({ query: q, target, sort, max_results: n });
res.json(result);
}
@@ -146,7 +146,7 @@ export function registerMiscRoutes(app: express.Application, deps: MiscRouteDeps
const article = String(req.query.article || '').trim();
if (!id) { res.status(400).json({ error: 'id is required' }); return; }
try {
const { koreanLawFetchTool } = await import('../tools/legal.js');
const { koreanLawFetchTool } = await import('../../tools/legal.js');
const result = await koreanLawFetchTool.execute({ law_id: id, target, ...(article ? { article } : {}) });
res.json(result);
} catch (e: any) {
@@ -4,7 +4,7 @@ import fs from 'fs';
import os from 'os';
import { randomBytes } from 'crypto';
import { spawn } from 'child_process';
import { renderMusic, renderMidi, getRenderFile, getRenderPageFile, renderMidiAsync, saveMidiFile } from './music-renderer';
import { renderMusic, renderMidi, getRenderFile, getRenderPageFile, renderMidiAsync, saveMidiFile } from '../music-renderer';
// ── Job/temp-dir retention ───────────────────────────────────────────────────
// Completed jobs and their temp dirs are not deleted automatically by the OS, so
@@ -4,7 +4,7 @@ import {
clampOrchestrationConfig,
clampPreemptConfig,
checkOrchestrationEligibility,
} from '../orchestration/multi-agent';
} from '../../orchestration/multi-agent';
function clampInt(value: any, min: number, max: number, fallback: number): number {
const n = Number(value);
@@ -1,7 +1,7 @@
import express from 'express';
import fs from 'fs';
import path from 'path';
import { getPaths } from '../config/paths';
import { getPaths } from '../../config/paths';
// Static-ish PPT template/skin browsing — distinct from routes-pptx.ts (the
// actual PPT generation/editing API).
@@ -1,10 +1,10 @@
import express from 'express';
import path from 'path';
import fs from 'fs';
import { getConfig, getUserWorkspace } from '../config/config';
import { getOllamaClient } from '../agents/ollama-client';
import { filterImageMarkdown } from './link-validator';
import { getToolRegistry } from '../tools/registry.js';
import { getConfig, getUserWorkspace } from '../../config/config';
import { getOllamaClient } from '../../agents/ollama-client';
import { filterImageMarkdown } from '../link-validator';
import { getToolRegistry } from '../../tools/registry.js';
function isPathInsideDir(base: string, target: string): boolean {
const resolvedBase = path.resolve(base);
@@ -335,7 +335,7 @@ app.get('/api/pubmed/fetch', requireGatewayAuth, async (req: express.Request, re
try {
const pmids = String(req.query.pmids || req.query.pmid || '').trim();
if (!pmids) { res.status(400).json({ error: 'pmids parameter required' }); return; }
const { pubmedFetchTool } = await import('../tools/pubmed.js');
const { pubmedFetchTool } = await import('../../tools/pubmed.js');
const result = await pubmedFetchTool.execute({ pmids });
res.json(result);
} catch (err) {
@@ -361,7 +361,7 @@ app.post('/api/pptx/read-pdf', requireGatewayAuth, async (req: express.Request,
if (!pdfPath) { res.status(400).json({ error: 'pdf_path required' }); return; }
const workspacePath = username ? getUserWorkspace(username) : getConfig().getWorkspacePath();
const maxChars = Math.min(200_000, Number(req.body?.max_chars || 4000));
const { pdfReadTool } = await import('../tools/pdf.js');
const { pdfReadTool } = await import('../../tools/pdf.js');
const result = await pdfReadTool.execute({ path: pdfPath, max_chars: maxChars, _workspacePath: workspacePath });
// Strip references section for PPTX prep (not useful for slide generation)
if (result.success && result.stdout) {
@@ -398,7 +398,7 @@ app.get('/api/pubmed/search', requireGatewayAuth, async (req: express.Request, r
const minYear = req.query.min_year ? Number(req.query.min_year) : undefined;
const sort = req.query.sort === 'date' ? 'date' : 'relevance';
if (!query) { res.status(400).json({ error: 'q parameter required' }); return; }
const { pubmedSearchTool } = await import('../tools/pubmed.js');
const { pubmedSearchTool } = await import('../../tools/pubmed.js');
const result = await pubmedSearchTool.execute({ query, max_results: maxResults, sort, min_year: minYear });
res.json(result);
} catch (err) {
@@ -413,7 +413,7 @@ app.get('/api/openalex/search', requireGatewayAuth, async (req: express.Request,
const minYear = req.query.min_year ? Number(req.query.min_year) : undefined;
const sort = req.query.sort === 'date' ? 'publication_date' : 'relevance';
if (!query) { res.status(400).json({ error: 'q parameter required' }); return; }
const { openalexSearchTool } = await import('../tools/scholar.js');
const { openalexSearchTool } = await import('../../tools/scholar.js');
const result = await openalexSearchTool.execute({ query, max_results: maxResults, sort, min_year: minYear });
res.json(result);
} catch (err) {
@@ -427,7 +427,7 @@ app.get('/api/semantic/search', requireGatewayAuth, async (req: express.Request,
const maxResults = Math.min(Number(req.query.max || 20), 50);
const minYear = req.query.min_year ? Number(req.query.min_year) : undefined;
if (!query) { res.status(400).json({ error: 'q parameter required' }); return; }
const { semanticSearchTool } = await import('../tools/scholar.js');
const { semanticSearchTool } = await import('../../tools/scholar.js');
const result = await semanticSearchTool.execute({ query, max_results: maxResults, year_from: minYear });
res.json(result);
} catch (err) {
@@ -508,7 +508,7 @@ app.post('/api/pptx/download-pdf', requireGatewayAuth, async (req: express.Reque
const hit = (epmcData?.resultList?.result || []).find((r: any) => r.inPMC === 'Y' && r.pmcid);
if (hit?.pmcid) {
console.log(`[download-pdf] DOI→PMC: ${hit.pmcid}`);
const { pubmedFulltextTool } = await import('../tools/pubmed.js');
const { pubmedFulltextTool } = await import('../../tools/pubmed.js');
const savePath = projectSlug ? pptxRelPath(projectSlug, `${hit.pmcid}.pdf`) : undefined;
const result = await pubmedFulltextTool.execute({ pmcid: hit.pmcid, format: 'pdf', save_path: savePath, _workspacePath: workspacePath });
res.json(result);
@@ -556,7 +556,7 @@ app.post('/api/pptx/download-pdf', requireGatewayAuth, async (req: express.Reque
}
const pmcid = String(req.body?.pmcid || '').trim();
if (!pmcid) { res.status(400).json({ error: 'pmcid or url required' }); return; }
const { pubmedFulltextTool } = await import('../tools/pubmed.js');
const { pubmedFulltextTool } = await import('../../tools/pubmed.js');
const savePath = projectSlug ? pptxRelPath(projectSlug, `${pmcid}.pdf`) : undefined;
const result = await pubmedFulltextTool.execute({ pmcid, format: 'pdf', save_path: savePath, _workspacePath: workspacePath });
if (result.success) { res.json(result); return; }
@@ -665,7 +665,7 @@ app.post('/api/pptx/download-pdf-stream', requireGatewayAuth, async (req: expres
// 4. Text fallback via efetch
send({ type: 'progress', msg: 'PDF 없음 → PMC 전문 텍스트 추출 중...' });
const txtDest = path.join(workspacePath, projectSlug ? pptxRelPath(projectSlug, `${pmcid}.txt`) : `pubmed/${pmcid}.txt`);
const { pubmedFulltextTool } = await import('../tools/pubmed.js');
const { pubmedFulltextTool } = await import('../../tools/pubmed.js');
const txtSavePath = path.relative(workspacePath, txtDest);
const txtResult = await pubmedFulltextTool.execute({ pmcid, format: 'text', save_path: txtSavePath, _workspacePath: workspacePath });
if (txtResult.success) {
@@ -851,7 +851,7 @@ app.post('/api/pptx/extract-images', requireGatewayAuth, async (req: express.Req
}
if (!pdfPath) { res.status(400).json({ error: 'pdf_path required' }); return; }
const workspacePath = username ? getUserWorkspace(username) : getConfig().getWorkspacePath();
const { pdfExtractImagesTool } = await import('../tools/pdf-extract.js');
const { pdfExtractImagesTool } = await import('../../tools/pdf-extract.js');
const result = await pdfExtractImagesTool.execute({ path: pdfPath, mode: 'figures', out_dir: outDir || undefined, _workspacePath: workspacePath });
res.json(result);
} catch (err) {
@@ -1,5 +1,5 @@
import express from 'express';
import type { CronScheduler } from './cron-scheduler';
import type { CronScheduler } from '../tasks/cron-scheduler';
// cronScheduler stays defined in server-v2.ts (module-level singleton used
// well beyond this route cluster, e.g. the task-tool schedule_* handlers).
@@ -1,7 +1,7 @@
import express from 'express';
import fs from 'fs';
import path from 'path';
import { getConfig } from '../config/config';
import { getConfig } from '../../config/config';
// 회로도(Arduino circuit editor) 저장 API — workspace/<project>/ 아래에 JSON으로 저장.
export function registerSchematicRoutes(app: express.Application): void {
@@ -1,11 +1,11 @@
import express from 'express';
import fs from 'fs';
import path from 'path';
import type { SkillsManager } from './skills-manager';
import { getUserWorkspace } from '../config/config';
import { checkOrchestrationEligibility } from '../orchestration/multi-agent';
import { writeSkillPackFromContent } from '../skills/processor.js';
import { summarizeSkillForApi } from '../tools/skills.js';
import type { SkillsManager } from '../skills-manager';
import { getUserWorkspace } from '../../config/config';
import { checkOrchestrationEligibility } from '../../orchestration/multi-agent';
import { writeSkillPackFromContent } from '../../skills/processor.js';
import { summarizeSkillForApi } from '../../tools/skills.js';
// skillsManager/recoverSkillsIfEmpty/setOrchestrationEnabled stay defined in
// server-v2.ts (module-level singleton + boot-time helpers used outside this
@@ -1,5 +1,5 @@
import express from 'express';
import type { CronScheduler } from './cron-scheduler';
import type { CronScheduler } from '../tasks/cron-scheduler';
// Same cronScheduler singleton as routes-schedules.ts — /api/tasks and
// /api/schedules are two different UIs over the same CronJob store.
File renamed without changes.
@@ -1,7 +1,7 @@
import express from 'express';
import fs from 'fs';
import path from 'path';
import { getUserWorkspace } from '../config/config';
import { getUserWorkspace } from '../../config/config';
// ─── Per-user App Session IDs ─────────────────────────────────────────────────
// Stored at <user-workspace>/.smallclaw/app-sessions.json
@@ -1,9 +1,9 @@
import express from 'express';
import fs from 'fs';
import path from 'path';
import { getUserWorkspace } from '../config/config';
import { getVault, SecretValue } from '../security/vault';
import type { SkillsManager } from './skills-manager';
import { getUserWorkspace } from '../../config/config';
import { getVault, SecretValue } from '../../security/vault';
import type { SkillsManager } from '../skills-manager';
// listUsers/getUserField/saveUserField/saveUserList/hashPassword/activeSessions/
// saveActiveSessions/skillsManager/saveUserChannelId/userTelegramManager all stay
@@ -1,7 +1,7 @@
import * as http from 'http';
import * as net from 'net';
import express from 'express';
import { ensureEngineRunning, getEnginePort, isEngineReady, isVoiceEngineConfigured } from '../tools/voice-engine-client.js';
import { ensureEngineRunning, getEnginePort, isEngineReady, isVoiceEngineConfigured } from '../../tools/voice-engine-client.js';
export function registerVoiceRealtimeRoutes(app: express.Application): void {
app.get('/api/voice/engine/status', (_req, res) => {
@@ -1,8 +1,8 @@
import express from 'express';
import path from 'path';
import fs from 'fs';
import { transcribeAudio } from '../tools/stt.js';
import { getConfig } from '../config/config';
import { transcribeAudio } from '../../tools/stt.js';
import { getConfig } from '../../config/config';
export function registerVoiceRoutes(app: express.Application): void {
@@ -38,7 +38,7 @@ app.post('/api/voice/tts', async (req: express.Request, res: express.Response) =
const os = await import('os');
const { spawn: spawnProc } = await import('child_process');
if (provider === 'omnivoice_gpu') {
const { synthesizeFullGPU } = await import('../tools/voice-engine-client.js');
const { synthesizeFullGPU } = await import('../../tools/voice-engine-client.js');
const { pcm, sampleRate } = await synthesizeFullGPU(text);
const pcmPath = path.join(os.tmpdir(), `tts_gpu_${Date.now()}.pcm`);
const wavPath = path.join(os.tmpdir(), `tts_gpu_${Date.now()}.wav`);
@@ -1,8 +1,8 @@
import express from 'express';
import path from 'path';
import fs from 'fs';
import { getConfig, getUserWorkspace } from '../config/config';
import { getOllamaClient } from '../agents/ollama-client';
import { getConfig, getUserWorkspace } from '../../config/config';
import { getOllamaClient } from '../../agents/ollama-client';
function getWorkspacePath(userId?: string): string {
if (userId) {
@@ -253,7 +253,7 @@ export function registerWriterRoutes(app: express.Application): void {
try {
const query = String(req.body?.query || '').trim();
if (!query) return res.status(400).json({ success: false, error: 'query required' });
const { executeWebSearch } = await import('../tools/web.js');
const { executeWebSearch } = await import('../../tools/web.js');
const result = await executeWebSearch({ query, max_results: 6 });
if (!result.success) return res.json({ success: false, error: result.error || '검색 실패' });
const items = Array.isArray(result.data?.results) ? result.data.results : [];
@@ -430,25 +430,55 @@ export function registerWriterRoutes(app: express.Application): void {
}
return body.trim();
}
const CHAPTER_HEADING_RE = /^[ \t]*(?:CHAPTER|LETTER|PART|BOOK|VOLUME)\s+[IVXLCDM0-9]+\.?[ \t]*$/im;
function skipTableOfContents(body: string): string {
const tocHeading = body.match(/^\s*(contents|table of contents)\s*$/im);
if (!tocHeading || tocHeading.index == null) return body;
// Gutenberg 텍스트는 보통 70~75자로 강제 줄바꿈돼 있어서 "긴 줄"로 본문을 구분할 수
// 없다(2026-07-22 실측 — 셜록 홈즈 목차 스킵이 그 가정 때문에 실패했었음) — 대신
// 목차 항목은 "로마숫자/숫자 + 구분자 + 짧은 제목" 모양의 줄이 연속으로 나오는 걸로
// 판단하고, 그 연속 줄이 끊기는 지점까지만 건너뛴다.
// 판단하고, 그 연속 줄이 끊기는 지점까지만 건너뛴다. 프랑켄슈타인처럼 "Letter 1",
// "Chapter 12"만 딱 있는(구분자·부제 없는) 형식도 있어 그것도 같이 인정한다(2026-07-23).
// 다만 이 형식은 진짜 챕터 제목(본문 시작)이랑 모양이 똑같아서, 그냥 "다음 줄도 항목이면
// 계속 소비"만 하면 목차의 마지막 항목 바로 뒤에 오는 "진짜" 첫 장 제목까지 목차로 오인해
// 같이 삼켜버린다(실측: "Letter 1"이 목차 마지막 줄로 잘못 먹혀 본문이 인사말부터 시작돼
// 버림). 그래서 "다음다음 줄(빈 줄 건너뛰고)도 항목 모양이어야만" 아직 목차로 보고,
// 그렇지 않으면(=바로 뒤에 본문이 이어지면) 그 줄에서 멈춘다.
const beforeHeading = body.slice(0, tocHeading.index);
const afterHeading = body.slice(tocHeading.index + tocHeading[0].length);
const lines = afterHeading.split(/\r?\n/);
const tocEntryRe = /^\s*(?:[IVXLCDM]+|\d+)[.)]\s+\S.{0,80}$/;
const tocEntryRe = /^\s*(?:(?:[IVXLCDM]+|\d+)[.)]\s+\S.{0,80}|(?:CHAPTER|LETTER|PART|BOOK|VOLUME)\s+[IVXLCDM0-9]+\.?)\s*$/i;
const nextNonBlankIsEntry = (fromIdx: number): boolean => {
let j = fromIdx;
while (j < lines.length && lines[j].trim() === '') j++;
return j < lines.length && tocEntryRe.test(lines[j]);
};
let i = 0, sawEntry = false;
while (i < lines.length) {
const line = lines[i];
if (line.trim() === '') { i++; continue; }
if (tocEntryRe.test(line)) { sawEntry = true; i++; continue; }
if (tocEntryRe.test(line) && nextNonBlankIsEntry(i + 1)) { sawEntry = true; i++; continue; }
break;
}
if (!sawEntry) return body; // 목차 항목을 하나도 못 찾았으면 원문 그대로(과잉 삭제보다 안전)
return lines.slice(i).join('\n').trim();
return (beforeHeading + lines.slice(i).join('\n')).trim();
}
// PREFACE는 목차와 달리 자유 산문이라 "항목 나열" 판정이 안 통한다 — 대신 그 다음에 나오는
// 진짜 장/편지 제목 앞까지를 통째로 건너뛴다(2026-07-23, 사용자 요청: "제목/목차 같은 건
// 본문과 구분하자" → preface/index도 같이 필터링).
function skipPreface(body: string): string {
const heading = body.match(/^\s*preface\s*$/im);
if (!heading || heading.index == null) return body;
const afterHeading = body.slice(heading.index + heading[0].length);
const nextChapter = afterHeading.match(CHAPTER_HEADING_RE);
if (!nextChapter || nextChapter.index == null) return body; // 다음 장을 못 찾으면 과잉삭제 방지로 원문 유지
return (body.slice(0, heading.index) + afterHeading.slice(nextChapter.index)).trim();
}
// INDEX(찾아보기)는 거의 항상 책 맨 뒤 부록이라, 헤딩부터 끝까지 통째로 잘라낸다.
function skipIndex(body: string): string {
const heading = body.match(/^\s*index\s*$/im);
if (!heading || heading.index == null) return body;
return body.slice(0, heading.index).trim();
}
// Gutenberg 텍스트는 본문 문단도 70~75자로 강제 줄바꿈돼 있어서, 우리 리더처럼 좁은
// 페이지 폭에 그대로 넣으면 문단 중간에 원본 줄바꿈이 그대로 남아 들쭉날쭉하게 끊겨
@@ -491,7 +521,7 @@ export function registerWriterRoutes(app: express.Application): void {
const r = await fetchWithRetry(key);
if (!r.ok) return res.json({ success: false, error: `다운로드 실패 (${r.status})` });
const raw = await r.text();
text = reflowHardWrappedProse(skipTableOfContents(trimGutenbergBoilerplate(raw)));
text = reflowHardWrappedProse(skipIndex(skipPreface(skipTableOfContents(trimGutenbergBoilerplate(raw)))));
if (ebookTextCache.size >= 20) ebookTextCache.delete(ebookTextCache.keys().next().value as string);
ebookTextCache.set(key, text);
}
@@ -515,8 +545,18 @@ export function registerWriterRoutes(app: express.Application): void {
app.post('/api/writer/ebooks/tts', async (req: express.Request, res: express.Response) => {
const user = (req as any).user;
if (!user) return res.status(401).json({ success: false, error: 'Unauthorized' });
const text = String(req.body?.text || '').trim();
if (!text) return res.status(400).json({ success: false, error: 'text required' });
const rawText = String(req.body?.text || '').trim();
if (!rawText) return res.status(400).json({ success: false, error: 'text required' });
// 페이지 텍스트엔 문단 구분용 줄바꿈(\n\n)이 그대로 남아있는데, edge-tts에 그대로 넘기면
// 문장 중간 마침표가 아니라 그 줄바꿈에서 뚝뚝 끊어 읽는다 — 줄바꿈은 공백으로 뭉개서
// 마침표/물음표 등 문장부호 기준으로만 자연스럽게 끊어 읽히게 한다(2026-07-23).
const text = rawText.replace(/\s*\n+\s*/g, ' ').trim();
// 0.7~1.5배속 슬라이더 값을 edge-tts의 rate 문자열("+50%"/"-30%")로 변환. 서버에서도
// 한 번 더 clamp해서 클라이언트가 슬라이더 범위 밖 값을 보내도 이상한 CLI 인자가 안 되게 한다.
const speedRaw = Number(req.body?.speed);
const speed = Number.isFinite(speedRaw) ? Math.min(1.5, Math.max(0.7, speedRaw)) : 0.9;
const ratePct = Math.round((speed - 1) * 100);
const rate = `${ratePct >= 0 ? '+' : ''}${ratePct}%`;
try {
const os = await import('os');
const { spawn: spawnProc } = await import('child_process');
@@ -524,7 +564,7 @@ export function registerWriterRoutes(app: express.Application): void {
const mp3Path = path.join(os.tmpdir(), `writer_tts_${Date.now()}.mp3`);
const scriptPath = path.join(__dirname, '../../src/tools/edge_tts_synth.py');
await new Promise<void>((resolve, reject) => {
const py = spawnProc('python3', [scriptPath, voice, mp3Path]);
const py = spawnProc('python3', [scriptPath, voice, mp3Path, rate]);
py.stdin.write(text.slice(0, 3000), 'utf8');
py.stdin.end();
let stderr = '';
@@ -625,6 +665,20 @@ export function registerWriterRoutes(app: express.Application): void {
res.download(filePath, `${book.title}.${book.filename.split('.').pop()}`, { dotfiles: 'allow' } as any);
});
// 책갈피: 이북 리더에서 페이지 넘길 때마다 현재 위치(원문 글자 오프셋)를 저장해뒀다가,
// 서재에서 다시 "읽기"를 누르면 그 자리로 바로 이어서 열리게 한다(2026-07-23).
app.put('/api/writer/ebooks/library/:id/bookmark', (req: express.Request, res: express.Response) => {
const user = (req as any).user;
if (!user) return res.status(401).json({ success: false, error: 'Unauthorized' });
const offset = Math.max(0, Math.floor(Number(req.body?.offset)) || 0);
const books = loadJson<any[]>(ebookLibraryPath(user.username), []);
const book = books.find((b) => b.id === req.params.id);
if (!book) return res.status(404).json({ success: false, error: 'not found' });
book.bookmarkOffset = offset;
saveJson(ebookLibraryPath(user.username), books);
res.json({ success: true });
});
app.delete('/api/writer/ebooks/library/:id', (req: express.Request, res: express.Response) => {
const user = (req as any).user;
if (!user) return res.status(401).json({ success: false, error: 'Unauthorized' });
@@ -49,38 +49,38 @@ import {
requestedFullTemplate,
userRequestedImageEdit,
} from './prompt-gates';
import { registerArduinoRoutes } from './routes-arduino';
import { registerAndroidRoutes, attachAndroidWsProxy } from './routes-android';
import { registerBgTasksRoutes, loadTaskHeartbeatConfig } from './routes-bg-tasks';
import { registerKakaoRoutes } from './routes-kakao';
import { registerScheduleRoutes } from './routes-schedules';
import { registerSkillsRoutes } from './routes-skills';
import { registerCodeRoutes } from './routes-code';
import { registerTaskRoutes } from './routes-tasks';
import { registerAgentRoutes } from './routes-agents';
import { registerChannelsRoutes } from './routes-channels';
import { registerLegacyTelegramRoutes } from './routes-telegram';
import { registerOrchestrationRoutes } from './routes-orchestration';
import { registerSchematicRoutes } from './routes-schematics';
import { registerCanvasRoutes } from './routes-canvas';
import { registerPptStaticRoutes } from './routes-ppt';
import { registerMiscRoutes } from './routes-misc';
import { registerChatSessionRoutes } from './routes-chat-sessions';
import { registerOpenAIAuthRoutes } from './routes-auth-openai';
import { registerUserAppSessionRoutes } from './routes-user-app-sessions';
import { registerChannelMappingRoutes } from './routes-channel-mappings';
import { registerAdminSessionRoutes } from './routes-admin-sessions';
import { registerUserRoutes } from './routes-users';
import { registerDetectiveRoutes, detectiveFilesDir, resolveDetectiveUploadPath } from './routes-detective';
import { registerPptxRoutes } from './routes-pptx';
import { registerVoiceRoutes } from './routes-voice';
import { registerVoiceRealtimeRoutes, attachVoiceRealtimeWsProxy } from './routes-voice-realtime';
import { registerMusicRoutes } from './routes-music';
import { registerMCPRoutes } from './routes-mcp';
import { registerLanguageRoutes } from './routes-language';
import { registerWriterRoutes } from './routes-writer';
import { registerDentalRoutes } from './routes-dental';
import { registerDetectiveDateRoutes } from './routes-detective-dates';
import { registerArduinoRoutes } from './routes/routes-arduino';
import { registerAndroidRoutes, attachAndroidWsProxy } from './routes/routes-android';
import { registerBgTasksRoutes, loadTaskHeartbeatConfig } from './routes/routes-bg-tasks';
import { registerKakaoRoutes } from './routes/routes-kakao';
import { registerScheduleRoutes } from './routes/routes-schedules';
import { registerSkillsRoutes } from './routes/routes-skills';
import { registerCodeRoutes } from './routes/routes-code';
import { registerTaskRoutes } from './routes/routes-tasks';
import { registerAgentRoutes } from './routes/routes-agents';
import { registerChannelsRoutes } from './routes/routes-channels';
import { registerLegacyTelegramRoutes } from './routes/routes-telegram';
import { registerOrchestrationRoutes } from './routes/routes-orchestration';
import { registerSchematicRoutes } from './routes/routes-schematics';
import { registerCanvasRoutes } from './routes/routes-canvas';
import { registerPptStaticRoutes } from './routes/routes-ppt';
import { registerMiscRoutes } from './routes/routes-misc';
import { registerChatSessionRoutes } from './routes/routes-chat-sessions';
import { registerOpenAIAuthRoutes } from './routes/routes-auth-openai';
import { registerUserAppSessionRoutes } from './routes/routes-user-app-sessions';
import { registerChannelMappingRoutes } from './routes/routes-channel-mappings';
import { registerAdminSessionRoutes } from './routes/routes-admin-sessions';
import { registerUserRoutes } from './routes/routes-users';
import { registerDetectiveRoutes, detectiveFilesDir, resolveDetectiveUploadPath } from './routes/routes-detective';
import { registerPptxRoutes } from './routes/routes-pptx';
import { registerVoiceRoutes } from './routes/routes-voice';
import { registerVoiceRealtimeRoutes, attachVoiceRealtimeWsProxy } from './routes/routes-voice-realtime';
import { registerMusicRoutes } from './routes/routes-music';
import { registerMCPRoutes } from './routes/routes-mcp';
import { registerLanguageRoutes } from './routes/routes-language';
import { registerWriterRoutes } from './routes/routes-writer';
import { registerDentalRoutes } from './routes/routes-dental';
import { registerDetectiveDateRoutes } from './routes/routes-detective-dates';
import {
getConfig,
getAgents,
@@ -99,12 +99,12 @@ import { hookBus } from './hooks';
import { loadWorkspaceHooks } from './hook-loader';
import { validateLinksInText, filterImageMarkdown } from './link-validator';
import { runBootMd } from './boot';
import { TaskRunner, runTask, TaskTool, TaskState } from './task-runner';
import { setupErrorResponseEndpoint } from './error-response-endpoint-integrated';
import { TaskRunner, runTask, TaskTool, TaskState } from './tasks/task-runner';
import { setupErrorResponseEndpoint } from './errors/error-response-endpoint-integrated';
import { initCredentialHandler, getCredentialHandler } from '../security/credential-handler';
import { getVerificationFlowManager } from './verification-flow';
import { getErrorAnalyzer } from './error-analyzer';
import { getErrorHistory } from './error-history';
import { getErrorAnalyzer } from './errors/error-analyzer';
import { getErrorHistory } from './errors/error-history';
import { getRetryStrategy } from './retry-strategy';
import { getVisualErrorDetector } from './visual-error-detection';
import { getErrorAudit } from '../security/error-audit';
@@ -129,7 +129,7 @@ import {
getBrowserToolDefinitions,
getBrowserSessionInfo,
getBrowserAdvisorPacket,
} from './browser-tools';
} from './automation/browser-tools';
import {
desktopScreenshot,
desktopFindWindow,
@@ -143,9 +143,9 @@ import {
desktopSetClipboard,
getDesktopToolDefinitions,
getDesktopAdvisorPacket,
} from './desktop-tools';
import { CronScheduler } from './cron-scheduler';
import { HeartbeatRunner } from './heartbeat-runner';
} from './automation/desktop-tools';
import { CronScheduler } from './tasks/cron-scheduler';
import { HeartbeatRunner } from './tasks/heartbeat-runner';
import {
initializeAgentSchedules,
reloadAgentSchedules,
@@ -154,9 +154,9 @@ import {
getAgentLastRun,
recordAgentRun,
} from '../scheduler';
import { TelegramChannel } from './telegram-channel';
import { KakaoNotify, resolveKakaoImageToken } from './kakao-notify';
import { KakaoChannel } from './kakao-channel';
import { TelegramChannel } from './channels/telegram-channel';
import { KakaoNotify, resolveKakaoImageToken } from './channels/kakao-notify';
import { KakaoChannel } from './channels/kakao-channel';
import {
OrchestrationTriggerState,
callSecondaryPreflight,
@@ -193,9 +193,9 @@ import {
buildTaskSnapshot,
type TaskRecord,
type TaskStatus,
} from './task-store';
import { BackgroundTaskRunner } from './background-task-runner';
import { SubagentManager } from './subagent-manager';
} from './tasks/task-store';
import { BackgroundTaskRunner } from './tasks/background-task-runner';
import { SubagentManager } from './tasks/subagent-manager';
import {
FileOpProgressWatchdog,
FileOpType,
@@ -218,7 +218,7 @@ import {
import { OllamaProcessManager } from './ollama-process-manager';
import { transcribeAudio } from '../tools/stt.js';
import { synthesizeSpeech, isTTSAvailable } from '../tools/tts.js';
import { raceWithWatchdog, PreemptState } from './preempt-watchdog';
import { raceWithWatchdog, PreemptState } from './tasks/preempt-watchdog';
import { detectGpu, logGpuStatus } from './gpu-detector';
import { internalAgentTaskRouter } from './internal-agent-task';
@@ -4547,7 +4547,7 @@ print(json.dumps({'slides': slides, 'total': len(prs.slides)}, ensure_ascii=Fals
if (isTaskSession) {
try {
const taskId = sessionId.replace(/^task_/, '');
const { appendJournal } = require('./task-store');
const { appendJournal } = require('./tasks/task-store');
appendJournal(taskId, {
type: 'write_note',
content: `[${noteTag}] ${noteContent.slice(0, 300)}`,
@@ -10986,7 +10986,7 @@ app.post('/api/open-path', requireGatewayAuth, async (req, res) => {
// trigger the OpenAI OAuth flow.
import { getProvider, resetProvider, buildProviderForLLM, getModelForRole } from '../providers/factory';
import { buildWebhookRouter, resolveHookConfig } from './webhook-handler';
import { buildWebhookRouter, resolveHookConfig } from './channels/webhook-handler';
import { getMCPManager } from './mcp-manager';
import { startOAuthFlow, isConnected, clearTokens, loadTokens, exchangeManualCodeFromPending } from '../auth/openai-oauth';
import { renderMusic, renderMidi, getRenderFile, getRenderPageFile, renderMidiAsync, saveMidiFile } from './music-renderer';
@@ -16,14 +16,14 @@ import {
resolveSubagentCompletion,
type TaskRecord,
} from './task-store';
import { clearHistory, addMessage, getHistory, flushSession } from './session';
import { getConfig, getUserWorkspace } from '../config/config';
import { callSecondaryTaskStepAuditor } from '../orchestration/multi-agent';
import { getModelForRole } from '../providers/factory';
import { errorCategorizer } from './error-categorizer';
import { getRetryStrategy } from './retry-strategy';
import { getErrorAnalyzer } from './error-analyzer';
import { getErrorHistory } from './error-history';
import { clearHistory, addMessage, getHistory, flushSession } from '../session';
import { getConfig, getUserWorkspace } from '../../config/config';
import { callSecondaryTaskStepAuditor } from '../../orchestration/multi-agent';
import { getModelForRole } from '../../providers/factory';
import { errorCategorizer } from '../errors/error-categorizer';
import { getRetryStrategy } from '../retry-strategy';
import { getErrorAnalyzer } from '../errors/error-analyzer';
import { getErrorHistory } from '../errors/error-history';
import {
callErrorHealer,
callCompletionVerifier,
@@ -14,8 +14,8 @@ import fs from 'fs';
import path from 'path';
import { Cron } from 'croner';
import { BackgroundTaskRunner } from './background-task-runner';
import { clearHistory } from './session';
import { getConfig } from '../config/config';
import { clearHistory } from '../session';
import { getConfig } from '../../config/config';
// ─── Types ─────────────────────────────────────────────────────────────────────
File renamed without changes.
File renamed without changes.
File renamed without changes.
@@ -10,7 +10,7 @@
* This enables 20-30 step workflows on a 4B model with 8K context.
*/
import { getOllamaClient } from '../agents/ollama-client';
import { getOllamaClient } from '../../agents/ollama-client';
// ─── Types ─────────────────────────────────────────────────────────────────────
@@ -23,8 +23,8 @@
* • DELIVER_ANYWAY – resynth failed or we're past patience, send what we have
*/
import { getOrchestrationConfig } from '../orchestration/multi-agent';
import { contentToString } from '../providers/content-utils';
import { getOrchestrationConfig } from '../../orchestration/multi-agent';
import { contentToString } from '../../providers/content-utils';
import type { TaskRecord, TaskJournalEntry } from './task-store';
// ─── Public constants ──────────────────────────────────────────────────────────
@@ -56,7 +56,7 @@ async function buildSecondaryProvider(): Promise<{ provider: any; config: any }
const config = getOrchestrationConfig();
if (!config) return null;
try {
const { buildProviderById } = await import('../providers/factory');
const { buildProviderById } = await import('../../providers/factory');
const provider = buildProviderById(config.secondary.provider);
return { provider, config };
} catch (err: any) {
@@ -10,7 +10,7 @@
import fs from 'fs';
import path from 'path';
import crypto from 'crypto';
import { getConfig } from '../config/config';
import { getConfig } from '../../config/config';
// ─── Types ─────────────────────────────────────────────────────────────────────
+1 -1
View File
@@ -3,7 +3,7 @@ import fs from 'fs';
import { ToolResult } from '../types.js';
import { getConfig } from '../config/config.js';
import { getVault } from '../security/vault.js';
import { KakaoNotify, registerKakaoImageToken } from '../gateway/kakao-notify.js';
import { KakaoNotify, registerKakaoImageToken } from '../gateway/channels/kakao-notify.js';
const KAKAO_IMAGE_EXTS: Record<string, string> = {
'.png': 'image/png', '.jpg': 'image/jpeg', '.jpeg': 'image/jpeg',
+2 -2
View File
@@ -446,9 +446,9 @@ async function searchPixabay(query: string, apiKey: string): Promise<ImageHit |
* Korean queries. Lazy-imported so pptx.ts doesn't pull Playwright at boot.
*/
async function searchBrowser(query: string): Promise<ImageHit | null> {
let bt: typeof import('../gateway/browser-tools.js');
let bt: typeof import('../gateway/automation/browser-tools.js');
try {
bt = await import('../gateway/browser-tools.js');
bt = await import('../gateway/automation/browser-tools.js');
} catch (e: any) {
console.log(`[pptx] Browser fallback: import failed: ${e.message}`);
return null;
+1 -1
View File
@@ -106,7 +106,7 @@ export async function executeShell(args: ShellToolArgs): Promise<ToolResult> {
try {
// Lazy-load node-pty (63MB native module) only when shell is actually invoked
const { default: PTYManager } = await import('../gateway/pty-manager.js');
const { default: PTYManager } = await import('../gateway/automation/pty-manager.js');
const pty = PTYManager.getInstance();
const output = await pty.runCommand(args.command);
return {
+1 -1
View File
@@ -22,7 +22,7 @@ import {
deleteTask,
type TaskRecord,
type TaskStatus,
} from '../gateway/task-store.js';
} from '../gateway/tasks/task-store.js';
const VALID_STATUSES: TaskStatus[] = [
'queued', 'running', 'paused', 'stalled', 'needs_assistance',