@cortex-agent/server 2026.9.14 → 2026.9.21
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 +3 -2
- package/defaults/config/hooks/08-agents-md-injector-post-tool.json +10 -0
- package/defaults/config/hooks/{10-cortex-md-injector-session-start.json → 10-agents-md-injector-session-start.json} +3 -3
- package/defaults/config/hooks/{CORTEX.md → AGENTS.md} +2 -2
- package/defaults/hooks/{CORTEX.md → AGENTS.md} +1 -1
- package/defaults/hooks/{cortex-md-injector.mjs → agents-md-injector.mjs} +117 -26
- package/defaults/hooks/cortex-hook-api.mjs +2 -2
- package/defaults/hooks/new-session-hook.mjs +2 -2
- package/defaults/hooks/rules-loader.mjs +2 -2
- package/defaults/hooks/status-md-guard.mjs +8 -8
- package/defaults/hooks/task-status-check.mjs +18 -76
- package/defaults/hooks/tasks-yaml-guard.mjs +2 -2
- package/defaults/plugins/cortex-commission/.claude-plugin/plugin.json +2 -2
- package/defaults/plugins/cortex-commission/plugin.json +2 -2
- package/defaults/plugins/cortex-commission/skills/commission/SKILL.md +3 -3
- package/defaults/plugins/cortex-feishu/skills/feishu-doc/SKILL.md +1 -1
- package/defaults/plugins/cortex-system/skills/client-manage/SKILL.md +2 -2
- package/defaults/plugins/cortex-system/skills/project-init/SKILL.md +4 -4
- package/defaults/plugins/cortex-system/skills/task/SKILL.md +1 -1
- package/defaults/rules/{cortex-md.md → agents-md.md} +4 -4
- package/defaults/rules/decision-records.md +1 -1
- package/defaults/rules/meta-conventions.md +4 -4
- package/defaults/rules/mission-md.md +1 -1
- package/dist/agent-adapter/claude/adapter.d.ts +0 -6
- package/dist/agent-adapter/claude/adapter.js +0 -8
- package/dist/agent-adapter/claude/defaults.d.ts +10 -7
- package/dist/agent-adapter/claude/defaults.js +18 -16
- package/dist/agent-adapter/claude/hooks-builder.js +2 -2
- package/dist/agent-adapter/claude/spawn-args.d.ts +0 -3
- package/dist/agent-adapter/claude/spawn-args.js +20 -16
- package/dist/agent-adapter/claude/turn-machine.d.ts +11 -0
- package/dist/agent-adapter/claude/turn-machine.js +46 -5
- package/dist/agent-adapter/normalize/prompt-builder.d.ts +16 -1
- package/dist/agent-adapter/normalize/prompt-builder.js +24 -6
- package/dist/agent-adapter/pi/mcp-bridge-logic.d.ts +11 -2
- package/dist/agent-adapter/pi/mcp-bridge-logic.js +32 -1
- package/dist/agent-adapter/pi/mcp-bridge.js +16 -15
- package/dist/agent-adapter/pi/session-options.d.ts +0 -6
- package/dist/agent-adapter/pi/session-options.js +1 -8
- package/dist/agent-adapter/types.d.ts +1 -1
- package/dist/core/mcp-tool-gate.d.ts +3 -17
- package/dist/core/mcp-tool-gate.js +4 -19
- package/dist/core/media-types.d.ts +10 -0
- package/dist/core/media-types.js +34 -0
- package/dist/core/platform-settings-spec.js +1 -1
- package/dist/core/settings-spec.d.ts +22 -1
- package/dist/core/settings-spec.js +33 -2
- package/dist/core/types/agent-types.d.ts +3 -1
- package/dist/core/utils.d.ts +1 -1
- package/dist/core/utils.js +1 -1
- package/dist/domain/agents/config.d.ts +1 -1
- package/dist/domain/agents/config.js +1 -1
- package/dist/domain/agents/profile-switch.d.ts +1 -1
- package/dist/domain/agents/profile-switch.js +3 -5
- package/dist/domain/agents/subagent/runner.js +0 -1
- package/dist/domain/commissions/commission-draft.d.ts +58 -0
- package/dist/domain/commissions/commission-draft.js +87 -4
- package/dist/domain/commissions/commission-finalize.d.ts +8 -3
- package/dist/domain/commissions/commission-finalize.js +14 -0
- package/dist/domain/executions/registry.d.ts +1 -2
- package/dist/domain/executions/registry.js +0 -3
- package/dist/domain/mcp/bundled-server.js +4 -3
- package/dist/domain/mcp/feishu/file.js +37 -18
- package/dist/domain/mcp/feishu/types.d.ts +3 -0
- package/dist/domain/mcp/feishu-server.js +1 -1
- package/dist/domain/mcp/tools/{cortex-md.d.ts → agents-md.d.ts} +6 -6
- package/dist/domain/mcp/tools/{cortex-md.js → agents-md.js} +6 -6
- package/dist/domain/mcp/tools/commission-tools.d.ts +12 -1
- package/dist/domain/mcp/tools/commission-tools.js +68 -14
- package/dist/domain/mcp/tools/remote-file.d.ts +20 -0
- package/dist/domain/mcp/tools/remote-file.js +44 -0
- package/dist/domain/mcp/tools/slack.d.ts +2 -0
- package/dist/domain/mcp/tools/slack.js +22 -7
- package/dist/domain/mcp/tools/task-ops.js +5 -13
- package/dist/domain/mcp/tools/ui-file.js +23 -10
- package/dist/domain/mcp/tools/waitpoint.d.ts +3 -0
- package/dist/domain/mcp/tools/waitpoint.js +122 -0
- package/dist/domain/memory/agents-md-injector.d.ts +24 -0
- package/dist/domain/memory/{cortex-md-injector.js → agents-md-injector.js} +10 -7
- package/dist/domain/projects/project-store.d.ts +1 -1
- package/dist/domain/projects/project-store.js +3 -3
- package/dist/domain/remote/client-hot-reload.js +3 -1
- package/dist/domain/remote/client-manager.js +105 -126
- package/dist/domain/remote/client-ssh-tunnel.d.ts +16 -5
- package/dist/domain/remote/client-ssh-tunnel.js +12 -5
- package/dist/domain/remote/cortex-client-config.d.ts +1 -1
- package/dist/domain/remote/cortex-client-config.js +1 -1
- package/dist/domain/remote/device-file.d.ts +51 -0
- package/dist/domain/remote/device-file.js +193 -0
- package/dist/domain/remote/device-port.js +3 -0
- package/dist/domain/remote/reverse-stream.d.ts +18 -7
- package/dist/domain/remote/reverse-stream.js +19 -6
- package/dist/domain/runs/builders.js +0 -1
- package/dist/domain/runs/compact.js +0 -1
- package/dist/domain/runs/engine-spec.d.ts +11 -4
- package/dist/domain/runs/engine-spec.js +7 -4
- package/dist/domain/runs/prompt.js +16 -10
- package/dist/domain/runs/request.d.ts +0 -1
- package/dist/domain/sessions/session-hooks.d.ts +5 -12
- package/dist/domain/sessions/session-hooks.js +6 -13
- package/dist/domain/sessions/session-lifecycle.d.ts +4 -4
- package/dist/domain/sessions/session-lifecycle.js +5 -6
- package/dist/domain/sessions/session-retention.d.ts +1 -3
- package/dist/domain/sessions/session-retention.js +9 -26
- package/dist/domain/sessions/session-use.d.ts +32 -0
- package/dist/domain/sessions/session-use.js +63 -0
- package/dist/domain/sessions/session.js +6 -5
- package/dist/domain/system/server-update-check.js +29 -1
- package/dist/domain/system/update-ui-state.d.ts +32 -0
- package/dist/domain/system/update-ui-state.js +63 -0
- package/dist/domain/tasks/claim-recovery.js +2 -2
- package/dist/domain/tasks/dispatch-utils.d.ts +10 -1
- package/dist/domain/tasks/dispatch-utils.js +46 -1
- package/dist/domain/tasks/dispatcher.js +4 -5
- package/dist/domain/tasks/mutator.d.ts +2 -2
- package/dist/domain/tasks/mutator.js +2 -2
- package/dist/domain/tasks/system/task-cli.js +2 -2
- package/dist/domain/tasks/system/task-state.js +1 -1
- package/dist/domain/threads/runner.js +3 -2
- package/dist/domain/ui-service/app-router.d.ts +54 -3
- package/dist/domain/ui-service/app-router.js +12 -14
- package/dist/domain/ui-service/input-schemas.d.ts +49 -5
- package/dist/domain/ui-service/input-schemas.js +35 -9
- package/dist/domain/ui-service/mutate/platform-settings.js +1 -1
- package/dist/domain/ui-service/mutate/sessions.d.ts +17 -1
- package/dist/domain/ui-service/mutate/sessions.js +83 -3
- package/dist/domain/ui-service/mutate/system.d.ts +3 -1
- package/dist/domain/ui-service/mutate/system.js +13 -0
- package/dist/domain/ui-service/mutate/waitpoints.d.ts +2 -0
- package/dist/domain/ui-service/mutate/waitpoints.js +20 -0
- package/dist/domain/ui-service/platform-settings.js +1 -1
- package/dist/domain/ui-service/plugins-shared.js +1 -1
- package/dist/domain/ui-service/query/config.js +1 -1
- package/dist/domain/ui-service/query/executions.js +0 -2
- package/dist/domain/ui-service/query/machine-detail.js +3 -8
- package/dist/domain/ui-service/query/memory.js +1 -1
- package/dist/domain/ui-service/query/sessions.js +7 -0
- package/dist/domain/ui-service/query/system.d.ts +2 -1
- package/dist/domain/ui-service/query/system.js +4 -0
- package/dist/domain/ui-service/query/threads.js +1 -54
- package/dist/domain/ui-service/query/waitpoints.d.ts +30 -0
- package/dist/domain/ui-service/query/waitpoints.js +117 -0
- package/dist/domain/ui-service/query-input-schemas.d.ts +3 -0
- package/dist/domain/ui-service/query-input-schemas.js +3 -0
- package/dist/domain/ui-service/trpc.js +1 -1
- package/dist/domain/ui-service/types.d.ts +175 -50
- package/dist/domain/ui-service/types.js +1 -1
- package/dist/domain/ui-service/ui-service.js +13 -33
- package/dist/domain/waitpoints/notices.d.ts +21 -0
- package/dist/domain/waitpoints/notices.js +115 -0
- package/dist/domain/waitpoints/service.d.ts +91 -0
- package/dist/domain/waitpoints/service.js +243 -0
- package/dist/entry/app.js +39 -29
- package/dist/entry/auth-login-cli.js +1 -1
- package/dist/entry/auth-login-terminal.js +1 -1
- package/dist/entry/init-auth.js +1 -1
- package/dist/entry/init.js +6 -6
- package/dist/entry/signal-cli.d.ts +30 -0
- package/dist/entry/signal-cli.js +207 -0
- package/dist/entry/start-ui-http.d.ts +1 -1
- package/dist/entry/start-ui-http.js +5 -3
- package/dist/events/event-types.d.ts +5 -7
- package/dist/hooks/{cortex-md-injector.mjs → agents-md-injector.mjs} +117 -26
- package/dist/hooks/cortex-hook-api.mjs +2 -2
- package/dist/hooks/new-session-hook.mjs +2 -2
- package/dist/hooks/rules-loader.mjs +2 -2
- package/dist/hooks/status-md-guard.mjs +8 -8
- package/dist/hooks/task-status-check.mjs +18 -76
- package/dist/hooks/tasks-yaml-guard.mjs +2 -2
- package/dist/orchestration/agent-file-send.d.ts +9 -0
- package/dist/orchestration/agent-file-send.js +21 -2
- package/dist/orchestration/agent-runner.d.ts +4 -3
- package/dist/orchestration/agent-runner.js +25 -23
- package/dist/orchestration/attachments-store.d.ts +31 -0
- package/dist/orchestration/attachments-store.js +184 -0
- package/dist/orchestration/conversation-request.d.ts +30 -8
- package/dist/orchestration/conversation-request.js +62 -26
- package/dist/orchestration/edit-retry.js +2 -1
- package/dist/orchestration/interactions/ask-user-resume.js +2 -1
- package/dist/orchestration/interactions/plan-approvals.js +1 -1
- package/dist/orchestration/interactions/ui-update-prompt.d.ts +8 -0
- package/dist/orchestration/interactions/ui-update-prompt.js +47 -0
- package/dist/orchestration/outputs-store.d.ts +11 -0
- package/dist/orchestration/outputs-store.js +32 -6
- package/dist/orchestration/resume-dispatcher.js +2 -2
- package/dist/orchestration/routing/file-handler.d.ts +23 -2
- package/dist/orchestration/routing/file-handler.js +22 -5
- package/dist/orchestration/routing/webhook.js +240 -39
- package/dist/orchestration/session-compact.d.ts +3 -0
- package/dist/orchestration/session-compact.js +3 -2
- package/dist/orchestration/session-events.d.ts +6 -0
- package/dist/orchestration/session-events.js +5 -0
- package/dist/orchestration/session-gateway.d.ts +1 -1
- package/dist/orchestration/session-gateway.js +1 -0
- package/dist/orchestration/thread-executor.d.ts +2 -0
- package/dist/orchestration/thread-executor.js +11 -1
- package/dist/orchestration/thread-input.d.ts +3 -2
- package/dist/orchestration/thread-input.js +8 -9
- package/dist/orchestration/turn/turn-prep.d.ts +15 -1
- package/dist/orchestration/turn/turn-prep.js +21 -9
- package/dist/orchestration/waitpoint-ingress.d.ts +41 -0
- package/dist/orchestration/waitpoint-ingress.js +172 -0
- package/dist/orchestration/waitpoint-notifier.d.ts +21 -0
- package/dist/orchestration/waitpoint-notifier.js +119 -0
- package/dist/orchestration/waitpoint-remote-drain.d.ts +20 -0
- package/dist/orchestration/waitpoint-remote-drain.js +147 -0
- package/dist/orchestration/waitpoint-sweep.d.ts +42 -0
- package/dist/orchestration/waitpoint-sweep.js +87 -0
- package/dist/platform/adapters/feishu-image.d.ts +19 -0
- package/dist/platform/adapters/feishu-image.js +71 -0
- package/dist/platform/adapters/feishu.d.ts +2 -0
- package/dist/platform/adapters/feishu.js +26 -16
- package/dist/platform/ui-http/app-update.d.ts +11 -0
- package/dist/platform/ui-http/app-update.js +3 -0
- package/dist/platform/ui-http/listening-ports.d.ts +1 -1
- package/dist/platform/ui-http/listening-ports.js +1 -1
- package/dist/platform/ui-http/ui-session.js +1 -1
- package/dist/store/conversation-ledger-repo.d.ts +10 -19
- package/dist/store/conversation-ledger-repo.js +143 -152
- package/dist/store/execution-repo.d.ts +1 -19
- package/dist/store/execution-repo.js +1 -18
- package/dist/store/project-notes-repo.js +11 -2
- package/dist/store/prompt-migration-replacements.js +1 -1
- package/dist/store/session-registry-import.d.ts +34 -0
- package/dist/store/session-registry-import.js +182 -0
- package/dist/store/session-registry-journal.d.ts +107 -0
- package/dist/store/session-registry-journal.js +308 -19
- package/dist/store/session-registry-repo.d.ts +113 -28
- package/dist/store/session-registry-repo.js +288 -105
- package/dist/store/version-migrations.d.ts +29 -3
- package/dist/store/version-migrations.js +288 -24
- package/dist/store/waitpoint-repo.d.ts +108 -0
- package/dist/store/waitpoint-repo.js +94 -0
- package/package.json +2 -2
- package/web/dist/assets/index-CwwQNMpP.css +1 -0
- package/web/dist/assets/index-DLSfgq3o.js +444 -0
- package/web/dist/assets/{index-aHbOZSP6.js → index-DZTuqUO4.js} +1 -1
- package/web/dist/index.html +2 -2
- package/defaults/config/hooks/08-cortex-md-injector-post-tool.json +0 -10
- package/dist/domain/executions/log-tailer.d.ts +0 -71
- package/dist/domain/executions/log-tailer.js +0 -194
- package/dist/domain/memory/cortex-md-injector.d.ts +0 -24
- package/dist/domain/memory/cortex-md-scanner.d.ts +0 -10
- package/dist/domain/memory/cortex-md-scanner.js +0 -66
- package/dist/domain/remote/cortex-client.d.ts +0 -1
- package/dist/domain/remote/cortex-client.js +0 -662
- package/dist/domain/tasks/system/cortex-run.d.ts +0 -25
- package/dist/domain/tasks/system/cortex-run.js +0 -360
- package/dist/store/session-repo.d.ts +0 -65
- package/dist/store/session-repo.js +0 -184
- package/web/dist/assets/index-BuXbCsuz.js +0 -444
- package/web/dist/assets/index-CCPxQ94C.css +0 -1
- /package/defaults/{CORTEX.md → AGENTS.md} +0 -0
- /package/defaults/config/{CORTEX.md → AGENTS.md} +0 -0
- /package/defaults/context/{CORTEX.md → AGENTS.md} +0 -0
- /package/defaults/context/ideas/{CORTEX.md → AGENTS.md} +0 -0
- /package/defaults/context/projects/{CORTEX.md → AGENTS.md} +0 -0
- /package/defaults/context/scans/{CORTEX.md → AGENTS.md} +0 -0
- /package/defaults/context/user/{CORTEX.md → AGENTS.md} +0 -0
|
@@ -4,13 +4,24 @@ export interface SshTunnelSpec {
|
|
|
4
4
|
host: string;
|
|
5
5
|
remotePort: number;
|
|
6
6
|
serverPort: number;
|
|
7
|
+
/**
|
|
8
|
+
* Optional remote command run for the lifetime of the tunnel, in place of `-N`. Its only job is
|
|
9
|
+
* to leave a findable process on the far side: `ssh -N` puts nothing there but sshd itself, and
|
|
10
|
+
* sshd marks itself non-dumpable, so an unprivileged `fuser`/`lsof`/`ss -p` cannot say which
|
|
11
|
+
* process owns a forward listener. A marker command gives the session an ordinary greppable
|
|
12
|
+
* child whose parent is exactly the sshd holding `remotePort`.
|
|
13
|
+
*/
|
|
14
|
+
markerCommand?: string;
|
|
7
15
|
/**
|
|
8
16
|
* Optional remote shell command run immediately before each `ssh -R` spawn, to release
|
|
9
|
-
* `remotePort` on the far side.
|
|
10
|
-
*
|
|
11
|
-
*
|
|
12
|
-
*
|
|
13
|
-
*
|
|
17
|
+
* `remotePort` on the far side. Both platforms strand the listener when our end dies without a
|
|
18
|
+
* clean close, for different reasons:
|
|
19
|
+
* - Windows OpenSSH leaves it in an orphaned `sshd -z` child and then lets a second sshd bind
|
|
20
|
+
* the same loopback port instead of failing, so the cortex-client reconnects into the dead
|
|
21
|
+
* listener and the device stays offline even though a healthy tunnel exists.
|
|
22
|
+
* - POSIX sshd keeps it while it blocks writing the session's exit status into the black hole,
|
|
23
|
+
* so it outlives the session by a full TCP retransmission timeout (~15 min) and every spawn
|
|
24
|
+
* in between dies on `ExitOnForwardFailure`.
|
|
14
25
|
*/
|
|
15
26
|
freeRemotePortCommand?: string;
|
|
16
27
|
}
|
|
@@ -20,8 +20,11 @@ function defaultSpawnSsh(args) {
|
|
|
20
20
|
return spawn('ssh', args, { stdio: 'ignore' });
|
|
21
21
|
}
|
|
22
22
|
export function buildSshTunnelArgs(spec, controlPath) {
|
|
23
|
-
|
|
24
|
-
'-M', '-S', controlPath, '-
|
|
23
|
+
const args = [
|
|
24
|
+
'-M', '-S', controlPath, '-T',
|
|
25
|
+
// A marker command replaces `-N`: the session has to run something for the far side to be
|
|
26
|
+
// identifiable later. Both forms keep the forward alive for the life of the ssh process.
|
|
27
|
+
...(spec.markerCommand ? [] : ['-N']),
|
|
25
28
|
'-o', 'BatchMode=yes',
|
|
26
29
|
'-o', 'ConnectTimeout=5',
|
|
27
30
|
'-o', 'StrictHostKeyChecking=no',
|
|
@@ -31,11 +34,15 @@ export function buildSshTunnelArgs(spec, controlPath) {
|
|
|
31
34
|
'-R', `127.0.0.1:${spec.remotePort}:127.0.0.1:${spec.serverPort}`,
|
|
32
35
|
spec.host,
|
|
33
36
|
];
|
|
37
|
+
if (spec.markerCommand)
|
|
38
|
+
args.push(spec.markerCommand);
|
|
39
|
+
return args;
|
|
34
40
|
}
|
|
35
41
|
// Compares where the tunnel points, which is what cannot change under a live supervisor.
|
|
36
|
-
// `freeRemotePortCommand`
|
|
37
|
-
// plus the host's OS, so treating
|
|
38
|
-
// and wedging a device permanently over that is a worse failure than using a
|
|
42
|
+
// `markerCommand` and `freeRemotePortCommand` are deliberately excluded: both are derived from the
|
|
43
|
+
// ports compared here plus the host's OS, so treating either as a route change would only fire on
|
|
44
|
+
// a `win` flag edit — and wedging a device permanently over that is a worse failure than using a
|
|
45
|
+
// stale command.
|
|
39
46
|
function sameSpec(a, b) {
|
|
40
47
|
return a.host === b.host && a.remotePort === b.remotePort && a.serverPort === b.serverPort;
|
|
41
48
|
}
|
|
@@ -10,7 +10,7 @@ export interface ClientConnectEnv {
|
|
|
10
10
|
/**
|
|
11
11
|
* Resolve the WebSocket URL the cortex-client dials.
|
|
12
12
|
*
|
|
13
|
-
* A full ``CORTEX_SERVER_URL`` (e.g. ``wss://cortex.
|
|
13
|
+
* A full ``CORTEX_SERVER_URL`` (e.g. ``wss://cortex.example.com``) takes
|
|
14
14
|
* precedence so the client can reach the agent-server through a Cloudflare
|
|
15
15
|
* Tunnel over 443/TLS. Otherwise it falls back to ``ws://<host>:<port>`` for
|
|
16
16
|
* direct/LAN reach.
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
/**
|
|
2
2
|
* Resolve the WebSocket URL the cortex-client dials.
|
|
3
3
|
*
|
|
4
|
-
* A full ``CORTEX_SERVER_URL`` (e.g. ``wss://cortex.
|
|
4
|
+
* A full ``CORTEX_SERVER_URL`` (e.g. ``wss://cortex.example.com``) takes
|
|
5
5
|
* precedence so the client can reach the agent-server through a Cloudflare
|
|
6
6
|
* Tunnel over 443/TLS. Otherwise it falls back to ``ws://<host>:<port>`` for
|
|
7
7
|
* direct/LAN reach.
|
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
/** `file.stat` is a metadata round trip — the client-manager file-command timeout is plenty. */
|
|
2
|
+
export interface RemoteFileStat {
|
|
3
|
+
size: number;
|
|
4
|
+
name: string;
|
|
5
|
+
mtimeMs?: number;
|
|
6
|
+
}
|
|
7
|
+
/** Metadata probe: existence, regular-file-ness and size, with the device's own error text. */
|
|
8
|
+
export declare function statRemoteFile(device: string, filePath: string): Promise<RemoteFileStat>;
|
|
9
|
+
/**
|
|
10
|
+
* Everything that can be known — and refused — before a single byte moves: that the device is
|
|
11
|
+
* online and new enough, that the path is a readable file, and that it fits under the cap. Callers
|
|
12
|
+
* that need the file's NAME to choose a destination run this first and hand the result back to
|
|
13
|
+
* `fetchRemoteFile`, so the device is stat'ed once rather than twice.
|
|
14
|
+
*/
|
|
15
|
+
export declare function prepareRemoteFetch(a: {
|
|
16
|
+
device: string;
|
|
17
|
+
filePath: string;
|
|
18
|
+
maxBytes?: number;
|
|
19
|
+
}): Promise<RemoteFileStat>;
|
|
20
|
+
export interface FetchRemoteFileArgs {
|
|
21
|
+
device: string;
|
|
22
|
+
/** Absolute path ON THE DEVICE. */
|
|
23
|
+
filePath: string;
|
|
24
|
+
/** Local destination; its directory must already exist. */
|
|
25
|
+
destPath: string;
|
|
26
|
+
/** Refuse before transferring anything when the device reports a larger file. */
|
|
27
|
+
maxBytes?: number;
|
|
28
|
+
/** Result of an earlier `prepareRemoteFetch` for this exact file; skips the second stat. */
|
|
29
|
+
stat?: RemoteFileStat;
|
|
30
|
+
}
|
|
31
|
+
/**
|
|
32
|
+
* Copy `filePath` from `device` into `destPath`. Throws — leaving no partial file behind — when the
|
|
33
|
+
* device is offline, too old, the path is not a readable file, it exceeds `maxBytes`, or the
|
|
34
|
+
* transfer ends short.
|
|
35
|
+
*/
|
|
36
|
+
export declare function fetchRemoteFile(a: FetchRemoteFileArgs): Promise<RemoteFileStat>;
|
|
37
|
+
export interface StagedRemoteFile {
|
|
38
|
+
/** Server-local path the caller reads, and is expected to delete when done. */
|
|
39
|
+
localPath: string;
|
|
40
|
+
name: string;
|
|
41
|
+
size: number;
|
|
42
|
+
}
|
|
43
|
+
/**
|
|
44
|
+
* Stream a device's file into a server-local staging path. Used by senders that do their own upload
|
|
45
|
+
* from disk (Slack, Feishu); the Web sender writes into the session's outputs directly instead.
|
|
46
|
+
*/
|
|
47
|
+
export declare function stageRemoteFile(a: {
|
|
48
|
+
device: string;
|
|
49
|
+
filePath: string;
|
|
50
|
+
maxBytes?: number;
|
|
51
|
+
}): Promise<StagedRemoteFile>;
|
|
@@ -0,0 +1,193 @@
|
|
|
1
|
+
import * as fs from 'fs';
|
|
2
|
+
import * as path from 'path';
|
|
3
|
+
import * as crypto from 'crypto';
|
|
4
|
+
import { WORKSPACE_DIR } from '../../core/paths.js';
|
|
5
|
+
import { createLogger } from '../../core/log.js';
|
|
6
|
+
import { sendCommand, sendControlMessage, getOnlineDevices } from './client-manager.js';
|
|
7
|
+
import { requestFileStream } from './reverse-stream.js';
|
|
8
|
+
const log = createLogger('device-file');
|
|
9
|
+
/**
|
|
10
|
+
* Pull a whole file off a device (`send_file device=…`). Every other remote tool answers on the
|
|
11
|
+
* control socket as one JSON message, which is fine for text but not for bytes: a file would be
|
|
12
|
+
* base64'd whole into memory on both ends and would hold the device's single command channel for
|
|
13
|
+
* the length of the transfer. So this uses the reverse channel instead — the same handshake the
|
|
14
|
+
* port forward already relies on — and streams binary frames straight to disk.
|
|
15
|
+
*
|
|
16
|
+
* The transfer is two steps on purpose. `file.stat` first, over the ordinary command path, so a
|
|
17
|
+
* missing path or an over-cap file fails with a real error message; only then is the stream opened.
|
|
18
|
+
* The stat'd size then doubles as the completeness check: a transfer that ends early is rejected
|
|
19
|
+
* rather than silently delivering a truncated file.
|
|
20
|
+
*/
|
|
21
|
+
/** The device must have dialled back AND finished within this; a stalled transfer is not a hang. */
|
|
22
|
+
const IDLE_TIMEOUT_MS = 60_000;
|
|
23
|
+
/** Capability advertised in the device's `hello`. Absent on clients older than this feature. */
|
|
24
|
+
const FILE_STREAM_CAPABILITY = 'file-stream';
|
|
25
|
+
function assertCanStreamFiles(device) {
|
|
26
|
+
const info = getOnlineDevices().find(d => d.device === device);
|
|
27
|
+
if (!info)
|
|
28
|
+
throw new Error(`Device "${device}" is not online`);
|
|
29
|
+
if (!info.capabilities?.includes(FILE_STREAM_CAPABILITY)) {
|
|
30
|
+
throw new Error(`Device "${device}" runs a client too old to stream files. It updates itself on its next `
|
|
31
|
+
+ 'reconnect; until then, copy the file to the server yourself.');
|
|
32
|
+
}
|
|
33
|
+
}
|
|
34
|
+
/** Metadata probe: existence, regular-file-ness and size, with the device's own error text. */
|
|
35
|
+
export async function statRemoteFile(device, filePath) {
|
|
36
|
+
const data = await sendCommand(device, { action: 'file.stat', params: { file_path: filePath } });
|
|
37
|
+
if (typeof data?.size !== 'number')
|
|
38
|
+
throw new Error(`Device "${device}" returned no size for ${filePath}`);
|
|
39
|
+
return { size: data.size, name: data.name || filePath.split(/[/\\]/).pop() || 'file', mtimeMs: data.mtimeMs };
|
|
40
|
+
}
|
|
41
|
+
/** Receive the callback socket's frames into `destPath`, resolving with the byte count. */
|
|
42
|
+
function receiveInto(ws, destPath, expected) {
|
|
43
|
+
return new Promise((resolve, reject) => {
|
|
44
|
+
const out = fs.createWriteStream(destPath);
|
|
45
|
+
let received = 0;
|
|
46
|
+
let settled = false;
|
|
47
|
+
let idle;
|
|
48
|
+
const finish = (err) => {
|
|
49
|
+
if (settled)
|
|
50
|
+
return;
|
|
51
|
+
settled = true;
|
|
52
|
+
clearTimeout(idle);
|
|
53
|
+
// End the file either way: the caller deletes a failed destination, and leaving the handle
|
|
54
|
+
// open would keep it undeletable on Windows.
|
|
55
|
+
out.end(() => (err ? reject(err) : resolve(received)));
|
|
56
|
+
if (err) {
|
|
57
|
+
try {
|
|
58
|
+
ws.close();
|
|
59
|
+
}
|
|
60
|
+
catch { /* already closing */ }
|
|
61
|
+
}
|
|
62
|
+
};
|
|
63
|
+
const armIdle = () => {
|
|
64
|
+
clearTimeout(idle);
|
|
65
|
+
idle = setTimeout(() => finish(new Error(`transfer stalled after ${received}/${expected} bytes`)), IDLE_TIMEOUT_MS);
|
|
66
|
+
idle.unref?.();
|
|
67
|
+
};
|
|
68
|
+
armIdle();
|
|
69
|
+
ws.on('message', (data) => {
|
|
70
|
+
const buf = Array.isArray(data) ? Buffer.concat(data) : Buffer.from(data);
|
|
71
|
+
received += buf.length;
|
|
72
|
+
armIdle();
|
|
73
|
+
if (received > expected) {
|
|
74
|
+
finish(new Error(`device sent more than the ${expected} bytes it declared`));
|
|
75
|
+
return;
|
|
76
|
+
}
|
|
77
|
+
// Pause the socket while the disk catches up, so a slow filesystem costs time, not memory.
|
|
78
|
+
if (!out.write(buf)) {
|
|
79
|
+
ws.pause?.();
|
|
80
|
+
out.once('drain', () => ws.resume?.());
|
|
81
|
+
}
|
|
82
|
+
});
|
|
83
|
+
ws.on('error', (e) => finish(new Error(`stream error: ${e.message}`)));
|
|
84
|
+
out.on('error', (e) => finish(new Error(`write failed: ${e.message}`)));
|
|
85
|
+
ws.on('close', (code, reason) => {
|
|
86
|
+
const why = reason?.toString() || '';
|
|
87
|
+
// The client reports a read-side failure by closing with a reason instead of by sending
|
|
88
|
+
// fewer bytes, so an explicit error is never mistaken for a short file and vice versa.
|
|
89
|
+
if (code !== 1000) {
|
|
90
|
+
finish(new Error(why || `device closed the stream (code ${code})`));
|
|
91
|
+
return;
|
|
92
|
+
}
|
|
93
|
+
if (received !== expected) {
|
|
94
|
+
finish(new Error(`truncated transfer: got ${received} of ${expected} bytes${why ? ` (${why})` : ''}`));
|
|
95
|
+
return;
|
|
96
|
+
}
|
|
97
|
+
finish(null);
|
|
98
|
+
});
|
|
99
|
+
});
|
|
100
|
+
}
|
|
101
|
+
/**
|
|
102
|
+
* Everything that can be known — and refused — before a single byte moves: that the device is
|
|
103
|
+
* online and new enough, that the path is a readable file, and that it fits under the cap. Callers
|
|
104
|
+
* that need the file's NAME to choose a destination run this first and hand the result back to
|
|
105
|
+
* `fetchRemoteFile`, so the device is stat'ed once rather than twice.
|
|
106
|
+
*/
|
|
107
|
+
export async function prepareRemoteFetch(a) {
|
|
108
|
+
assertCanStreamFiles(a.device);
|
|
109
|
+
const stat = await statRemoteFile(a.device, a.filePath);
|
|
110
|
+
if (a.maxBytes !== undefined && stat.size > a.maxBytes) {
|
|
111
|
+
throw new Error(`File is ${stat.size} bytes on ${a.device}, over the ${a.maxBytes}-byte limit`);
|
|
112
|
+
}
|
|
113
|
+
return stat;
|
|
114
|
+
}
|
|
115
|
+
/**
|
|
116
|
+
* Copy `filePath` from `device` into `destPath`. Throws — leaving no partial file behind — when the
|
|
117
|
+
* device is offline, too old, the path is not a readable file, it exceeds `maxBytes`, or the
|
|
118
|
+
* transfer ends short.
|
|
119
|
+
*/
|
|
120
|
+
export async function fetchRemoteFile(a) {
|
|
121
|
+
const stat = a.stat ?? await prepareRemoteFetch(a);
|
|
122
|
+
const req = requestFileStream(a.device, a.filePath);
|
|
123
|
+
// The claim rejects on its own timer (or when the device disconnects) whether or not anyone is
|
|
124
|
+
// waiting — and if `sendControlMessage` throws we never reach the await. An unobserved rejection
|
|
125
|
+
// would take the daemon down, so mark it handled now; the await below still sees the real error.
|
|
126
|
+
req.socket.catch(() => { });
|
|
127
|
+
let ws;
|
|
128
|
+
try {
|
|
129
|
+
sendControlMessage(a.device, req.message);
|
|
130
|
+
ws = await req.socket;
|
|
131
|
+
}
|
|
132
|
+
catch (e) {
|
|
133
|
+
throw new Error(`Failed to open a file stream from "${a.device}": ${e.message}`);
|
|
134
|
+
}
|
|
135
|
+
try {
|
|
136
|
+
const received = await receiveInto(ws, a.destPath, stat.size);
|
|
137
|
+
log.info(`fetched ${a.filePath} from ${a.device} (${received} bytes)`);
|
|
138
|
+
return stat;
|
|
139
|
+
}
|
|
140
|
+
catch (e) {
|
|
141
|
+
await fs.promises.rm(a.destPath, { force: true }).catch(() => { });
|
|
142
|
+
throw new Error(`Transfer of ${a.filePath} from "${a.device}" failed: ${e.message}`);
|
|
143
|
+
}
|
|
144
|
+
}
|
|
145
|
+
// --- Staging for senders that upload from a local path ---
|
|
146
|
+
/** Transfers in flight for a platform upload live here, one directory per transfer so two files of
|
|
147
|
+
* the same name never collide. */
|
|
148
|
+
const STAGING_DIR = path.join(WORKSPACE_DIR, 'remote-files');
|
|
149
|
+
/** A staged file outlives its upload only if that upload crashed; an hour is far past any transfer
|
|
150
|
+
* still worth waiting for. */
|
|
151
|
+
const STAGING_TTL_MS = 60 * 60_000;
|
|
152
|
+
/** Opportunistic sweep so a crashed uploader leaks at most one TTL window rather than forever. */
|
|
153
|
+
async function sweepStaging() {
|
|
154
|
+
const cutoff = Date.now() - STAGING_TTL_MS;
|
|
155
|
+
let entries;
|
|
156
|
+
try {
|
|
157
|
+
entries = await fs.promises.readdir(STAGING_DIR);
|
|
158
|
+
}
|
|
159
|
+
catch {
|
|
160
|
+
return;
|
|
161
|
+
}
|
|
162
|
+
await Promise.all(entries.map(async (name) => {
|
|
163
|
+
const dir = path.join(STAGING_DIR, name);
|
|
164
|
+
try {
|
|
165
|
+
const st = await fs.promises.stat(dir);
|
|
166
|
+
if (st.mtimeMs < cutoff)
|
|
167
|
+
await fs.promises.rm(dir, { recursive: true, force: true });
|
|
168
|
+
}
|
|
169
|
+
catch { /* raced with another sweep or an active uploader */ }
|
|
170
|
+
}));
|
|
171
|
+
}
|
|
172
|
+
/**
|
|
173
|
+
* Stream a device's file into a server-local staging path. Used by senders that do their own upload
|
|
174
|
+
* from disk (Slack, Feishu); the Web sender writes into the session's outputs directly instead.
|
|
175
|
+
*/
|
|
176
|
+
export async function stageRemoteFile(a) {
|
|
177
|
+
const stat = await prepareRemoteFetch(a);
|
|
178
|
+
void sweepStaging();
|
|
179
|
+
const dir = path.join(STAGING_DIR, crypto.randomBytes(8).toString('hex'));
|
|
180
|
+
await fs.promises.mkdir(dir, { recursive: true });
|
|
181
|
+
// The device's own basename, with separators stripped: it is remote input, and it must not be
|
|
182
|
+
// able to steer the write out of the staging directory.
|
|
183
|
+
const safeName = (stat.name.replace(/[/\\]/g, '_') || 'file').slice(0, 200);
|
|
184
|
+
const localPath = path.join(dir, safeName);
|
|
185
|
+
try {
|
|
186
|
+
await fetchRemoteFile({ device: a.device, filePath: a.filePath, destPath: localPath, stat });
|
|
187
|
+
}
|
|
188
|
+
catch (e) {
|
|
189
|
+
await fs.promises.rm(dir, { recursive: true, force: true }).catch(() => { });
|
|
190
|
+
throw e;
|
|
191
|
+
}
|
|
192
|
+
return { localPath, name: safeName, size: stat.size };
|
|
193
|
+
}
|
|
@@ -92,6 +92,9 @@ async function serveConnection(entry, tcp) {
|
|
|
92
92
|
tcp.destroy();
|
|
93
93
|
return;
|
|
94
94
|
}
|
|
95
|
+
// The claim rejects on its own timer even if we bail out below without awaiting it, and an
|
|
96
|
+
// unobserved rejection would take the daemon down. The await further down still sees the error.
|
|
97
|
+
req.socket.catch(() => { });
|
|
95
98
|
try {
|
|
96
99
|
sendControl(device, req.message);
|
|
97
100
|
}
|
|
@@ -13,15 +13,15 @@ import type { WebSocket } from 'ws';
|
|
|
13
13
|
export declare const REVERSE_PATH_PREFIX = "/reverse";
|
|
14
14
|
/** `/reverse?stream=<id>` → the id, or null when this is not a callback socket. */
|
|
15
15
|
export declare function parseStreamId(rawUrl: string | undefined): string | null;
|
|
16
|
-
export interface StreamRequest {
|
|
16
|
+
export interface StreamRequest<M = {
|
|
17
|
+
type: 'open-stream';
|
|
18
|
+
streamId: string;
|
|
19
|
+
host: string;
|
|
20
|
+
port: number;
|
|
21
|
+
}> {
|
|
17
22
|
id: string;
|
|
18
23
|
/** Message to hand to the device over its control socket. */
|
|
19
|
-
message:
|
|
20
|
-
type: 'open-stream';
|
|
21
|
-
streamId: string;
|
|
22
|
-
host: string;
|
|
23
|
-
port: number;
|
|
24
|
-
};
|
|
24
|
+
message: M;
|
|
25
25
|
/** Resolves with the device's callback socket, or rejects on timeout. */
|
|
26
26
|
socket: Promise<WebSocket>;
|
|
27
27
|
}
|
|
@@ -30,6 +30,17 @@ export interface StreamRequest {
|
|
|
30
30
|
* device's control socket and then awaits `socket`.
|
|
31
31
|
*/
|
|
32
32
|
export declare function requestStream(device: string, host: string, port: number): StreamRequest;
|
|
33
|
+
export type OpenFileStreamMessage = {
|
|
34
|
+
type: 'open-file-stream';
|
|
35
|
+
streamId: string;
|
|
36
|
+
path: string;
|
|
37
|
+
};
|
|
38
|
+
/**
|
|
39
|
+
* Same handshake as `requestStream`, but the device answers with the bytes of a FILE rather than a
|
|
40
|
+
* TCP connection. Both share the claim table, the cap and the callback path, so a file transfer
|
|
41
|
+
* needs no new port, credential or tunnel — only a different message on the control socket.
|
|
42
|
+
*/
|
|
43
|
+
export declare function requestFileStream(device: string, filePath: string): StreamRequest<OpenFileStreamMessage>;
|
|
33
44
|
/**
|
|
34
45
|
* Pair a callback socket with its request. Returns false when the id is unknown — a stale or forged
|
|
35
46
|
* callback, which the caller closes rather than trusts.
|
|
@@ -29,16 +29,12 @@ export function parseStreamId(rawUrl) {
|
|
|
29
29
|
// Ids are minted here and echoed back verbatim; anything else is not ours.
|
|
30
30
|
return id && /^[0-9a-f]{32}$/.test(id) ? id : null;
|
|
31
31
|
}
|
|
32
|
-
/**
|
|
33
|
-
|
|
34
|
-
* device's control socket and then awaits `socket`.
|
|
35
|
-
*/
|
|
36
|
-
export function requestStream(device, host, port) {
|
|
32
|
+
/** Mint a pending callback slot. `target` is for logging and the timeout message only. */
|
|
33
|
+
function mintStream(device, target) {
|
|
37
34
|
if (pending.size >= MAX_PENDING) {
|
|
38
35
|
throw new Error(`too many pending reverse streams (${pending.size})`);
|
|
39
36
|
}
|
|
40
37
|
const id = crypto.randomBytes(16).toString('hex');
|
|
41
|
-
const target = `${host}:${port}`;
|
|
42
38
|
let resolve;
|
|
43
39
|
let reject;
|
|
44
40
|
const socket = new Promise((res, rej) => { resolve = res; reject = rej; });
|
|
@@ -48,8 +44,25 @@ export function requestStream(device, host, port) {
|
|
|
48
44
|
}, CLAIM_TIMEOUT_MS);
|
|
49
45
|
timer.unref?.();
|
|
50
46
|
pending.set(id, { device, target, resolve, reject, timer });
|
|
47
|
+
return { id, socket };
|
|
48
|
+
}
|
|
49
|
+
/**
|
|
50
|
+
* Mint a stream the device is expected to dial back for. The caller sends `message` over the
|
|
51
|
+
* device's control socket and then awaits `socket`.
|
|
52
|
+
*/
|
|
53
|
+
export function requestStream(device, host, port) {
|
|
54
|
+
const { id, socket } = mintStream(device, `${host}:${port}`);
|
|
51
55
|
return { id, message: { type: 'open-stream', streamId: id, host, port }, socket };
|
|
52
56
|
}
|
|
57
|
+
/**
|
|
58
|
+
* Same handshake as `requestStream`, but the device answers with the bytes of a FILE rather than a
|
|
59
|
+
* TCP connection. Both share the claim table, the cap and the callback path, so a file transfer
|
|
60
|
+
* needs no new port, credential or tunnel — only a different message on the control socket.
|
|
61
|
+
*/
|
|
62
|
+
export function requestFileStream(device, filePath) {
|
|
63
|
+
const { id, socket } = mintStream(device, filePath);
|
|
64
|
+
return { id, message: { type: 'open-file-stream', streamId: id, path: filePath }, socket };
|
|
65
|
+
}
|
|
53
66
|
/**
|
|
54
67
|
* Pair a callback socket with its request. Returns false when the id is unknown — a stale or forged
|
|
55
68
|
* callback, which the caller closes rather than trusts.
|
|
@@ -44,7 +44,6 @@ export function continuationRunRequest(o) {
|
|
|
44
44
|
executionKind: o.executionKind ?? 'local',
|
|
45
45
|
isUserInitiated: o.isUserInitiated ?? false,
|
|
46
46
|
commissionMode: false,
|
|
47
|
-
commissionTools: false,
|
|
48
47
|
scheduleTaskId: o.scheduleTaskId ?? null,
|
|
49
48
|
},
|
|
50
49
|
policy: { ...DIRECT_RUN_POLICY },
|
|
@@ -6,7 +6,10 @@ import type { RunRequest } from './request.js';
|
|
|
6
6
|
export interface PluginScope {
|
|
7
7
|
channel?: string;
|
|
8
8
|
feishuSkillsInWeb?: boolean;
|
|
9
|
-
/** True
|
|
9
|
+
/** True once the session is BOUND to a landed commission. Drafting deliberately does not count
|
|
10
|
+
* (DR-0037 v4): the creation protocol lives in `cortex_commission_start`'s return value, and the
|
|
11
|
+
* skill covers maintenance only — it says so itself. Loading it during the drill would put the
|
|
12
|
+
* wrong half of the procedure in front of the model. */
|
|
10
13
|
commissionMode?: boolean;
|
|
11
14
|
}
|
|
12
15
|
/** Default channel scopes. The Feishu skill bundle also permits web: sessions when
|
|
@@ -15,9 +18,13 @@ export declare const CHANNEL_SCOPED_PLUGINS: ReadonlyArray<{
|
|
|
15
18
|
plugin: string;
|
|
16
19
|
channelPrefix: string;
|
|
17
20
|
}>;
|
|
18
|
-
/** Plugins that load only for sessions
|
|
19
|
-
* prescriptive (
|
|
20
|
-
* session would put a procedure nobody asked for in front of the model (DR-0037 v2).
|
|
21
|
+
/** Plugins that load only for sessions BOUND to a commission. The commission skill is long and
|
|
22
|
+
* prescriptive (ledger entries, surprise triage, checkpoint discipline); loading it into every
|
|
23
|
+
* session would put a procedure nobody asked for in front of the model (DR-0037 v2).
|
|
24
|
+
*
|
|
25
|
+
* Plugin dirs are part of the pool identity, so a contract landing mid-session brings the skill in
|
|
26
|
+
* on the next turn via a fresh spawn + `--resume`. The turn the contract lands on is covered by
|
|
27
|
+
* the protocol `cortex_commission_submit` returns on approval. */
|
|
21
28
|
export declare const COMMISSION_SCOPED_PLUGINS: readonly string[];
|
|
22
29
|
/** Drop scoped plugin dirs the current session does not qualify for. Non-scoped plugins always pass
|
|
23
30
|
* through. Matched by the plugin dir's final path segment (basename) so substrings like
|
|
@@ -10,9 +10,13 @@ import { resolvePluginRuntime } from '../plugins/runtime.js';
|
|
|
10
10
|
export const CHANNEL_SCOPED_PLUGINS = [
|
|
11
11
|
{ plugin: 'cortex-feishu', channelPrefix: 'feishu:' },
|
|
12
12
|
];
|
|
13
|
-
/** Plugins that load only for sessions
|
|
14
|
-
* prescriptive (
|
|
15
|
-
* session would put a procedure nobody asked for in front of the model (DR-0037 v2).
|
|
13
|
+
/** Plugins that load only for sessions BOUND to a commission. The commission skill is long and
|
|
14
|
+
* prescriptive (ledger entries, surprise triage, checkpoint discipline); loading it into every
|
|
15
|
+
* session would put a procedure nobody asked for in front of the model (DR-0037 v2).
|
|
16
|
+
*
|
|
17
|
+
* Plugin dirs are part of the pool identity, so a contract landing mid-session brings the skill in
|
|
18
|
+
* on the next turn via a fresh spawn + `--resume`. The turn the contract lands on is covered by
|
|
19
|
+
* the protocol `cortex_commission_submit` returns on approval. */
|
|
16
20
|
export const COMMISSION_SCOPED_PLUGINS = ['cortex-commission'];
|
|
17
21
|
/** Drop scoped plugin dirs the current session does not qualify for. Non-scoped plugins always pass
|
|
18
22
|
* through. Matched by the plugin dir's final path segment (basename) so substrings like
|
|
@@ -96,7 +100,6 @@ function spawnPolicy(request) {
|
|
|
96
100
|
allowlist: request.policy.mcpToolAllowlist === undefined
|
|
97
101
|
? undefined : canonicalizeMcpToolAllowlist(request.policy.mcpToolAllowlist),
|
|
98
102
|
configPaths: request.isolation?.mcpConfigPaths,
|
|
99
|
-
commissionTools: request.context.commissionTools,
|
|
100
103
|
browserCdpEndpoint: request.policy.browserCdpEndpoint ?? undefined,
|
|
101
104
|
},
|
|
102
105
|
flags: {
|
|
@@ -81,19 +81,25 @@ const COMMISSION_PROTOCOL = `Commission protocol:
|
|
|
81
81
|
2. Completion claims need evidence pointers (file paths, command outputs, EXP ids) in ledger.md. Scope cuts and deferrals go in the plan section's "Cuts and deferrals" note.
|
|
82
82
|
3. Before this session ends, and at each stage boundary, append a checkpoint CP-N to ledger.md with three diffs — plan vs done, contract vs current direction, assumptions vs reality — graded ok / attention / gate. Re-read contract.md (including its Revisions section) before writing it.
|
|
83
83
|
4. Contract gates are blocking: ask the user and wait. A streak of approvals never downgrades a gate.`;
|
|
84
|
-
/** A session
|
|
85
|
-
*
|
|
86
|
-
*
|
|
87
|
-
*
|
|
84
|
+
/** A session drafting a contract. It has no contract and no ledger yet, so the block's whole job is
|
|
85
|
+
* to say so and hand the agent to cortex_commission_start, which carries the drill protocol.
|
|
86
|
+
*
|
|
87
|
+
* Two ways in since v4 — the agent called the tool itself, or the user switched the mode on for a
|
|
88
|
+
* session already in flight — and the block cannot tell which. It does not need to: the tool is
|
|
89
|
+
* idempotent, so "call it if you have not already" is correct either way, and the second sentence
|
|
90
|
+
* keeps a user-initiated entry from turning into a round of asking whether to proceed. */
|
|
88
91
|
function buildDraftCommissionBlock(c) {
|
|
89
92
|
return [
|
|
90
|
-
'[Commission] This session
|
|
91
|
-
+ '
|
|
92
|
-
`Draft directory
|
|
93
|
+
'[Commission] This session is drafting a commission contract: a long task anchored by a '
|
|
94
|
+
+ 'contract the user approves before any work begins.',
|
|
95
|
+
`Draft directory: ${c.dir}`,
|
|
93
96
|
'',
|
|
94
|
-
'
|
|
95
|
-
+ '
|
|
96
|
-
+ '
|
|
97
|
+
'If you have not already received the creation protocol in this session, call '
|
|
98
|
+
+ 'cortex_commission_start now, before investigating or asking anything — it carries the drill '
|
|
99
|
+
+ 'protocol and the contract structure, and is idempotent. If the user turned this mode on for '
|
|
100
|
+
+ 'you, that is the decision made: start drilling rather than asking whether to.',
|
|
101
|
+
'Implement nothing until the contract is approved through cortex_commission_submit. If you '
|
|
102
|
+
+ 'conclude the task does not warrant a commission, say so plainly and let the user close it.',
|
|
97
103
|
].join('\n');
|
|
98
104
|
}
|
|
99
105
|
/** Index, not snapshot: the block names the two files and tells the agent to read them. Their
|
|
@@ -82,23 +82,16 @@ export interface SessionHookSpec {
|
|
|
82
82
|
/** Run configured session subscribers and preserve the display/injection pipeline. */
|
|
83
83
|
export declare function runSessionHook(spec: SessionHookSpec, stream: OutputStream, deps?: InjectDeps): Promise<void>;
|
|
84
84
|
/** Resolve the profile name to use when injecting the onNew hook's stdout as a fresh
|
|
85
|
-
* agent turn.
|
|
86
|
-
*
|
|
87
|
-
*
|
|
88
|
-
*
|
|
89
|
-
*
|
|
90
|
-
*
|
|
91
|
-
* The two sources can disagree on a channel that hosts both kinds of session — e.g.
|
|
92
|
-
* a thread session running profile `deepseek-pro` while the user's main conversation
|
|
93
|
-
* is on profile `plan`. Reading from the ledger alone causes Cortex to resume the
|
|
94
|
-
* thread session with the wrong profile, which routes through the wrong gateway mode
|
|
95
|
-
* and triggers Anthropic's "Invalid signature in thinking block" 400.
|
|
85
|
+
* agent turn. The session registry is the SINGLE source of truth (B.T2): the per-session
|
|
86
|
+
* record carries the profileName, correct for both user-conversation and thread-spawned
|
|
87
|
+
* sessions. The old channel-level conversation-ledger fallback is gone — it could disagree
|
|
88
|
+
* with the registry on a channel hosting both kinds of session and resume with the wrong
|
|
89
|
+
* profile (routing through the wrong gateway mode → Anthropic 400 on thinking blocks).
|
|
96
90
|
*
|
|
97
91
|
* Exported (rather than inlined) so the priority logic is unit-testable in isolation
|
|
98
92
|
* without spinning up the real repo singletons. */
|
|
99
93
|
export interface ProfileLookupDeps {
|
|
100
94
|
lookupRegistryProfile: (sessionId: string) => Promise<string | null>;
|
|
101
|
-
lookupLedgerProfile: (channel: string) => Promise<string | null>;
|
|
102
95
|
}
|
|
103
96
|
export declare function resolveOnNewProfileName(channel: string, sessionId: string, deps: ProfileLookupDeps): Promise<string | null>;
|
|
104
97
|
/** Fire-and-forget onNew hook used by the !new command and the "New" status button.
|
|
@@ -249,10 +249,7 @@ async function resolveOnNewThreadAnchor(channel, threadAnchorId) {
|
|
|
249
249
|
return null;
|
|
250
250
|
}
|
|
251
251
|
export async function resolveOnNewProfileName(channel, sessionId, deps) {
|
|
252
|
-
|
|
253
|
-
if (fromRegistry)
|
|
254
|
-
return fromRegistry;
|
|
255
|
-
return deps.lookupLedgerProfile(channel);
|
|
252
|
+
return deps.lookupRegistryProfile(sessionId);
|
|
256
253
|
}
|
|
257
254
|
/** Default binding of the registry lookup — composes lookupBySessionId + lookupSession.
|
|
258
255
|
* Extracted so prepareOnNewRun's call site stays one line and tests can swap in fakes. */
|
|
@@ -263,10 +260,6 @@ async function defaultLookupRegistryProfile(sessionId) {
|
|
|
263
260
|
const record = await sessionStore.lookupSession(name);
|
|
264
261
|
return record?.profileName ?? null;
|
|
265
262
|
}
|
|
266
|
-
async function defaultLookupLedgerProfile(channel) {
|
|
267
|
-
const conv = await conversationLedger.getConversation(channel);
|
|
268
|
-
return conv?.profileName ?? null;
|
|
269
|
-
}
|
|
270
263
|
/** Build the onNew SessionHookSpec + a fresh stream. Returns null when the hook isn't
|
|
271
264
|
* configured or there's no live session to capture context from. */
|
|
272
265
|
async function prepareOnNewRun(channel, adapter, threadAnchorId) {
|
|
@@ -279,11 +272,9 @@ async function prepareOnNewRun(channel, adapter, threadAnchorId) {
|
|
|
279
272
|
return null;
|
|
280
273
|
}
|
|
281
274
|
const sessionName = (await sessionStore.lookupBySessionId(sessionId)) || sessionId.slice(0, 8);
|
|
282
|
-
//
|
|
283
|
-
// Registry is the per-session truth; ledger is the channel-level fallback.
|
|
275
|
+
// Registry is the single source of truth for the per-session profileName.
|
|
284
276
|
const profileName = await resolveOnNewProfileName(channel, sessionId, {
|
|
285
277
|
lookupRegistryProfile: defaultLookupRegistryProfile,
|
|
286
|
-
lookupLedgerProfile: defaultLookupLedgerProfile,
|
|
287
278
|
});
|
|
288
279
|
const anchor = await resolveOnNewThreadAnchor(channel, threadAnchorId);
|
|
289
280
|
const stream = adapter.openOutputStream({ type: 'interactive-reply', conduit: channel, sessionId: '' }, { threadId: anchor });
|
|
@@ -358,13 +349,15 @@ export async function runMessageEndForTurn(args) {
|
|
|
358
349
|
return;
|
|
359
350
|
}
|
|
360
351
|
try {
|
|
361
|
-
|
|
352
|
+
// Profile comes from the session registry (the single source of truth), keyed by the turn's
|
|
353
|
+
// sessionId — never from the channel-level ledger, which could name a different session.
|
|
354
|
+
const profile = await defaultLookupRegistryProfile(args.sessionId);
|
|
362
355
|
await runMessageEndSessionHook({
|
|
363
356
|
channel: args.channel,
|
|
364
357
|
sessionId: args.sessionId,
|
|
365
358
|
sessionName: args.sessionName ?? '',
|
|
366
359
|
executionId: args.executionId ?? '',
|
|
367
|
-
profile
|
|
360
|
+
profile,
|
|
368
361
|
stream: args.stream,
|
|
369
362
|
});
|
|
370
363
|
}
|