@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
|
@@ -1,24 +1,6 @@
|
|
|
1
|
-
// input:
|
|
2
|
-
//
|
|
3
|
-
//
|
|
4
|
-
// injected UiService and starts the Web UI HTTP+SSE transport-host behind the dual-path
|
|
5
|
-
// auth gate — x-cortex-token (getClientToken) OR a Cloudflare Access JWT verifier built
|
|
6
|
-
// from env (accessVerifierFromEnv) — bound 127.0.0.1. Returns null (clean skip) when the
|
|
7
|
-
// env gate is off. Same-origin: serves the built SPA (web/dist) and /trpc on one port.
|
|
8
|
-
// pos: Web UI wiring, in-core (entry layer). The only place that binds the AppRouter
|
|
9
|
-
// (createAppRouter, domain/ui-service) to the transport-host (createUiHttpServer,
|
|
10
|
-
// platform/ui-http) — kept out of both so the router stays transport-agnostic and the
|
|
11
|
-
// transport-host stays router-agnostic; the wiring sits in entry, the one layer allowed to
|
|
12
|
-
// depend on both domain and platform. app.ts loads this on demand via a CORTEX_UI_HTTP-gated
|
|
13
|
-
// dynamic import (entry/ui-http-gate.ts), so @trpc/server + jose stay runtime-lazy, and
|
|
14
|
-
// closes the returned handle on shutdown. SPA dir: opts.spaDir ?? CORTEX_UI_SPA_DIR ??
|
|
15
|
-
// web/dist resolved relative to this module's compiled location (installed-package root,
|
|
16
|
-
// else the monorepo repo-root — see defaultSpaDir).
|
|
17
|
-
// CORS: resolves the transport-host's allow-list from opts.corsOrigins else the
|
|
18
|
-
// CORTEX_UI_CORS_ORIGINS env var (comma-separated) — lets the Tauri desktop webview reach
|
|
19
|
-
// tRPC directly. Also mounts the frontend-OTA custom routes (createOtaRoutes(spaDir)) so the
|
|
20
|
-
// desktop shell can self-update its SPA (disabled cleanly when the SPA is not built), and
|
|
21
|
-
// the app-update manifest route (createAppUpdateRoutes) for native shell self-update.
|
|
1
|
+
// input: UiService, runtime settings, HTTP/auth/static dependencies
|
|
2
|
+
// output: optional Web UI HTTP/SSE server with live CORS wiring
|
|
3
|
+
// pos: Entry-layer Web UI transport composition
|
|
22
4
|
// >>> If I am updated, update CORTEX.md <<<
|
|
23
5
|
import * as path from 'node:path';
|
|
24
6
|
import * as fs from 'node:fs';
|
|
@@ -32,6 +14,7 @@ import { createAppUpdateRoutes } from '../platform/ui-http/app-update.js';
|
|
|
32
14
|
import { accessVerifierFromEnv } from '../platform/ui-http/access-jwt.js';
|
|
33
15
|
import { getClientToken } from '../core/auth.js';
|
|
34
16
|
import { createLogger } from '../core/log.js';
|
|
17
|
+
import { getSettings } from '../core/settings.js';
|
|
35
18
|
import { WORKSPACE_DIR, resolveWorkspaceRelPath } from '../core/paths.js';
|
|
36
19
|
const log = createLogger('ui-http');
|
|
37
20
|
/** Default TCP port for the Web UI tRPC endpoint (loopback-only; exposure is via a tunnel). */
|
|
@@ -64,17 +47,6 @@ function defaultSpaDir() {
|
|
|
64
47
|
return undefined;
|
|
65
48
|
}
|
|
66
49
|
}
|
|
67
|
-
/**
|
|
68
|
-
* Parse a comma-separated origin list (from CORTEX_UI_CORS_ORIGINS) into a trimmed, empties-dropped
|
|
69
|
-
* array. Returns undefined when the raw value is absent or yields no entries, so the transport-host
|
|
70
|
-
* keeps its backward-compatible "no CORS headers" default rather than an empty allow-list.
|
|
71
|
-
*/
|
|
72
|
-
function parseCorsOrigins(raw) {
|
|
73
|
-
if (!raw)
|
|
74
|
-
return undefined;
|
|
75
|
-
const origins = raw.split(',').map((o) => o.trim()).filter((o) => o.length > 0);
|
|
76
|
-
return origins.length > 0 ? origins : undefined;
|
|
77
|
-
}
|
|
78
50
|
// ── File upload route (15a attachments) ───────────────────────────────────────
|
|
79
51
|
const ATTACHMENTS_DIR = path.join(WORKSPACE_DIR, 'attachments');
|
|
80
52
|
const UPLOAD_PATH = '/api/attachments/upload';
|
|
@@ -259,12 +231,13 @@ export function startUiHttpServer(opts) {
|
|
|
259
231
|
const parsedPort = parseInt(env.CORTEX_UI_PORT ?? '', 10);
|
|
260
232
|
const port = Number.isNaN(parsedPort) ? DEFAULT_UI_PORT : parsedPort;
|
|
261
233
|
const router = createAppRouter(opts.uiService);
|
|
262
|
-
const corsOrigins = opts.corsOrigins ??
|
|
234
|
+
const corsOrigins = opts.corsOrigins ?? (() => getSettings().uiCorsOrigins);
|
|
235
|
+
const initialCorsOrigins = typeof corsOrigins === 'function' ? corsOrigins() : corsOrigins;
|
|
263
236
|
const spaDir = opts.spaDir ?? env.CORTEX_UI_SPA_DIR ?? defaultSpaDir();
|
|
264
237
|
const verifyAccessJwt = opts.verifyAccessJwt ?? accessVerifierFromEnv(env);
|
|
265
238
|
log.info(`Web UI enabled — starting tRPC HTTP+SSE on 127.0.0.1:${port}` +
|
|
266
239
|
(spaDir ? ` (SPA: ${spaDir})` : ' (SPA: not built — non-tRPC paths 404)') +
|
|
267
|
-
(
|
|
240
|
+
(initialCorsOrigins.length > 0 ? ` (CORS allow-list: ${initialCorsOrigins.join(', ')})` : '') +
|
|
268
241
|
(verifyAccessJwt ? ' (Cloudflare Access JWT path enabled)' : ''));
|
|
269
242
|
return createUiHttpServer({
|
|
270
243
|
router,
|
|
@@ -1,11 +1,12 @@
|
|
|
1
|
-
// input: EventBus
|
|
2
|
-
// output: createEventLogger
|
|
3
|
-
// pos:
|
|
1
|
+
// input: EventBus, CortexEvent, runtime settings
|
|
2
|
+
// output: createEventLogger with hot-toggleable JSONL persistence
|
|
3
|
+
// pos: Settings-gated event log writer
|
|
4
4
|
// >>> If I am updated, update my header comment and the parent folder's CORTEX.md <<<
|
|
5
5
|
import fs from 'node:fs/promises';
|
|
6
6
|
import path from 'node:path';
|
|
7
7
|
import { AsyncMutex } from '../core/async-mutex.js';
|
|
8
8
|
import { DATA_DIR } from '../core/paths.js';
|
|
9
|
+
import { getSettings } from '../core/settings.js';
|
|
9
10
|
// ── Constants ────────────────────────────────────────────────────────────────
|
|
10
11
|
const DEFAULT_BUFFER_SIZE = 1024;
|
|
11
12
|
const FLUSH_INTERVAL_MS = 100;
|
|
@@ -34,7 +35,6 @@ const TRANSIENT_EVENTS = new Set([
|
|
|
34
35
|
// ── Implementation ────────────────────────────────────────────────────────────
|
|
35
36
|
export function createEventLogger(bus, opts) {
|
|
36
37
|
const bufferSize = opts?.bufferSize ?? DEFAULT_BUFFER_SIZE;
|
|
37
|
-
const disabled = process.env.CORTEX_EVENT_LOG === 'off';
|
|
38
38
|
const logDir = opts?.logDir ?? path.join(DATA_DIR, 'logs', 'events');
|
|
39
39
|
let buffer = [];
|
|
40
40
|
let seq = 0;
|
|
@@ -46,7 +46,7 @@ export function createEventLogger(bus, opts) {
|
|
|
46
46
|
return new Date().toISOString().slice(0, 10).replace(/-/g, '');
|
|
47
47
|
}
|
|
48
48
|
function onEvent(e) {
|
|
49
|
-
if (
|
|
49
|
+
if (!getSettings().eventLog)
|
|
50
50
|
return;
|
|
51
51
|
// Skip meta-events to prevent re-entrant backpressure loops (see META_EVENTS comment above)
|
|
52
52
|
if (META_EVENTS.has(e.type))
|
|
@@ -84,7 +84,7 @@ export function createEventLogger(bus, opts) {
|
|
|
84
84
|
}
|
|
85
85
|
}
|
|
86
86
|
async function flushNow() {
|
|
87
|
-
if (
|
|
87
|
+
if (!getSettings().eventLog)
|
|
88
88
|
return;
|
|
89
89
|
// Snapshot buffer outside the mutex to minimise lock hold time
|
|
90
90
|
if (buffer.length === 0)
|
|
@@ -137,13 +137,11 @@ export function createEventLogger(bus, opts) {
|
|
|
137
137
|
return flushNow();
|
|
138
138
|
}
|
|
139
139
|
// ── Wire up ────────────────────────────────────────────────────────────────
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
flushTimer.unref();
|
|
146
|
-
}
|
|
140
|
+
bus.subscribe('*', onEvent);
|
|
141
|
+
flushTimer = setInterval(() => { void flushNow(); }, FLUSH_INTERVAL_MS);
|
|
142
|
+
// Prevent the timer from keeping the process alive after bus.close()
|
|
143
|
+
if (flushTimer.unref)
|
|
144
|
+
flushTimer.unref();
|
|
147
145
|
bus.registerCloseHook(close);
|
|
148
146
|
return { close };
|
|
149
147
|
}
|
|
@@ -1,4 +1,5 @@
|
|
|
1
|
-
import type { ChatNoticeLevel, SessionContextUsage } from '../core/types/agent-types.js';
|
|
1
|
+
import type { AuthNoticeAction, ChatNoticeLevel, SessionContextUsage } from '../core/types/agent-types.js';
|
|
2
|
+
export type AuthErrorKind = 'login_required' | 'oauth_expired' | 'invalid_api_key' | 'unauthorized' | 'invalid_grant';
|
|
2
3
|
/** All CortexEvent variants. `ts` is ISO-8601, injected by EventBus.publish(). */
|
|
3
4
|
export type CortexEvent = {
|
|
4
5
|
type: 'message.received';
|
|
@@ -23,6 +24,7 @@ export type CortexEvent = {
|
|
|
23
24
|
toolInput?: string;
|
|
24
25
|
blockId?: string;
|
|
25
26
|
noticeLevel?: ChatNoticeLevel;
|
|
27
|
+
authAction?: AuthNoticeAction;
|
|
26
28
|
pending?: boolean;
|
|
27
29
|
pendingId?: string;
|
|
28
30
|
attachments?: {
|
|
@@ -155,6 +157,20 @@ export type CortexEvent = {
|
|
|
155
157
|
seq: number;
|
|
156
158
|
lines: string[];
|
|
157
159
|
dropped?: number;
|
|
160
|
+
} | {
|
|
161
|
+
type: 'auth.required';
|
|
162
|
+
ts: string;
|
|
163
|
+
backend: 'claude' | 'pi';
|
|
164
|
+
provider: string;
|
|
165
|
+
authType: 'oauth' | 'api_key' | null;
|
|
166
|
+
kind: AuthErrorKind;
|
|
167
|
+
channel: string | null;
|
|
168
|
+
sessionId: string | null;
|
|
169
|
+
} | {
|
|
170
|
+
type: 'auth.recovered';
|
|
171
|
+
ts: string;
|
|
172
|
+
backend: 'claude' | 'pi';
|
|
173
|
+
provider: string;
|
|
158
174
|
} | {
|
|
159
175
|
type: 'thread.created';
|
|
160
176
|
ts: string;
|
|
@@ -199,6 +215,7 @@ export type CortexEvent = {
|
|
|
199
215
|
type: 'task.completed';
|
|
200
216
|
ts: string;
|
|
201
217
|
taskId: string;
|
|
218
|
+
dispatchGeneration?: string | null;
|
|
202
219
|
} | {
|
|
203
220
|
type: 'task.dispatched';
|
|
204
221
|
ts: string;
|
|
@@ -209,6 +226,7 @@ export type CortexEvent = {
|
|
|
209
226
|
ts: string;
|
|
210
227
|
taskId: string;
|
|
211
228
|
reason: string;
|
|
229
|
+
dispatchGeneration?: string | null;
|
|
212
230
|
} | {
|
|
213
231
|
type: 'task.unblocked';
|
|
214
232
|
ts: string;
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
// input: ChatNoticeLevel
|
|
2
|
-
// output: CortexEvent
|
|
1
|
+
// input: ChatNoticeLevel and SessionContextUsage
|
|
2
|
+
// output: CortexEvent with task provenance and auth notice actions
|
|
3
3
|
// pos: Typed event contract for the shared EventBus
|
|
4
|
-
// >>>
|
|
4
|
+
// >>> 一旦我被更新,务必更新我的开头注释与所属文件夹 CORTEX.md <<<
|
|
5
5
|
export {};
|
package/dist/events/index.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
export type { CortexEvent, CortexEventInput, DistributiveOmit } from './event-types.js';
|
|
1
|
+
export type { AuthErrorKind, CortexEvent, CortexEventInput, DistributiveOmit } from './event-types.js';
|
|
2
2
|
export { EventBus } from './event-bus.js';
|
|
3
3
|
export type { Subscription } from './event-bus.js';
|
|
4
4
|
export { createEventLogger } from './event-logger.js';
|
package/dist/events/index.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
// input: event-bus, event-types, event-logger
|
|
2
|
-
// output: public
|
|
3
|
-
// pos:
|
|
4
|
-
// >>>
|
|
2
|
+
// output: public event bus and typed event contracts
|
|
3
|
+
// pos: Public entry point for the events layer
|
|
4
|
+
// >>> 一旦我被更新,务必更新我的开头注释与所属文件夹 CORTEX.md <<<
|
|
5
5
|
export { EventBus } from './event-bus.js';
|
|
6
6
|
export { createEventLogger } from './event-logger.js';
|
|
@@ -49,13 +49,13 @@ Did this session produce findings, decisions, or changes that future sessions ne
|
|
|
49
49
|
Examples of what to record:
|
|
50
50
|
- A new experiment was launched → update STATUS.md with what's running
|
|
51
51
|
- A non-obvious fact was discovered ("the dataset is on gpu-server at /data/xxx") → create a K-NNN.md entry so it's indexed
|
|
52
|
-
- External resource locations → "The paper source is at ~/papers/conference2026/", "Training data lives on gpu-server:/datasets/dataset-v3/", "Reference implementation at https://github.com/xxx/yyy" — record
|
|
52
|
+
- External resource locations → "The paper source is at ~/papers/conference2026/", "Training data lives on gpu-server:/datasets/dataset-v3/", "Reference implementation at https://github.com/xxx/yyy" — record as a knowledge entry (K-NNN); durable facts do not go in STATUS.md
|
|
53
53
|
- A recurring friction was encountered ("the GPU on local always OOMs with batch_size > 32") → append to ISSUES.md
|
|
54
54
|
- A design decision was made → add to decisions/ directory
|
|
55
55
|
- A new project dependency or constraint was discovered → update STATUS.md
|
|
56
56
|
|
|
57
57
|
File update rules you MUST respect:
|
|
58
|
-
- **STATUS.md** —
|
|
58
|
+
- **STATUS.md** — state register (hard cap 80 lines AND 6KB): replace stale lines with the latest state, never append; one line + pointer per change, details live in EXP/K/tasks-archive; adding a line requires checking which old lines expired
|
|
59
59
|
- **ISSUES.md** — append mode: add new entries at the end, keep history
|
|
60
60
|
- **knowledge/K-NNN.md** — atomic: one file per knowledge entry, with YAML frontmatter
|
|
61
61
|
- **knowledge/index.md, experiments/index.md, patterns/index.md** — AUTO-GENERATED, do NOT edit manually
|
|
@@ -0,0 +1,193 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
// @cortex-hook-version 2026.8.2
|
|
3
|
+
// input: stdin JSON — Claude Code PreToolUse event payload
|
|
4
|
+
// output: stdout JSON — { hookSpecificOutput: { hookEventName: 'PreToolUse', permissionDecision, permissionDecisionReason }, systemMessage? }
|
|
5
|
+
// pos: PreToolUse hook — intercepts Edit/Write on size-capped context files and
|
|
6
|
+
// enforces their caps (limit table below; rules/status-md.md, rules/issues-md.md,
|
|
7
|
+
// rules/cortex-md.md): deny writes whose result exceeds the caps, unless the
|
|
8
|
+
// write shrinks an already-over-limit file (so cleanup stays possible); warn
|
|
9
|
+
// when approaching the cap. Guarded files:
|
|
10
|
+
// context/projects/<p>/STATUS.md — 80 lines / 6KB (state register)
|
|
11
|
+
// context/projects/<p>/ISSUES.md — 80 lines / 6KB (friction log)
|
|
12
|
+
// CORTEX.md anywhere under a context/ tree — 120 lines / 8KB (injected index)
|
|
13
|
+
// >>> If I am updated, be sure to update my header comment and the CORTEX.md in the same folder <<<
|
|
14
|
+
|
|
15
|
+
import { readFileSync, existsSync } from 'fs';
|
|
16
|
+
import { resolve, sep } from 'path';
|
|
17
|
+
|
|
18
|
+
// ── Constants ──
|
|
19
|
+
|
|
20
|
+
const TOOLS = new Set(['Edit', 'Write']);
|
|
21
|
+
|
|
22
|
+
/** .../context/projects/<name>/<file> */
|
|
23
|
+
function isProjectRootFile(parts, fileName) {
|
|
24
|
+
if (parts[parts.length - 1] !== fileName) return false;
|
|
25
|
+
const projectsIdx = parts.length - 3;
|
|
26
|
+
const contextIdx = parts.length - 4;
|
|
27
|
+
return projectsIdx > 0 && parts[projectsIdx] === 'projects' && parts[contextIdx] === 'context';
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
const LIMIT_RULES = [
|
|
31
|
+
{
|
|
32
|
+
name: 'STATUS.md',
|
|
33
|
+
ruleFile: 'rules/status-md.md',
|
|
34
|
+
matches: (parts) => isProjectRootFile(parts, 'STATUS.md'),
|
|
35
|
+
maxLines: 80,
|
|
36
|
+
maxBytes: 6 * 1024,
|
|
37
|
+
warnLines: 60,
|
|
38
|
+
warnBytes: 4 * 1024,
|
|
39
|
+
capLabel: '80 lines AND 6KB',
|
|
40
|
+
trimAdvice: [
|
|
41
|
+
'STATUS is a state register, not a changelog. Trim before writing:',
|
|
42
|
+
'- delete entries that no longer affect decisions (their content already lives in tasks-archive / git / EXP records),',
|
|
43
|
+
'- compress each bullet to one line + pointer (task-id / EXP-NNN / K-NNN / DR-NNNN / commit SHA),',
|
|
44
|
+
'- move completion reports to the task note, durable facts to knowledge entries, verdict analysis to the gate artifact.',
|
|
45
|
+
],
|
|
46
|
+
},
|
|
47
|
+
{
|
|
48
|
+
name: 'ISSUES.md',
|
|
49
|
+
ruleFile: 'rules/issues-md.md',
|
|
50
|
+
matches: (parts) => isProjectRootFile(parts, 'ISSUES.md'),
|
|
51
|
+
maxLines: 80,
|
|
52
|
+
maxBytes: 6 * 1024,
|
|
53
|
+
warnLines: 60,
|
|
54
|
+
warnBytes: 4 * 1024,
|
|
55
|
+
capLabel: '80 lines AND 6KB',
|
|
56
|
+
trimAdvice: [
|
|
57
|
+
'ISSUES.md is a friction log with <=4-line entries. Trim before writing:',
|
|
58
|
+
'- delete resolved entries outright (no changelog),',
|
|
59
|
+
'- compress each entry to symptom + one-line root cause + pointer (K-NNN / task artifact / EXP-NNN / file:line),',
|
|
60
|
+
'- merge same-cause frictions into one entry.',
|
|
61
|
+
],
|
|
62
|
+
},
|
|
63
|
+
{
|
|
64
|
+
name: 'CORTEX.md',
|
|
65
|
+
ruleFile: 'rules/cortex-md.md',
|
|
66
|
+
matches: (parts) => parts[parts.length - 1] === 'CORTEX.md' && parts.includes('context'),
|
|
67
|
+
maxLines: 120,
|
|
68
|
+
maxBytes: 8 * 1024,
|
|
69
|
+
warnLines: 90,
|
|
70
|
+
warnBytes: 6656,
|
|
71
|
+
capLabel: '120 lines AND 8KB',
|
|
72
|
+
trimAdvice: [
|
|
73
|
+
'CORTEX.md is an injected index (truncated at 9500 chars): it answers "what is here, where to look", not the content itself. Trim before writing:',
|
|
74
|
+
'- collapse atomic directories (experiments/ knowledge/ patterns/ decisions/) to one line each pointing at their index.md,',
|
|
75
|
+
'- entry summaries already live in the atomic files and their auto-generated index.md — never duplicate them here,',
|
|
76
|
+
'- keep each index line to one sentence + pointer (<=200 chars).',
|
|
77
|
+
],
|
|
78
|
+
},
|
|
79
|
+
];
|
|
80
|
+
|
|
81
|
+
// ── Helpers ──
|
|
82
|
+
|
|
83
|
+
function countLines(content) {
|
|
84
|
+
if (content === '') return 0;
|
|
85
|
+
const chunks = content.split('\n');
|
|
86
|
+
return chunks[chunks.length - 1] === '' ? chunks.length - 1 : chunks.length;
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
/** Compute the content the tool call would leave on disk, or null when indeterminable. */
|
|
90
|
+
function proposedContent(toolName, toolInput, currentContent) {
|
|
91
|
+
if (toolName === 'Write') return typeof toolInput.content === 'string' ? toolInput.content : null;
|
|
92
|
+
// Edit
|
|
93
|
+
const oldString = toolInput.old_string;
|
|
94
|
+
const newString = toolInput.new_string;
|
|
95
|
+
if (typeof oldString !== 'string' || typeof newString !== 'string') return null;
|
|
96
|
+
if (currentContent === null || !currentContent.includes(oldString)) return null; // tool will fail on its own
|
|
97
|
+
return toolInput.replace_all
|
|
98
|
+
? currentContent.split(oldString).join(newString)
|
|
99
|
+
: currentContent.replace(oldString, newString);
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
function denyReason(rule, lineCount, byteCount) {
|
|
103
|
+
return [
|
|
104
|
+
`${rule.name} write rejected: the result would be ${lineCount} lines / ${byteCount} bytes — the hard cap is ${rule.capLabel} (${rule.ruleFile}).`,
|
|
105
|
+
'',
|
|
106
|
+
...rule.trimAdvice,
|
|
107
|
+
'',
|
|
108
|
+
'Writes that shrink an already-over-limit file are allowed — reduce the size, then write.',
|
|
109
|
+
].join('\n');
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
// ── Main ──
|
|
113
|
+
|
|
114
|
+
function main() {
|
|
115
|
+
let input = '';
|
|
116
|
+
try {
|
|
117
|
+
input = readFileSync(0, 'utf8');
|
|
118
|
+
} catch {
|
|
119
|
+
return;
|
|
120
|
+
}
|
|
121
|
+
if (!input.trim()) return;
|
|
122
|
+
|
|
123
|
+
let payload;
|
|
124
|
+
try {
|
|
125
|
+
payload = JSON.parse(input);
|
|
126
|
+
} catch {
|
|
127
|
+
return;
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
if (!TOOLS.has(payload.tool_name)) return;
|
|
131
|
+
|
|
132
|
+
const toolInput = payload.tool_input || {};
|
|
133
|
+
const filePath = toolInput.file_path || '';
|
|
134
|
+
if (!filePath) return;
|
|
135
|
+
|
|
136
|
+
const cwd = payload.cwd || process.cwd();
|
|
137
|
+
const parts = resolve(cwd, filePath).split(sep);
|
|
138
|
+
const rule = LIMIT_RULES.find((r) => r.matches(parts));
|
|
139
|
+
if (!rule) return;
|
|
140
|
+
|
|
141
|
+
const absPath = resolve(cwd, filePath);
|
|
142
|
+
let currentContent = null;
|
|
143
|
+
if (existsSync(absPath)) {
|
|
144
|
+
try {
|
|
145
|
+
currentContent = readFileSync(absPath, 'utf8');
|
|
146
|
+
} catch {
|
|
147
|
+
return;
|
|
148
|
+
}
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
const proposed = proposedContent(payload.tool_name, toolInput, currentContent);
|
|
152
|
+
if (proposed === null) return;
|
|
153
|
+
|
|
154
|
+
const lineCount = countLines(proposed);
|
|
155
|
+
const byteCount = Buffer.byteLength(proposed, 'utf8');
|
|
156
|
+
const currentBytes = currentContent === null ? null : Buffer.byteLength(currentContent, 'utf8');
|
|
157
|
+
|
|
158
|
+
if (lineCount > rule.maxLines || byteCount > rule.maxBytes) {
|
|
159
|
+
// Shrink exception: an over-limit file may be reduced step by step.
|
|
160
|
+
if (currentBytes !== null && byteCount < currentBytes) {
|
|
161
|
+
process.stdout.write(JSON.stringify({
|
|
162
|
+
hookSpecificOutput: {
|
|
163
|
+
hookEventName: 'PreToolUse',
|
|
164
|
+
permissionDecision: 'allow',
|
|
165
|
+
permissionDecisionReason: `Still over the ${rule.name} cap (${lineCount} lines / ${byteCount} bytes > ${rule.capLabel}) but shrinking — keep trimming to within the limit.`,
|
|
166
|
+
},
|
|
167
|
+
systemMessage: `${rule.name} is still over the ${rule.capLabel} cap (${lineCount} lines / ${byteCount} bytes). This write shrinks it and is allowed — keep trimming.`,
|
|
168
|
+
}));
|
|
169
|
+
return;
|
|
170
|
+
}
|
|
171
|
+
process.stdout.write(JSON.stringify({
|
|
172
|
+
hookSpecificOutput: {
|
|
173
|
+
hookEventName: 'PreToolUse',
|
|
174
|
+
permissionDecision: 'deny',
|
|
175
|
+
permissionDecisionReason: denyReason(rule, lineCount, byteCount),
|
|
176
|
+
},
|
|
177
|
+
}));
|
|
178
|
+
return;
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
if (lineCount >= rule.warnLines || byteCount >= rule.warnBytes) {
|
|
182
|
+
process.stdout.write(JSON.stringify({
|
|
183
|
+
hookSpecificOutput: {
|
|
184
|
+
hookEventName: 'PreToolUse',
|
|
185
|
+
permissionDecision: 'allow',
|
|
186
|
+
permissionDecisionReason: `${rule.name} approaching its cap (${lineCount} lines / ${byteCount} bytes; hard cap ${rule.capLabel}) — trim proactively.`,
|
|
187
|
+
},
|
|
188
|
+
systemMessage: `${rule.name} is approaching its cap (${lineCount} lines / ${byteCount} bytes; hard cap ${rule.capLabel}). Trim proactively (${rule.ruleFile}).`,
|
|
189
|
+
}));
|
|
190
|
+
}
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
main();
|
|
@@ -1,11 +1,6 @@
|
|
|
1
|
-
// input:
|
|
2
|
-
// output: sendAgentFile
|
|
3
|
-
// pos:
|
|
4
|
-
// the session's workspace/outputs/<sessionId>/ area (a stable, download-safe location under
|
|
5
|
-
// WORKSPACE_DIR), records it as an assistant message carrying file attachments (so it survives
|
|
6
|
-
// reload via sessions.transcript), and publishes a `session.message` event (so the live web UI
|
|
7
|
-
// renders the file card immediately). Invoked by the daemon `/webhook/ui-file` route on behalf
|
|
8
|
-
// of the web-only `send_file` MCP tool. Deps are injectable for tests.
|
|
1
|
+
// input: file args, filesystem, conversation history, session events
|
|
2
|
+
// output: sendAgentFile and safe workspace copy metadata
|
|
3
|
+
// pos: delivers agent-produced files into Web chat sessions
|
|
9
4
|
// >>> If I am updated, update my header comment and the parent folder's CORTEX.md <<<
|
|
10
5
|
import * as path from 'path';
|
|
11
6
|
import { promises as fs } from 'fs';
|
|
@@ -37,9 +32,43 @@ export function classifyAttachment(mimeType) {
|
|
|
37
32
|
return 'video';
|
|
38
33
|
return 'file';
|
|
39
34
|
}
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
35
|
+
const MAX_FILENAME_BYTES = 200;
|
|
36
|
+
/** Bound a Unicode filename without splitting code points, retaining a short extension when possible. */
|
|
37
|
+
function truncateDisplayFilename(name) {
|
|
38
|
+
if (Buffer.byteLength(name) <= MAX_FILENAME_BYTES)
|
|
39
|
+
return name;
|
|
40
|
+
const ext = path.extname(name);
|
|
41
|
+
const keptExt = Buffer.byteLength(ext) <= 32 ? ext : '';
|
|
42
|
+
const stem = keptExt ? name.slice(0, -keptExt.length) : name;
|
|
43
|
+
let result = '';
|
|
44
|
+
let bytes = Buffer.byteLength(keptExt);
|
|
45
|
+
for (const char of stem) {
|
|
46
|
+
const charBytes = Buffer.byteLength(char);
|
|
47
|
+
if (bytes + charBytes > MAX_FILENAME_BYTES)
|
|
48
|
+
break;
|
|
49
|
+
result += char;
|
|
50
|
+
bytes += charBytes;
|
|
51
|
+
}
|
|
52
|
+
return `${result || 'file'}${keptExt}`;
|
|
53
|
+
}
|
|
54
|
+
/** Preserve a safe Unicode leaf name for display and client-side downloads. */
|
|
55
|
+
function sanitizeDisplayFilename(name) {
|
|
56
|
+
const leaf = name.replace(/\\/g, '/').split('/').pop() ?? '';
|
|
57
|
+
const cleaned = leaf.replace(/[\u0000-\u001F\u007F]/g, '_').trim();
|
|
58
|
+
if (!cleaned || cleaned === '.' || cleaned === '..')
|
|
59
|
+
return 'file';
|
|
60
|
+
return truncateDisplayFilename(cleaned);
|
|
61
|
+
}
|
|
62
|
+
/** Derive a narrow ASCII-only basename used solely for internal workspace storage. */
|
|
63
|
+
function sanitizeStorageFilename(displayName) {
|
|
64
|
+
const ext = path.extname(displayName);
|
|
65
|
+
const safeExt = /^\.[A-Za-z0-9]{1,16}$/.test(ext) ? ext : '';
|
|
66
|
+
const stem = safeExt ? displayName.slice(0, -ext.length) : displayName;
|
|
67
|
+
const asciiStem = stem
|
|
68
|
+
.replace(/[^A-Za-z0-9._-]/g, '_')
|
|
69
|
+
.replace(/^[._-]+|[._-]+$/g, '');
|
|
70
|
+
const safeStem = asciiStem || 'file';
|
|
71
|
+
return `${safeStem.slice(0, MAX_FILENAME_BYTES - safeExt.length)}${safeExt}`;
|
|
43
72
|
}
|
|
44
73
|
/** Find an available filename in `dir`: on collision try `name_1`, `name_2`, … */
|
|
45
74
|
async function resolveAvailablePath(dir, base) {
|
|
@@ -78,13 +107,14 @@ export async function copyFileIntoOutputs(a) {
|
|
|
78
107
|
}
|
|
79
108
|
if (!stat.isFile())
|
|
80
109
|
throw new Error(`Not a file: ${resolvedSrc}`);
|
|
81
|
-
const
|
|
110
|
+
const displayName = sanitizeDisplayFilename(a.fileName || path.basename(resolvedSrc));
|
|
111
|
+
const storageName = sanitizeStorageFilename(displayName);
|
|
82
112
|
const dir = path.join(OUTPUTS_DIR, a.sessionId);
|
|
83
113
|
await fs.mkdir(dir, { recursive: true });
|
|
84
|
-
const { destPath, finalName } = await resolveAvailablePath(dir,
|
|
114
|
+
const { destPath, finalName } = await resolveAvailablePath(dir, storageName);
|
|
85
115
|
await fs.copyFile(resolvedSrc, destPath);
|
|
86
116
|
const outStat = await fs.stat(destPath);
|
|
87
|
-
return { relPath: `workspace/outputs/${a.sessionId}/${finalName}`, name:
|
|
117
|
+
return { relPath: `workspace/outputs/${a.sessionId}/${finalName}`, name: displayName, size: outStat.size };
|
|
88
118
|
}
|
|
89
119
|
/**
|
|
90
120
|
* Deliver a file into a web chat session as an agent-sent attachment (20a). Copies the file into the
|
|
@@ -1,11 +1,13 @@
|
|
|
1
|
-
import type { PlatformAdapter, IncomingMessage } from '../platform/index.js';
|
|
1
|
+
import type { PlatformAdapter, DownloadedFile, IncomingMessage } from '../platform/index.js';
|
|
2
2
|
import type { ContextUsage, SessionContextUsage } from '../core/types/agent-types.js';
|
|
3
|
+
import { type TurnMutationRelease } from './turn-mutation-lock.js';
|
|
3
4
|
type Enqueuer = (channel: string, fn: () => Promise<void>) => boolean;
|
|
4
5
|
type Tracker = (delta: number) => void;
|
|
5
|
-
type
|
|
6
|
+
type PlatformFileLoader = () => Promise<DownloadedFile[]>;
|
|
7
|
+
type Executor = (ctx: AgentRunnerCtx, mutationRelease: TurnMutationRelease, loadPlatformFiles: PlatformFileLoader) => Promise<void>;
|
|
6
8
|
/** Attempt mid-turn injection; true ⇒ the message was delivered into the live turn and must NOT
|
|
7
9
|
* be queued. Injectable so the routing branch is testable without a live backend. */
|
|
8
|
-
type Injector = (ctx: AgentRunnerCtx) => Promise<boolean>;
|
|
10
|
+
type Injector = (ctx: AgentRunnerCtx, loadPlatformFiles: PlatformFileLoader) => Promise<boolean>;
|
|
9
11
|
interface AgentConfig {
|
|
10
12
|
effectiveMessage: string;
|
|
11
13
|
profileForRun: string;
|
|
@@ -24,6 +26,7 @@ export interface AgentRunnerCtx {
|
|
|
24
26
|
hasFiles: boolean;
|
|
25
27
|
userMessage: string;
|
|
26
28
|
agentMessage: string;
|
|
29
|
+
mutationRelease?: TurnMutationRelease;
|
|
27
30
|
}
|
|
28
31
|
export declare class AgentRunner {
|
|
29
32
|
readonly _enqueue: Enqueuer;
|
|
@@ -38,6 +41,7 @@ export declare class AgentRunner {
|
|
|
38
41
|
tryInject?: Injector;
|
|
39
42
|
});
|
|
40
43
|
route(ctx: AgentRunnerCtx): Promise<void>;
|
|
44
|
+
private _routeWithAdmission;
|
|
41
45
|
private _runQueued;
|
|
42
46
|
/**
|
|
43
47
|
* Production mid-turn injection: resolve this channel's live turn and session, then hand the
|