Commit Graph

766 Commits

Author SHA1 Message Date
Askhz
40dc2720d0 fix(server): 修复 csc.exe server 模式下探针进程因 --feature 参数崩溃导致模型列表为空
Bun 将源码编译为独立可执行文件后,process.argv[1] 变为内部虚拟路径
(B:/~BUN/root/cli.js),该路径含 / 被误判为脚本模式,导致 saveChildSpawnPrefix
为子进程生成 --feature / -d 参数。子进程(csc.exe 本身)不识别这些 Bun
运行时参数,以 exit code 1 退出,探针失败,/provider/capabilities 返回空模型。

修复:
- getScriptArgsForChild: 识别并跳过 Bun snapshot 虚拟路径前缀 (B:/~BUN/, /snapshot/)
- saveChildSpawnPrefix: 仅在 scriptArgs 非空(脚本模式)时才生成 --feature/define 参数
- build.ts: 补充 Step 7 编译独立可执行文件 csc.exe / csc

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-05-11 20:59:10 +08:00
DoSun
ad2d4508c8
Merge pull request #58 from Askhz/fix/delete-session
fix: DELETE 历史 session 时删除磁盘 transcript 文件
2026-05-11 16:15:27 +08:00
Askhz
0a93873e3d fix: DELETE 历史 session 时删除磁盘 transcript 文件
- PATCH 接口:历史 session 不在内存时不再 404,直接返回成功
- DELETE 接口:历史 session 通过 resolveSessionFilePath 定位并删除磁盘 .jsonl 文件

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-05-11 16:11:52 +08:00
DoSun
3aab6fb889 fix: 修复 services/utils 层 strict 模式类型错误
- api/errors: formatAPIError 参数类型适配
- rawDump/logger: 导出可同时作为函数和对象调用的 log
- rawDump/worker: postJson body 类型断言、reduce 泛型标注
- sideQueryOpenAICompat: tool_calls 类型收窄为 FunctionToolCall
2026-05-11 14:33:50 +08:00
DoSun
5d6b31398a fix: strict 模式类型修复 + 恢复 allow-dangerously-skip-permissions 选项
- LogoV2: 抽取 ChannelsNoticeIfLoaded 消除重复,修复 nullability
- main.tsx: 恢复 --allow-dangerously-skip-permissions 选项
- global.d.ts: 添加 doubaoime-asr 模块类型声明
2026-05-11 14:33:44 +08:00
DoSun
c96fe77c45 fix(server): 修复 strict 模式下类型错误
- errors.ts: status 转为 ContentfulStatusCode
- server.ts: BunServer 泛型参数修正
- transcriptReader.ts: 补充 compactMetadata 类型声明
2026-05-11 14:33:37 +08:00
DoSun
799ed96b37 feat(server): prompt 支持 parts/agent 传递,import 迁移至子模块
- session route: ssePrompt 支持 parts 参数,支持 agent mentions
- session route: createSession 支持自定义 session_id
- provider/sessionManager: InitData import 从 types.js 统一导入
2026-05-11 14:33:31 +08:00
DoSun
3ebfb2c05d refactor(server): 拆分 SessionHandle 为三个子模块
- childSpawn.ts: spawn 参数构建、INIT_TIMEOUT_MS、save/loadChildSpawnPrefix
- sessionControlChannel.ts: control response pending 管理
- sessionMessageRouter.ts: stdout 消息路由 + opencode 事件发射
- sessionHandle.ts: 精简为编排层,委托给子模块
- types.ts: 统一导出 InitData/PendingPermission/PendingQuestion
2026-05-11 14:33:23 +08:00
DoSun
7c3d9da000
Merge pull request #57 from y574444354/feat/cloud-question
Feat/cloud question
2026-05-11 14:16:24 +08:00
林凯90331
1ef4182a9e fix(server): resolve merge conflicts with feat/server-refactor
- event.ts: combine /event endpoint with cwdFilter support,
  remove unused /global/event endpoint
- sessionHandle.ts: keep INIT_TIMEOUT_MS, emitOpencodeEvent,
  emitBusyStatus, toPermissionKey and extractPatterns

Co-authored-by: CoStrict <zgsm@sangfor.com.cn>
2026-05-11 13:31:24 +08:00
林凯90331
009e9f0c49 feat(server): opencode-compatible question/permission with AskUserQuestion popup support
- emit opencode-compatible SSE events for questions and permissions
  (flat shape with top-level session_id for wrapEventStream routing)
- adapt question API (/question, /question/:id/reply, /question/:id/reject)
  for AskUserQuestion and elicitation workflows
- fix AskUserQuestion tool name matching and guard against double-wrapped events
- allow requiresUserInteraction tools to ask user even in bypassPermissions mode
- avoid blocking on session init to prevent cold-start timeout
- add /global/event SSE endpoint and cwdFilter support
- add question routes and session handle tests

Co-authored-by: CoStrict <zgsm@sangfor.com.cn>
2026-05-11 12:54:44 +08:00
DoSun
434ee9e806 feat: session status 改造为 prompt 级别 busy/idle 三态,SSE 事件和 status 接口按 cwd 过滤
- 新增 SessionBusyStatus 类型(idle/busy/retry),替代进程生命周期状态
- SessionHandle 在 prompt/result/abort/close/error 中追踪 busyStatus 并通过 EventBus 发布 session.status SSE 事件
- /session/status 接口返回扁平 Record<string, SessionBusyStatus>,支持按 cwd 过滤
- EventBus 支持客户端 cwdFilter,SSE 事件按工作空间过滤推送
- sessionManager 在 create/delete 时注册/注销 sessionCwd 映射
2026-05-11 09:26:15 +08:00
林凯90331
59d3460554 Merge remote-tracking branch 'origin/feat/server-refactor' into feat/cloud-question 2026-05-09 18:18:55 +08:00
DoSun
7e04ca159b
Merge pull request #52 from Askhz/feat/serve-session-create
Feat/serve session create
2026-05-09 18:00:21 +08:00
Askhz
550dbb5532 feat: serve 模式支持 resume 历史会话继续对话
- prompt/prompt_async 接口找不到内存 session 时自动从磁盘历史恢复
- 从 transcript 读取历史 session 的原始 cwd,保证子进程在正确目录启动
- resume 时不传 --session-id 避免与 --resume 冲突(csc 限制)
- sessionManager.createSession 支持传入指定 sessionId,resume 时复用历史 id

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-05-09 17:54:25 +08:00
林凯90331
0b36424820 feat(server/question): adapt question API to opencode-compatible format
Refactor csc serve question endpoints to match opencode/app-ai-native
expected data models and request/response shapes:

- GET /question now returns QuestionRequest[] (direct array) instead of
  { questions: [...] }
- POST /question/:id/reply accepts { answers: string[][] } mapping to
  selected option labels per question
- POST /question/:id/reject no longer requires a request body
- Support dual question sources:
  - MCP Elicitation (converted to opencode format with enum→options)
  - AskUserQuestionTool permissions exposed as questions
- Add conversion helpers: convertAskUserQuestionToOpencode,
  convertElicitationToOpencode, buildElicitationContent
- Reply to AskUserQuestionTool via replyPermission('allow') with
  constructed updatedInput.answers map

Also includes serve-mode infrastructure improvements:
- Session routes auto-create sessions on demand via getOrCreateSession
- Set CSC_SERVE_MODE env var in child process spawn
- Skip push-suggestion stream waiting in serve mode

Add comprehensive unit tests for question route opencode conversion.

Co-authored-by: CoStrict <zgsm@sangfor.com.cn>
2026-05-09 17:52:43 +08:00
Askhz
f34325f60a feat: 修复 serve 模式新建会话及消息读取问题
- tsconfig.json 加 baseUrl 修复 dev 模式子进程 src/* 路径别名解析
- waitReady/initReject 修复:子进程退出时正确 reject,避免永久 pending
- POST /session 等待子进程 ready 后再返回,避免立即发 prompt 崩溃
- transcriptReader pathCache 不缓存 null,文件未写入时下次可重新查找
- session/status 用 prompting 判断 busy/idle,prompt 结束后正确变为 idle
- /agent 接口补充默认 build 模式
- message.ts 使用 spawnCwd 定位 transcript 文件

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-05-09 17:35:05 +08:00
DoSun
265ff7d864 fix: 中断对话时添加 is_interrupted 标记并优化 abort 响应速度
- QueryEngine: result 消息新增 is_interrupted 字段,标识用户中断
- sessionHandle: abort() 不再等待子进程退出,改为等待 result 事件(2s 超时兜底)
2026-05-09 16:37:03 +08:00
DoSun
6274c0e2be fix: 过滤子进程内部合成消息(model switch breadcrumb)不转发给前端 2026-05-09 11:43:10 +08:00
DoSun
0393ce927d feat: GET /permission 响应格式对齐前端 PermissionRequest 类型
- 工具名 PascalCase 映射为小写 permission key(匹配 i18n)
- 从 tool input 提取 patterns(file_path/command 等)
- 补齐 sessionID/id/tool/callID/metadata/always 字段
2026-05-09 11:18:46 +08:00
DoSun
9c3441331c feat: serve 模式默认启用权限问询(acceptEdits)并修复回复链路
- 默认权限模式从 undefined 改为 acceptEdits(工作目录内读写自动放行)
- 始终传递 --permission-prompt-tool stdio 给子进程
- 修复 updatedInput 为 undefined 导致子进程 Zod 解析失败
- always 回复附带 updatedPermissions + decisionClassification
- 新增 permission_replied/question_replied SSE 事件通知 UI 撤销弹窗
- hook_callback 控制请求自动回复防止子进程阻塞
- PendingPermission 保存 permission_suggestions 供 always 回复使用
2026-05-09 11:10:13 +08:00
DoSun
e37e9d3ad5 feat: enable stream_event forwarding for serve mode streaming
QueryEngine previously guarded stream_event yields behind includePartialMessages,
which was undefined in serve mode. Remove the guard so stream_event messages
always flow to the child process stdout. Add stream_event handling in
sessionHandle.routeMessage to emit via EventBus for downstream consumers.
2026-05-09 10:04:19 +08:00
DoSun
862a16c295
Merge pull request #50 from Askhz/feat/server-add-session
feat: serve 模式 session 列表按工作目录过滤
2026-05-09 10:01:45 +08:00
Askhz
aca6133318 feat: serve 模式 session 列表按工作目录过滤
从请求头 x-csc-directory 读取工作目录(cs-cloud 通过此头传递),
GET /session 和 GET /session/status 只返回该目录下的历史会话

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-05-09 09:59:26 +08:00
DoSun
5c3f1e16db fix: read workspace from x-csc-directory header in session creation 2026-05-08 19:02:09 +08:00
DoSun
02161dd2a6 fix: pass dynamic provider_id from initData instead of hardcoding
- Add _providerId field to SessionHandle, extracted from initData.account.apiProvider
- Include provider_id in user message emit, assistant message fallback, and session.ready
- Revert getProviderId normalization (keep raw value from subprocess)
2026-05-08 18:59:00 +08:00
DoSun
e258f58fd7 fix: normalize provider ID to anthropic (was firstParty causing model validation mismatch)
The subprocess returns apiProvider='firstParty' for direct Anthropic access,
but the adapter hardcodes providerID='anthropic' in SSE events. This mismatch
causes the frontend's isModelValid check to fail, clearing the model selector.
2026-05-08 18:42:51 +08:00
DoSun
880782b1dd fix: remove debug logs, add model fallback, fix prompt_async flow
- Remove process.stderr.write debug logs from sessionHandle and prompt_async
- Add model fallback in assistant message (use this._model if msg.model missing)
- Add model field to user message emit for adapter consumption
- Wait for session ready before setModel/prompt in prompt_async
- Return 200 JSON instead of 204 No Content from prompt_async
- Set Bun.serve idleTimeout to 255s to prevent connection drops
2026-05-08 18:42:51 +08:00
DoSun
d7a65170cd
Merge pull request #48 from y574444354/feat/favorite-migrate
Feat/favorite migrate
2026-05-08 18:42:01 +08:00
林凯90331
9a2469f8a8 Merge remote-tracking branch 'origin/feat/server-refactor' into feat/favorite-migrate 2026-05-08 18:34:37 +08:00
DoSun
8261385cbb
Merge pull request #49 from Askhz/feat/server-add-session
Feat/server add session
2026-05-08 18:34:17 +08:00
林凯90331
41dbd44b4e feat(hub): migrate favorite command with auto-enable, real-time toggle and server refactor
- Migrate favorite command from opencode to csc with /hub command
- Rename /favorite → /cloud-enabled → /knowledge-hub → /hub
- Auto-enable cloud favorites on startup without manual Update button
- Toggle items immediately on check/uncheck without Update button
- Add favorite REST routes and kh alias (later removed)
- Fix UDS socket path length exceeding macOS sockaddr_un.sun_path limit
- Add AbortController timeout to CoStrict fetch to prevent startup blocking
- Fix build robustness (handle missing download-ripgrep script)
- Merge server refactor: Hono-based HTTP API, session management, transcript reader
- Add serve API docs, server module unit tests, and cloud command handler

Signed-off-by: 林凯90331 <90331@sangfor.com>
Co-authored-by: CoStrict <zgsm@sangfor.com.cn>
2026-05-08 18:18:44 +08:00
Askhz
231c76df84 fix: 完善 serve 模式 session 列表接口
- GET /session/:id 支持从磁盘历史记录 fallback,修复历史 session 404
- 过滤无意义的管理命令会话(/exit、/model、/login 等)
- 保留 /crewpilot:plan 等有意义的斜杠命令触发的会话

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-05-08 18:12:22 +08:00
Askhz
a62989e245 Merge branch 'feat/server-refactor' into feat/server-add-session 2026-05-08 17:38:11 +08:00
Askhz
084d3fa468 feat: serve 模式 GET /session 接口从磁盘读取历史会话列表
- GET /session:调用 listSessionsImpl 扫描 ~/.claude/projects/ 历史 transcript,
  合并内存中活跃 handle 的运行时状态,支持 ?dir= 过滤
- GET /session/status:补充磁盘历史 session(全部标为 idle),不再返回空对象
- POST /session/:id/command_async、revert、summarize:补充缺失接口
- Bun.serve 设置 idleTimeout: 0,修复 SSE 长连接被 10s 超时切断的问题

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-05-08 17:32:04 +08:00
DoSun
ca147a40b7 fix: 修复 serve 模式 SSE 事件流、权限响应、协议对齐
- 修复 emitEvent 无限递归(调用自身→调用 eventBus.publishSessionEvent)
- 修复 prompt() 用户消息缺失 uuid/content 字段
- session.ready 事件映射为 session.updated(非重复 session.created)
- 新增用户消息事件(message.updated role:user + message.part.updated)
- 新增 session.status busy/idle、step-start/step-finish、session.idle/diff
- 清理 heartbeat properties 为空对象
- 仅 assistant 类型消息作为 session.message 转发,过滤 system/其他杂消息
- 权限响应映射 once/always/reject → allow/deny
- 会话创建支持 permission ruleset 推导 permission mode
- prompt 路由支持 model 字段切换模型
- 初始化消息支持 hooks 配置
- 新增 HookCallback/ControlCancelRequest 处理
- 权限响应支持 updatedPermissions 和 interrupt
- 新增 --resume-session-at、--permission-prompt-tool stdio 参数
- 追踪 lastMessageUuid 用于消息级回退
- EventBus dead client 清理
2026-05-08 16:59:45 +08:00
林凯90331
dacbf1f7ab feat: migrate favorite command from opencode to csc
- Add /favorite REPL slash command with list/view/download/load/unload/uninstall

- Implement core favorite logic in src/costrict/favorite/ using createCoStrictFetch

- Extend GlobalConfig with agents and commands fields for config-layer storage

- Adapt skill load/unload to csc's directory-scanning mechanism (~/.claude/skills/)

- Adapt MCP load/unload to csc's mcpServers config via saveGlobalConfig()

- Decouple from opencode-specific deps: jsonc-parser, Config.invalidate, Filesystem.*

Signed-off-by: 林凯90331 <90331@sangfor.com>

Co-authored-by: CoStrict <zgsm@sangfor.com.cn>
2026-05-08 08:20:57 +08:00
linkai0924
7363519887
Merge pull request #45 from y574444354/feat/report-raw-dump
feat(rawDump): add session data raw-dump reporting module
2026-05-07 22:16:02 +08:00
林凯90331
f3ece2f469 refactor(rawDump): prevent 429 with queue + batch worker
Replace per-turn detached workers with a file-backed queue consumed by
a single long-running batch worker (30s interval, 0-10s jitter).

- queue.ts, batchWorker.ts: file queue with pid-based lock for worker
  singleton; tasks deduped by sessionID:messageID before processing
- worker.ts: retry with backoff (5s, 10s) for 429 and network errors;
  update commit state per upload so partial failures resume cleanly;
  export auth, loadSessionMessages, getSessionDirectory and upload*
  helpers for batchWorker reuse
- git.ts: cap commit log at 50 entries within last 7 days; pause 500ms
  every 10 commits to spread load
- worker.ts: resolve session jsonl via ~/.claude/projects/{normalized}
  with fallbacks, scanning for the file containing the target session
- logger.ts: file + stderr logger gated by CSC_RAW_DUMP_DEBUG, default
  silent
- sessionDataUploader.ts: implement createSessionTurnUploader to pick
  the last assistant message; query.ts fires uploadSessionTurn after
  query_api_streaming_end (non-blocking)

Signed-off-by: 林凯90331 <90331@sangfor.com>
Co-authored-by: CoStrict <zgsm@sangfor.com.cn>
2026-05-07 21:45:20 +08:00
DoSun
33ad9cd568 fix: prompt 路由支持 parts 格式请求体
消费端发送 parts 数组格式([{type:'text', text:'...'}]),
csc 同时支持 content 字符串和 parts 数组两种格式
2026-05-07 20:29:49 +08:00
DoSun
d5cfe0aff0 fix: 修复 serve 模式模型接口返回空数据
多层问题修复:
- setup.ts: CoStrict 模型预取从 fire-and-forget 改为 await,确保缓存就绪
- sessionHandle.ts: 修复子进程 spawn 参数丢失 -d/--feature 的问题,
  修复 models 数组被当 Record 处理的类型错误,始终传 --verbose
- sessionManager.ts: 新增 probe session 预热机制和 initData 缓存,
  provider 路由不再依赖活跃 session
- provider.ts: 输出格式匹配消费端 ProviderCapabilitiesResponse 类型,
  models 从数组转为 Record<string, ModelInfo>
- session.ts: 修复 scriptArgs 计算逻辑,避免传入 serve 子命令
2026-05-07 20:08:27 +08:00
DoSun
954c218085 fix: 修复 serve 模式 GET /agent 接口,直接从内置 agent 列表加载数据 2026-05-07 18:00:52 +08:00
林凯90331
28d4f1f4e5 feat(rawDump): add session data raw-dump reporting module
Introduce a framework-decoupled raw-dump module that uploads conversation, summary, and commits data to the CoStrict server in a non-blocking detached worker process.

- Add src/services/rawDump/ with index, types, state, spawn, git, worker, and README

- Implement reportTurn and reportSession entry points with in-memory dedup and env-based disable switch (CSC_DISABLE_RAW_DUMP / COSTRICT_DISABLE_RAW_DUMP)

- Replace sessionDataUploader stub with uploadSessionTurn that delegates to reportTurn

Signed-off-by: 林凯90331 <90331@sangfor.com>

Co-authored-by: CoStrict <zgsm@sangfor.com.cn>
2026-05-07 17:27:56 +08:00
DoSun
de144bc0cb fix: 修复 Windows 下 dev serve 模式 Ctrl+C 无法关闭的问题 2026-05-07 16:36:35 +08:00
DoSun
9a8faf1481 feat: 添加 cloud 命令(cs-cloud 二进制下载与命令转发) 2026-05-07 10:44:43 +08:00
DoSun
ae6366c504 docs: 添加 serve API 文档 2026-05-06 14:35:38 +08:00
DoSun
c55bd43f2e test: 添加 server 模块单元测试 2026-05-06 14:32:55 +08:00
DoSun
7814a6f50a feat: 添加 serve 命令别名并重构 server 启动逻辑 2026-05-06 14:32:18 +08:00
DoSun
5058953a30 feat: 实现基于 Hono 的 HTTP API 服务器(serve 模式) 2026-05-06 14:32:04 +08:00
DoSun
7b8bc9f314 refactor: 重构构建流程,新增 DIRECT_CONNECT feature 并添加 Node.js polyfill 2026-05-06 14:31:50 +08:00