@cortex-agent/server 2026.8.3-2 → 2026.8.6

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.
Files changed (219) hide show
  1. package/defaults/config/thread-templates/agents/benchmark-coder.json +2 -2
  2. package/defaults/config/thread-templates/agents/benchmark-fixer.json +17 -0
  3. package/defaults/config/thread-templates/agents/benchmark-reviewer.json +5 -5
  4. package/defaults/config/thread-templates/templates/benchmark-coder-review-fix.json +21 -0
  5. package/defaults/plugins/cortex-system/skills/thread/SKILL.md +1 -0
  6. package/defaults/prompts/directives/benchmark-coder.md +1 -0
  7. package/defaults/prompts/directives/benchmark-fixer.md +1 -0
  8. package/defaults/prompts/directives/benchmark-reviewer.md +1 -0
  9. package/defaults/prompts/systemPrompts/benchmark-coder.md +1 -0
  10. package/defaults/prompts/systemPrompts/benchmark-fixer.md +1 -0
  11. package/defaults/prompts/systemPrompts/benchmark-reviewer.md +1 -0
  12. package/dist/agent-adapter/capabilities.d.ts +32 -1
  13. package/dist/agent-adapter/capabilities.js +39 -1
  14. package/dist/agent-adapter/claude/adapter.d.ts +15 -0
  15. package/dist/agent-adapter/claude/adapter.js +29 -7
  16. package/dist/agent-adapter/claude/spawn-args.d.ts +5 -2
  17. package/dist/agent-adapter/claude/spawn-args.js +29 -6
  18. package/dist/agent-adapter/index.js +11 -1
  19. package/dist/agent-adapter/normalize/tool-names.d.ts +4 -0
  20. package/dist/agent-adapter/normalize/tool-names.js +10 -0
  21. package/dist/agent-adapter/pi/adapter.d.ts +20 -8
  22. package/dist/agent-adapter/pi/adapter.js +130 -35
  23. package/dist/agent-adapter/pi/agent-dir.d.ts +20 -53
  24. package/dist/agent-adapter/pi/agent-dir.js +48 -89
  25. package/dist/agent-adapter/pi/custom-catalog.d.ts +10 -0
  26. package/dist/agent-adapter/pi/custom-catalog.js +42 -0
  27. package/dist/agent-adapter/pi/defaults.d.ts +9 -0
  28. package/dist/agent-adapter/pi/defaults.js +14 -4
  29. package/dist/agent-adapter/pi/discovery.d.ts +1 -3
  30. package/dist/agent-adapter/pi/discovery.js +3 -15
  31. package/dist/agent-adapter/pi/event-parser.js +8 -0
  32. package/dist/agent-adapter/pi/mcp-bridge.d.ts +13 -0
  33. package/dist/agent-adapter/pi/mcp-bridge.js +31 -6
  34. package/dist/agent-adapter/pi/mcp-duration.d.ts +28 -0
  35. package/dist/agent-adapter/pi/mcp-duration.js +48 -0
  36. package/dist/agent-adapter/pi/policy-guard.d.ts +40 -0
  37. package/dist/agent-adapter/pi/policy-guard.js +111 -0
  38. package/dist/agent-adapter/pi/providers-config.d.ts +62 -0
  39. package/dist/agent-adapter/pi/providers-config.js +101 -0
  40. package/dist/agent-adapter/pi/quota-probe.d.ts +11 -0
  41. package/dist/agent-adapter/pi/quota-probe.js +36 -0
  42. package/dist/agent-adapter/pi/quota-sink.d.ts +25 -0
  43. package/dist/agent-adapter/pi/quota-sink.js +31 -0
  44. package/dist/agent-adapter/pi/session-files.d.ts +2 -0
  45. package/dist/agent-adapter/pi/session-files.js +19 -0
  46. package/dist/agent-adapter/pi/session-support.d.ts +14 -3
  47. package/dist/agent-adapter/pi/session-support.js +8 -0
  48. package/dist/agent-adapter/pi/spawn-args.d.ts +11 -1
  49. package/dist/agent-adapter/pi/spawn-args.js +13 -0
  50. package/dist/agent-adapter/pi/tool-shims.d.ts +2 -2
  51. package/dist/agent-adapter/pi/tool-shims.js +32 -21
  52. package/dist/agent-adapter/pi/web-search.js +36 -8
  53. package/dist/agent-adapter/types.d.ts +14 -0
  54. package/dist/core/locales/en.d.ts +54 -1
  55. package/dist/core/locales/en.js +2 -0
  56. package/dist/core/locales/slices/commands.d.ts +12 -1
  57. package/dist/core/locales/slices/commands.js +24 -2
  58. package/dist/core/locales/slices/providers.d.ts +45 -0
  59. package/dist/core/locales/slices/providers.js +95 -0
  60. package/dist/core/locales/zh.js +2 -0
  61. package/dist/core/resilient-watch.d.ts +28 -0
  62. package/dist/core/resilient-watch.js +110 -0
  63. package/dist/core/settings.js +15 -20
  64. package/dist/core/types/agent-types.d.ts +6 -0
  65. package/dist/core/types/thread-types.d.ts +21 -3
  66. package/dist/domain/agent-run/agent-run-cli.js +3 -1
  67. package/dist/domain/agent-run/benchmark-local-thread-orchestrator.d.ts +31 -0
  68. package/dist/domain/agent-run/benchmark-local-thread-orchestrator.js +231 -24
  69. package/dist/domain/agent-run/benchmark-thread-identity.d.ts +15 -2
  70. package/dist/domain/agent-run/benchmark-thread-identity.js +123 -34
  71. package/dist/domain/agent-run/identity.d.ts +5 -0
  72. package/dist/domain/agent-run/identity.js +4 -1
  73. package/dist/domain/agent-run/journal.d.ts +3 -2
  74. package/dist/domain/agent-run/manifest.js +11 -4
  75. package/dist/domain/agent-run/pinned-node-process.d.ts +4 -0
  76. package/dist/domain/agent-run/pinned-node-process.js +9 -0
  77. package/dist/domain/agent-run/role-surface.d.ts +2 -2
  78. package/dist/domain/agent-run/role-surface.js +7 -3
  79. package/dist/domain/agent-run/run-config.d.ts +10 -1
  80. package/dist/domain/agent-run/run-config.js +57 -6
  81. package/dist/domain/agent-run/runner.js +149 -31
  82. package/dist/domain/agents/facade.d.ts +37 -122
  83. package/dist/domain/agents/facade.js +47 -115
  84. package/dist/domain/agents/spawn-config.d.ts +135 -0
  85. package/dist/domain/agents/spawn-config.js +121 -0
  86. package/dist/domain/benchmark/accounting-reconciliation.d.ts +98 -0
  87. package/dist/domain/benchmark/accounting-reconciliation.js +218 -0
  88. package/dist/domain/benchmark/arm-schema.d.ts +43 -0
  89. package/dist/domain/benchmark/arm-schema.js +243 -0
  90. package/dist/domain/benchmark/capabilities.d.ts +4 -0
  91. package/dist/domain/benchmark/capabilities.js +54 -0
  92. package/dist/domain/benchmark/decimal-text.d.ts +27 -0
  93. package/dist/domain/benchmark/decimal-text.js +67 -0
  94. package/dist/domain/benchmark/lease-echo.d.ts +43 -0
  95. package/dist/domain/benchmark/lease-echo.js +56 -0
  96. package/dist/domain/benchmark/policy-backed-runtime-deps.d.ts +14 -0
  97. package/dist/domain/benchmark/policy-backed-runtime-deps.js +47 -0
  98. package/dist/domain/benchmark/policy-compiler.d.ts +68 -0
  99. package/dist/domain/benchmark/policy-compiler.js +680 -0
  100. package/dist/domain/benchmark/resolved-policy.d.ts +110 -0
  101. package/dist/domain/benchmark/resolved-policy.js +195 -0
  102. package/dist/domain/benchmark/trial-adapter-factory.d.ts +38 -0
  103. package/dist/domain/benchmark/trial-adapter-factory.js +165 -0
  104. package/dist/domain/benchmark/trial-thread-adapter.d.ts +25 -0
  105. package/dist/domain/benchmark/trial-thread-adapter.js +106 -0
  106. package/dist/domain/benchmark/variant-proposal.d.ts +45 -0
  107. package/dist/domain/benchmark/variant-proposal.js +42 -0
  108. package/dist/domain/benchmark/workspace-lease.d.ts +99 -0
  109. package/dist/domain/benchmark/workspace-lease.js +272 -0
  110. package/dist/domain/costs/codex-quota.d.ts +29 -0
  111. package/dist/domain/costs/codex-quota.js +102 -0
  112. package/dist/domain/costs/cost-tracker.d.ts +48 -9
  113. package/dist/domain/costs/cost-tracker.js +74 -18
  114. package/dist/domain/costs/rate-limit-throttle.d.ts +23 -1
  115. package/dist/domain/costs/rate-limit-throttle.js +61 -6
  116. package/dist/domain/costs/resume-registry.d.ts +3 -1
  117. package/dist/domain/costs/resume-registry.js +10 -1
  118. package/dist/domain/mcp/tools/benchmark-thread-run.d.ts +26 -2
  119. package/dist/domain/mcp/tools/benchmark-thread-run.js +63 -20
  120. package/dist/domain/mcp/tools/cost.js +15 -6
  121. package/dist/domain/pi-providers/custom-provider-model.d.ts +53 -0
  122. package/dist/domain/pi-providers/custom-provider-model.js +122 -0
  123. package/dist/domain/pi-providers/custom-provider-service.d.ts +59 -0
  124. package/dist/domain/pi-providers/custom-provider-service.js +143 -0
  125. package/dist/domain/pi-providers/gateway-route-store.d.ts +23 -0
  126. package/dist/domain/pi-providers/gateway-route-store.js +78 -0
  127. package/dist/domain/pi-providers/index.d.ts +4 -0
  128. package/dist/domain/pi-providers/index.js +8 -0
  129. package/dist/domain/pi-providers/models-json-store.d.ts +6 -0
  130. package/dist/domain/pi-providers/models-json-store.js +77 -0
  131. package/dist/domain/scheduling/jobs/_shared.d.ts +4 -1
  132. package/dist/domain/scheduling/jobs/_shared.js +11 -2
  133. package/dist/domain/scheduling/jobs/scheduled-task.js +1 -0
  134. package/dist/domain/scheduling/jobs/task-dispatch.js +49 -54
  135. package/dist/domain/sessions/session-lifecycle.d.ts +22 -0
  136. package/dist/domain/sessions/session-lifecycle.js +20 -1
  137. package/dist/domain/system/system-notice.d.ts +4 -1
  138. package/dist/domain/system/system-notice.js +6 -2
  139. package/dist/domain/tasks/dispatch-utils.d.ts +0 -4
  140. package/dist/domain/tasks/dispatch-utils.js +24 -37
  141. package/dist/domain/threads/runner.d.ts +16 -1
  142. package/dist/domain/threads/runner.js +62 -8
  143. package/dist/domain/threads/template-loader.d.ts +5 -0
  144. package/dist/domain/threads/template-loader.js +120 -36
  145. package/dist/domain/threads/template-validate.d.ts +244 -0
  146. package/dist/domain/threads/template-validate.js +574 -0
  147. package/dist/domain/threads/template-validate.parity.d.ts +1 -0
  148. package/dist/domain/threads/template-validate.parity.js +47 -0
  149. package/dist/domain/threads/template-writer.d.ts +55 -0
  150. package/dist/domain/threads/template-writer.js +131 -0
  151. package/dist/domain/ui-service/app-router.d.ts +143 -1
  152. package/dist/domain/ui-service/app-router.js +29 -3
  153. package/dist/domain/ui-service/input-schemas.d.ts +228 -4
  154. package/dist/domain/ui-service/input-schemas.js +132 -1
  155. package/dist/domain/ui-service/mutate/config.d.ts +10 -1
  156. package/dist/domain/ui-service/mutate/config.js +45 -5
  157. package/dist/domain/ui-service/mutate/custom-providers.d.ts +8 -0
  158. package/dist/domain/ui-service/mutate/custom-providers.js +37 -0
  159. package/dist/domain/ui-service/mutate/profiles.d.ts +21 -0
  160. package/dist/domain/ui-service/mutate/profiles.js +156 -0
  161. package/dist/domain/ui-service/mutate/schedules.d.ts +2 -1
  162. package/dist/domain/ui-service/mutate/schedules.js +53 -3
  163. package/dist/domain/ui-service/mutate/sessions.d.ts +2 -1
  164. package/dist/domain/ui-service/mutate/sessions.js +25 -1
  165. package/dist/domain/ui-service/mutate/system.d.ts +2 -1
  166. package/dist/domain/ui-service/mutate/system.js +17 -3
  167. package/dist/domain/ui-service/mutate/thread-templates.d.ts +4 -0
  168. package/dist/domain/ui-service/mutate/thread-templates.js +71 -0
  169. package/dist/domain/ui-service/query/config.js +30 -0
  170. package/dist/domain/ui-service/query/custom-providers.d.ts +8 -0
  171. package/dist/domain/ui-service/query/custom-providers.js +13 -0
  172. package/dist/domain/ui-service/query/machine-detail.d.ts +2 -0
  173. package/dist/domain/ui-service/query/machine-detail.js +56 -0
  174. package/dist/domain/ui-service/query/machine-probe.d.ts +18 -0
  175. package/dist/domain/ui-service/query/machine-probe.js +136 -0
  176. package/dist/domain/ui-service/query/schedules.js +5 -0
  177. package/dist/domain/ui-service/query/sessions.js +8 -2
  178. package/dist/domain/ui-service/query/thread-template-detail.d.ts +8 -0
  179. package/dist/domain/ui-service/query/thread-template-detail.js +94 -0
  180. package/dist/domain/ui-service/query/thread-templates.d.ts +5 -3
  181. package/dist/domain/ui-service/query/thread-templates.js +44 -7
  182. package/dist/domain/ui-service/types.d.ts +298 -7
  183. package/dist/domain/ui-service/ui-service.js +27 -3
  184. package/dist/entry/app.js +24 -3
  185. package/dist/entry/auth-cli.d.ts +4 -1
  186. package/dist/entry/auth-cli.js +10 -2
  187. package/dist/entry/cli-help.js +6 -2
  188. package/dist/entry/cli.js +2 -1
  189. package/dist/entry/daemon.d.ts +0 -11
  190. package/dist/entry/daemon.js +5 -49
  191. package/dist/entry/provider-cli.d.ts +16 -0
  192. package/dist/entry/provider-cli.js +203 -0
  193. package/dist/events/event-types.d.ts +2 -1
  194. package/dist/orchestration/agent-runner.js +3 -2
  195. package/dist/orchestration/routing/commands/cost.d.ts +8 -0
  196. package/dist/orchestration/routing/commands/cost.js +93 -21
  197. package/dist/orchestration/routing/commands/login-custom.d.ts +26 -0
  198. package/dist/orchestration/routing/commands/login-custom.js +89 -0
  199. package/dist/orchestration/routing/commands/login.d.ts +3 -0
  200. package/dist/orchestration/routing/commands/login.js +7 -0
  201. package/dist/orchestration/routing/message-router.js +48 -33
  202. package/dist/orchestration/routing/webhook.js +1 -1
  203. package/dist/orchestration/session-events.d.ts +2 -1
  204. package/dist/orchestration/session-events.js +1 -0
  205. package/dist/orchestration/thread-callback.js +1 -1
  206. package/dist/store/conversation-history-repo.d.ts +5 -1
  207. package/dist/store/conversation-history-repo.js +2 -1
  208. package/dist/store/cost-repo.d.ts +17 -0
  209. package/dist/store/cost-repo.js +47 -5
  210. package/dist/store/profile-repo.d.ts +0 -10
  211. package/dist/store/profile-repo.js +34 -56
  212. package/dist/store/session-registry-repo.d.ts +12 -0
  213. package/dist/store/session-registry-repo.js +16 -0
  214. package/package.json +1 -1
  215. package/web/dist/assets/index-DYMfaAi4.css +1 -0
  216. package/web/dist/assets/index-uOoZjGKa.js +141 -0
  217. package/web/dist/index.html +2 -2
  218. package/web/dist/assets/index-XqBCYtkw.js +0 -139
  219. package/web/dist/assets/index-zpf3OSKC.css +0 -1
@@ -0,0 +1,121 @@
1
+ // input: run options, agent config, route base URL
2
+ // output: the single backend-neutral AgentSpawnConfig every launcher hands an adapter
3
+ // pos: Registry-free spawn-config builder
4
+ // >>> 一旦我被更新,务必更新我的开头注释与所属文件夹 CORTEX.md <<<
5
+ import { resolveMcpComposition } from '../../agent-adapter/types.js';
6
+ import { GATEWAY_URL } from '../costs/gateway-manager.js';
7
+ import { loadCortexRules } from '../memory/rules-loader.js';
8
+ // --- PI gateway routing ---
9
+ /**
10
+ * Build the gateway sub-path for a PI provider's models.json override, following the gateway's URL
11
+ * convention `/m/<mode>/<endpoint>`. The `mode` selects the gateway route (gateway.yaml owns the
12
+ * upstream + keys); the `provider` is both the PI `--provider` and the gateway endpoint segment.
13
+ *
14
+ * `provider` is required for pi profiles (validated at load time — no default, no fallback). Returns
15
+ * undefined when `mode` is absent — the PI adapter then falls back to the default `/<provider>` path
16
+ * (direct per-provider routing, no `/m/` mode indirection).
17
+ *
18
+ * Keeping this derivation in code (not in the profile) means profiles only carry the logical
19
+ * `mode` name; no gateway path string leaks into profiles.json.
20
+ */
21
+ export function buildPiGatewaySubPath(mode, provider) {
22
+ if (!mode)
23
+ return undefined;
24
+ return `/m/${mode}/${provider}`;
25
+ }
26
+ // --- Channel-scoped plugin gating ---
27
+ /** Plugins that load only for sessions originating from a specific platform channel.
28
+ * Mirrors the channel-gated MCP loading (loadFeishuMcp = channel.startsWith('feishu:')):
29
+ * the cortex-feishu skill bundle is only relevant when the user is working inside Feishu,
30
+ * so it is stripped from non-Feishu sessions even when listed in an agent's pluginDirs. */
31
+ export const CHANNEL_SCOPED_PLUGINS = [
32
+ { plugin: 'cortex-feishu', channelPrefix: 'feishu:' },
33
+ ];
34
+ /** Drop channel-scoped plugin dirs whose channel prefix the current session does not match.
35
+ * Non-scoped plugins always pass through. Matched by the plugin dir's final path segment
36
+ * (basename) so substrings like `cortex-feishu-x` are not affected. */
37
+ export function filterChannelScopedPlugins(dirs, channel) {
38
+ if (!dirs)
39
+ return dirs;
40
+ return dirs.filter((dir) => {
41
+ const base = dir.split('/').filter(Boolean).pop();
42
+ const rule = CHANNEL_SCOPED_PLUGINS.find((r) => r.plugin === base);
43
+ if (!rule)
44
+ return true;
45
+ return !!channel && channel.startsWith(rule.channelPrefix);
46
+ });
47
+ }
48
+ // --- Spawn config ---
49
+ export function buildAgentSpawnConfig(options, config, anthropicBaseUrl) {
50
+ // Pack the Cortex execution context only if at least one field is set, so adapters can
51
+ // skip writing CORTEX_* env vars / route-context fields when there's nothing to report.
52
+ const ctx = {
53
+ threadId: options.threadId ?? null,
54
+ profile: options.profileName ?? null,
55
+ project: options.project ?? null,
56
+ sessionName: options.sessionName ?? null,
57
+ // Stable Cortex tracking id for CORTEX_SESSION_ID; falls back to the backend id (threads/legacy).
58
+ trackSessionId: options.trackSessionId ?? options.sessionId ?? null,
59
+ executionId: options.executionId ?? null,
60
+ useCoreMcp: options.useCoreMcp ?? undefined,
61
+ threadDepth: options.threadDepth ?? null,
62
+ taskId: options.taskId ?? null,
63
+ taskProject: options.taskProject ?? null,
64
+ taskGeneration: options.taskGeneration ?? null,
65
+ };
66
+ const hasContext = !!(ctx.threadId || ctx.profile || ctx.project || ctx.sessionName || ctx.trackSessionId ||
67
+ ctx.executionId || ctx.useCoreMcp || ctx.threadDepth != null || ctx.taskId ||
68
+ ctx.taskProject || ctx.taskGeneration);
69
+ // Load global rules (no paths frontmatter) and inject as appendSystemPrompt.
70
+ // Scoped rules (with paths) are handled by the Read/Grep PostToolUse hook.
71
+ const rules = options.loadCortexRules === false ? [] : loadCortexRules().global;
72
+ const appendSystemPrompt = rules.length > 0
73
+ ? rules.map(rule => rule.body).join('\n\n---\n\n')
74
+ : undefined;
75
+ return {
76
+ sessionId: options.sessionId ?? null,
77
+ sessionKey: options.sessionKey || options.channel || 'default',
78
+ resume: !!options.sessionId,
79
+ model: config.model,
80
+ systemPrompt: typeof options.systemPrompt === 'string' ? options.systemPrompt : undefined,
81
+ outputStyle: typeof options.outputStyle === 'string' ? options.outputStyle : undefined,
82
+ cwd: options.cwd,
83
+ mcpComposition: resolveMcpComposition(options.mcpComposition, options.useCoreMcp),
84
+ mcpConfigPaths: options.mcpConfigPaths,
85
+ disableHooks: options.disableHooks,
86
+ streamDeltas: options.streamDeltas,
87
+ captureTranscriptLogs: options.captureTranscriptLogs,
88
+ preserveUnreportedAccounting: options.preserveUnreportedAccounting,
89
+ processSpawner: options.processSpawner,
90
+ cliPath: typeof options.cliPath === 'string' ? options.cliPath : undefined,
91
+ benchmarkPolicyGuard: options.benchmarkPolicyGuard,
92
+ pinnedEnv: options.pinnedEnv,
93
+ benchmarkDeadlineEpochMs: options.benchmarkDeadlineEpochMs,
94
+ pluginDirs: filterChannelScopedPlugins(Array.isArray(options.pluginDirs) ? options.pluginDirs : undefined, options.channel),
95
+ env: config.extraEnv && Object.keys(config.extraEnv).length > 0 ? config.extraEnv : undefined,
96
+ extraOption: config.extraOption && Object.keys(config.extraOption).length > 0 ? config.extraOption : undefined,
97
+ claudeBackend: config.claudeBackend,
98
+ thinking: config.thinking || undefined,
99
+ channel: options.channel,
100
+ claudeAgent: options.claudeAgent ?? undefined,
101
+ callbackSource: options.callbackSource ?? undefined,
102
+ scheduleTaskId: options.scheduleTaskId ?? undefined,
103
+ isUserInitiated: !!options.isUserInitiated,
104
+ rawTools: typeof options.tools === 'string' ? options.tools : undefined,
105
+ anthropicBaseUrl,
106
+ // PI-specific routing: provider name (= profile mode) + gateway base URL. PI adapter writes
107
+ // a multi-provider models.json (writeProvidersConfig) so every PI provider lands on the
108
+ // gateway. Claude ignores these fields.
109
+ // PI routing: `provider` is the --provider (protocol; required for pi, validated at load — no
110
+ // default). The gateway sub-path `/m/<mode>/<provider>` is derived from the profile's logical
111
+ // `mode` (gateway.yaml owns the route).
112
+ piProvider: config.backend === 'pi' && config.provider ? config.provider : undefined,
113
+ piGatewayPath: config.backend === 'pi' && config.provider ? buildPiGatewaySubPath(config.mode, config.provider) : undefined,
114
+ // The host gateway authority, never the resolved Claude route: that URL already carries a
115
+ // `/m/<mode>/…/anthropic` path, and PI appends `piGatewayPath` to whatever it is given.
116
+ // P12: a trial is routed at its own proxy authority, which its factory writes over this default.
117
+ piGatewayBaseUrl: config.backend === 'pi' ? GATEWAY_URL : undefined,
118
+ cortexContext: hasContext ? ctx : undefined,
119
+ appendSystemPrompt,
120
+ };
121
+ }
@@ -0,0 +1,98 @@
1
+ export declare const ACCOUNTING_RECORD_SCHEMA_VERSION = "cortex-bench-accounting/1";
2
+ export declare const PROXY_EXPORT_SCHEMA_VERSION = "cortex-bench-proxy-export/1";
3
+ /**
4
+ * Every figure is a tagged union rather than a number, so "the counter was never read" and "the
5
+ * counter read zero" cannot share a representation. A rule that merely forbids zero is violated by
6
+ * the next default initialiser; a shape that cannot hold a bare number is not.
7
+ */
8
+ export type Available<T> = {
9
+ readonly status: 'available';
10
+ readonly value: T;
11
+ };
12
+ export type Unavailable = {
13
+ readonly status: 'unavailable';
14
+ readonly reason: UnavailableReason;
15
+ };
16
+ export type Tagged<T> = Available<T> | Unavailable;
17
+ /** Closed on purpose: a reason the other side of the seam does not know is a refusal, not a pass. */
18
+ export declare const UNAVAILABLE_REASONS: readonly ["proxy_not_started", "counter_unreadable", "audit_log_unreadable", "no_echo_received", "journal_absent", "journal_underivable", "operand_unavailable"];
19
+ export type UnavailableReason = typeof UNAVAILABLE_REASONS[number];
20
+ export declare const ACCOUNTING_CHECK_IDS: readonly ["accounting_requests_mismatch", "accounting_cost_out_of_tolerance", "accounting_operand_unavailable"];
21
+ export type AccountingCheckId = typeof ACCOUNTING_CHECK_IDS[number];
22
+ export interface AccountingCheck {
23
+ readonly check_id: AccountingCheckId;
24
+ readonly passed: boolean;
25
+ readonly failure_code: number | null;
26
+ readonly detail: string;
27
+ }
28
+ export interface ProxyAccounting {
29
+ readonly requests: Tagged<number>;
30
+ readonly cost_usd: Tagged<string>;
31
+ readonly input_tokens: Tagged<number>;
32
+ readonly output_tokens: Tagged<number>;
33
+ readonly audit_log: Tagged<Record<string, unknown>>;
34
+ readonly lease_echo: Tagged<Record<string, unknown>>;
35
+ readonly source: 'proxy_export';
36
+ }
37
+ export interface ProxyExport extends ProxyAccounting {
38
+ readonly schema_version: typeof PROXY_EXPORT_SCHEMA_VERSION;
39
+ readonly trial_id: string;
40
+ readonly adapter_id: string;
41
+ }
42
+ export interface JournalAccounting {
43
+ readonly requests: Tagged<number>;
44
+ readonly cost_usd: Tagged<string>;
45
+ readonly steps: Tagged<number>;
46
+ readonly tokens: {
47
+ readonly input: Tagged<number>;
48
+ readonly output: Tagged<number>;
49
+ readonly cached: Tagged<number>;
50
+ };
51
+ readonly source: 'trajectory_merge';
52
+ }
53
+ export interface JournalTotals extends JournalAccounting {
54
+ /** The roles the attempt DAG did account for, so an excess can be reported against a named set. */
55
+ readonly roles: readonly string[];
56
+ }
57
+ /**
58
+ * Declared arm policy, frozen at compile and recorded in the record so a reader can see what was
59
+ * applied. `requests_abs` is the literal 0: a request either traversed the proxy or it did not, and
60
+ * a count has no rounding, so widening it is a type error rather than a judgement call.
61
+ */
62
+ export interface AccountingTolerance {
63
+ readonly requests_abs: 0;
64
+ readonly cost_usd_rel: string;
65
+ readonly cost_usd_abs_floor: string;
66
+ }
67
+ export declare const DEFAULT_ACCOUNTING_TOLERANCE: AccountingTolerance;
68
+ /** The proxy metered requests the attempt DAG never claimed — OC-11's observable, listed not hidden. */
69
+ export interface UnaccountedRole {
70
+ readonly kind: 'proxy_excess';
71
+ readonly journal_roles: readonly string[];
72
+ readonly requests: Tagged<number>;
73
+ readonly cost_usd: Tagged<string>;
74
+ }
75
+ export interface AccountingRecord {
76
+ readonly schema_version: typeof ACCOUNTING_RECORD_SCHEMA_VERSION;
77
+ readonly trial_id: string;
78
+ readonly proxy: ProxyAccounting;
79
+ readonly journal: JournalAccounting;
80
+ readonly tolerance: AccountingTolerance;
81
+ readonly deltas: {
82
+ readonly requests: Tagged<number>;
83
+ readonly cost_usd: Tagged<string>;
84
+ };
85
+ readonly reconciled: Tagged<boolean>;
86
+ readonly unaccounted_roles: readonly UnaccountedRole[];
87
+ readonly checks: readonly AccountingCheck[];
88
+ }
89
+ export declare class AccountingInputError extends Error {
90
+ constructor(detail: string);
91
+ }
92
+ /**
93
+ * Compare the proxy's own totals against the journal's. Pure: it reads its two arguments, mutates
94
+ * neither and writes nothing. Gate 4 places the result verbatim; it does not re-derive it.
95
+ */
96
+ export declare function reconcileAccounting(proxyExport: ProxyExport, journalTotals: JournalTotals, tolerance?: AccountingTolerance): AccountingRecord;
97
+ /** The journal reports cost as a JavaScript number; costs are compared as decimal strings. */
98
+ export declare function journalCostFromNumber(value: unknown): Tagged<string>;
@@ -0,0 +1,218 @@
1
+ // input: the proxy-authoritative export, journal-derived totals, the arm's tolerance
2
+ // output: the accounting record, its tagged figures, deltas and check ids
3
+ // pos: Pure §9.6 A1-A5 accounting reconciliation
4
+ // >>> 一旦我被更新,务必更新我的开头注释与所属文件夹 CORTEX.md <<<
5
+ import { absDecimal, compareDecimal, decimalFromNumber, decimalText, isDecimalText, maxDecimal, multiplyDecimal, parseDecimal, subtractDecimal, } from './decimal-text.js';
6
+ import { BENCHMARK_FAILURES } from './resolved-policy.js';
7
+ export const ACCOUNTING_RECORD_SCHEMA_VERSION = 'cortex-bench-accounting/1';
8
+ export const PROXY_EXPORT_SCHEMA_VERSION = 'cortex-bench-proxy-export/1';
9
+ /** Closed on purpose: a reason the other side of the seam does not know is a refusal, not a pass. */
10
+ export const UNAVAILABLE_REASONS = [
11
+ 'proxy_not_started', 'counter_unreadable', 'audit_log_unreadable', 'no_echo_received',
12
+ 'journal_absent', 'journal_underivable', 'operand_unavailable',
13
+ ];
14
+ export const ACCOUNTING_CHECK_IDS = [
15
+ 'accounting_requests_mismatch', 'accounting_cost_out_of_tolerance',
16
+ 'accounting_operand_unavailable',
17
+ ];
18
+ /** No new failure code is allocated: the distinctions ride as check ids on the shipped code 41. */
19
+ const TERMINAL_PREDICATE_UNMET = BENCHMARK_FAILURES
20
+ .find(failure => failure.reason === 'terminal_predicate_unmet').code;
21
+ export const DEFAULT_ACCOUNTING_TOLERANCE = Object.freeze({
22
+ requests_abs: 0, cost_usd_rel: '0.01', cost_usd_abs_floor: '0.000001',
23
+ });
24
+ export class AccountingInputError extends Error {
25
+ constructor(detail) {
26
+ super(`accounting input invalid: ${detail}`);
27
+ this.name = 'AccountingInputError';
28
+ }
29
+ }
30
+ /**
31
+ * Compare the proxy's own totals against the journal's. Pure: it reads its two arguments, mutates
32
+ * neither and writes nothing. Gate 4 places the result verbatim; it does not re-derive it.
33
+ */
34
+ export function reconcileAccounting(proxyExport, journalTotals, tolerance = DEFAULT_ACCOUNTING_TOLERANCE) {
35
+ assertTolerance(tolerance);
36
+ const proxy = readProxy(proxyExport);
37
+ const journal = readJournal(journalTotals);
38
+ const missing = unavailableOperands(proxy, journal);
39
+ const requests = compareRequests(proxy.requests, journal.requests);
40
+ const cost = compareCost(proxy.cost_usd, journal.cost_usd, tolerance);
41
+ return deepFreeze({
42
+ schema_version: ACCOUNTING_RECORD_SCHEMA_VERSION,
43
+ trial_id: assertTrialId(proxyExport.trial_id),
44
+ proxy,
45
+ journal,
46
+ tolerance: { ...tolerance },
47
+ deltas: { requests: requests.delta, cost_usd: cost.delta },
48
+ reconciled: reconciledFlag(missing, [requests, cost]),
49
+ unaccounted_roles: unaccountedRoles(proxy, journal, journalTotals.roles),
50
+ checks: buildChecks(missing, [requests, cost]),
51
+ });
52
+ }
53
+ /** The journal reports cost as a JavaScript number; costs are compared as decimal strings. */
54
+ export function journalCostFromNumber(value) {
55
+ if (typeof value !== 'number' || !Number.isFinite(value) || value < 0) {
56
+ return { status: 'unavailable', reason: 'journal_underivable' };
57
+ }
58
+ return { status: 'available', value: decimalText(decimalFromNumber(value)) };
59
+ }
60
+ const OPERAND_PATHS = [
61
+ 'proxy.requests', 'proxy.cost_usd', 'proxy.lease_echo',
62
+ 'journal.requests', 'journal.cost_usd',
63
+ ];
64
+ function unavailableOperands(proxy, journal) {
65
+ const slots = [
66
+ proxy.requests, proxy.cost_usd, proxy.lease_echo, journal.requests, journal.cost_usd,
67
+ ];
68
+ return OPERAND_PATHS.filter((_path, index) => slots[index].status === 'unavailable');
69
+ }
70
+ function compareRequests(proxy, journal) {
71
+ if (proxy.status !== 'available' || journal.status !== 'available')
72
+ return notComparable();
73
+ const delta = proxy.value - journal.value;
74
+ return {
75
+ delta: { status: 'available', value: delta },
76
+ check: check('accounting_requests_mismatch', delta === 0, `proxy ${proxy.value} journal ${journal.value}`),
77
+ };
78
+ }
79
+ function compareCost(proxy, journal, tolerance) {
80
+ if (proxy.status !== 'available' || journal.status !== 'available')
81
+ return notComparable();
82
+ const observed = parseDecimal(proxy.value);
83
+ const delta = subtractDecimal(observed, parseDecimal(journal.value));
84
+ const limit = costLimit(observed, tolerance);
85
+ return {
86
+ delta: { status: 'available', value: decimalText(delta) },
87
+ check: check('accounting_cost_out_of_tolerance', compareDecimal(absDecimal(delta), limit) <= 0, `delta ${decimalText(delta)} tolerance ${decimalText(limit)}`),
88
+ };
89
+ }
90
+ /** The floor exists so a near-zero trial is not compared by ratio. */
91
+ function costLimit(observed, tolerance) {
92
+ const relative = absDecimal(multiplyDecimal(observed, parseDecimal(tolerance.cost_usd_rel)));
93
+ return maxDecimal(parseDecimal(tolerance.cost_usd_abs_floor), relative);
94
+ }
95
+ function notComparable() {
96
+ return { delta: { status: 'unavailable', reason: 'operand_unavailable' }, check: null };
97
+ }
98
+ function check(id, passed, detail) {
99
+ return { check_id: id, passed, failure_code: passed ? null : TERMINAL_PREDICATE_UNMET, detail };
100
+ }
101
+ /** R-A5-2: a missing operand is neither a mismatch nor a match, so it is neither false nor true. */
102
+ function reconciledFlag(missing, comparisons) {
103
+ if (missing.length > 0)
104
+ return { status: 'unavailable', reason: 'operand_unavailable' };
105
+ return {
106
+ status: 'available',
107
+ value: comparisons.every(comparison => comparison.check?.passed === true),
108
+ };
109
+ }
110
+ function buildChecks(missing, comparisons) {
111
+ const evaluated = comparisons
112
+ .map(comparison => comparison.check)
113
+ .filter((entry) => entry !== null);
114
+ if (missing.length === 0)
115
+ return evaluated;
116
+ return [check('accounting_operand_unavailable', false, missing.join(', ')), ...evaluated];
117
+ }
118
+ /**
119
+ * A4 detection. The proxy meters by route and source IP, so every role's traffic is inside its
120
+ * totals by construction; the journal side is the one that can miss a role. An excess is listed
121
+ * here rather than absorbed into the tolerance, because absorbing it is how OC-11 disappears.
122
+ */
123
+ function unaccountedRoles(proxy, journal, roles) {
124
+ if (proxy.requests.status !== 'available' || journal.requests.status !== 'available')
125
+ return [];
126
+ const excess = proxy.requests.value - journal.requests.value;
127
+ if (excess <= 0)
128
+ return [];
129
+ return [{
130
+ kind: 'proxy_excess',
131
+ journal_roles: [...roles],
132
+ requests: { status: 'available', value: excess },
133
+ cost_usd: costExcess(proxy.cost_usd, journal.cost_usd),
134
+ }];
135
+ }
136
+ function costExcess(proxy, journal) {
137
+ if (proxy.status !== 'available' || journal.status !== 'available') {
138
+ return { status: 'unavailable', reason: 'operand_unavailable' };
139
+ }
140
+ const delta = subtractDecimal(parseDecimal(proxy.value), parseDecimal(journal.value));
141
+ return { status: 'available', value: decimalText(maxDecimal(delta, parseDecimal('0'))) };
142
+ }
143
+ function readProxy(document) {
144
+ assertMember(document?.schema_version === PROXY_EXPORT_SCHEMA_VERSION, 'proxy.schema_version');
145
+ assertMember(document.source === 'proxy_export', 'proxy.source');
146
+ return {
147
+ requests: taggedCount(document.requests, 'proxy.requests'),
148
+ cost_usd: taggedDecimal(document.cost_usd, 'proxy.cost_usd'),
149
+ input_tokens: taggedCount(document.input_tokens, 'proxy.input_tokens'),
150
+ output_tokens: taggedCount(document.output_tokens, 'proxy.output_tokens'),
151
+ audit_log: taggedObject(document.audit_log, 'proxy.audit_log'),
152
+ lease_echo: taggedObject(document.lease_echo, 'proxy.lease_echo'),
153
+ source: 'proxy_export',
154
+ };
155
+ }
156
+ function readJournal(totals) {
157
+ assertMember(totals?.source === 'trajectory_merge', 'journal.source');
158
+ assertMember(Array.isArray(totals.roles), 'journal.roles');
159
+ return {
160
+ requests: taggedCount(totals.requests, 'journal.requests'),
161
+ cost_usd: taggedDecimal(totals.cost_usd, 'journal.cost_usd'),
162
+ steps: taggedCount(totals.steps, 'journal.steps'),
163
+ tokens: {
164
+ input: taggedCount(totals.tokens?.input, 'journal.tokens.input'),
165
+ output: taggedCount(totals.tokens?.output, 'journal.tokens.output'),
166
+ cached: taggedCount(totals.tokens?.cached, 'journal.tokens.cached'),
167
+ },
168
+ source: 'trajectory_merge',
169
+ };
170
+ }
171
+ function tagged(slot, path, shape) {
172
+ assertMember(typeof slot === 'object' && slot !== null, path);
173
+ const entry = slot;
174
+ if (entry.status === 'unavailable') {
175
+ assertMember(UNAVAILABLE_REASONS.includes(entry.reason), `${path}.reason`);
176
+ return { status: 'unavailable', reason: entry.reason };
177
+ }
178
+ assertMember(entry.status === 'available', `${path}.status`);
179
+ assertMember(shape(entry.value), `${path}.value`);
180
+ return { status: 'available', value: entry.value };
181
+ }
182
+ function taggedCount(slot, path) {
183
+ return tagged(slot, path, value => Number.isSafeInteger(value) && value >= 0);
184
+ }
185
+ function taggedDecimal(slot, path) {
186
+ return tagged(slot, path, value => isDecimalText(value) && !value.startsWith('-'));
187
+ }
188
+ function taggedObject(slot, path) {
189
+ const entry = tagged(slot, path, value => typeof value === 'object' && value !== null);
190
+ // The record is frozen on the way out. An opaque block carried through by reference would be
191
+ // frozen inside the caller's own document too, which is a mutation of an input however equal its
192
+ // values still compare afterwards.
193
+ if (entry.status !== 'available')
194
+ return entry;
195
+ return { status: 'available', value: structuredClone(entry.value) };
196
+ }
197
+ function assertTolerance(tolerance) {
198
+ assertMember(tolerance?.requests_abs === 0, 'tolerance.requests_abs');
199
+ for (const member of ['cost_usd_rel', 'cost_usd_abs_floor']) {
200
+ assertMember(isDecimalText(tolerance[member]), `tolerance.${member}`);
201
+ assertMember(!tolerance[member].startsWith('-'), `tolerance.${member}`);
202
+ }
203
+ }
204
+ function assertTrialId(trialId) {
205
+ assertMember(typeof trialId === 'string' && trialId.length > 0, 'proxy.trial_id');
206
+ return trialId;
207
+ }
208
+ function assertMember(valid, path) {
209
+ if (!valid)
210
+ throw new AccountingInputError(path);
211
+ }
212
+ function deepFreeze(document) {
213
+ for (const value of Object.values(document)) {
214
+ if (value !== null && typeof value === 'object')
215
+ deepFreeze(value);
216
+ }
217
+ return Object.freeze(document);
218
+ }
@@ -0,0 +1,43 @@
1
+ export declare const ARM_SCHEMA_VERSION: "cortex-benchmark-arm/2";
2
+ export declare const ARM_RESOLUTION_SCHEMA_VERSION: "cortex-benchmark-arm-resolution/1";
3
+ export type ArmKind = 'cortex' | 'vendor-baseline';
4
+ export type OrchestrationMode = 'direct' | 'coder-review' | 'manager';
5
+ export type CoderReviewVariant = 'audit-retry' | 'reviewer-fix';
6
+ export type VendorAgent = 'claude-code' | 'pi' | 'codex';
7
+ export interface ArmLimits {
8
+ max_thread_starts: number;
9
+ max_parent_questions: number;
10
+ max_task_depth: number;
11
+ max_tasks: number;
12
+ max_provider_requests: number;
13
+ max_resident_agent_processes: number;
14
+ max_cost_usd: string;
15
+ deadline_seconds: number;
16
+ }
17
+ export interface ArmOrchestration {
18
+ mode: OrchestrationMode;
19
+ coder_review_variant?: CoderReviewVariant;
20
+ ask_manager: boolean;
21
+ }
22
+ export interface ArmDefinition {
23
+ schema_version: typeof ARM_SCHEMA_VERSION;
24
+ kind: ArmKind;
25
+ name: string;
26
+ backend?: 'claude' | 'pi';
27
+ vendor_agent?: VendorAgent;
28
+ provider: string | null;
29
+ model: string;
30
+ credential_capability: string;
31
+ orchestration?: ArmOrchestration;
32
+ limits: ArmLimits;
33
+ }
34
+ export type ArmValidationReason = 'arm_schema_invalid' | 'arm_field_conflict' | 'coder_review_variant_invalid' | 'ask_manager_unsupported_mode' | 'limit_out_of_range' | 'capacity_rule_violated';
35
+ export declare class ArmValidationError extends Error {
36
+ readonly reason: ArmValidationReason;
37
+ constructor(reason: ArmValidationReason, detail: string);
38
+ }
39
+ export declare function validateArmResolutionShape(value: unknown): void;
40
+ export declare function parseArmDefinitionForCompiler(value: unknown): ArmDefinition;
41
+ export declare function validateArmPostCredential(arm: ArmDefinition): void;
42
+ export declare function parseArmDefinition(value: unknown): ArmDefinition;
43
+ export declare function parseArmDefinitionSet(values: unknown[]): ArmDefinition[];