@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
|
@@ -0,0 +1,505 @@
|
|
|
1
|
+
// input: relocatable C2/C3 files, output path, filesystem
|
|
2
|
+
// output: exclusive ATIF metrics or typed fail-closed errors
|
|
3
|
+
// pos: Parent-plus-child journal merge boundary
|
|
4
|
+
// >>> If I am updated, update my header and folder CORTEX.md <<<
|
|
5
|
+
import { createHash } from 'node:crypto';
|
|
6
|
+
import fs from 'node:fs';
|
|
7
|
+
import os from 'node:os';
|
|
8
|
+
import path from 'node:path';
|
|
9
|
+
import { validateTrajectoryRoot } from './manifest.js';
|
|
10
|
+
import { buildAtifTree, } from './atif.js';
|
|
11
|
+
export class TrajectoryMergeError extends Error {
|
|
12
|
+
reason;
|
|
13
|
+
constructor(reason, message, options) {
|
|
14
|
+
super(message, options);
|
|
15
|
+
this.reason = reason;
|
|
16
|
+
this.name = 'TrajectoryMergeError';
|
|
17
|
+
}
|
|
18
|
+
}
|
|
19
|
+
export const NODE_TRAJECTORY_MERGE_FS = {
|
|
20
|
+
readdir: directory => fs.readdirSync(directory),
|
|
21
|
+
readFile: filePath => fs.readFileSync(filePath),
|
|
22
|
+
exists: filePath => fs.existsSync(filePath),
|
|
23
|
+
realpath: filePath => fs.realpathSync(filePath),
|
|
24
|
+
access: (filePath, mode) => fs.accessSync(filePath, mode),
|
|
25
|
+
open: (filePath, flags, mode) => fs.openSync(filePath, flags, mode),
|
|
26
|
+
write: (fd, data, offset, length = data.length - offset) => fs.writeSync(fd, data, offset, length),
|
|
27
|
+
fsync: fd => fs.fsyncSync(fd),
|
|
28
|
+
close: fd => fs.closeSync(fd),
|
|
29
|
+
link: (source, destination) => fs.linkSync(source, destination),
|
|
30
|
+
unlink: filePath => fs.unlinkSync(filePath),
|
|
31
|
+
};
|
|
32
|
+
function mergeError(reason, message, cause) {
|
|
33
|
+
throw new TrajectoryMergeError(reason, message, cause === undefined ? undefined : { cause });
|
|
34
|
+
}
|
|
35
|
+
function isErrno(error, code) {
|
|
36
|
+
return Boolean(error && typeof error === 'object' && error.code === code);
|
|
37
|
+
}
|
|
38
|
+
function errorMessage(error) {
|
|
39
|
+
return error instanceof Error ? error.message : String(error);
|
|
40
|
+
}
|
|
41
|
+
function normalizeError(error) {
|
|
42
|
+
if (error instanceof TrajectoryMergeError)
|
|
43
|
+
return error;
|
|
44
|
+
if (isErrno(error, 'EACCES'))
|
|
45
|
+
return new TrajectoryMergeError('EACCES', 'Filesystem access denied', { cause: error });
|
|
46
|
+
if (isErrno(error, 'ENOSPC'))
|
|
47
|
+
return new TrajectoryMergeError('ENOSPC', 'Filesystem has no space', { cause: error });
|
|
48
|
+
return new TrajectoryMergeError('malformed_fragment', errorMessage(error), { cause: error });
|
|
49
|
+
}
|
|
50
|
+
function parseObject(bytes, context) {
|
|
51
|
+
try {
|
|
52
|
+
const value = JSON.parse(bytes.toString('utf8'));
|
|
53
|
+
if (typeof value === 'object' && value !== null && !Array.isArray(value))
|
|
54
|
+
return value;
|
|
55
|
+
}
|
|
56
|
+
catch (error) {
|
|
57
|
+
mergeError('malformed_fragment', `${context} is not valid JSON`, error);
|
|
58
|
+
}
|
|
59
|
+
return mergeError('malformed_fragment', `${context} is not a JSON object`);
|
|
60
|
+
}
|
|
61
|
+
function isWithin(root, candidate) {
|
|
62
|
+
return candidate === root || candidate.startsWith(`${root}${path.sep}`);
|
|
63
|
+
}
|
|
64
|
+
function confinedJournalPath(root, journalPath, fileSystem) {
|
|
65
|
+
if (typeof journalPath !== 'string')
|
|
66
|
+
return mergeError('malformed_fragment', 'Missing journal path');
|
|
67
|
+
const resolvedRoot = path.resolve(root);
|
|
68
|
+
const resolvedJournal = path.resolve(root, journalPath);
|
|
69
|
+
if (!isWithin(resolvedRoot, resolvedJournal))
|
|
70
|
+
return mergeError('malformed_fragment', 'Journal is outside root');
|
|
71
|
+
const realRoot = fileSystem.realpath(resolvedRoot);
|
|
72
|
+
const realJournal = fileSystem.realpath(resolvedJournal);
|
|
73
|
+
if (!isWithin(realRoot, realJournal))
|
|
74
|
+
return mergeError('malformed_fragment', 'Journal resolves outside root');
|
|
75
|
+
return realJournal;
|
|
76
|
+
}
|
|
77
|
+
function loadLifecycle(root, name, fileSystem) {
|
|
78
|
+
const markerPath = path.join(root, name);
|
|
79
|
+
const markerBytes = fileSystem.readFile(markerPath);
|
|
80
|
+
const marker = parseObject(markerBytes, markerPath);
|
|
81
|
+
const terminalPath = markerPath.replace(/\.started\.json$/, '.terminal.json');
|
|
82
|
+
if (!fileSystem.exists(terminalPath)) {
|
|
83
|
+
return mergeError('started_without_terminal', `Missing terminal manifest for ${name}`);
|
|
84
|
+
}
|
|
85
|
+
const terminalBytes = fileSystem.readFile(terminalPath);
|
|
86
|
+
const terminal = parseObject(terminalBytes, terminalPath);
|
|
87
|
+
const journalPath = confinedJournalPath(root, marker.journal_path, fileSystem);
|
|
88
|
+
const journalBytes = fileSystem.readFile(journalPath);
|
|
89
|
+
return {
|
|
90
|
+
markerPath, marker, markerBytes, terminalPath, terminal, terminalBytes,
|
|
91
|
+
journalPath, journalBytes,
|
|
92
|
+
};
|
|
93
|
+
}
|
|
94
|
+
function loadInputs(root, fileSystem) {
|
|
95
|
+
const names = fileSystem.readdir(root).filter(name => name.endsWith('.started.json')).sort();
|
|
96
|
+
if (names.length === 0)
|
|
97
|
+
return mergeError('malformed_fragment', 'No started markers found');
|
|
98
|
+
return names.map(name => loadLifecycle(root, name, fileSystem));
|
|
99
|
+
}
|
|
100
|
+
function supervisorEvidence(terminal) {
|
|
101
|
+
const supervisor = terminal.supervisor;
|
|
102
|
+
if (!supervisor || typeof supervisor !== 'object' || Array.isArray(supervisor)) {
|
|
103
|
+
return mergeError('malformed_fragment', 'Terminal manifest has no supervisor evidence');
|
|
104
|
+
}
|
|
105
|
+
const evidence = supervisor;
|
|
106
|
+
if (typeof evidence.quiescent !== 'boolean' || !Number.isInteger(evidence.descendants)) {
|
|
107
|
+
return mergeError('malformed_fragment', 'Terminal supervisor evidence is unparseable');
|
|
108
|
+
}
|
|
109
|
+
return evidence;
|
|
110
|
+
}
|
|
111
|
+
function assertContainment(inputs) {
|
|
112
|
+
for (const input of inputs) {
|
|
113
|
+
const evidence = supervisorEvidence(input.terminal);
|
|
114
|
+
if (evidence.quiescent !== true || evidence.descendants !== 0) {
|
|
115
|
+
mergeError('containment_failure', 'Terminal manifest is not quiescent');
|
|
116
|
+
}
|
|
117
|
+
}
|
|
118
|
+
}
|
|
119
|
+
function assertJournalLinkage(input) {
|
|
120
|
+
if (input.terminal.journal_path !== input.marker.journal_path) {
|
|
121
|
+
mergeError('malformed_fragment', 'Lifecycle journal paths disagree');
|
|
122
|
+
}
|
|
123
|
+
}
|
|
124
|
+
// Remap only journal_path; validate all other fields and exact journal bytes from one snapshot.
|
|
125
|
+
function writeValidationInput(root, input, index) {
|
|
126
|
+
assertJournalLinkage(input);
|
|
127
|
+
const journalPath = path.join(root, `journal-${index}.ndjson`);
|
|
128
|
+
fs.writeFileSync(journalPath, input.journalBytes);
|
|
129
|
+
const marker = { ...input.marker, journal_path: journalPath };
|
|
130
|
+
const terminal = { ...input.terminal, journal_path: journalPath };
|
|
131
|
+
fs.writeFileSync(path.join(root, path.basename(input.markerPath)), `${JSON.stringify(marker)}\n`);
|
|
132
|
+
fs.writeFileSync(path.join(root, path.basename(input.terminalPath)), `${JSON.stringify(terminal)}\n`);
|
|
133
|
+
}
|
|
134
|
+
function validateSnapshot(inputs) {
|
|
135
|
+
const validationRoot = fs.mkdtempSync(path.join(os.tmpdir(), 'trajectory-merge-validate-'));
|
|
136
|
+
try {
|
|
137
|
+
inputs.forEach((input, index) => writeValidationInput(validationRoot, input, index));
|
|
138
|
+
const validation = validateTrajectoryRoot(validationRoot);
|
|
139
|
+
if (!validation.ok)
|
|
140
|
+
mergeError('malformed_fragment', validation.problems.join('\n'));
|
|
141
|
+
}
|
|
142
|
+
finally {
|
|
143
|
+
fs.rmSync(validationRoot, { recursive: true, force: true });
|
|
144
|
+
}
|
|
145
|
+
}
|
|
146
|
+
function parseJournal(input) {
|
|
147
|
+
const text = input.journalBytes.toString('utf8');
|
|
148
|
+
if (!text.endsWith('\n'))
|
|
149
|
+
return mergeError('malformed_fragment', 'Incomplete journal line');
|
|
150
|
+
const lines = text.slice(0, -1).split('\n');
|
|
151
|
+
const records = lines.map((line, index) => parseObject(Buffer.from(line), `${input.journalPath}:${index + 1}`));
|
|
152
|
+
if (records.length < 1)
|
|
153
|
+
return mergeError('malformed_fragment', 'Journal has no header');
|
|
154
|
+
return {
|
|
155
|
+
header: records[0],
|
|
156
|
+
events: records.slice(1),
|
|
157
|
+
terminal: input.terminal,
|
|
158
|
+
};
|
|
159
|
+
}
|
|
160
|
+
function partitionFragments(fragments) {
|
|
161
|
+
const parents = fragments.filter(fragment => fragment.header.thread_id === null);
|
|
162
|
+
if (parents.length !== 1)
|
|
163
|
+
return mergeError('malformed_fragment', 'Expected exactly one parent fragment');
|
|
164
|
+
const children = fragments.filter(fragment => fragment.header.thread_id !== null);
|
|
165
|
+
const ids = children.map(child => child.header.thread_id);
|
|
166
|
+
if (new Set(ids).size !== ids.length) {
|
|
167
|
+
return mergeError('ambiguous_subagent_link', 'Two child fragments claim one thread id');
|
|
168
|
+
}
|
|
169
|
+
return { parent: parents[0], children };
|
|
170
|
+
}
|
|
171
|
+
function assertRootIdentity(parent, children) {
|
|
172
|
+
const rootRunId = parent.header.root_run_id;
|
|
173
|
+
if (children.some(child => child.header.root_run_id !== rootRunId)) {
|
|
174
|
+
mergeError('malformed_fragment', 'Root run id differs between parent and child');
|
|
175
|
+
}
|
|
176
|
+
const modelHash = parent.header.model_execution_identity_hash;
|
|
177
|
+
if (children.some(child => child.header.model_execution_identity_hash !== modelHash)) {
|
|
178
|
+
mergeError('identity_hash_drift', 'Model execution identity differs between parent and child');
|
|
179
|
+
}
|
|
180
|
+
}
|
|
181
|
+
function toolResults(events) {
|
|
182
|
+
const results = new Map();
|
|
183
|
+
for (const record of events) {
|
|
184
|
+
const event = record.event;
|
|
185
|
+
if (event.type !== 'tool_result')
|
|
186
|
+
continue;
|
|
187
|
+
results.set(event.toolUseId, [...(results.get(event.toolUseId) ?? []), record]);
|
|
188
|
+
}
|
|
189
|
+
return results;
|
|
190
|
+
}
|
|
191
|
+
function isThreadRun(name) {
|
|
192
|
+
return name === 'thread_run' || name === 'mcp__cortex-benchmark-thread__thread_run';
|
|
193
|
+
}
|
|
194
|
+
function parseJson(value) {
|
|
195
|
+
try {
|
|
196
|
+
return JSON.parse(value);
|
|
197
|
+
}
|
|
198
|
+
catch {
|
|
199
|
+
return null;
|
|
200
|
+
}
|
|
201
|
+
}
|
|
202
|
+
function contentBlocks(value) {
|
|
203
|
+
if (Array.isArray(value))
|
|
204
|
+
return value;
|
|
205
|
+
if (!value || typeof value !== 'object')
|
|
206
|
+
return null;
|
|
207
|
+
const content = value.content;
|
|
208
|
+
return Array.isArray(content) ? content : null;
|
|
209
|
+
}
|
|
210
|
+
function textFromBlock(value) {
|
|
211
|
+
if (!value || typeof value !== 'object')
|
|
212
|
+
return null;
|
|
213
|
+
const block = value;
|
|
214
|
+
if (block.type !== 'text')
|
|
215
|
+
return null;
|
|
216
|
+
return typeof block.text === 'string' ? block.text : null;
|
|
217
|
+
}
|
|
218
|
+
function textBlockPayload(value) {
|
|
219
|
+
const blocks = contentBlocks(value);
|
|
220
|
+
if (!blocks || blocks.length !== 1)
|
|
221
|
+
return null;
|
|
222
|
+
const text = textFromBlock(blocks[0]);
|
|
223
|
+
return text === null ? null : parseJson(text);
|
|
224
|
+
}
|
|
225
|
+
function payloadThreadId(content) {
|
|
226
|
+
const parsed = parseJson(content);
|
|
227
|
+
const payload = parsed && typeof parsed === 'object' && !Array.isArray(parsed)
|
|
228
|
+
&& typeof parsed.thread_id === 'string'
|
|
229
|
+
? parsed : textBlockPayload(parsed);
|
|
230
|
+
if (!payload || typeof payload !== 'object')
|
|
231
|
+
return null;
|
|
232
|
+
const threadId = payload.thread_id;
|
|
233
|
+
return typeof threadId === 'string' && threadId.length > 0 ? threadId : null;
|
|
234
|
+
}
|
|
235
|
+
function successfulResult(records) {
|
|
236
|
+
if (!records || records.length === 0) {
|
|
237
|
+
return mergeError('unresolvable_subagent_link', 'Thread call has no tool result');
|
|
238
|
+
}
|
|
239
|
+
if (records.length !== 1) {
|
|
240
|
+
return mergeError('ambiguous_subagent_link', 'Thread call has ambiguous tool results');
|
|
241
|
+
}
|
|
242
|
+
const event = records[0].event;
|
|
243
|
+
if (event.type !== 'tool_result' || !event.ok) {
|
|
244
|
+
return mergeError('unresolvable_subagent_link', 'Thread run has no successful result');
|
|
245
|
+
}
|
|
246
|
+
return records[0];
|
|
247
|
+
}
|
|
248
|
+
function threadIdFromResults(records) {
|
|
249
|
+
const record = successfulResult(records);
|
|
250
|
+
const event = record.event;
|
|
251
|
+
const threadId = payloadThreadId(event.content);
|
|
252
|
+
if (!threadId)
|
|
253
|
+
return mergeError('unresolvable_subagent_link', 'Thread result has no thread_id');
|
|
254
|
+
return threadId;
|
|
255
|
+
}
|
|
256
|
+
function threadCalls(events) {
|
|
257
|
+
return events.flatMap(record => {
|
|
258
|
+
const event = record.event;
|
|
259
|
+
if (event.type !== 'tool_use' || !isThreadRun(event.name))
|
|
260
|
+
return [];
|
|
261
|
+
return [{ callId: event.toolUseId }];
|
|
262
|
+
});
|
|
263
|
+
}
|
|
264
|
+
function collectThreadLinks(events) {
|
|
265
|
+
const results = toolResults(events);
|
|
266
|
+
return threadCalls(events).map(call => ({
|
|
267
|
+
callId: call.callId,
|
|
268
|
+
threadId: threadIdFromResults(results.get(call.callId)),
|
|
269
|
+
}));
|
|
270
|
+
}
|
|
271
|
+
function explicitLinksInCallOrder(events, links) {
|
|
272
|
+
const calls = threadCalls(events);
|
|
273
|
+
const callIds = new Set(calls.map(call => call.callId));
|
|
274
|
+
if (links.some(link => !callIds.has(link.callId))) {
|
|
275
|
+
return mergeError('unresolvable_subagent_link', 'Explicit link has no thread_run tool call');
|
|
276
|
+
}
|
|
277
|
+
if (new Set(links.map(link => link.callId)).size !== links.length) {
|
|
278
|
+
return mergeError('ambiguous_subagent_link', 'Thread call is explicitly linked more than once');
|
|
279
|
+
}
|
|
280
|
+
if (links.length !== calls.length) {
|
|
281
|
+
return mergeError('unresolvable_subagent_link', 'Explicit link map is incomplete');
|
|
282
|
+
}
|
|
283
|
+
const byCall = new Map(links.map(link => [link.callId, link.threadId]));
|
|
284
|
+
const results = toolResults(events);
|
|
285
|
+
return calls.map(call => {
|
|
286
|
+
successfulResult(results.get(call.callId));
|
|
287
|
+
return { callId: call.callId, threadId: byCall.get(call.callId) };
|
|
288
|
+
});
|
|
289
|
+
}
|
|
290
|
+
function orderChildren(children, links) {
|
|
291
|
+
const childIds = children.map(child => child.header.thread_id);
|
|
292
|
+
const linkIds = links.map(link => link.threadId);
|
|
293
|
+
if (new Set(linkIds).size !== linkIds.length) {
|
|
294
|
+
return mergeError('ambiguous_subagent_link', 'Two tool results claim one child thread');
|
|
295
|
+
}
|
|
296
|
+
const byId = new Map(children.map(child => [child.header.thread_id, child]));
|
|
297
|
+
if (linkIds.some(threadId => !byId.has(threadId))) {
|
|
298
|
+
return mergeError('missing_child_fragment', 'Resolved thread has no child fragment');
|
|
299
|
+
}
|
|
300
|
+
if (childIds.some(threadId => !linkIds.includes(threadId))) {
|
|
301
|
+
return mergeError('unbound_child_fragment', 'Child fragment has no resolved tool result');
|
|
302
|
+
}
|
|
303
|
+
return links.map(link => byId.get(link.threadId));
|
|
304
|
+
}
|
|
305
|
+
function removeIfExists(filePath, fileSystem) {
|
|
306
|
+
if (fileSystem.exists(filePath))
|
|
307
|
+
fileSystem.unlink(filePath);
|
|
308
|
+
}
|
|
309
|
+
function assertOutputPrecondition(outputPath, fileSystem) {
|
|
310
|
+
if (fileSystem.exists(outputPath)) {
|
|
311
|
+
mergeError('output_path_exists', 'Output path already exists');
|
|
312
|
+
}
|
|
313
|
+
try {
|
|
314
|
+
fileSystem.access(path.dirname(outputPath), fs.constants.W_OK);
|
|
315
|
+
}
|
|
316
|
+
catch (error) {
|
|
317
|
+
mergeError('output_path_not_writable', 'Output directory is not writable', error);
|
|
318
|
+
}
|
|
319
|
+
}
|
|
320
|
+
function writeFull(fd, bytes, fileSystem) {
|
|
321
|
+
let offset = 0;
|
|
322
|
+
while (offset < bytes.length) {
|
|
323
|
+
const written = fileSystem.write(fd, bytes, offset);
|
|
324
|
+
if (written <= 0)
|
|
325
|
+
return mergeError('malformed_fragment', 'Output write returned zero bytes');
|
|
326
|
+
offset += written;
|
|
327
|
+
}
|
|
328
|
+
}
|
|
329
|
+
function safeCleanup(filePath, fileSystem) {
|
|
330
|
+
try {
|
|
331
|
+
removeIfExists(filePath, fileSystem);
|
|
332
|
+
}
|
|
333
|
+
catch { }
|
|
334
|
+
}
|
|
335
|
+
function temporaryPath(outputPath) {
|
|
336
|
+
const nonce = `${process.pid}.${Date.now()}.${Math.random().toString(36).slice(2)}`;
|
|
337
|
+
return `${outputPath}.tmp.${nonce}`;
|
|
338
|
+
}
|
|
339
|
+
function linkOutput(temporary, outputPath, fileSystem) {
|
|
340
|
+
try {
|
|
341
|
+
fileSystem.link(temporary, outputPath);
|
|
342
|
+
}
|
|
343
|
+
catch (error) {
|
|
344
|
+
if (isErrno(error, 'EEXIST')) {
|
|
345
|
+
mergeError('output_path_exists', 'Output path was created during publication', error);
|
|
346
|
+
}
|
|
347
|
+
throw error;
|
|
348
|
+
}
|
|
349
|
+
}
|
|
350
|
+
function publish(outputPath, bytes, fileSystem) {
|
|
351
|
+
const temporary = temporaryPath(outputPath);
|
|
352
|
+
let fd = null;
|
|
353
|
+
try {
|
|
354
|
+
fd = fileSystem.open(temporary, fs.constants.O_WRONLY | fs.constants.O_CREAT | fs.constants.O_EXCL, 0o600);
|
|
355
|
+
writeFull(fd, bytes, fileSystem);
|
|
356
|
+
fileSystem.fsync(fd);
|
|
357
|
+
fileSystem.close(fd);
|
|
358
|
+
fd = null;
|
|
359
|
+
linkOutput(temporary, outputPath, fileSystem);
|
|
360
|
+
safeCleanup(temporary, fileSystem);
|
|
361
|
+
}
|
|
362
|
+
catch (error) {
|
|
363
|
+
if (fd !== null) {
|
|
364
|
+
try {
|
|
365
|
+
fileSystem.close(fd);
|
|
366
|
+
}
|
|
367
|
+
catch { }
|
|
368
|
+
}
|
|
369
|
+
safeCleanup(temporary, fileSystem);
|
|
370
|
+
throw normalizeError(error);
|
|
371
|
+
}
|
|
372
|
+
}
|
|
373
|
+
function underivable(detail) {
|
|
374
|
+
return mergeError('aggregate_metrics_underivable', detail);
|
|
375
|
+
}
|
|
376
|
+
function tokenMetric(value, field) {
|
|
377
|
+
if (Number.isSafeInteger(value) && Number(value) >= 0)
|
|
378
|
+
return Number(value);
|
|
379
|
+
return underivable(`Missing or invalid ${field}`);
|
|
380
|
+
}
|
|
381
|
+
function costMetric(value) {
|
|
382
|
+
if (typeof value === 'number' && Number.isFinite(value) && value >= 0)
|
|
383
|
+
return value;
|
|
384
|
+
return underivable('Missing or invalid cost_usd');
|
|
385
|
+
}
|
|
386
|
+
function sumToken(left, right, field) {
|
|
387
|
+
const total = left + right;
|
|
388
|
+
if (Number.isSafeInteger(total))
|
|
389
|
+
return total;
|
|
390
|
+
return underivable(`${field} aggregate exceeds safe integer range`);
|
|
391
|
+
}
|
|
392
|
+
function addCostRecord(total, record) {
|
|
393
|
+
const event = record.event;
|
|
394
|
+
if (event.type !== 'cost_record')
|
|
395
|
+
return total;
|
|
396
|
+
return {
|
|
397
|
+
...total,
|
|
398
|
+
prompt: sumToken(total.prompt, tokenMetric(event.prompt_tokens, 'prompt_tokens'), 'prompt_tokens'),
|
|
399
|
+
completion: sumToken(total.completion, tokenMetric(event.tokens_out, 'tokens_out'), 'tokens_out'),
|
|
400
|
+
cached: sumToken(total.cached, tokenMetric(event.cached_tokens, 'cached_tokens'), 'cached_tokens'),
|
|
401
|
+
cost: total.cost + costMetric(event.cost_usd),
|
|
402
|
+
};
|
|
403
|
+
}
|
|
404
|
+
function fragmentCostMetrics(fragment) {
|
|
405
|
+
const records = fragment.events.filter(record => record.event.type === 'cost_record');
|
|
406
|
+
if (records.length === 0)
|
|
407
|
+
return underivable('Fragment has no cost_record event');
|
|
408
|
+
return records.reduce(addCostRecord, { prompt: 0, completion: 0, cached: 0, cost: 0, steps: 0 });
|
|
409
|
+
}
|
|
410
|
+
function fragmentSteps(fragment) {
|
|
411
|
+
const records = fragment.events.filter(record => record.event.type === 'turn_complete');
|
|
412
|
+
if (records.length === 0)
|
|
413
|
+
return underivable('Fragment has no turn_complete event');
|
|
414
|
+
return records.reduce((total, record) => {
|
|
415
|
+
const event = record.event;
|
|
416
|
+
if (event.type !== 'turn_complete')
|
|
417
|
+
return total;
|
|
418
|
+
return sumToken(total, tokenMetric(event.numTurns, 'numTurns'), 'numTurns');
|
|
419
|
+
}, 0);
|
|
420
|
+
}
|
|
421
|
+
function fragmentMetrics(fragment) {
|
|
422
|
+
const metrics = fragmentCostMetrics(fragment);
|
|
423
|
+
return { ...metrics, steps: fragmentSteps(fragment) };
|
|
424
|
+
}
|
|
425
|
+
function addFragmentMetrics(total, fragment) {
|
|
426
|
+
const metrics = fragmentMetrics(fragment);
|
|
427
|
+
return {
|
|
428
|
+
prompt: sumToken(total.prompt, metrics.prompt, 'total_prompt_tokens'),
|
|
429
|
+
completion: sumToken(total.completion, metrics.completion, 'total_completion_tokens'),
|
|
430
|
+
cached: sumToken(total.cached, metrics.cached, 'total_cached_tokens'),
|
|
431
|
+
cost: total.cost + metrics.cost,
|
|
432
|
+
steps: sumToken(total.steps, metrics.steps, 'total_steps'),
|
|
433
|
+
};
|
|
434
|
+
}
|
|
435
|
+
function assertMetricsDerivable(fragments) {
|
|
436
|
+
for (const fragment of fragments)
|
|
437
|
+
fragmentMetrics(fragment);
|
|
438
|
+
}
|
|
439
|
+
function aggregateFinalMetrics(fragments) {
|
|
440
|
+
const zero = { prompt: 0, completion: 0, cached: 0, cost: 0, steps: 0 };
|
|
441
|
+
const total = fragments.reduce(addFragmentMetrics, zero);
|
|
442
|
+
if (!Number.isFinite(total.cost))
|
|
443
|
+
return underivable('total_cost_usd is not finite');
|
|
444
|
+
return {
|
|
445
|
+
total_prompt_tokens: total.prompt,
|
|
446
|
+
total_completion_tokens: total.completion,
|
|
447
|
+
total_cached_tokens: total.cached,
|
|
448
|
+
total_cost_usd: total.cost,
|
|
449
|
+
total_steps: total.steps,
|
|
450
|
+
extra: {
|
|
451
|
+
prompt_tokens_definition: 'input_tokens + cache_creation_input_tokens + cache_read_input_tokens',
|
|
452
|
+
cached_tokens_definition: 'cache_read_input_tokens',
|
|
453
|
+
},
|
|
454
|
+
};
|
|
455
|
+
}
|
|
456
|
+
function fragmentOutcome(fragment) {
|
|
457
|
+
return {
|
|
458
|
+
thread_id: fragment.header.thread_id,
|
|
459
|
+
state: fragment.terminal.state,
|
|
460
|
+
terminal_reason: fragment.terminal.terminal_reason,
|
|
461
|
+
};
|
|
462
|
+
}
|
|
463
|
+
function resolveLinks(parent, explicit) {
|
|
464
|
+
if (!explicit || explicit.length === 0) {
|
|
465
|
+
return { links: collectThreadLinks(parent.events), source: 'tool_result' };
|
|
466
|
+
}
|
|
467
|
+
return { links: explicitLinksInCallOrder(parent.events, explicit), source: 'explicit' };
|
|
468
|
+
}
|
|
469
|
+
function mergeBytes(root, fileSystem, explicit) {
|
|
470
|
+
const inputs = loadInputs(root, fileSystem);
|
|
471
|
+
assertContainment(inputs);
|
|
472
|
+
const fragments = inputs.map(parseJournal);
|
|
473
|
+
assertMetricsDerivable(fragments);
|
|
474
|
+
validateSnapshot(inputs);
|
|
475
|
+
const { parent, children } = partitionFragments(fragments);
|
|
476
|
+
assertRootIdentity(parent, children);
|
|
477
|
+
const resolved = resolveLinks(parent, explicit);
|
|
478
|
+
const orderedChildren = orderChildren(children, resolved.links);
|
|
479
|
+
const orderedFragments = [parent, ...orderedChildren];
|
|
480
|
+
const finalMetrics = aggregateFinalMetrics(orderedFragments);
|
|
481
|
+
const trajectory = buildAtifTree(parent, orderedChildren, resolved.links, resolved.source, finalMetrics);
|
|
482
|
+
const outcomes = orderedFragments.map(fragmentOutcome);
|
|
483
|
+
return {
|
|
484
|
+
bytes: Buffer.from(`${JSON.stringify(trajectory, null, 2)}\n`),
|
|
485
|
+
trajectoryId: trajectory.trajectory_id,
|
|
486
|
+
fragments: outcomes,
|
|
487
|
+
};
|
|
488
|
+
}
|
|
489
|
+
export function mergeTrajectory(options, fileSystem = NODE_TRAJECTORY_MERGE_FS) {
|
|
490
|
+
const outputPath = path.resolve(options.outputPath);
|
|
491
|
+
try {
|
|
492
|
+
assertOutputPrecondition(outputPath, fileSystem);
|
|
493
|
+
const merged = mergeBytes(path.resolve(options.trajectoryRoot), fileSystem, options.subagentLinks);
|
|
494
|
+
publish(outputPath, merged.bytes, fileSystem);
|
|
495
|
+
return {
|
|
496
|
+
outputPath,
|
|
497
|
+
sha256: createHash('sha256').update(merged.bytes).digest('hex'),
|
|
498
|
+
trajectoryId: merged.trajectoryId,
|
|
499
|
+
fragments: merged.fragments,
|
|
500
|
+
};
|
|
501
|
+
}
|
|
502
|
+
catch (error) {
|
|
503
|
+
throw normalizeError(error);
|
|
504
|
+
}
|
|
505
|
+
}
|
|
@@ -12,9 +12,19 @@ export interface ModeFileData {
|
|
|
12
12
|
export interface ApiEnv {
|
|
13
13
|
ANTHROPIC_API_KEY: string | undefined;
|
|
14
14
|
ANTHROPIC_BASE_URL: string | undefined;
|
|
15
|
+
CLAUDE_CODE_OAUTH_TOKEN: string | undefined;
|
|
16
|
+
CLAUDE_CODE_OAUTH_TOKEN_EXPIRES_AT: string | undefined;
|
|
15
17
|
}
|
|
16
18
|
declare const GATEWAY_ANTHROPIC_URL = "http://127.0.0.1:9880/anthropic";
|
|
17
19
|
export declare function gatewayModeUrl(mode: string, metadata?: Record<string, string>): string;
|
|
20
|
+
export declare function getSavedApiEnv(): ApiEnv;
|
|
21
|
+
export declare function saveAnthropicApiKey(value: string): Promise<void>;
|
|
22
|
+
export declare function saveClaudeCodeOAuthToken(value: string, options?: {
|
|
23
|
+
expiresAt?: string;
|
|
24
|
+
signal?: AbortSignal;
|
|
25
|
+
}): Promise<void>;
|
|
26
|
+
export declare function removeAnthropicApiKey(): Promise<void>;
|
|
27
|
+
export declare function removeClaudeCodeOAuthToken(): Promise<void>;
|
|
18
28
|
declare function loadModeFile(): ModeFileData;
|
|
19
29
|
export declare function loadMode(): string;
|
|
20
30
|
export declare function loadBackend(): Backend;
|