@cortex-agent/server 2026.7.30 → 2026.8.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +1 -1
- package/defaults/CORTEX.md +1 -0
- package/defaults/config/CORTEX.md +2 -1
- package/defaults/config/hooks/13-status-md-guard.json +11 -0
- package/defaults/config/hooks/CORTEX.md +1 -0
- package/defaults/config/mcp-config-empty.json +3 -0
- package/defaults/config/thread-templates/agents/benchmark-coder.json +22 -0
- package/defaults/config/thread-templates/agents/benchmark-reviewer.json +22 -0
- package/defaults/config/thread-templates/agents/coder-reviewer.json +4 -9
- package/defaults/config/thread-templates/agents/coder.json +4 -14
- package/defaults/config/thread-templates/templates/benchmark-coder-review.json +37 -0
- package/defaults/config/thread-templates/templates/coder-review.json +3 -27
- package/defaults/context/projects/CORTEX.md +1 -1
- package/defaults/data/schedules.json +12 -0
- package/defaults/hooks/CORTEX.md +1 -0
- package/defaults/hooks/new-session-hook.mjs +2 -2
- package/defaults/hooks/status-md-guard.mjs +193 -0
- package/defaults/plugins/cortex-coder/.claude-plugin/plugin.json +1 -1
- package/defaults/plugins/cortex-coder/skills/develop/SKILL.md +28 -2
- package/defaults/plugins/cortex-common/.claude-plugin/plugin.json +1 -1
- package/defaults/plugins/cortex-common/skills/compound/SKILL.md +1 -1
- package/defaults/plugins/cortex-common/skills/compound-simple/SKILL.md +4 -2
- package/defaults/plugins/cortex-common/skills/postmortem/SKILL.md +1 -1
- package/defaults/plugins/cortex-stage-gate/.claude-plugin/plugin.json +1 -1
- package/defaults/plugins/cortex-stage-gate/skills/director-method/SKILL.md +1 -1
- package/defaults/plugins/cortex-stage-gate/skills/need-approval/SKILL.md +1 -0
- package/defaults/plugins/cortex-stage-gate/skills/reorient/SKILL.md +2 -2
- package/defaults/plugins/cortex-stage-gate/skills/task/SKILL.md +11 -8
- package/defaults/plugins/cortex-system/skills/feedback/SKILL.md +1 -1
- package/defaults/plugins/cortex-system/skills/project-init/SKILL.md +13 -16
- package/defaults/prompts/directives/coder-reviewer.md +24 -20
- package/defaults/prompts/directives/coder.md +4 -5
- package/defaults/prompts/directives/director.md +4 -10
- package/defaults/prompts/directives/manager.md +9 -10
- package/defaults/prompts/systemPrompts/worker.md +2 -2
- package/defaults/rules/cortex-md.md +31 -0
- package/defaults/rules/experiment-format.md +8 -1
- package/defaults/rules/issues-md.md +10 -9
- package/defaults/rules/meta-conventions.md +5 -4
- package/defaults/rules/mission-md.md +2 -1
- package/defaults/rules/status-md.md +39 -21
- package/dist/agent-adapter/bg-wait.d.ts +10 -12
- package/dist/agent-adapter/bg-wait.js +209 -129
- package/dist/agent-adapter/claude/adapter-tui.d.ts +3 -1
- package/dist/agent-adapter/claude/adapter-tui.js +8 -5
- package/dist/agent-adapter/claude/adapter.d.ts +43 -14
- package/dist/agent-adapter/claude/adapter.js +276 -161
- package/dist/agent-adapter/claude/defaults.d.ts +2 -0
- package/dist/agent-adapter/claude/defaults.js +5 -5
- package/dist/agent-adapter/claude/event-parser.d.ts +3 -8
- package/dist/agent-adapter/claude/event-parser.js +28 -31
- package/dist/agent-adapter/claude/hooks-builder.js +4 -3
- package/dist/agent-adapter/claude/jsonl-tail.js +54 -35
- package/dist/agent-adapter/claude/spawn-args.d.ts +15 -12
- package/dist/agent-adapter/claude/spawn-args.js +44 -38
- package/dist/agent-adapter/claude/tmux-control.d.ts +4 -17
- package/dist/agent-adapter/claude/tmux-control.js +39 -32
- package/dist/agent-adapter/event-tee.d.ts +19 -0
- package/dist/agent-adapter/event-tee.js +145 -0
- package/dist/agent-adapter/index.d.ts +1 -0
- package/dist/agent-adapter/index.js +7 -3
- package/dist/agent-adapter/normalize/event-types.d.ts +17 -9
- package/dist/agent-adapter/normalize/event-types.js +4 -4
- package/dist/agent-adapter/pi/adapter.d.ts +16 -4
- package/dist/agent-adapter/pi/adapter.js +69 -36
- package/dist/agent-adapter/pi/discovery.d.ts +19 -3
- package/dist/agent-adapter/pi/discovery.js +81 -43
- package/dist/agent-adapter/pi/event-parser.js +4 -2
- package/dist/agent-adapter/pi/spawn-args.d.ts +2 -4
- package/dist/agent-adapter/pi/spawn-args.js +6 -5
- package/dist/agent-adapter/types.d.ts +43 -2
- package/dist/agent-adapter/types.js +8 -4
- package/dist/core/atomic-write.d.ts +6 -1
- package/dist/core/atomic-write.js +183 -7
- package/dist/core/cli-utils.d.ts +15 -2
- package/dist/core/cli-utils.js +46 -41
- package/dist/core/config-generator.d.ts +4 -0
- package/dist/core/config-generator.js +34 -21
- package/dist/core/json-repository.d.ts +4 -0
- package/dist/core/json-repository.js +6 -3
- package/dist/core/locales/en.d.ts +94 -0
- package/dist/core/locales/slices/commands.d.ts +76 -0
- package/dist/core/locales/slices/commands.js +155 -1
- package/dist/core/locales/slices/status.d.ts +18 -0
- package/dist/core/locales/slices/status.js +43 -2
- package/dist/core/log.d.ts +5 -0
- package/dist/core/log.js +25 -23
- package/dist/core/pi-session-filename.d.ts +2 -0
- package/dist/core/pi-session-filename.js +18 -0
- package/dist/core/resume-reminder.d.ts +5 -0
- package/dist/core/resume-reminder.js +18 -0
- package/dist/core/runtime-env.d.ts +1 -0
- package/dist/core/runtime-env.js +15 -0
- package/dist/core/settings-migration.d.ts +5 -0
- package/dist/core/settings-migration.js +128 -0
- package/dist/core/settings-spec.d.ts +174 -0
- package/dist/core/settings-spec.js +150 -0
- package/dist/core/settings.d.ts +10 -0
- package/dist/core/settings.js +235 -0
- package/dist/core/task-parser.d.ts +11 -1
- package/dist/core/task-parser.js +34 -3
- package/dist/core/types/agent-types.d.ts +19 -0
- package/dist/core/types/agent-types.js +1 -1
- package/dist/core/types/thread-types.d.ts +48 -3
- package/dist/core/types/thread-types.js +2 -2
- package/dist/domain/agent-run/access-probe-cli.d.ts +7 -0
- package/dist/domain/agent-run/access-probe-cli.js +139 -0
- package/dist/domain/agent-run/access-probe-policy.d.ts +61 -0
- package/dist/domain/agent-run/access-probe-policy.js +614 -0
- package/dist/domain/agent-run/access-probe.d.ts +21 -0
- package/dist/domain/agent-run/access-probe.js +194 -0
- package/dist/domain/agent-run/agent-run-cli.d.ts +19 -0
- package/dist/domain/agent-run/agent-run-cli.js +171 -0
- package/dist/domain/agent-run/atif.d.ts +54 -0
- package/dist/domain/agent-run/atif.js +211 -0
- package/dist/domain/agent-run/benchmark-local-thread-orchestrator.d.ts +32 -0
- package/dist/domain/agent-run/benchmark-local-thread-orchestrator.js +616 -0
- package/dist/domain/agent-run/benchmark-thread-identity.d.ts +34 -0
- package/dist/domain/agent-run/benchmark-thread-identity.js +106 -0
- package/dist/domain/agent-run/identity.d.ts +62 -0
- package/dist/domain/agent-run/identity.js +118 -0
- package/dist/domain/agent-run/journal.d.ts +51 -0
- package/dist/domain/agent-run/journal.js +259 -0
- package/dist/domain/agent-run/manifest-contract.d.ts +44 -0
- package/dist/domain/agent-run/manifest-contract.js +134 -0
- package/dist/domain/agent-run/manifest.d.ts +51 -0
- package/dist/domain/agent-run/manifest.js +801 -0
- package/dist/domain/agent-run/pinned-node-process.d.ts +35 -0
- package/dist/domain/agent-run/pinned-node-process.js +206 -0
- package/dist/domain/agent-run/role-surface.d.ts +4 -0
- package/dist/domain/agent-run/role-surface.js +99 -0
- package/dist/domain/agent-run/run-config.d.ts +22 -0
- package/dist/domain/agent-run/run-config.js +135 -0
- package/dist/domain/agent-run/runner.d.ts +7 -0
- package/dist/domain/agent-run/runner.js +518 -0
- package/dist/domain/agent-run/supervisor.d.ts +78 -0
- package/dist/domain/agent-run/supervisor.js +425 -0
- package/dist/domain/agent-run/trajectory-merge-cli.d.ts +11 -0
- package/dist/domain/agent-run/trajectory-merge-cli.js +111 -0
- package/dist/domain/agent-run/trajectory-merge.d.ts +39 -0
- package/dist/domain/agent-run/trajectory-merge.js +505 -0
- package/dist/domain/agents/config.d.ts +10 -0
- package/dist/domain/agents/config.js +149 -44
- package/dist/domain/agents/facade.d.ts +42 -7
- package/dist/domain/agents/facade.js +174 -170
- package/dist/domain/agents/provider-run-lifecycle.d.ts +18 -0
- package/dist/domain/agents/provider-run-lifecycle.js +60 -0
- package/dist/domain/auth/auth-events.d.ts +18 -0
- package/dist/domain/auth/auth-events.js +38 -0
- package/dist/domain/auth/auth-format.d.ts +2 -0
- package/dist/domain/auth/auth-format.js +58 -0
- package/dist/domain/auth/auth-status.d.ts +61 -0
- package/dist/domain/auth/auth-status.js +304 -0
- package/dist/domain/auth/auth-watch.d.ts +16 -0
- package/dist/domain/auth/auth-watch.js +125 -0
- package/dist/domain/auth/cc-login.d.ts +7 -0
- package/dist/domain/auth/cc-login.js +16 -0
- package/dist/domain/auth/cc-subscription.d.ts +38 -0
- package/dist/domain/auth/cc-subscription.js +204 -0
- package/dist/domain/auth/index.d.ts +12 -0
- package/dist/domain/auth/index.js +16 -0
- package/dist/domain/auth/login-flow.d.ts +120 -0
- package/dist/domain/auth/login-flow.js +253 -0
- package/dist/domain/auth/login-service.d.ts +32 -0
- package/dist/domain/auth/login-service.js +97 -0
- package/dist/domain/auth/logout.d.ts +32 -0
- package/dist/domain/auth/logout.js +123 -0
- package/dist/domain/auth/pi-login.d.ts +36 -0
- package/dist/domain/auth/pi-login.js +72 -0
- package/dist/domain/auth/pi-oauth.d.ts +36 -0
- package/dist/domain/auth/pi-oauth.js +84 -0
- package/dist/domain/auth/pi-runtime.d.ts +72 -0
- package/dist/domain/auth/pi-runtime.js +86 -0
- package/dist/domain/mcp/benchmark-thread-server.d.ts +1 -0
- package/dist/domain/mcp/benchmark-thread-server.js +26 -0
- package/dist/domain/mcp/tools/benchmark-thread-run.d.ts +23 -0
- package/dist/domain/mcp/tools/benchmark-thread-run.js +146 -0
- package/dist/domain/memory/user-context.js +6 -8
- package/dist/domain/monitor/disk-monitor.js +47 -16
- package/dist/domain/projects/project-store.js +23 -6
- package/dist/domain/remote/client-manager.js +12 -6
- package/dist/domain/scheduling/jobs/auth-expiry-scan.d.ts +14 -0
- package/dist/domain/scheduling/jobs/auth-expiry-scan.js +86 -0
- package/dist/domain/scheduling/jobs/task-dispatch.js +36 -40
- package/dist/domain/scheduling/runner.d.ts +2 -0
- package/dist/domain/scheduling/runner.js +7 -4
- package/dist/domain/sessions/session-backup.d.ts +14 -20
- package/dist/domain/sessions/session-backup.js +57 -68
- package/dist/domain/system/doctor.d.ts +4 -0
- package/dist/domain/system/doctor.js +113 -28
- package/dist/domain/system/server-update-check.js +7 -5
- package/dist/domain/system/system-notice.d.ts +3 -1
- package/dist/domain/system/system-notice.js +6 -11
- package/dist/domain/tasks/archiver.d.ts +1 -0
- package/dist/domain/tasks/archiver.js +13 -7
- package/dist/domain/tasks/claim-recovery.d.ts +3 -3
- package/dist/domain/tasks/claim-recovery.js +12 -8
- package/dist/domain/tasks/dispatch-utils.d.ts +15 -14
- package/dist/domain/tasks/dispatch-utils.js +22 -18
- package/dist/domain/tasks/dispatcher.d.ts +1 -0
- package/dist/domain/tasks/dispatcher.js +9 -5
- package/dist/domain/tasks/mutator.d.ts +21 -11
- package/dist/domain/tasks/mutator.js +30 -24
- package/dist/domain/tasks/pending-tracker.d.ts +5 -2
- package/dist/domain/tasks/pending-tracker.js +11 -5
- package/dist/domain/tasks/system/cortex-run.d.ts +2 -1
- package/dist/domain/tasks/system/cortex-run.js +24 -4
- package/dist/domain/tasks/system/task-cli.d.ts +1 -0
- package/dist/domain/tasks/system/task-cli.js +72 -22
- package/dist/domain/tasks/system/task-completion.d.ts +19 -2
- package/dist/domain/tasks/system/task-completion.js +31 -17
- package/dist/domain/tasks/system/task-file-input.d.ts +10 -0
- package/dist/domain/tasks/system/task-file-input.js +57 -0
- package/dist/domain/tasks/system/task-id-utils.d.ts +9 -9
- package/dist/domain/tasks/system/task-id-utils.js +13 -4
- package/dist/domain/tasks/system/task-lifecycle-edit.d.ts +6 -2
- package/dist/domain/tasks/system/task-lifecycle-edit.js +200 -6
- package/dist/domain/tasks/system/task-lock.js +19 -5
- package/dist/domain/tasks/system/task-mutations.d.ts +22 -12
- package/dist/domain/tasks/system/task-mutations.js +28 -4
- package/dist/domain/tasks/system/task-process.js +10 -8
- package/dist/domain/tasks/system/task-state.d.ts +65 -11
- package/dist/domain/tasks/system/task-state.js +86 -13
- package/dist/domain/threads/local-runtime-deps.d.ts +32 -0
- package/dist/domain/threads/local-runtime-deps.js +91 -0
- package/dist/domain/threads/local-runtime-scope.d.ts +6 -0
- package/dist/domain/threads/local-runtime-scope.js +12 -0
- package/dist/domain/threads/pending-user-inputs.d.ts +3 -0
- package/dist/domain/threads/pending-user-inputs.js +37 -0
- package/dist/domain/threads/prompt-builder.d.ts +12 -1
- package/dist/domain/threads/prompt-builder.js +73 -26
- package/dist/domain/threads/runner.d.ts +15 -3
- package/dist/domain/threads/runner.js +261 -105
- package/dist/domain/threads/state-machine.d.ts +1 -1
- package/dist/domain/threads/state-machine.js +17 -8
- package/dist/domain/ui-service/app-router.d.ts +86 -6
- package/dist/domain/ui-service/app-router.js +171 -133
- package/dist/domain/ui-service/input-schemas.d.ts +132 -10
- package/dist/domain/ui-service/input-schemas.js +59 -5
- package/dist/domain/ui-service/mutate/approvals.d.ts +2 -1
- package/dist/domain/ui-service/mutate/approvals.js +2 -1
- package/dist/domain/ui-service/mutate/auth.d.ts +6 -0
- package/dist/domain/ui-service/mutate/auth.js +83 -0
- package/dist/domain/ui-service/mutate/config.js +11 -10
- package/dist/domain/ui-service/query/approvals.js +3 -0
- package/dist/domain/ui-service/query/auth.d.ts +6 -0
- package/dist/domain/ui-service/query/auth.js +12 -0
- package/dist/domain/ui-service/query/config.d.ts +5 -5
- package/dist/domain/ui-service/query/config.js +27 -17
- package/dist/domain/ui-service/query/tasks.d.ts +1 -1
- package/dist/domain/ui-service/query/tasks.js +69 -30
- package/dist/domain/ui-service/query/threads.js +3 -3
- package/dist/domain/ui-service/types.d.ts +67 -8
- package/dist/domain/ui-service/types.js +2 -2
- package/dist/domain/ui-service/ui-service.js +16 -2
- package/dist/entry/admin-channel-hot-reload.d.ts +4 -0
- package/dist/entry/admin-channel-hot-reload.js +22 -0
- package/dist/entry/app.js +38 -38
- package/dist/entry/auth-cli.d.ts +10 -0
- package/dist/entry/auth-cli.js +52 -0
- package/dist/entry/cli-help.d.ts +5 -0
- package/dist/entry/cli-help.js +130 -0
- package/dist/entry/cli.d.ts +5 -5
- package/dist/entry/cli.js +174 -248
- package/dist/entry/daemon.d.ts +11 -0
- package/dist/entry/daemon.js +204 -103
- package/dist/entry/draft-attachments.d.ts +8 -0
- package/dist/entry/draft-attachments.js +83 -0
- package/dist/entry/feishu-login.d.ts +2 -6
- package/dist/entry/feishu-login.js +16 -21
- package/dist/entry/init.js +6 -4
- package/dist/entry/start-ui-http.d.ts +2 -8
- package/dist/entry/start-ui-http.js +7 -34
- package/dist/events/event-logger.js +11 -13
- package/dist/events/event-types.d.ts +19 -1
- package/dist/events/event-types.js +3 -3
- package/dist/events/index.d.ts +1 -1
- package/dist/events/index.js +3 -3
- package/dist/hooks/new-session-hook.mjs +2 -2
- package/dist/hooks/status-md-guard.mjs +193 -0
- package/dist/orchestration/agent-file-send.js +44 -14
- package/dist/orchestration/agent-runner.d.ts +7 -3
- package/dist/orchestration/agent-runner.js +65 -41
- package/dist/orchestration/conversation-runner.d.ts +5 -1
- package/dist/orchestration/conversation-runner.js +16 -7
- package/dist/orchestration/lifecycle.d.ts +23 -1
- package/dist/orchestration/lifecycle.js +103 -40
- package/dist/orchestration/mid-turn-inject.d.ts +2 -0
- package/dist/orchestration/mid-turn-inject.js +29 -13
- package/dist/orchestration/resume-dispatcher.d.ts +3 -5
- package/dist/orchestration/resume-dispatcher.js +9 -17
- package/dist/orchestration/routing/commands/index.d.ts +4 -1
- package/dist/orchestration/routing/commands/index.js +83 -61
- package/dist/orchestration/routing/commands/login-notice.d.ts +21 -0
- package/dist/orchestration/routing/commands/login-notice.js +97 -0
- package/dist/orchestration/routing/commands/login.d.ts +12 -0
- package/dist/orchestration/routing/commands/login.js +555 -0
- package/dist/orchestration/routing/commands/status.js +45 -59
- package/dist/orchestration/routing/edit-handler.d.ts +5 -0
- package/dist/orchestration/routing/edit-handler.js +127 -73
- package/dist/orchestration/routing/webhook.js +5 -4
- package/dist/orchestration/session-rewind.d.ts +5 -1
- package/dist/orchestration/session-rewind.js +106 -62
- package/dist/orchestration/session-send.d.ts +2 -0
- package/dist/orchestration/session-send.js +5 -6
- package/dist/orchestration/status-helpers.d.ts +1 -2
- package/dist/orchestration/status-helpers.js +7 -10
- package/dist/orchestration/thread-callback.d.ts +19 -11
- package/dist/orchestration/thread-callback.js +132 -61
- package/dist/orchestration/thread-executor.js +37 -27
- package/dist/orchestration/turn-mutation-lock.d.ts +3 -0
- package/dist/orchestration/turn-mutation-lock.js +36 -0
- package/dist/orchestration/turn-notify.d.ts +2 -5
- package/dist/orchestration/turn-notify.js +9 -21
- package/dist/platform/adapter.d.ts +1 -0
- package/dist/platform/adapter.js +2 -2
- package/dist/platform/adapters/composite-adapter.d.ts +2 -0
- package/dist/platform/adapters/composite-adapter.js +13 -3
- package/dist/platform/adapters/feishu.d.ts +2 -4
- package/dist/platform/adapters/feishu.js +38 -59
- package/dist/platform/adapters/index.d.ts +1 -1
- package/dist/platform/adapters/index.js +13 -12
- package/dist/platform/adapters/slack.d.ts +1 -1
- package/dist/platform/adapters/slack.js +12 -35
- package/dist/platform/index.d.ts +2 -1
- package/dist/platform/index.js +3 -3
- package/dist/platform/testing.d.ts +1 -0
- package/dist/platform/testing.js +13 -4
- package/dist/platform/tool-trace.js +6 -11
- package/dist/platform/ui-http/ui-http-server.d.ts +1 -1
- package/dist/platform/ui-http/ui-http-server.js +6 -18
- package/dist/store/execution-repo.d.ts +17 -1
- package/dist/store/execution-repo.js +55 -4
- package/dist/store/prompt-migration-replacements.d.ts +4 -0
- package/dist/store/prompt-migration-replacements.js +149 -0
- package/dist/store/thread-repo.d.ts +15 -4
- package/dist/store/thread-repo.js +61 -24
- package/dist/store/version-migrations.js +36 -1
- package/native/cortex-supervisor/dist/build-manifest.json +22 -0
- package/native/cortex-supervisor/dist/cortex-supervisor +0 -0
- package/package.json +5 -2
- package/web/dist/assets/index-DrNx9R6c.js +139 -0
- package/web/dist/assets/index-zpf3OSKC.css +1 -0
- package/web/dist/index.html +2 -2
- package/dist/domain/scheduling/jobs/failed-dispatch-reconciliation.d.ts +0 -1
- package/dist/domain/scheduling/jobs/failed-dispatch-reconciliation.js +0 -78
- package/web/dist/assets/index-B19jLgji.js +0 -138
- package/web/dist/assets/index-BuFyPyRW.css +0 -1
package/dist/entry/daemon.js
CHANGED
|
@@ -1,12 +1,7 @@
|
|
|
1
|
-
// input:
|
|
2
|
-
//
|
|
3
|
-
//
|
|
4
|
-
//
|
|
5
|
-
// on src change: npm run build (server→ui-contract→web) → npm pack → npm install -g <tgz> → restart();
|
|
6
|
-
// on .restart in dev mode (CORTEX_REPO set): same rebuild pipeline
|
|
7
|
-
// pos: system entry point, top-level process in daemon mode (node dist/entry/daemon.js);
|
|
8
|
-
// logs/PID persisted to DATA_DIR
|
|
9
|
-
// >>> If I am updated, update my header comment and CORTEX.md <<<
|
|
1
|
+
// input: runtime env, source changes, restart triggers
|
|
2
|
+
// output: supervised app, resilient watchers, serialized restarts
|
|
3
|
+
// pos: Agent-server process supervisor
|
|
4
|
+
// >>> 一旦我被更新,务必更新我的开头注释与所属文件夹 CORTEX.md <<<
|
|
10
5
|
/**
|
|
11
6
|
* Cortex Daemon — Supervisor for app.ts
|
|
12
7
|
*
|
|
@@ -45,17 +40,17 @@
|
|
|
45
40
|
* watcher below picks up. In dev mode (CORTEX_REPO set) this triggers the full
|
|
46
41
|
* rebuild pipeline; in production mode it just respawns app.js.
|
|
47
42
|
*/
|
|
48
|
-
import * as dotenv from 'dotenv';
|
|
49
43
|
import { fork, spawn } from 'child_process';
|
|
50
|
-
import { watch, existsSync, unlinkSync, statSync, writeFileSync, readdirSync } from 'fs';
|
|
44
|
+
import { watch, existsSync, unlinkSync, statSync, writeFileSync, readdirSync, } from 'fs';
|
|
51
45
|
import * as path from 'path';
|
|
52
46
|
import { createLogger } from '../core/log.js';
|
|
47
|
+
import { loadRuntimeDotenv } from '../core/runtime-env.js';
|
|
53
48
|
import { isMainModule, moduleDir, DATA_DIR, CONFIG_DIR, STORE_DIR } from '../core/utils.js';
|
|
54
49
|
import { tryAcquireSingletonLock, releaseSingletonLock as releaseLock } from '../core/singleton-lock.js';
|
|
55
50
|
// Load .env BEFORE reading any CORTEX_* env vars below. Mirrors app.ts §61 — the
|
|
56
51
|
// daemon needs CORTEX_REPO (and potentially other vars) from .env, not just from
|
|
57
52
|
// the OS shell env. Must be sync and before the `CORTEX_REPO` constant below.
|
|
58
|
-
|
|
53
|
+
loadRuntimeDotenv(path.join(CONFIG_DIR, '.env'));
|
|
59
54
|
// --- Logger ---
|
|
60
55
|
const log = createLogger('daemon');
|
|
61
56
|
// --- Paths ---
|
|
@@ -82,6 +77,7 @@ const BUILD_DEBOUNCE_MS = 2500; // src/*.ts — slower, build takes seconds anyw
|
|
|
82
77
|
const BACKOFF_INITIAL = 1000;
|
|
83
78
|
const BACKOFF_MAX = 30_000;
|
|
84
79
|
const HEALTHY_THRESHOLD = 10_000; // if alive > 10s, reset backoff
|
|
80
|
+
const WATCH_FALLBACK_MS = 5000;
|
|
85
81
|
// Src-watch filter: paths under SRC_WATCH_PATH that should NOT trigger a rebuild.
|
|
86
82
|
const SRC_IGNORE_PREFIXES = ['tests/', 'tmp/', 'node_modules/', 'dist/', 'vendor/'];
|
|
87
83
|
const SRC_IGNORE_SUFFIXES = ['.d.ts', '.test.ts', '.spec.ts'];
|
|
@@ -99,6 +95,7 @@ let pendingRebuild = null; // reason string if rebuild is deferred (busy or in-f
|
|
|
99
95
|
let restarting = false; // true while restart() stop→start cycle is in progress
|
|
100
96
|
let rebuilding = false; // true while runRebuildPipeline() is running
|
|
101
97
|
let nextRestartReason = null; // forwarded to next child via CORTEX_RESTART_REASON
|
|
98
|
+
let watchMonitors = [];
|
|
102
99
|
// Daemon logs are written by the centralized logger (src/core/log.ts)
|
|
103
100
|
// — console + daily-rotating file output in DATA_DIR/logs/.
|
|
104
101
|
// --- Cancel all pending restart timers ---
|
|
@@ -268,13 +265,67 @@ async function restart(reason) {
|
|
|
268
265
|
nextRestartReason = reason;
|
|
269
266
|
startChild();
|
|
270
267
|
}
|
|
271
|
-
|
|
272
|
-
|
|
273
|
-
|
|
268
|
+
function formatWatchError(error) {
|
|
269
|
+
if (!(error instanceof Error))
|
|
270
|
+
return String(error);
|
|
271
|
+
const code = error.code;
|
|
272
|
+
return code ? `${code}: ${error.message}` : error.message;
|
|
273
|
+
}
|
|
274
|
+
function closeWatchers(watchers) {
|
|
275
|
+
for (const watcher of watchers.splice(0)) {
|
|
276
|
+
try {
|
|
277
|
+
watcher.close();
|
|
278
|
+
}
|
|
279
|
+
catch { }
|
|
280
|
+
}
|
|
281
|
+
}
|
|
282
|
+
function pollSafely(options, warn) {
|
|
283
|
+
try {
|
|
284
|
+
options.poll?.();
|
|
285
|
+
}
|
|
286
|
+
catch (error) {
|
|
287
|
+
warn(`${options.label} polling failed (${formatWatchError(error)})`);
|
|
288
|
+
}
|
|
289
|
+
}
|
|
290
|
+
function failWatchMonitor(state, options, warn, error) {
|
|
291
|
+
if (state.failed || state.closed)
|
|
292
|
+
return;
|
|
293
|
+
state.failed = true;
|
|
294
|
+
closeWatchers(state.watchers);
|
|
295
|
+
const detail = formatWatchError(error);
|
|
296
|
+
if (!options.poll) {
|
|
297
|
+
warn(`${options.label} watcher failed (${detail}); watcher disabled`);
|
|
298
|
+
return;
|
|
299
|
+
}
|
|
300
|
+
warn(`${options.label} watcher failed (${detail}); polling every ${WATCH_FALLBACK_MS}ms`);
|
|
301
|
+
state.pollTimer = setInterval(() => pollSafely(options, warn), WATCH_FALLBACK_MS);
|
|
302
|
+
}
|
|
303
|
+
function closeWatchMonitor(state) {
|
|
304
|
+
state.closed = true;
|
|
305
|
+
closeWatchers(state.watchers);
|
|
306
|
+
if (state.pollTimer)
|
|
307
|
+
clearInterval(state.pollTimer);
|
|
308
|
+
state.pollTimer = null;
|
|
309
|
+
}
|
|
310
|
+
export function createResilientWatchMonitor(options) {
|
|
311
|
+
const state = { watchers: [], pollTimer: null, failed: false, closed: false };
|
|
312
|
+
const warn = options.warn ?? (message => log.warn(message));
|
|
313
|
+
const fallBack = (error) => failWatchMonitor(state, options, warn, error);
|
|
314
|
+
try {
|
|
315
|
+
state.watchers = options.startWatching();
|
|
316
|
+
for (const watcher of state.watchers)
|
|
317
|
+
watcher.on('error', fallBack);
|
|
318
|
+
}
|
|
319
|
+
catch (error) {
|
|
320
|
+
fallBack(error);
|
|
321
|
+
}
|
|
322
|
+
return { close: () => closeWatchMonitor(state) };
|
|
323
|
+
}
|
|
324
|
+
/** Recursively watch each directory on Windows, closing partial setup on failure. */
|
|
274
325
|
function watchTree(root, callback) {
|
|
275
326
|
const watchers = [];
|
|
276
327
|
const walk = (dir) => {
|
|
277
|
-
watchers.push(watch(dir, (
|
|
328
|
+
watchers.push(watch(dir, (eventType, filename) => callback(eventType, filename)));
|
|
278
329
|
let entries;
|
|
279
330
|
try {
|
|
280
331
|
entries = readdirSync(dir, { withFileTypes: true });
|
|
@@ -290,79 +341,133 @@ function watchTree(root, callback) {
|
|
|
290
341
|
walk(path.join(dir, entry.name));
|
|
291
342
|
}
|
|
292
343
|
};
|
|
293
|
-
|
|
344
|
+
try {
|
|
345
|
+
walk(root);
|
|
346
|
+
}
|
|
347
|
+
catch (error) {
|
|
348
|
+
closeWatchers(watchers);
|
|
349
|
+
throw error;
|
|
350
|
+
}
|
|
294
351
|
return watchers;
|
|
295
352
|
}
|
|
296
|
-
function
|
|
297
|
-
|
|
298
|
-
|
|
299
|
-
|
|
300
|
-
|
|
301
|
-
|
|
302
|
-
|
|
303
|
-
|
|
304
|
-
|
|
305
|
-
|
|
306
|
-
|
|
307
|
-
|
|
308
|
-
|
|
309
|
-
|
|
310
|
-
|
|
311
|
-
|
|
312
|
-
|
|
313
|
-
|
|
314
|
-
|
|
315
|
-
|
|
316
|
-
|
|
317
|
-
|
|
318
|
-
|
|
319
|
-
|
|
320
|
-
|
|
321
|
-
}
|
|
322
|
-
|
|
323
|
-
|
|
324
|
-
|
|
353
|
+
function isDirectory(dir) {
|
|
354
|
+
try {
|
|
355
|
+
return existsSync(dir) && statSync(dir).isDirectory();
|
|
356
|
+
}
|
|
357
|
+
catch {
|
|
358
|
+
return false;
|
|
359
|
+
}
|
|
360
|
+
}
|
|
361
|
+
function handleSourceChange(filename) {
|
|
362
|
+
if (!filename)
|
|
363
|
+
return;
|
|
364
|
+
const changedName = String(filename).replace(/\\/g, '/');
|
|
365
|
+
if (!changedName.endsWith('.ts'))
|
|
366
|
+
return;
|
|
367
|
+
if (SRC_IGNORE_SUFFIXES.some(suffix => changedName.endsWith(suffix)))
|
|
368
|
+
return;
|
|
369
|
+
if (SRC_IGNORE_PREFIXES.some(prefix => changedName.startsWith(prefix) || changedName.includes(`/${prefix}`)))
|
|
370
|
+
return;
|
|
371
|
+
debouncedRebuild(`src change: ${changedName}`);
|
|
372
|
+
}
|
|
373
|
+
function setupSourceMonitor() {
|
|
374
|
+
if (!SRC_WATCH_PATH || !isDirectory(SRC_WATCH_PATH)) {
|
|
375
|
+
const detail = CORTEX_REPO
|
|
376
|
+
? `CORTEX_REPO=${CORTEX_REPO} set but ${SRC_WATCH_PATH} not a directory`
|
|
377
|
+
: 'CORTEX_REPO unset';
|
|
378
|
+
log.warn(`${detail} — src watcher disabled, only .restart trigger available`);
|
|
379
|
+
return null;
|
|
380
|
+
}
|
|
381
|
+
return createResilientWatchMonitor({
|
|
382
|
+
label: `Source ${SRC_WATCH_PATH}`,
|
|
383
|
+
startWatching: () => {
|
|
384
|
+
if (process.platform === 'win32') {
|
|
385
|
+
const watchers = watchTree(SRC_WATCH_PATH, (_event, filename) => handleSourceChange(filename));
|
|
386
|
+
log.info(`Watching src: ${SRC_WATCH_PATH} (per-directory, *.ts, ${watchers.length} dirs)`);
|
|
387
|
+
return watchers;
|
|
388
|
+
}
|
|
389
|
+
const watcher = watch(SRC_WATCH_PATH, { recursive: true }, (_event, filename) => handleSourceChange(filename));
|
|
325
390
|
log.info(`Watching src: ${SRC_WATCH_PATH} (recursive, *.ts)`);
|
|
326
|
-
|
|
391
|
+
return [watcher];
|
|
392
|
+
},
|
|
393
|
+
});
|
|
394
|
+
}
|
|
395
|
+
function consumeRestartTrigger() {
|
|
396
|
+
if (!existsSync(RESTART_TRIGGER))
|
|
397
|
+
return;
|
|
398
|
+
try {
|
|
399
|
+
unlinkSync(RESTART_TRIGGER);
|
|
327
400
|
}
|
|
328
|
-
|
|
329
|
-
|
|
401
|
+
catch { }
|
|
402
|
+
if (CORTEX_REPO) {
|
|
403
|
+
debouncedRebuild('manual trigger (.restart file)');
|
|
330
404
|
}
|
|
331
405
|
else {
|
|
332
|
-
|
|
406
|
+
debouncedRestart('manual trigger (.restart file)');
|
|
333
407
|
}
|
|
334
|
-
|
|
408
|
+
}
|
|
409
|
+
function setupRestartTriggerMonitor() {
|
|
335
410
|
const triggerDir = path.dirname(RESTART_TRIGGER);
|
|
336
411
|
const triggerName = path.basename(RESTART_TRIGGER);
|
|
337
|
-
|
|
338
|
-
|
|
339
|
-
|
|
340
|
-
|
|
341
|
-
|
|
342
|
-
|
|
343
|
-
|
|
344
|
-
|
|
345
|
-
|
|
346
|
-
|
|
347
|
-
|
|
348
|
-
|
|
349
|
-
|
|
412
|
+
return createResilientWatchMonitor({
|
|
413
|
+
label: `Restart trigger ${RESTART_TRIGGER}`,
|
|
414
|
+
startWatching: () => {
|
|
415
|
+
const watcher = watch(triggerDir, (_event, filename) => {
|
|
416
|
+
if (filename && String(filename) === triggerName)
|
|
417
|
+
consumeRestartTrigger();
|
|
418
|
+
});
|
|
419
|
+
log.info(`Watching for restart trigger: ${RESTART_TRIGGER}`);
|
|
420
|
+
return [watcher];
|
|
421
|
+
},
|
|
422
|
+
poll: consumeRestartTrigger,
|
|
423
|
+
});
|
|
424
|
+
}
|
|
425
|
+
function fileStamp(filePath) {
|
|
426
|
+
try {
|
|
427
|
+
const stat = statSync(filePath);
|
|
428
|
+
return `${stat.mtimeMs}:${stat.size}`;
|
|
429
|
+
}
|
|
430
|
+
catch {
|
|
431
|
+
return null;
|
|
432
|
+
}
|
|
433
|
+
}
|
|
434
|
+
function startEnvWatcher(envDir, envName, onChange) {
|
|
435
|
+
const watcher = watch(envDir, (_event, filename) => {
|
|
436
|
+
if (filename && String(filename) === envName)
|
|
437
|
+
onChange();
|
|
350
438
|
});
|
|
351
|
-
|
|
352
|
-
|
|
353
|
-
|
|
439
|
+
log.info(`Watching env file: ${ENV_FILE}`);
|
|
440
|
+
return [watcher];
|
|
441
|
+
}
|
|
442
|
+
function setupEnvMonitor() {
|
|
354
443
|
const envDir = path.dirname(ENV_FILE);
|
|
444
|
+
if (!existsSync(envDir))
|
|
445
|
+
return null;
|
|
355
446
|
const envName = path.basename(ENV_FILE);
|
|
356
|
-
|
|
357
|
-
|
|
358
|
-
|
|
359
|
-
|
|
360
|
-
|
|
361
|
-
|
|
362
|
-
|
|
363
|
-
|
|
364
|
-
|
|
365
|
-
|
|
447
|
+
let observedStamp = fileStamp(ENV_FILE);
|
|
448
|
+
const handleChange = () => {
|
|
449
|
+
observedStamp = fileStamp(ENV_FILE);
|
|
450
|
+
debouncedRestart('env change (.env)');
|
|
451
|
+
};
|
|
452
|
+
const poll = () => {
|
|
453
|
+
const nextStamp = fileStamp(ENV_FILE);
|
|
454
|
+
if (nextStamp === observedStamp)
|
|
455
|
+
return;
|
|
456
|
+
observedStamp = nextStamp;
|
|
457
|
+
debouncedRestart('env change (.env)');
|
|
458
|
+
};
|
|
459
|
+
return createResilientWatchMonitor({
|
|
460
|
+
label: `Environment file ${ENV_FILE}`,
|
|
461
|
+
startWatching: () => startEnvWatcher(envDir, envName, handleChange),
|
|
462
|
+
poll,
|
|
463
|
+
});
|
|
464
|
+
}
|
|
465
|
+
function setupWatchers() {
|
|
466
|
+
const monitors = [setupRestartTriggerMonitor(), setupEnvMonitor()];
|
|
467
|
+
const sourceMonitor = setupSourceMonitor();
|
|
468
|
+
if (sourceMonitor)
|
|
469
|
+
monitors.push(sourceMonitor);
|
|
470
|
+
return monitors.filter((monitor) => monitor !== null);
|
|
366
471
|
}
|
|
367
472
|
function debouncedRestart(reason) {
|
|
368
473
|
if (restartTimer)
|
|
@@ -550,6 +655,10 @@ async function runRebuildPipeline(reason) {
|
|
|
550
655
|
}
|
|
551
656
|
}
|
|
552
657
|
// --- Graceful Shutdown ---
|
|
658
|
+
function closeWatchMonitors() {
|
|
659
|
+
for (const monitor of watchMonitors.splice(0))
|
|
660
|
+
monitor.close();
|
|
661
|
+
}
|
|
553
662
|
function setupShutdown() {
|
|
554
663
|
const shutdown = async (signal) => {
|
|
555
664
|
if (shuttingDown)
|
|
@@ -557,6 +666,7 @@ function setupShutdown() {
|
|
|
557
666
|
shuttingDown = true;
|
|
558
667
|
log.info(`Received ${signal}, shutting down...`);
|
|
559
668
|
cancelPendingTimers();
|
|
669
|
+
closeWatchMonitors();
|
|
560
670
|
await stopChild();
|
|
561
671
|
log.info('Daemon stopped.');
|
|
562
672
|
process.exit(0);
|
|
@@ -585,45 +695,36 @@ function releaseSingletonLock() {
|
|
|
585
695
|
}
|
|
586
696
|
catch { }
|
|
587
697
|
}
|
|
588
|
-
function
|
|
589
|
-
//
|
|
590
|
-
|
|
591
|
-
|
|
592
|
-
|
|
593
|
-
process.on('uncaughtException', (err) => {
|
|
594
|
-
if (inExceptionHandler)
|
|
595
|
-
return; // already handling an exception — avoid re-entrant loop
|
|
596
|
-
inExceptionHandler = true;
|
|
597
|
-
try {
|
|
598
|
-
log.error(`uncaughtException: ${err?.stack ?? err}`);
|
|
599
|
-
}
|
|
600
|
-
catch {
|
|
601
|
-
// log.error() itself threw (shouldn't happen after log.ts EPIPE fix, but guard anyway)
|
|
602
|
-
}
|
|
603
|
-
finally {
|
|
604
|
-
inExceptionHandler = false;
|
|
605
|
-
}
|
|
606
|
-
});
|
|
607
|
-
process.on('unhandledRejection', (reason) => {
|
|
608
|
-
if (inExceptionHandler)
|
|
698
|
+
function setupProcessErrorHandlers() {
|
|
699
|
+
// Prevent log failures from recursively re-entering the process error handlers.
|
|
700
|
+
let handlingError = false;
|
|
701
|
+
const report = (kind, detail) => {
|
|
702
|
+
if (handlingError)
|
|
609
703
|
return;
|
|
610
|
-
|
|
704
|
+
handlingError = true;
|
|
611
705
|
try {
|
|
612
|
-
log.error(
|
|
706
|
+
log.error(`${kind}: ${String(detail)}`);
|
|
613
707
|
}
|
|
614
708
|
catch {
|
|
615
|
-
//
|
|
709
|
+
// The logger may itself fail on a broken stderr; avoid recursive handling.
|
|
616
710
|
}
|
|
617
711
|
finally {
|
|
618
|
-
|
|
712
|
+
handlingError = false;
|
|
619
713
|
}
|
|
714
|
+
};
|
|
715
|
+
process.on('uncaughtException', error => report('uncaughtException', error?.stack ?? error));
|
|
716
|
+
process.on('unhandledRejection', reason => {
|
|
717
|
+
report('unhandledRejection', reason instanceof Error ? reason.stack : reason);
|
|
620
718
|
});
|
|
719
|
+
}
|
|
720
|
+
function main() {
|
|
721
|
+
setupProcessErrorHandlers();
|
|
621
722
|
acquireSingletonLock();
|
|
622
723
|
process.on('exit', releaseSingletonLock);
|
|
623
724
|
log.info('Cortex Daemon starting...');
|
|
624
725
|
setupShutdown();
|
|
625
|
-
setupWatchers();
|
|
626
726
|
startChild();
|
|
727
|
+
watchMonitors = setupWatchers();
|
|
627
728
|
}
|
|
628
729
|
if (isMainModule(import.meta.url)) {
|
|
629
730
|
main();
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
import type { AttachmentMeta } from '../domain/ui-service/types.js';
|
|
2
|
+
interface MoveDraftAttachmentsOptions {
|
|
3
|
+
draftUploadId: string | null;
|
|
4
|
+
sessionId: string;
|
|
5
|
+
attachments: AttachmentMeta[];
|
|
6
|
+
}
|
|
7
|
+
export declare function moveDraftAttachments(opts: MoveDraftAttachmentsOptions): Promise<AttachmentMeta[]>;
|
|
8
|
+
export {};
|
|
@@ -0,0 +1,83 @@
|
|
|
1
|
+
// input: draft/session ids, attachment metadata, workspace filesystem
|
|
2
|
+
// output: moveDraftAttachments with canonical truthful aliases
|
|
3
|
+
// pos: Promotes Web draft uploads into session storage
|
|
4
|
+
// >>> 一旦我被更新,务必更新我的开头注释与所属文件夹 CORTEX.md <<<
|
|
5
|
+
import * as path from 'node:path';
|
|
6
|
+
import { promises as fs } from 'node:fs';
|
|
7
|
+
import { createLogger } from '../core/log.js';
|
|
8
|
+
import { WORKSPACE_DIR, resolveWorkspaceRelPath } from '../core/paths.js';
|
|
9
|
+
const log = createLogger('draft-attachments');
|
|
10
|
+
const ATTACHMENTS_DIR = path.resolve(WORKSPACE_DIR, 'attachments');
|
|
11
|
+
const SAFE_BUCKET_ID = /^[A-Za-z0-9_-]+$/;
|
|
12
|
+
function bucketDirectory(id) {
|
|
13
|
+
if (!SAFE_BUCKET_ID.test(id))
|
|
14
|
+
return null;
|
|
15
|
+
const directory = path.resolve(ATTACHMENTS_DIR, id);
|
|
16
|
+
return path.dirname(directory) === ATTACHMENTS_DIR ? directory : null;
|
|
17
|
+
}
|
|
18
|
+
function resolveCandidate(draftUploadId, sessionId, attachment) {
|
|
19
|
+
const draftDir = bucketDirectory(draftUploadId);
|
|
20
|
+
const sessionDir = bucketDirectory(sessionId);
|
|
21
|
+
const prefix = `workspace/attachments/${draftUploadId}/`;
|
|
22
|
+
if (!draftDir || !sessionDir || !attachment.path.startsWith(prefix))
|
|
23
|
+
return null;
|
|
24
|
+
const fileName = attachment.path.slice(prefix.length);
|
|
25
|
+
if (!fileName || path.basename(fileName) !== fileName || fileName === '.' || fileName === '..')
|
|
26
|
+
return null;
|
|
27
|
+
const source = resolveWorkspaceRelPath(attachment.path);
|
|
28
|
+
if (!source || path.dirname(source) !== draftDir)
|
|
29
|
+
return null;
|
|
30
|
+
return {
|
|
31
|
+
source,
|
|
32
|
+
destination: path.join(sessionDir, fileName),
|
|
33
|
+
promotedAlias: `workspace/attachments/${sessionId}/${fileName}`,
|
|
34
|
+
};
|
|
35
|
+
}
|
|
36
|
+
async function isRegularFile(filename) {
|
|
37
|
+
try {
|
|
38
|
+
const stat = await fs.lstat(filename);
|
|
39
|
+
return stat.isFile() && !stat.isSymbolicLink();
|
|
40
|
+
}
|
|
41
|
+
catch {
|
|
42
|
+
return false;
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
async function promoteCandidate(candidate) {
|
|
46
|
+
if (!await isRegularFile(candidate.source))
|
|
47
|
+
return { kind: 'drop' };
|
|
48
|
+
try {
|
|
49
|
+
await fs.mkdir(path.dirname(candidate.destination), { recursive: true });
|
|
50
|
+
await fs.link(candidate.source, candidate.destination);
|
|
51
|
+
}
|
|
52
|
+
catch {
|
|
53
|
+
return await isRegularFile(candidate.source) ? { kind: 'retain' } : { kind: 'drop' };
|
|
54
|
+
}
|
|
55
|
+
if (!await isRegularFile(candidate.destination)) {
|
|
56
|
+
await fs.unlink(candidate.destination).catch(() => { });
|
|
57
|
+
return await isRegularFile(candidate.source) ? { kind: 'retain' } : { kind: 'drop' };
|
|
58
|
+
}
|
|
59
|
+
await fs.unlink(candidate.source).catch((error) => {
|
|
60
|
+
log.warn(`Promoted draft attachment but could not remove source: ${error.message}`);
|
|
61
|
+
});
|
|
62
|
+
return { kind: 'promoted', alias: candidate.promotedAlias };
|
|
63
|
+
}
|
|
64
|
+
export async function moveDraftAttachments(opts) {
|
|
65
|
+
if (!opts.draftUploadId || opts.attachments.length === 0)
|
|
66
|
+
return opts.attachments;
|
|
67
|
+
const outcomes = new Map();
|
|
68
|
+
const result = [];
|
|
69
|
+
for (const attachment of opts.attachments) {
|
|
70
|
+
const candidate = resolveCandidate(opts.draftUploadId, opts.sessionId, attachment);
|
|
71
|
+
if (!candidate)
|
|
72
|
+
continue;
|
|
73
|
+
if (!outcomes.has(candidate.source)) {
|
|
74
|
+
outcomes.set(candidate.source, await promoteCandidate(candidate));
|
|
75
|
+
}
|
|
76
|
+
const outcome = outcomes.get(candidate.source);
|
|
77
|
+
if (outcome.kind === 'promoted')
|
|
78
|
+
result.push({ ...attachment, path: outcome.alias });
|
|
79
|
+
else if (outcome.kind === 'retain')
|
|
80
|
+
result.push(attachment);
|
|
81
|
+
}
|
|
82
|
+
return result;
|
|
83
|
+
}
|
|
@@ -18,11 +18,7 @@ export interface FeishuCliDeps {
|
|
|
18
18
|
/** dotenv file that a successful login flips to FEISHU_AUTH_MODE=user (default: CONFIG_DIR/.env). */
|
|
19
19
|
envFile?: string;
|
|
20
20
|
}
|
|
21
|
-
/**
|
|
22
|
-
|
|
23
|
-
* exists, append it otherwise, creating the file (and parent dir) when missing.
|
|
24
|
-
* The rest of the file is preserved so hand-written credentials stay intact.
|
|
25
|
-
*/
|
|
26
|
-
export declare function upsertEnvVar(file: string, key: string, value: string): void;
|
|
21
|
+
/** Serialize dotenv read-modify-write across processes so unrelated settings survive. */
|
|
22
|
+
export declare function upsertEnvVar(file: string, key: string, value: string): Promise<void>;
|
|
27
23
|
export declare function getFeishuHelp(): string;
|
|
28
24
|
export declare function cmdFeishu(args: string[], deps?: FeishuCliDeps): Promise<CliResult>;
|
|
@@ -1,36 +1,31 @@
|
|
|
1
|
-
// input: readline, dotenv,
|
|
2
|
-
// output: cmdFeishu
|
|
3
|
-
// pos:
|
|
4
|
-
// URL, poll for the token); --manual keeps the legacy paste-the-code flow. status/logout
|
|
5
|
-
// inspect/clear the on-disk token. Dispatched from cli.ts.
|
|
1
|
+
// input: readline, dotenv, atomic mutation, Feishu user auth
|
|
2
|
+
// output: cmdFeishu and serialized dotenv updates
|
|
3
|
+
// pos: Feishu user-login command-line adapter
|
|
6
4
|
// >>> If I am updated, update my header comment and the parent folder's CORTEX.md <<<
|
|
7
5
|
import * as readline from 'readline';
|
|
8
6
|
import * as path from 'path';
|
|
9
7
|
import * as dotenv from 'dotenv';
|
|
10
|
-
import {
|
|
8
|
+
import { mutateFileAtomically } from '../core/atomic-write.js';
|
|
11
9
|
import { CONFIG_DIR } from '../core/utils.js';
|
|
12
10
|
import { buildAuthorizeUrl, parseCodeFromInput, exchangeCode, requestDeviceAuthorization, pollDeviceToken, saveUserToken, loadUserToken, clearUserToken, userTokenPath, DEFAULT_DOC_SCOPE, } from '../domain/mcp/feishu/user-auth.js';
|
|
13
|
-
|
|
14
|
-
* Idempotently set KEY=value in a dotenv file: rewrite the line if KEY already
|
|
15
|
-
* exists, append it otherwise, creating the file (and parent dir) when missing.
|
|
16
|
-
* The rest of the file is preserved so hand-written credentials stay intact.
|
|
17
|
-
*/
|
|
18
|
-
export function upsertEnvVar(file, key, value) {
|
|
11
|
+
function upsertEnvContents(existing, key, value) {
|
|
19
12
|
const line = `${key}=${value}`;
|
|
20
|
-
const existing = existsSync(file) ? readFileSync(file, 'utf8') : '';
|
|
21
13
|
const lines = existing === '' ? [] : existing.replace(/\n+$/, '').split('\n');
|
|
22
14
|
const re = new RegExp(`^\\s*${key}\\s*=`);
|
|
23
|
-
const idx = lines.findIndex(
|
|
15
|
+
const idx = lines.findIndex(candidate => re.test(candidate));
|
|
24
16
|
if (idx >= 0) {
|
|
25
17
|
if (lines[idx] === line)
|
|
26
|
-
return;
|
|
18
|
+
return existing;
|
|
27
19
|
lines[idx] = line;
|
|
28
20
|
}
|
|
29
21
|
else {
|
|
30
22
|
lines.push(line);
|
|
31
23
|
}
|
|
32
|
-
|
|
33
|
-
|
|
24
|
+
return lines.join('\n') + '\n';
|
|
25
|
+
}
|
|
26
|
+
/** Serialize dotenv read-modify-write across processes so unrelated settings survive. */
|
|
27
|
+
export function upsertEnvVar(file, key, value) {
|
|
28
|
+
return mutateFileAtomically(file, existing => upsertEnvContents(existing, key, value), { mode: 0o600 });
|
|
34
29
|
}
|
|
35
30
|
export function getFeishuHelp() {
|
|
36
31
|
return [
|
|
@@ -93,11 +88,11 @@ export async function cmdFeishu(args, deps = {}) {
|
|
|
93
88
|
// restart — without it the login succeeds but the MCP server keeps bot identity.
|
|
94
89
|
// Skipped when loadDotenv is off (tests) so the real .env is never touched there.
|
|
95
90
|
const envFile = deps.envFile ?? path.join(CONFIG_DIR, '.env');
|
|
96
|
-
const persistAuthMode = () => {
|
|
91
|
+
const persistAuthMode = async () => {
|
|
97
92
|
if (deps.loadDotenv === false)
|
|
98
93
|
return false;
|
|
99
94
|
try {
|
|
100
|
-
upsertEnvVar(envFile, 'FEISHU_AUTH_MODE', 'user');
|
|
95
|
+
await upsertEnvVar(envFile, 'FEISHU_AUTH_MODE', 'user');
|
|
101
96
|
return true;
|
|
102
97
|
}
|
|
103
98
|
catch {
|
|
@@ -149,7 +144,7 @@ export async function cmdFeishu(args, deps = {}) {
|
|
|
149
144
|
try {
|
|
150
145
|
const tok = await exchangeCode({ appId, appSecret, code, redirectUri, domain, fetchImpl: deps.fetchImpl, now: deps.now });
|
|
151
146
|
saveUserToken(tok, tokenFile);
|
|
152
|
-
return successResult(tok, persistAuthMode());
|
|
147
|
+
return successResult(tok, await persistAuthMode());
|
|
153
148
|
}
|
|
154
149
|
catch (e) {
|
|
155
150
|
return { exitCode: 1, stdout: '', stderr: `Login failed: ${e.message}\n` };
|
|
@@ -181,7 +176,7 @@ export async function cmdFeishu(args, deps = {}) {
|
|
|
181
176
|
onPending: () => process.stdout.write('.'),
|
|
182
177
|
});
|
|
183
178
|
saveUserToken(tok, tokenFile);
|
|
184
|
-
return successResult(tok, persistAuthMode());
|
|
179
|
+
return successResult(tok, await persistAuthMode());
|
|
185
180
|
}
|
|
186
181
|
catch (e) {
|
|
187
182
|
return { exitCode: 1, stdout: '', stderr: `\nLogin failed: ${e.message}\n` };
|
package/dist/entry/init.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
// input: defaults, filesystem, MCP builders,
|
|
2
|
-
// output: runInit and
|
|
3
|
-
// pos: Initializes Cortex home and
|
|
1
|
+
// input: defaults, filesystem, MCP builders, setup
|
|
2
|
+
// output: runInit and runtime configuration
|
|
3
|
+
// pos: Initializes Cortex home and config surfaces
|
|
4
4
|
// >>> 一旦我被更新,务必更新我的开头注释与所属文件夹 CORTEX.md <<<
|
|
5
5
|
import { mkdirSync, writeFileSync, copyFileSync, existsSync, readFileSync, readdirSync } from 'fs';
|
|
6
6
|
import { randomBytes } from 'crypto';
|
|
@@ -12,7 +12,7 @@ import { createInterface } from 'readline/promises';
|
|
|
12
12
|
import { stdin as processStdin } from 'process';
|
|
13
13
|
import * as clack from '@clack/prompts';
|
|
14
14
|
import * as yaml from 'yaml';
|
|
15
|
-
import { buildCoreConfig, buildFullConfig, buildManagerQaConfig, buildTasksConfig, buildThreadConfig, buildTuiConfig, } from '../core/config-generator.js';
|
|
15
|
+
import { buildBenchmarkThreadConfig, buildCoreConfig, buildEmptyConfig, buildFullConfig, buildManagerQaConfig, buildTasksConfig, buildThreadConfig, buildTuiConfig, } from '../core/config-generator.js';
|
|
16
16
|
import { discoverEndpoints, writeMergedGatewayYaml, validateProfilesAgainstGateway } from '../core/gateway-generator.js';
|
|
17
17
|
import { generateProfiles, writeProfilesJson, listChoices } from '../core/profile-generator.js';
|
|
18
18
|
import { mergeThreadTemplates } from '../domain/threads/index.js';
|
|
@@ -1117,6 +1117,8 @@ function writeMcpConfigs(configDir) {
|
|
|
1117
1117
|
['mcp-config-tasks.json', buildTasksConfig(INSTALL_ROOT)],
|
|
1118
1118
|
['mcp-config-manager-qa.json', buildManagerQaConfig(INSTALL_ROOT)],
|
|
1119
1119
|
['mcp-config-thread.json', buildThreadConfig(INSTALL_ROOT)],
|
|
1120
|
+
['mcp-config-empty.json', buildEmptyConfig()],
|
|
1121
|
+
['mcp-config-benchmark-thread.json', buildBenchmarkThreadConfig(INSTALL_ROOT)],
|
|
1120
1122
|
['mcp-config-tui.json', buildTuiConfig(INSTALL_ROOT)],
|
|
1121
1123
|
];
|
|
1122
1124
|
for (const [fileName, config] of configs) {
|
|
@@ -6,20 +6,14 @@ export interface StartUiHttpOptions {
|
|
|
6
6
|
uiService: UiService;
|
|
7
7
|
/** Token accessor the server accepts. Defaults to getClientToken (the shared secret clients carry). */
|
|
8
8
|
getToken?: () => string;
|
|
9
|
-
/** Env to read the gate/port from. Defaults to process.env (injectable for tests). */
|
|
9
|
+
/** Env to read the startup gate/port from. Defaults to process.env (injectable for tests). */
|
|
10
10
|
env?: NodeJS.ProcessEnv;
|
|
11
11
|
/**
|
|
12
12
|
* Directory of the built SPA to serve for non-tRPC paths. When omitted, resolved from
|
|
13
13
|
* CORTEX_UI_SPA_DIR else the monorepo web/dist. Absent/missing on disk → 404 stub.
|
|
14
14
|
*/
|
|
15
15
|
spaDir?: string;
|
|
16
|
-
/**
|
|
17
|
-
* Explicit CORS allow-list forwarded to the transport-host. When omitted, the list is parsed
|
|
18
|
-
* from the CORTEX_UI_CORS_ORIGINS env var (comma-separated; entries trimmed, empties dropped).
|
|
19
|
-
* Env-driven so the running-server path (agent-server) can enable CORS for the Tauri desktop
|
|
20
|
-
* webview (e.g. tauri://localhost) with no code change — just the env var. Absent/empty → no
|
|
21
|
-
* CORS headers.
|
|
22
|
-
*/
|
|
16
|
+
/** Explicit static CORS allow-list override; production reads runtime settings per request. */
|
|
23
17
|
corsOrigins?: string[];
|
|
24
18
|
/**
|
|
25
19
|
* Explicit Cloudflare Access JWT verifier forwarded to the transport-host (the browser auth path).
|