@tangle-network/agent-runtime 0.348.1 → 0.350.2
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/dist/{activation-BEGalhOL.js → activation-CfJMyzEs.js} +12 -14
- package/dist/{activation-BEGalhOL.js.map → activation-CfJMyzEs.js.map} +1 -1
- package/dist/{activation-NQZP_mdI.d.ts → activation-DyiHrTlS.d.ts} +2 -24
- package/dist/agent.d.ts +8 -12
- package/dist/agent.js +9 -12
- package/dist/agent.js.map +1 -1
- package/dist/{analyst-loop-DZw5QWT9.js → analyst-loop-BZvXCDKy.js} +2 -3
- package/dist/{analyst-loop-DZw5QWT9.js.map → analyst-loop-BZvXCDKy.js.map} +1 -1
- package/dist/analyst-loop.d.ts +3 -5
- package/dist/analyst-loop.js +1 -2
- package/dist/{bundle-DKQtOO9d.js → bundle-Ze8pd07a.js} +3 -4
- package/dist/{bundle-DKQtOO9d.js.map → bundle-Ze8pd07a.js.map} +1 -1
- package/dist/candidate-execution/index.d.ts +13 -33
- package/dist/candidate-execution/index.js +16 -18
- package/dist/candidate-execution/index.js.map +1 -1
- package/dist/{coordination-manager-Bm6leXc6.js → coordination-manager-BkVfWlMz.js} +101 -132
- package/dist/coordination-manager-BkVfWlMz.js.map +1 -0
- package/dist/{delegate-Cp5-PsaX.js → delegate-DgEie4ad.js} +19 -21
- package/dist/delegate-DgEie4ad.js.map +1 -0
- package/dist/durable.d.ts +13 -23
- package/dist/durable.js +48 -43
- package/dist/durable.js.map +1 -1
- package/dist/{errors-DodWX-cb.js → errors-wuhGvpE3.js} +2 -3
- package/dist/{errors-DodWX-cb.js.map → errors-wuhGvpE3.js.map} +1 -1
- package/dist/{graph-CE_pzU31.js → graph-Cx0FhKSE.js} +192 -15
- package/dist/graph-Cx0FhKSE.js.map +1 -0
- package/dist/{improve-wT11zteg.js → improve-i0HU1-aa.js} +35 -53
- package/dist/{improve-wT11zteg.js.map → improve-i0HU1-aa.js.map} +1 -1
- package/dist/{improvement-adapter-sIthWkcN.d.ts → improvement-adapter-D5GRU1eY.d.ts} +2 -6
- package/dist/index.d.ts +41 -89
- package/dist/index.js +43 -61
- package/dist/index.js.map +1 -1
- package/dist/intelligence.d.ts +39 -59
- package/dist/intelligence.js +23 -33
- package/dist/intelligence.js.map +1 -1
- package/dist/kernel.d.ts +5 -5
- package/dist/kernel.js +11 -11
- package/dist/{loop-runner-CZzeeJTG.js → loop-runner-BwN9MhdP.js} +5 -6
- package/dist/{loop-runner-CZzeeJTG.js.map → loop-runner-BwN9MhdP.js.map} +1 -1
- package/dist/{loop-runner-CY5HHhtR.d.ts → loop-runner-DvfOXVx9.d.ts} +3 -5
- package/dist/loop-runner-bin.d.ts +5 -8
- package/dist/loop-runner-bin.js +2 -3
- package/dist/mcp/bin.js +6 -8
- package/dist/mcp/bin.js.map +1 -1
- package/dist/mcp/index.d.ts +8 -18
- package/dist/mcp/index.js +17 -25
- package/dist/mcp/index.js.map +1 -1
- package/dist/mcp/memory-bin.js +4 -6
- package/dist/mcp/memory-bin.js.map +1 -1
- package/dist/{model-policy-CyCUwHed.js → model-policy-GSxWwP-b.js} +11 -13
- package/dist/model-policy-GSxWwP-b.js.map +1 -0
- package/dist/placement.d.ts +12 -14
- package/dist/placement.js +1 -2
- package/dist/platform.d.ts +7 -13
- package/dist/platform.js +3 -6
- package/dist/platform.js.map +1 -1
- package/dist/{prepare-TEEHSJwq.js → prepare-DE8TQnLu.js} +49 -69
- package/dist/{prepare-TEEHSJwq.js.map → prepare-DE8TQnLu.js.map} +1 -1
- package/dist/{profile-6OLpbjvV.js → profile-CAhZDW2T.js} +58 -92
- package/dist/profile-CAhZDW2T.js.map +1 -0
- package/dist/{profile-materialization-bPm0gGLO.d.ts → profile-materialization-BRY22Oh8.d.ts} +1 -3
- package/dist/profiles.d.ts +25 -12
- package/dist/profiles.js +52 -11
- package/dist/profiles.js.map +1 -1
- package/dist/{protected-model-port-DVVh-hEk.d.ts → protected-model-port-IKqhTypD.d.ts} +2 -14
- package/dist/{protected-redaction-DFCeo4vg.js → protected-redaction-DilFZch5.js} +2 -3
- package/dist/{protected-redaction-DFCeo4vg.js.map → protected-redaction-DilFZch5.js.map} +1 -1
- package/dist/{provision-supervisor-CC0HdOHo.js → provision-supervisor-Bde_FF0R.js} +11 -15
- package/dist/{provision-supervisor-CC0HdOHo.js.map → provision-supervisor-Bde_FF0R.js.map} +1 -1
- package/dist/{record-events-D93DkpAx.js → record-events-B2GUgYdz.js} +12 -14
- package/dist/{record-events-D93DkpAx.js.map → record-events-B2GUgYdz.js.map} +1 -1
- package/dist/{run-cancellation-CzFhQGMa.js → run-cancellation-BLy_Zz-w.js} +6 -7
- package/dist/{run-cancellation-CzFhQGMa.js.map → run-cancellation-BLy_Zz-w.js.map} +1 -1
- package/dist/{runtime-B_40dXlF.js → runtime-6Ec9sHRe.js} +833 -215
- package/dist/runtime-6Ec9sHRe.js.map +1 -0
- package/dist/{runtime-hooks-tXpAarhW.js → runtime-hooks-CsW2pfFk.js} +2 -3
- package/dist/{runtime-hooks-tXpAarhW.js.map → runtime-hooks-CsW2pfFk.js.map} +1 -1
- package/dist/{runtime-hooks-nsqxSUFL.d.ts → runtime-hooks-ZQqPw-0g.d.ts} +1 -3
- package/dist/{sandbox-profile-compat-_fEtHPCj.js → sandbox-profile-compat-BxMQ1VXv.js} +62 -44
- package/dist/sandbox-profile-compat-BxMQ1VXv.js.map +1 -0
- package/dist/{search-executor-COd2F2wp.js → search-executor-B7g_5Wjl.js} +12 -17
- package/dist/search-executor-B7g_5Wjl.js.map +1 -0
- package/dist/{server-BGB4R4wQ.js → server-fvEMwGMQ.js} +19 -30
- package/dist/{server-BGB4R4wQ.js.map → server-fvEMwGMQ.js.map} +1 -1
- package/dist/{structural-rollout-Wl_rCuzM.js → structural-rollout-B86bSixU.js} +69 -70
- package/dist/structural-rollout-B86bSixU.js.map +1 -0
- package/dist/{substrate-CGDFTSRh.js → substrate-Db2pp6y3.js} +2 -3
- package/dist/{substrate-CGDFTSRh.js.map → substrate-Db2pp6y3.js.map} +1 -1
- package/dist/{supervise-BUOeThuB.js → supervise-CaeZcgAW.js} +615 -203
- package/dist/supervise-CaeZcgAW.js.map +1 -0
- package/dist/{supervisor-DDy0aEtR.js → supervisor-C1OePYE-.js} +526 -642
- package/dist/supervisor-C1OePYE-.js.map +1 -0
- package/dist/{task-queue-0fKkoweu.d.ts → task-queue-kefGy79U.d.ts} +1 -3
- package/dist/task-queue.d.ts +1 -1
- package/dist/task-queue.js +1 -2
- package/dist/testing.d.ts +8 -16
- package/dist/testing.js +241 -244
- package/dist/testing.js.map +1 -1
- package/dist/tool-loop.d.ts +16 -19
- package/dist/tool-loop.js +2 -3
- package/dist/{tool-server-XV4aJwoQ.js → tool-server-CwuYeW_Z.js} +3 -4
- package/dist/{tool-server-XV4aJwoQ.js.map → tool-server-CwuYeW_Z.js.map} +1 -1
- package/dist/{top-snapshot-CflmaDgk.js → top-snapshot-ChwpTr7A.js} +4 -5
- package/dist/{top-snapshot-CflmaDgk.js.map → top-snapshot-ChwpTr7A.js.map} +1 -1
- package/dist/tui/bin.js +7 -9
- package/dist/tui/bin.js.map +1 -1
- package/dist/tui/index.d.ts +3 -5
- package/dist/tui/index.js +2 -2
- package/dist/{types-hc4cmSc7.d.ts → types-Fowuwdz2.d.ts} +555 -503
- package/dist/{types-Cwrea-bU.d.ts → types-qsqfyQoY.d.ts} +1 -3
- package/dist/workspace-store/index.d.ts +12 -22
- package/dist/workspace-store/index.js +4 -7
- package/dist/workspace-store/index.js.map +1 -1
- package/dist/{workspace-streams-BiS4ABah.d.ts → workspace-streams-Dq2Fzk3c.d.ts} +1 -11
- package/package.json +25 -25
- package/skills/agent-graphs/SKILL.md +19 -4
- package/skills/be-ambitious/SKILL.md +46 -0
- package/skills/graph-designer/SKILL.md +15 -2
- package/skills/profile-authoring/SKILL.md +1 -1
- package/dist/coordination-manager-Bm6leXc6.js.map +0 -1
- package/dist/delegate-Cp5-PsaX.js.map +0 -1
- package/dist/graph-CE_pzU31.js.map +0 -1
- package/dist/model-policy-CyCUwHed.js.map +0 -1
- package/dist/profile-6OLpbjvV.js.map +0 -1
- package/dist/runtime-B_40dXlF.js.map +0 -1
- package/dist/sandbox-profile-compat-_fEtHPCj.js.map +0 -1
- package/dist/search-executor-COd2F2wp.js.map +0 -1
- package/dist/structural-rollout-Wl_rCuzM.js.map +0 -1
- package/dist/supervise-BUOeThuB.js.map +0 -1
- package/dist/supervisor-DDy0aEtR.js.map +0 -1
package/dist/testing.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"testing.js","names":["canonicalAgentImprovementProposalFixture","canonicalAgentProfileImprovementProposalFixture","canonicalAgentProfileImprovementStateFixture","canonicalCandidateDigest"],"sources":["../src/testing/fixtures/agent-improvement-proposal.json","../src/testing/fixtures/agent-profile-improvement-proposal.json","../src/testing/fixtures/agent-profile-improvement-state.json","../src/testing/index.ts"],"sourcesContent":["","","","import {\n type AgentImprovementProposal,\n type AgentProfile,\n type AgentProfileImprovementMeasuredComparison,\n canonicalAgentProfileDigest,\n SANDBOX_SIZE_PRESET_NAMES,\n type SandboxSizePreset,\n} from '@tangle-network/agent-interface'\n\nimport { canonicalCandidateDigest, immutableCandidateValue } from '../candidate-execution/digest'\nimport { applyExactAgentProfileDiff, parseExactAgentProfile } from '../candidate-execution/profile'\nimport { verifyAgentImprovementProposal } from '../intelligence/activation'\nimport canonicalAgentImprovementProposalFixture from './fixtures/agent-improvement-proposal.json'\nimport canonicalAgentProfileImprovementProposalFixture from './fixtures/agent-profile-improvement-proposal.json'\nimport canonicalAgentProfileImprovementStateFixture from './fixtures/agent-profile-improvement-state.json'\n\nexport type { DriverAgentOptions } from '../runtime/supervise/driver-agent-options'\nexport { driverAgent } from '../runtime/supervise/driver-brain-agent'\nexport { type RunGraphTestOptions, runGraphWithTestBrain } from '../runtime/supervise/graph'\nexport { superviseWithTestBrain } from '../runtime/supervise/supervise'\nexport { supervisorAgentWithTestBrain } from '../runtime/supervise/supervisor-agent'\nexport type { ToolLoopCallContext, ToolLoopChat } from '../runtime/tool-loop'\n\nconst serializedAgentImprovementProposalFixture = JSON.stringify(\n canonicalAgentImprovementProposalFixture,\n)\nconst serializedAgentProfileImprovementProposalFixture = JSON.stringify(\n canonicalAgentProfileImprovementProposalFixture,\n)\nconst serializedAgentProfileImprovementStateFixture = JSON.stringify(\n canonicalAgentProfileImprovementStateFixture,\n)\n\n/** A proposal produced by Runtime's opaque profile-improvement path. */\nexport type AgentProfileImprovementProposalFixture = Omit<\n AgentImprovementProposal,\n 'evaluation'\n> & {\n evaluation: AgentProfileImprovementMeasuredComparison\n}\n\n/** Complete private state for exercising profile activation and restore in consumer tests. */\nexport interface AgentProfileImprovementFixture {\n proposal: AgentProfileImprovementProposalFixture\n baselineProfile: AgentProfile\n candidateProfile: AgentProfile\n recommendedSize: SandboxSizePreset\n}\n\n/** Load an isolated, production-validated Runtime proposal for consumer tests. */\nexport function loadAgentImprovementProposalFixture(): AgentImprovementProposal {\n return verifyAgentImprovementProposal(JSON.parse(serializedAgentImprovementProposalFixture))\n}\n\n/** Load an isolated profile proposal and its private activation state for consumer tests. */\nexport function loadAgentProfileImprovementFixture(): AgentProfileImprovementFixture {\n const proposal = loadAgentProfileImprovementProposal()\n const state = parseAgentProfileImprovementState(\n JSON.parse(serializedAgentProfileImprovementStateFixture),\n )\n const experiment = proposal.evaluation.experiment\n const baselineStateDigest = profileStateDigest(state.baselineProfile, state.recommendedSize)\n const candidateStateDigest = profileStateDigest(state.candidateProfile, state.recommendedSize)\n if (\n baselineStateDigest !== experiment.baseline.stateDigest ||\n candidateStateDigest !== experiment.candidate.stateDigest\n ) {\n throw new Error('profile improvement fixture state does not match its proposal')\n }\n const appliedCandidate = experiment.change.reduce(\n (profile, change, index) =>\n applyExactAgentProfileDiff(profile, change, `profile improvement fixture change ${index}`),\n state.baselineProfile,\n )\n if (\n canonicalAgentProfileDigest(appliedCandidate) !==\n canonicalAgentProfileDigest(state.candidateProfile)\n ) {\n throw new Error('profile improvement fixture candidate does not match its proposal changes')\n }\n return immutableCandidateValue({ proposal, ...state })\n}\n\nfunction loadAgentProfileImprovementProposal(): AgentProfileImprovementProposalFixture {\n const proposal = verifyAgentImprovementProposal(\n JSON.parse(serializedAgentProfileImprovementProposalFixture),\n )\n if (proposal.evaluation.kind !== 'agent-profile-improvement-measured-comparison') {\n throw new Error('profile improvement fixture contains a sealed candidate comparison')\n }\n return { ...proposal, evaluation: proposal.evaluation }\n}\n\nfunction parseAgentProfileImprovementState(\n input: unknown,\n): Omit<AgentProfileImprovementFixture, 'proposal'> {\n if (typeof input !== 'object' || input === null || Array.isArray(input)) {\n throw new Error('profile improvement fixture state must be an object')\n }\n const record = input as Record<string, unknown>\n const fields = Object.keys(record).sort()\n const expectedFields = ['baselineProfile', 'candidateProfile', 'recommendedSize']\n if (\n fields.length !== expectedFields.length ||\n fields.some((field, i) => field !== expectedFields[i])\n ) {\n throw new Error('profile improvement fixture state contains unsupported fields')\n }\n const recommendedSize = SANDBOX_SIZE_PRESET_NAMES.find((size) => size === record.recommendedSize)\n if (!recommendedSize) {\n throw new Error('profile improvement fixture has an invalid recommended size')\n }\n return {\n baselineProfile: parseExactAgentProfile(\n record.baselineProfile,\n 'profile improvement fixture baseline',\n ),\n candidateProfile: parseExactAgentProfile(\n record.candidateProfile,\n 'profile improvement fixture candidate',\n ),\n recommendedSize,\n }\n}\n\nfunction profileStateDigest(\n profile: AgentProfile,\n recommendedSize: SandboxSizePreset,\n): ReturnType<typeof canonicalCandidateDigest> {\n return canonicalCandidateDigest({ definition: profile, recommendedSize })\n}\n\nexport type {\n GraphSubtaskPreparation,\n GraphSubtasks,\n PeerAuditAccess,\n SpawnPreflight,\n SpawnPreflightContext,\n SpawnRefusal,\n} from '../mcp/tools/coordination-contracts'\nexport type { AuthorizeDownMessage } from '../mcp/tools/coordination-messages'\nexport type { ChildQuestionInbox } from '../mcp/tools/coordination-questions'\nexport type {\n CoordinationDeliveryEvidence,\n PriorCoordination,\n} from '../runtime/supervise/coordination-log'\nexport type { SuperviseTestOptions } from '../runtime/supervise/supervise-options'\nexport type { SupervisorAgentTestDeps } from '../runtime/supervise/supervisor-agent-contracts'\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;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qC,CAAC,MAC5C,4BAA4B,MAAM,gBAAgB,GAElD,MAAM,IAAI,MAAM,2EAA2E;CAE7F,OAAO,wBAAwB;EAAE;EAAU,GAAG;CAAM,CAAC;AACvD;AAEA,SAAS,sCAA8E;CACrF,MAAM,WAAW,+BACf,KAAK,MAAM,gDAAgD,CAC7D;CACA,IAAI,SAAS,WAAW,SAAS,iDAC/B,MAAM,IAAI,MAAM,oEAAoE;CAEtF,OAAO;EAAE,GAAG;EAAU,YAAY,SAAS;CAAW;AACxD;AAEA,SAAS,kCACP,OACkD;CAClD,IAAI,OAAO,UAAU,YAAY,UAAU,QAAQ,MAAM,QAAQ,KAAK,GACpE,MAAM,IAAI,MAAM,qDAAqD;CAEvE,MAAM,SAAS;CACf,MAAM,SAAS,OAAO,KAAK,MAAM,CAAC,CAAC,KAAK;CACxC,MAAM,iBAAiB;EAAC;EAAmB;EAAoB;CAAiB;CAChF,IACE,OAAO,WAAW,eAAe,UACjC,OAAO,MAAM,OAAO,MAAM,UAAU,eAAe,EAAE,GAErD,MAAM,IAAI,MAAM,+DAA+D;CAEjF,MAAM,kBAAkB,0BAA0B,MAAM,SAAS,SAAS,OAAO,eAAe;CAChG,IAAI,CAAC,iBACH,MAAM,IAAI,MAAM,6DAA6D;CAE/E,OAAO;EACL,iBAAiB,uBACf,OAAO,iBACP,sCACF;EACA,kBAAkB,uBAChB,OAAO,kBACP,uCACF;EACA;CACF;AACF;AAEA,SAAS,mBACP,SACA,iBAC6C;CAC7C,OAAOC,2BAAyB;EAAE,YAAY;EAAS;CAAgB,CAAC;AAC1E"}
|
|
1
|
+
{"version":3,"file":"testing.js","names":["canonicalAgentImprovementProposalFixture","canonicalAgentProfileImprovementProposalFixture","canonicalAgentProfileImprovementStateFixture","canonicalCandidateDigest"],"sources":["../src/testing/fixtures/agent-improvement-proposal.json","../src/testing/fixtures/agent-profile-improvement-proposal.json","../src/testing/fixtures/agent-profile-improvement-state.json","../src/testing/index.ts"],"sourcesContent":["","","","import {\n type AgentImprovementProposal,\n type AgentProfile,\n type AgentProfileImprovementMeasuredComparison,\n canonicalAgentProfileDigest,\n SANDBOX_SIZE_PRESET_NAMES,\n type SandboxSizePreset,\n} from '@tangle-network/agent-interface'\n\nimport { canonicalCandidateDigest, immutableCandidateValue } from '../candidate-execution/digest'\nimport { applyExactAgentProfileDiff, parseExactAgentProfile } from '../candidate-execution/profile'\nimport { verifyAgentImprovementProposal } from '../intelligence/activation'\nimport canonicalAgentImprovementProposalFixture from './fixtures/agent-improvement-proposal.json'\nimport canonicalAgentProfileImprovementProposalFixture from './fixtures/agent-profile-improvement-proposal.json'\nimport canonicalAgentProfileImprovementStateFixture from './fixtures/agent-profile-improvement-state.json'\n\nexport type { DriverAgentOptions } from '../runtime/supervise/driver-agent-options'\nexport { driverAgent } from '../runtime/supervise/driver-brain-agent'\nexport { type RunGraphTestOptions, runGraphWithTestBrain } from '../runtime/supervise/graph'\nexport { superviseWithTestBrain } from '../runtime/supervise/supervise'\nexport { supervisorAgentWithTestBrain } from '../runtime/supervise/supervisor-agent'\nexport type { ToolLoopCallContext, ToolLoopChat } from '../runtime/tool-loop'\n\nconst serializedAgentImprovementProposalFixture = JSON.stringify(\n canonicalAgentImprovementProposalFixture,\n)\nconst serializedAgentProfileImprovementProposalFixture = JSON.stringify(\n canonicalAgentProfileImprovementProposalFixture,\n)\nconst serializedAgentProfileImprovementStateFixture = JSON.stringify(\n canonicalAgentProfileImprovementStateFixture,\n)\n\n/** A proposal produced by Runtime's opaque profile-improvement path. */\nexport type AgentProfileImprovementProposalFixture = Omit<\n AgentImprovementProposal,\n 'evaluation'\n> & {\n evaluation: AgentProfileImprovementMeasuredComparison\n}\n\n/** Complete private state for exercising profile activation and restore in consumer tests. */\nexport interface AgentProfileImprovementFixture {\n proposal: AgentProfileImprovementProposalFixture\n baselineProfile: AgentProfile\n candidateProfile: AgentProfile\n recommendedSize: SandboxSizePreset\n}\n\n/** Load an isolated, production-validated Runtime proposal for consumer tests. */\nexport function loadAgentImprovementProposalFixture(): AgentImprovementProposal {\n return verifyAgentImprovementProposal(JSON.parse(serializedAgentImprovementProposalFixture))\n}\n\n/** Load an isolated profile proposal and its private activation state for consumer tests. */\nexport function loadAgentProfileImprovementFixture(): AgentProfileImprovementFixture {\n const proposal = loadAgentProfileImprovementProposal()\n const state = parseAgentProfileImprovementState(\n JSON.parse(serializedAgentProfileImprovementStateFixture),\n )\n const experiment = proposal.evaluation.experiment\n const baselineStateDigest = profileStateDigest(state.baselineProfile, state.recommendedSize)\n const candidateStateDigest = profileStateDigest(state.candidateProfile, state.recommendedSize)\n if (\n baselineStateDigest !== experiment.baseline.stateDigest ||\n candidateStateDigest !== experiment.candidate.stateDigest\n ) {\n throw new Error('profile improvement fixture state does not match its proposal')\n }\n const appliedCandidate = experiment.change.reduce(\n (profile, change, index) =>\n applyExactAgentProfileDiff(profile, change, `profile improvement fixture change ${index}`),\n state.baselineProfile,\n )\n if (\n canonicalAgentProfileDigest(appliedCandidate) !==\n canonicalAgentProfileDigest(state.candidateProfile)\n ) {\n throw new Error('profile improvement fixture candidate does not match its proposal changes')\n }\n return immutableCandidateValue({ proposal, ...state })\n}\n\nfunction loadAgentProfileImprovementProposal(): AgentProfileImprovementProposalFixture {\n const proposal = verifyAgentImprovementProposal(\n JSON.parse(serializedAgentProfileImprovementProposalFixture),\n )\n if (proposal.evaluation.kind !== 'agent-profile-improvement-measured-comparison') {\n throw new Error('profile improvement fixture contains a sealed candidate comparison')\n }\n return { ...proposal, evaluation: proposal.evaluation }\n}\n\nfunction parseAgentProfileImprovementState(\n input: unknown,\n): Omit<AgentProfileImprovementFixture, 'proposal'> {\n if (typeof input !== 'object' || input === null || Array.isArray(input)) {\n throw new Error('profile improvement fixture state must be an object')\n }\n const record = input as Record<string, unknown>\n const fields = Object.keys(record).sort()\n const expectedFields = ['baselineProfile', 'candidateProfile', 'recommendedSize']\n if (\n fields.length !== expectedFields.length ||\n fields.some((field, i) => field !== expectedFields[i])\n ) {\n throw new Error('profile improvement fixture state contains unsupported fields')\n }\n const recommendedSize = SANDBOX_SIZE_PRESET_NAMES.find((size) => size === record.recommendedSize)\n if (!recommendedSize) {\n throw new Error('profile improvement fixture has an invalid recommended size')\n }\n return {\n baselineProfile: parseExactAgentProfile(\n record.baselineProfile,\n 'profile improvement fixture baseline',\n ),\n candidateProfile: parseExactAgentProfile(\n record.candidateProfile,\n 'profile improvement fixture candidate',\n ),\n recommendedSize,\n }\n}\n\nfunction profileStateDigest(\n profile: AgentProfile,\n recommendedSize: SandboxSizePreset,\n): ReturnType<typeof canonicalCandidateDigest> {\n return canonicalCandidateDigest({ definition: profile, recommendedSize })\n}\n\nexport type {\n GraphSubtaskPreparation,\n GraphSubtasks,\n PeerAuditAccess,\n SpawnPreflight,\n SpawnPreflightContext,\n SpawnRefusal,\n} from '../mcp/tools/coordination-contracts'\nexport type { AuthorizeDownMessage } from '../mcp/tools/coordination-messages'\nexport type { ChildQuestionInbox } from '../mcp/tools/coordination-questions'\nexport type {\n CoordinationDeliveryEvidence,\n PriorCoordination,\n} from '../runtime/supervise/coordination-log'\nexport type { SuperviseTestOptions } from '../runtime/supervise/supervise-options'\nexport type { SupervisorAgentTestDeps } from '../runtime/supervise/supervisor-agent-contracts'\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;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ACjC,OAAO,MAAM,OAAO,MAAM,UAAU,eAAe,EAAE,GAErD,MAAM,IAAI,MAAM,+DAA+D;CAEjF,MAAM,kBAAkB,0BAA0B,MAAM,SAAS,SAAS,OAAO,eAAe;CAChG,IAAI,CAAC,iBACH,MAAM,IAAI,MAAM,6DAA6D;CAE/E,OAAO;EACL,iBAAiB,uBACf,OAAO,iBACP,sCACF;EACA,kBAAkB,uBAChB,OAAO,kBACP,uCACF;EACA;CACF;AACF;AAEA,SAAS,mBACP,SACA,iBAC6C;CAC7C,OAAOC,2BAAyB;EAAE,YAAY;EAAS;CAAgB,CAAC;AAC1E"}
|
package/dist/tool-loop.d.ts
CHANGED
|
@@ -1,6 +1,5 @@
|
|
|
1
|
-
import { l as RuntimeHooks } from "./runtime-hooks-
|
|
2
|
-
|
|
3
|
-
interface ToolLoopCall {
|
|
1
|
+
import { l as RuntimeHooks } from "./runtime-hooks-ZQqPw-0g.js";
|
|
2
|
+
export interface ToolLoopCall {
|
|
4
3
|
toolCallId?: string;
|
|
5
4
|
toolName: string;
|
|
6
5
|
args: Record<string, unknown>;
|
|
@@ -14,7 +13,7 @@ interface ToolLoopCall {
|
|
|
14
13
|
}
|
|
15
14
|
/** Outcome of one tool dispatch — structurally compatible with a hub/integration
|
|
16
15
|
* tool-outcome union, so callers can fold either through the loop. */
|
|
17
|
-
type ToolCallOutcome = {
|
|
16
|
+
export type ToolCallOutcome = {
|
|
18
17
|
ok: true;
|
|
19
18
|
result: unknown;
|
|
20
19
|
} | {
|
|
@@ -25,7 +24,7 @@ type ToolCallOutcome = {
|
|
|
25
24
|
};
|
|
26
25
|
/** One OpenAI-shaped tool-call entry carried on an assistant message, plus any
|
|
27
26
|
* provider-specific fields the model attached to the call (`ToolLoopCall.providerFields`). */
|
|
28
|
-
interface ToolLoopAssistantToolCall {
|
|
27
|
+
export interface ToolLoopAssistantToolCall {
|
|
29
28
|
[providerField: string]: unknown;
|
|
30
29
|
id: string;
|
|
31
30
|
type: 'function';
|
|
@@ -51,7 +50,7 @@ interface ToolLoopAssistantToolCall {
|
|
|
51
50
|
* works; one that forwards the whole message to an OpenAI-compatible endpoint
|
|
52
51
|
* now sends correct tool history.
|
|
53
52
|
*/
|
|
54
|
-
type ToolLoopMessage = {
|
|
53
|
+
export type ToolLoopMessage = {
|
|
55
54
|
role: string;
|
|
56
55
|
content: string | null;
|
|
57
56
|
tool_calls?: ToolLoopAssistantToolCall[];
|
|
@@ -62,14 +61,14 @@ type ToolLoopMessage = {
|
|
|
62
61
|
* payload: a free-text `message`, a monotonic `progress` count with an optional
|
|
63
62
|
* `total`, and any structured `data` the caller's UI understands.
|
|
64
63
|
*/
|
|
65
|
-
interface ToolProgressUpdate {
|
|
64
|
+
export interface ToolProgressUpdate {
|
|
66
65
|
message?: string;
|
|
67
66
|
progress?: number;
|
|
68
67
|
total?: number;
|
|
69
68
|
data?: unknown;
|
|
70
69
|
}
|
|
71
70
|
/** What the loop hands a running tool besides its call. */
|
|
72
|
-
interface ToolCallContext {
|
|
71
|
+
export interface ToolCallContext {
|
|
73
72
|
/**
|
|
74
73
|
* Report progress while the call runs. The streaming loop yields each update as a
|
|
75
74
|
* `tool_progress` step, in order, before the call's `tool_result`; updates sent after
|
|
@@ -78,8 +77,8 @@ interface ToolCallContext {
|
|
|
78
77
|
progress: (update: ToolProgressUpdate) => void;
|
|
79
78
|
}
|
|
80
79
|
/** Executes one tool call. Implementations that take only the call stay valid. */
|
|
81
|
-
type ToolCallExecutor = (call: ToolLoopCall, context: ToolCallContext) => Promise<ToolCallOutcome>;
|
|
82
|
-
type ToolLoopEvent = {
|
|
80
|
+
export type ToolCallExecutor = (call: ToolLoopCall, context: ToolCallContext) => Promise<ToolCallOutcome>;
|
|
81
|
+
export type ToolLoopEvent = {
|
|
83
82
|
type: 'text';
|
|
84
83
|
text: string;
|
|
85
84
|
} | {
|
|
@@ -94,8 +93,8 @@ type ToolLoopEvent = {
|
|
|
94
93
|
* runaway-backstop cap (200 by default); `deadline` = wall-clock deadlineMs
|
|
95
94
|
* exceeded; `budget` = maxCostUsd exhausted. Non-`completed` stops are infra /
|
|
96
95
|
* resource outcomes — eval scoring must distinguish them from capability failure. */
|
|
97
|
-
type ToolLoopStopReason = 'completed' | 'stuck-loop' | 'backstop' | 'deadline' | 'budget';
|
|
98
|
-
interface ToolLoopResult {
|
|
96
|
+
export type ToolLoopStopReason = 'completed' | 'stuck-loop' | 'backstop' | 'deadline' | 'budget';
|
|
97
|
+
export interface ToolLoopResult {
|
|
99
98
|
finalText: string;
|
|
100
99
|
toolResults: Array<{
|
|
101
100
|
call: ToolLoopCall;
|
|
@@ -107,7 +106,7 @@ interface ToolLoopResult {
|
|
|
107
106
|
/** @deprecated Use `stopReason !== 'completed'` instead. */
|
|
108
107
|
cappedOut: boolean;
|
|
109
108
|
}
|
|
110
|
-
interface RunToolLoopOptions {
|
|
109
|
+
export interface RunToolLoopOptions {
|
|
111
110
|
systemPrompt: string;
|
|
112
111
|
userMessage: string;
|
|
113
112
|
priorMessages?: ToolLoopMessage[];
|
|
@@ -135,8 +134,8 @@ interface RunToolLoopOptions {
|
|
|
135
134
|
/** Run the bounded tool loop and return the final text + every executed tool
|
|
136
135
|
* outcome. Awaitable — callers needing to stream events to a UI use
|
|
137
136
|
* {@link streamToolLoop}. */
|
|
138
|
-
declare function runToolLoop(opts: RunToolLoopOptions): Promise<ToolLoopResult>;
|
|
139
|
-
type StreamToolLoopYield<Raw> = {
|
|
137
|
+
export declare function runToolLoop(opts: RunToolLoopOptions): Promise<ToolLoopResult>;
|
|
138
|
+
export type StreamToolLoopYield<Raw> = {
|
|
140
139
|
kind: 'event';
|
|
141
140
|
event: Raw;
|
|
142
141
|
} | {
|
|
@@ -158,7 +157,7 @@ type StreamToolLoopYield<Raw> = {
|
|
|
158
157
|
* Passing it back as `priorMessages` with no `userMessage` continues the same turn. */
|
|
159
158
|
messages?: ToolLoopMessage[];
|
|
160
159
|
};
|
|
161
|
-
interface StreamToolLoopOptions<Raw> {
|
|
160
|
+
export interface StreamToolLoopOptions<Raw> {
|
|
162
161
|
systemPrompt: string;
|
|
163
162
|
/** Omit to continue a checkpointed turn whose `priorMessages` already end with tool results. */
|
|
164
163
|
userMessage?: string;
|
|
@@ -186,7 +185,5 @@ interface StreamToolLoopOptions<Raw> {
|
|
|
186
185
|
* telemetries + re-emits it), each `tool_progress` a running tool reports, and
|
|
187
186
|
* each executed `tool_result`; emits one `capped` if it stops for any
|
|
188
187
|
* non-completed reason with calls still pending. */
|
|
189
|
-
declare function streamToolLoop<Raw>(opts: StreamToolLoopOptions<Raw>): AsyncGenerator<StreamToolLoopYield<Raw>, void, unknown>;
|
|
190
|
-
//#endregion
|
|
191
|
-
export { RunToolLoopOptions, StreamToolLoopOptions, StreamToolLoopYield, ToolCallContext, ToolCallExecutor, ToolCallOutcome, ToolLoopAssistantToolCall, ToolLoopCall, ToolLoopEvent, ToolLoopMessage, ToolLoopResult, ToolLoopStopReason, ToolProgressUpdate, runToolLoop, streamToolLoop };
|
|
188
|
+
export declare function streamToolLoop<Raw>(opts: StreamToolLoopOptions<Raw>): AsyncGenerator<StreamToolLoopYield<Raw>, void, unknown>;
|
|
192
189
|
//# sourceMappingURL=tool-loop.d.ts.map
|
package/dist/tool-loop.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { i as notifyRuntimeHookEvent, r as notifyRuntimeDecisionPoint } from "./runtime-hooks-
|
|
2
|
-
|
|
1
|
+
import { i as notifyRuntimeHookEvent, r as notifyRuntimeDecisionPoint } from "./runtime-hooks-CsW2pfFk.js";
|
|
2
|
+
// src/tool-loop.ts
|
|
3
3
|
/** Runaway-backstop: stops an infinite tool loop where cost is unmetered. Set
|
|
4
4
|
* far above any legitimate workflow — this is a watchdog, not a policy cap.
|
|
5
5
|
* Legitimate per-call budgets come from `maxCostUsd` + `costOf`. */
|
|
@@ -652,7 +652,6 @@ function trimText(text, max) {
|
|
|
652
652
|
function randomSuffix(len = 8) {
|
|
653
653
|
return Math.random().toString(36).slice(2, 2 + len);
|
|
654
654
|
}
|
|
655
|
-
//#endregion
|
|
656
655
|
export { runToolLoop, streamToolLoop };
|
|
657
656
|
|
|
658
657
|
//# sourceMappingURL=tool-loop.js.map
|
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
import { m as ValidationError } from "./errors-
|
|
1
|
+
import { m as ValidationError } from "./errors-wuhGvpE3.js";
|
|
2
2
|
import { createInterface } from "node:readline";
|
|
3
|
-
|
|
3
|
+
// src/mcp/tool-server.ts
|
|
4
4
|
/**
|
|
5
5
|
* `createStdioToolServer` — the generic newline-delimited JSON-RPC 2.0 MCP
|
|
6
6
|
* server core: `initialize` / `notifications/initialized` / `tools/list` /
|
|
@@ -166,7 +166,6 @@ function rpcError(id, code, message, data) {
|
|
|
166
166
|
function writeResponse(output, response) {
|
|
167
167
|
output.write(`${JSON.stringify(response)}\n`);
|
|
168
168
|
}
|
|
169
|
-
//#endregion
|
|
170
169
|
export { createStdioToolServer as n, PROTOCOL_VERSION as t };
|
|
171
170
|
|
|
172
|
-
//# sourceMappingURL=tool-server-
|
|
171
|
+
//# sourceMappingURL=tool-server-CwuYeW_Z.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"tool-server-XV4aJwoQ.js","names":[],"sources":["../src/mcp/tool-server.ts"],"sourcesContent":["/**\n * `createStdioToolServer` — the generic newline-delimited JSON-RPC 2.0 MCP\n * server core: `initialize` / `notifications/initialized` / `tools/list` /\n * `ping` / `tools/call` over a stdio-shaped transport. It answers the\n * client's protocol version when listed in `SUPPORTED_PROTOCOL_VERSIONS`,\n * else 2024-11-05, and publishes tool annotations when a tool declares them.\n *\n * Extracted from `createMcpServer` (server.ts) so every in-repo MCP server —\n * the delegation server, the memory server — serves the ONE wire protocol the\n * same-host client (`connectStdioMcp`, runtime/stdio-mcp-client.ts) speaks.\n * A second hand-rolled serve loop could drift from what the client expects;\n * this core makes that impossible by construction.\n *\n * @experimental\n */\n\nimport { createInterface, type Interface as ReadlineInterface } from 'node:readline'\nimport { ValidationError } from '../errors'\nimport type { JsonRpcMessage, JsonRpcResponse, McpToolDescriptor, McpTransport } from './protocol'\n\nexport type { JsonRpcMessage, JsonRpcResponse, McpToolDescriptor, McpTransport } from './protocol'\n\nexport const PROTOCOL_VERSION = '2024-11-05'\n\n/**\n * Protocol versions this server speaks, newest first. `initialize` answers with\n * the client's requested version when it is listed here, and otherwise with\n * `PROTOCOL_VERSION` (2024-11-05), which every client that speaks 2024-11-05 accepts.\n */\nconst SUPPORTED_PROTOCOL_VERSIONS: readonly string[] = [\n '2025-11-25',\n '2025-06-18',\n '2025-03-26',\n PROTOCOL_VERSION,\n]\n\n/** @experimental */\nexport interface StdioToolServerOptions {\n /** Server display name surfaced via `initialize`. */\n serverName: string\n /** Server version surfaced via `initialize`. */\n serverVersion: string\n /** The tools to serve. Duplicate names throw — a silent shadow would hide a tool. */\n tools: readonly McpToolDescriptor[]\n}\n\n/** @experimental */\nexport interface StdioToolServer {\n /** Tools currently registered, keyed by name. */\n readonly tools: ReadonlyMap<string, McpToolDescriptor>\n /** Handle a single parsed JSON-RPC message. Returns the response object (or `null` for notifications). */\n handle(message: JsonRpcMessage): Promise<JsonRpcResponse | null>\n /** Drive the server on a stdio-shaped transport until `stop()` is called. */\n serve(transport?: McpTransport): Promise<void>\n /** Stop a `serve` call. Subsequent requests are rejected. */\n stop(): void\n}\n\n/** Build the generic stdio JSON-RPC tool server. */\nexport function createStdioToolServer(options: StdioToolServerOptions): StdioToolServer {\n const tools = new Map<string, McpToolDescriptor>()\n for (const tool of options.tools) {\n if (tools.has(tool.name)) {\n throw new ValidationError(`createStdioToolServer: duplicate tool name \"${tool.name}\"`)\n }\n tools.set(tool.name, tool)\n }\n\n let stopped = false\n let activeReadline: ReadlineInterface | undefined\n\n async function handle(message: JsonRpcMessage): Promise<JsonRpcResponse | null> {\n if (stopped) {\n return rpcError(message.id ?? null, -32099, 'server stopped')\n }\n if (message.method === 'initialize') {\n const requested = (message.params as { protocolVersion?: unknown } | undefined)\n ?.protocolVersion\n return rpcResult(message.id ?? null, {\n protocolVersion:\n typeof requested === 'string' && SUPPORTED_PROTOCOL_VERSIONS.includes(requested)\n ? requested\n : PROTOCOL_VERSION,\n capabilities: { tools: {} },\n serverInfo: { name: options.serverName, version: options.serverVersion },\n })\n }\n if (message.method === 'notifications/initialized') {\n // MCP clients send this after the handshake; it has no id and expects\n // no response.\n return null\n }\n if (message.method === 'ping') {\n return rpcResult(message.id ?? null, {})\n }\n if (message.method === 'tools/list') {\n return rpcResult(message.id ?? null, {\n tools: [...tools.values()].map((tool) => ({\n name: tool.name,\n description: tool.description,\n inputSchema: tool.inputSchema,\n ...(tool.annotations ? { annotations: tool.annotations } : {}),\n })),\n })\n }\n if (message.method === 'tools/call') {\n const params = (message.params ?? {}) as { name?: unknown; arguments?: unknown }\n const name = typeof params.name === 'string' ? params.name : ''\n const tool = tools.get(name)\n if (!tool) {\n return rpcError(message.id ?? null, -32601, `unknown tool: ${name}`)\n }\n try {\n const output = await tool.handler(params.arguments ?? {})\n return rpcResult(message.id ?? null, toolCallResult(output))\n } catch (err) {\n const reason = err instanceof Error ? err.message : String(err)\n const code = err instanceof TypeError || err instanceof RangeError ? -32602 : -32000\n return rpcError(message.id ?? null, code, reason)\n }\n }\n if (message.id === undefined || message.id === null) return null\n return rpcError(message.id, -32601, `unknown method: ${message.method}`)\n }\n\n async function serve(transport?: McpTransport): Promise<void> {\n const input = transport?.input ?? process.stdin\n const output = transport?.output ?? process.stdout\n const rl = createInterface({ input, crlfDelay: Number.POSITIVE_INFINITY })\n activeReadline = rl\n return new Promise<void>((resolve, reject) => {\n rl.on('line', (line) => {\n const trimmed = line.trim()\n if (!trimmed) return\n let parsed: JsonRpcMessage | undefined\n try {\n parsed = JSON.parse(trimmed) as JsonRpcMessage\n } catch (err) {\n writeResponse(output, rpcError(null, -32700, `parse error: ${(err as Error).message}`))\n return\n }\n if (parsed?.jsonrpc !== '2.0' || typeof parsed.method !== 'string') {\n writeResponse(output, rpcError(parsed?.id ?? null, -32600, 'invalid request'))\n return\n }\n void handle(parsed).then((response) => {\n if (response) writeResponse(output, response)\n })\n })\n rl.on('close', () => resolve())\n rl.on('error', (err) => reject(err))\n if (stopped) {\n rl.close()\n resolve()\n }\n })\n }\n\n function stop(): void {\n stopped = true\n activeReadline?.close()\n activeReadline = undefined\n }\n\n return { tools, handle, serve, stop }\n}\n\nfunction toolCallResult(output: unknown): {\n content: [{ type: 'text'; text: string }]\n structuredContent?: Record<string, unknown>\n isError: false\n} {\n let json: string | undefined\n try {\n json = JSON.stringify(output)\n } catch (err) {\n const reason = err instanceof Error ? `: ${err.message}` : ''\n throw new TypeError(`MCP tool result must be JSON-serializable${reason}`, { cause: err })\n }\n if (json === undefined) {\n throw new TypeError('MCP tool result must be JSON-serializable')\n }\n\n const serialized = JSON.parse(json) as unknown\n // Preserve string content verbatim. MCP clients pass this text directly to the calling agent.\n const result: {\n content: [{ type: 'text'; text: string }]\n structuredContent?: Record<string, unknown>\n isError: false\n } = {\n content: [{ type: 'text', text: typeof serialized === 'string' ? serialized : json }],\n isError: false,\n }\n if (serialized !== null && typeof serialized === 'object' && !Array.isArray(serialized)) {\n result.structuredContent = serialized as Record<string, unknown>\n }\n return result\n}\n\nfunction rpcResult(id: number | string | null, result: unknown): JsonRpcResponse {\n return { jsonrpc: '2.0', id, result }\n}\n\nfunction rpcError(\n id: number | string | null,\n code: number,\n message: string,\n data?: unknown,\n): JsonRpcResponse {\n return {\n jsonrpc: '2.0',\n id,\n error: data === undefined ? { code, message } : { code, message, data },\n }\n}\n\nfunction writeResponse(output: NodeJS.WritableStream, response: JsonRpcResponse): void {\n output.write(`${JSON.stringify(response)}\\n`)\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AAsBA,MAAa,mBAAmB;;;;;;AAOhC,MAAM,8BAAiD;CACrD;CACA;CACA;CACA;AACF;;AAyBA,SAAgB,sBAAsB,SAAkD;CACtF,MAAM,wBAAQ,IAAI,IAA+B;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ACH;CAEA,SAAS,OAAa;EACpB,UAAU;EACV,gBAAgB,MAAM;EACtB,iBAAiB,KAAA;CACnB;CAEA,OAAO;EAAE;EAAO;EAAQ;EAAO;CAAK;AACtC;AAEA,SAAS,eAAe,QAItB;CACA,IAAI;CACJ,IAAI;EACF,OAAO,KAAK,UAAU,MAAM;CAC9B,SAAS,KAAK;EACZ,MAAM,SAAS,eAAe,QAAQ,KAAK,IAAI,YAAY;EAC3D,MAAM,IAAI,UAAU,4CAA4C,UAAU,EAAE,OAAO,IAAI,CAAC;CAC1F;CACA,IAAI,SAAS,KAAA,GACX,MAAM,IAAI,UAAU,2CAA2C;CAGjE,MAAM,aAAa,KAAK,MAAM,IAAI;CAElC,MAAM,SAIF;EACF,SAAS,CAAC;GAAE,MAAM;GAAQ,MAAM,OAAO,eAAe,WAAW,aAAa;EAAK,CAAC;EACpF,SAAS;CACX;CACA,IAAI,eAAe,QAAQ,OAAO,eAAe,YAAY,CAAC,MAAM,QAAQ,UAAU,GACpF,OAAO,oBAAoB;CAE7B,OAAO;AACT;AAEA,SAAS,UAAU,IAA4B,QAAkC;CAC/E,OAAO;EAAE,SAAS;EAAO;EAAI;CAAO;AACtC;AAEA,SAAS,SACP,IACA,MACA,SACA,MACiB;CACjB,OAAO;EACL,SAAS;EACT;EACA,OAAO,SAAS,KAAA,IAAY;GAAE;GAAM;EAAQ,IAAI;GAAE;GAAM;GAAS;EAAK;CACxE;AACF;AAEA,SAAS,cAAc,QAA+B,UAAiC;CACrF,OAAO,MAAM,GAAG,KAAK,UAAU,QAAQ,EAAE,GAAG;AAC9C"}
|
|
1
|
+
{"version":3,"file":"tool-server-CwuYeW_Z.js","names":[],"sources":["../src/mcp/tool-server.ts"],"sourcesContent":["/**\n * `createStdioToolServer` — the generic newline-delimited JSON-RPC 2.0 MCP\n * server core: `initialize` / `notifications/initialized` / `tools/list` /\n * `ping` / `tools/call` over a stdio-shaped transport. It answers the\n * client's protocol version when listed in `SUPPORTED_PROTOCOL_VERSIONS`,\n * else 2024-11-05, and publishes tool annotations when a tool declares them.\n *\n * Extracted from `createMcpServer` (server.ts) so every in-repo MCP server —\n * the delegation server, the memory server — serves the ONE wire protocol the\n * same-host client (`connectStdioMcp`, runtime/stdio-mcp-client.ts) speaks.\n * A second hand-rolled serve loop could drift from what the client expects;\n * this core makes that impossible by construction.\n *\n * @experimental\n */\n\nimport { createInterface, type Interface as ReadlineInterface } from 'node:readline'\nimport { ValidationError } from '../errors'\nimport type { JsonRpcMessage, JsonRpcResponse, McpToolDescriptor, McpTransport } from './protocol'\n\nexport type { JsonRpcMessage, JsonRpcResponse, McpToolDescriptor, McpTransport } from './protocol'\n\nexport const PROTOCOL_VERSION = '2024-11-05'\n\n/**\n * Protocol versions this server speaks, newest first. `initialize` answers with\n * the client's requested version when it is listed here, and otherwise with\n * `PROTOCOL_VERSION` (2024-11-05), which every client that speaks 2024-11-05 accepts.\n */\nconst SUPPORTED_PROTOCOL_VERSIONS: readonly string[] = [\n '2025-11-25',\n '2025-06-18',\n '2025-03-26',\n PROTOCOL_VERSION,\n]\n\n/** @experimental */\nexport interface StdioToolServerOptions {\n /** Server display name surfaced via `initialize`. */\n serverName: string\n /** Server version surfaced via `initialize`. */\n serverVersion: string\n /** The tools to serve. Duplicate names throw — a silent shadow would hide a tool. */\n tools: readonly McpToolDescriptor[]\n}\n\n/** @experimental */\nexport interface StdioToolServer {\n /** Tools currently registered, keyed by name. */\n readonly tools: ReadonlyMap<string, McpToolDescriptor>\n /** Handle a single parsed JSON-RPC message. Returns the response object (or `null` for notifications). */\n handle(message: JsonRpcMessage): Promise<JsonRpcResponse | null>\n /** Drive the server on a stdio-shaped transport until `stop()` is called. */\n serve(transport?: McpTransport): Promise<void>\n /** Stop a `serve` call. Subsequent requests are rejected. */\n stop(): void\n}\n\n/** Build the generic stdio JSON-RPC tool server. */\nexport function createStdioToolServer(options: StdioToolServerOptions): StdioToolServer {\n const tools = new Map<string, McpToolDescriptor>()\n for (const tool of options.tools) {\n if (tools.has(tool.name)) {\n throw new ValidationError(`createStdioToolServer: duplicate tool name \"${tool.name}\"`)\n }\n tools.set(tool.name, tool)\n }\n\n let stopped = false\n let activeReadline: ReadlineInterface | undefined\n\n async function handle(message: JsonRpcMessage): Promise<JsonRpcResponse | null> {\n if (stopped) {\n return rpcError(message.id ?? null, -32099, 'server stopped')\n }\n if (message.method === 'initialize') {\n const requested = (message.params as { protocolVersion?: unknown } | undefined)\n ?.protocolVersion\n return rpcResult(message.id ?? null, {\n protocolVersion:\n typeof requested === 'string' && SUPPORTED_PROTOCOL_VERSIONS.includes(requested)\n ? requested\n : PROTOCOL_VERSION,\n capabilities: { tools: {} },\n serverInfo: { name: options.serverName, version: options.serverVersion },\n })\n }\n if (message.method === 'notifications/initialized') {\n // MCP clients send this after the handshake; it has no id and expects\n // no response.\n return null\n }\n if (message.method === 'ping') {\n return rpcResult(message.id ?? null, {})\n }\n if (message.method === 'tools/list') {\n return rpcResult(message.id ?? null, {\n tools: [...tools.values()].map((tool) => ({\n name: tool.name,\n description: tool.description,\n inputSchema: tool.inputSchema,\n ...(tool.annotations ? { annotations: tool.annotations } : {}),\n })),\n })\n }\n if (message.method === 'tools/call') {\n const params = (message.params ?? {}) as { name?: unknown; arguments?: unknown }\n const name = typeof params.name === 'string' ? params.name : ''\n const tool = tools.get(name)\n if (!tool) {\n return rpcError(message.id ?? null, -32601, `unknown tool: ${name}`)\n }\n try {\n const output = await tool.handler(params.arguments ?? {})\n return rpcResult(message.id ?? null, toolCallResult(output))\n } catch (err) {\n const reason = err instanceof Error ? err.message : String(err)\n const code = err instanceof TypeError || err instanceof RangeError ? -32602 : -32000\n return rpcError(message.id ?? null, code, reason)\n }\n }\n if (message.id === undefined || message.id === null) return null\n return rpcError(message.id, -32601, `unknown method: ${message.method}`)\n }\n\n async function serve(transport?: McpTransport): Promise<void> {\n const input = transport?.input ?? process.stdin\n const output = transport?.output ?? process.stdout\n const rl = createInterface({ input, crlfDelay: Number.POSITIVE_INFINITY })\n activeReadline = rl\n return new Promise<void>((resolve, reject) => {\n rl.on('line', (line) => {\n const trimmed = line.trim()\n if (!trimmed) return\n let parsed: JsonRpcMessage | undefined\n try {\n parsed = JSON.parse(trimmed) as JsonRpcMessage\n } catch (err) {\n writeResponse(output, rpcError(null, -32700, `parse error: ${(err as Error).message}`))\n return\n }\n if (parsed?.jsonrpc !== '2.0' || typeof parsed.method !== 'string') {\n writeResponse(output, rpcError(parsed?.id ?? null, -32600, 'invalid request'))\n return\n }\n void handle(parsed).then((response) => {\n if (response) writeResponse(output, response)\n })\n })\n rl.on('close', () => resolve())\n rl.on('error', (err) => reject(err))\n if (stopped) {\n rl.close()\n resolve()\n }\n })\n }\n\n function stop(): void {\n stopped = true\n activeReadline?.close()\n activeReadline = undefined\n }\n\n return { tools, handle, serve, stop }\n}\n\nfunction toolCallResult(output: unknown): {\n content: [{ type: 'text'; text: string }]\n structuredContent?: Record<string, unknown>\n isError: false\n} {\n let json: string | undefined\n try {\n json = JSON.stringify(output)\n } catch (err) {\n const reason = err instanceof Error ? `: ${err.message}` : ''\n throw new TypeError(`MCP tool result must be JSON-serializable${reason}`, { cause: err })\n }\n if (json === undefined) {\n throw new TypeError('MCP tool result must be JSON-serializable')\n }\n\n const serialized = JSON.parse(json) as unknown\n // Preserve string content verbatim. MCP clients pass this text directly to the calling agent.\n const result: {\n content: [{ type: 'text'; text: string }]\n structuredContent?: Record<string, unknown>\n isError: false\n } = {\n content: [{ type: 'text', text: typeof serialized === 'string' ? serialized : json }],\n isError: false,\n }\n if (serialized !== null && typeof serialized === 'object' && !Array.isArray(serialized)) {\n result.structuredContent = serialized as Record<string, unknown>\n }\n return result\n}\n\nfunction rpcResult(id: number | string | null, result: unknown): JsonRpcResponse {\n return { jsonrpc: '2.0', id, result }\n}\n\nfunction rpcError(\n id: number | string | null,\n code: number,\n message: string,\n data?: unknown,\n): JsonRpcResponse {\n return {\n jsonrpc: '2.0',\n id,\n error: data === undefined ? { code, message } : { code, message, data },\n }\n}\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AC9C"}
|
|
@@ -1,8 +1,8 @@
|
|
|
1
|
-
import { t as spawnJournalRecordEvents } from "./record-events-
|
|
2
|
-
import { _ as safeWorkerFile, b as supervisorWorkersDir, f as legacySupervisorRunsRoot, y as supervisorRunsRoot } from "./run-cancellation-
|
|
1
|
+
import { t as spawnJournalRecordEvents } from "./record-events-B2GUgYdz.js";
|
|
2
|
+
import { _ as safeWorkerFile, b as supervisorWorkersDir, f as legacySupervisorRunsRoot, y as supervisorRunsRoot } from "./run-cancellation-BLy_Zz-w.js";
|
|
3
3
|
import { existsSync, readFileSync, readdirSync, statSync } from "node:fs";
|
|
4
4
|
import { basename, join, resolve } from "node:path";
|
|
5
|
-
|
|
5
|
+
// src/tui/top-snapshot.ts
|
|
6
6
|
/**
|
|
7
7
|
* The snapshot reader for the supervisor-run TUI: turn the on-disk run layout into a `TopSnapshot`.
|
|
8
8
|
* ANSI frame presentation lives in `./top-frame`; this module owns reading and projection.
|
|
@@ -498,7 +498,6 @@ function parseTime(value) {
|
|
|
498
498
|
function sum(values) {
|
|
499
499
|
return values.reduce((total, value) => total + value, 0);
|
|
500
500
|
}
|
|
501
|
-
//#endregion
|
|
502
501
|
export { parseTime as a, parseSpend as i, loadTopSnapshot as n, totalSpend as o, numberValue as r, aggregateSnapshot as t };
|
|
503
502
|
|
|
504
|
-
//# sourceMappingURL=top-snapshot-
|
|
503
|
+
//# sourceMappingURL=top-snapshot-ChwpTr7A.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"top-snapshot-CflmaDgk.js","names":[],"sources":["../src/tui/top-snapshot.ts"],"sourcesContent":["/**\n * The snapshot reader for the supervisor-run TUI: turn the on-disk run layout into a `TopSnapshot`.\n * ANSI frame presentation lives in `./top-frame`; this module owns reading and projection.\n *\n * This module never derives a run path itself. Every directory and per-worker file it reads comes\n * from `../runtime/supervise/run-layout` — the same module the writers use — so the reader cannot\n * drift from the layout the way an independently-versioned copy of the contract would.\n *\n * Extracted from the `loops` repo (`src/top-model.ts`), which held a hand-joined copy of the\n * layout. Rendering is deliberately unchanged: raw ANSI, zero dependencies.\n *\n * This is the OPERATOR view: what is on disk right now, for a human watching a workspace. It\n * carries no model-call identity, so its per-supervisor totals cannot be joined with root stream\n * events without double counting. A client that needs one execution's totals reads\n * `projectPursuit` from `../durable` instead.\n *\n * @experimental\n */\n\nimport { existsSync, readdirSync, readFileSync, statSync } from 'node:fs'\nimport { basename, join, resolve } from 'node:path'\nimport { spawnJournalRecordEvents } from '../durable/spawn-journal/record-events'\nimport {\n legacySupervisorRunsRoot,\n safeWorkerFile,\n supervisorRunsRoot,\n supervisorWorkersDir,\n} from '../runtime/supervise/run-layout'\n\nexport interface TopSnapshot {\n readonly root: string\n readonly generatedAt: number\n readonly supervisors: SupervisorView[]\n /** `partial` when at least one discovered source could not be read completely. */\n readonly completeness: TopSnapshotCompleteness\n /** One bounded entry per skipped or partially read source; empty when complete. */\n readonly diagnostics: ReadonlyArray<TopSnapshotDiagnostic>\n /** Run directories found under the runs roots, readable or not. */\n readonly discovered: number\n /** Run directories whose state.json parsed into a valid supervisor view. */\n readonly loaded: number\n}\n\nexport type TopSnapshotCompleteness = 'complete' | 'partial'\n\nexport type TopSnapshotDiagnosticSource =\n | 'supervisor-state'\n | 'journal'\n | 'progress'\n | 'worker-tail'\n\nexport type TopSnapshotDiagnosticReason =\n | 'unreadable'\n | 'partial-json'\n | 'invalid-state'\n | 'missing'\n\n/**\n * One skipped or partially read snapshot source. `path` is relative to the run directory and\n * never carries file contents, so a diagnostic is safe to show or log without leaking run data.\n */\nexport interface TopSnapshotDiagnostic {\n readonly source: TopSnapshotDiagnosticSource\n readonly runId?: string\n readonly path: string\n readonly reason: TopSnapshotDiagnosticReason\n}\n\ninterface SupervisorBase {\n readonly id: string\n readonly status: string\n readonly task: string\n readonly workspaceDir: string\n readonly budget: number\n readonly verifyCmd?: string\n readonly workerModel?: string\n readonly driverModel?: string\n readonly verdict?: string\n readonly progress?: string\n readonly startedAt?: string\n readonly completedAt?: string\n readonly maxSandboxes?: number\n readonly maxLifetimeSeconds?: number\n readonly idleTimeoutSeconds?: number\n readonly maxUsd?: number\n readonly maxDepth?: number\n}\n\nexport interface SupervisorView extends SupervisorBase {\n readonly stateDir: string\n readonly resultSpentUsd?: number\n readonly resultSpentTokens?: number\n readonly workers: WorkerView[]\n readonly progressTail: string[]\n readonly journalTail: TopJournalEvent[]\n readonly driverSpend: SpendStats\n readonly totals: SupervisorTotals\n}\n\nexport interface WorkerView {\n readonly id: string\n readonly label: string\n readonly eventFile?: string\n readonly parent?: string\n readonly runtime?: string\n readonly status: 'running' | 'done' | 'down' | 'cancelled'\n readonly verdict?: string\n readonly infra?: boolean\n readonly startedAt?: string\n readonly endedAt?: string\n readonly latencyMs: number\n readonly budget?: BudgetStats\n readonly spend: SpendStats\n readonly metered: SpendStats\n readonly liveTail: string[]\n readonly outRef?: string\n readonly reason?: string\n}\n\nexport interface SupervisorTotals {\n readonly workers: number\n readonly running: number\n readonly done: number\n readonly down: number\n readonly cancelled: number\n readonly inFlight: number\n readonly settled: number\n readonly tokensInput: number\n readonly tokensOutput: number\n readonly tokensTotal: number\n readonly usd: number\n readonly latencyMs: number\n readonly workerLatency: Distribution\n}\n\nexport interface Distribution {\n readonly n: number\n readonly min: number\n readonly median: number\n readonly p90: number\n readonly max: number\n}\n\nexport interface BudgetStats {\n readonly maxIterations?: number\n readonly maxTokens?: number\n readonly maxUsd?: number\n}\n\nexport interface SpendStats {\n readonly iterations: number\n readonly tokensInput: number\n readonly tokensOutput: number\n readonly usd: number\n readonly ms: number\n}\n\nexport type TopJournalEvent =\n | {\n readonly kind: 'spawned'\n readonly id: string\n readonly parent?: string\n readonly label?: string\n readonly budget?: unknown\n readonly runtime?: string\n readonly seq?: number\n readonly at?: string\n }\n | {\n readonly kind: 'settled'\n readonly id: string\n readonly status?: string\n readonly outRef?: string\n readonly verdict?: unknown\n readonly spent?: unknown\n readonly infra?: boolean\n readonly seq?: number\n readonly at?: string\n }\n | {\n readonly kind: 'cancelled'\n readonly spent?: unknown\n readonly id: string\n readonly reason?: string\n readonly seq?: number\n readonly at?: string\n }\n | {\n readonly kind: 'metered'\n readonly id: string\n readonly spend?: unknown\n readonly accountingOnly?: boolean\n readonly seq?: number\n readonly at?: string\n }\n | {\n readonly kind: 'progress'\n readonly id: string\n readonly spend?: unknown\n readonly seq?: number\n readonly at?: string\n }\n\ninterface SupervisorState extends SupervisorBase {\n readonly result?: {\n readonly spentUsd?: number\n readonly spentTokens?: number\n }\n}\n\ntype MutableWorker = {\n -readonly [Key in keyof Omit<WorkerView, 'latencyMs'>]: WorkerView[Key]\n}\n\ninterface WorkerEventTail {\n readonly file: string\n readonly lines: string[]\n}\n\n/** A diagnostic before its run id is attached; `loadTopSnapshot` adds `runId`. */\ninterface SourceDiagnostic {\n readonly source: TopSnapshotDiagnosticSource\n readonly path: string\n readonly reason: TopSnapshotDiagnosticReason\n}\n\n/**\n * What one snapshot source read produced: the value it could recover, and the bounded diagnostics\n * the read raised. Every reader returns this one shape, so the loader folds them identically.\n */\ninterface SourceRead<T> {\n readonly value: T\n readonly diagnostics: readonly SourceDiagnostic[]\n}\n\nconst emptySpend: SpendStats = { iterations: 0, tokensInput: 0, tokensOutput: 0, usd: 0, ms: 0 }\n\n/**\n * Read every supervisor run under one workspace into a single point-in-time snapshot.\n *\n * Pure with respect to the process: it only reads, and it never throws for a writer mid-append.\n * An unreadable or half-written source is still skipped — an operator view must survive a live\n * writer — but every skip is reported as one bounded `TopSnapshotDiagnostic`, so a client can\n * tell a removed run from a partial read. `now` is injectable so elapsed time is deterministic\n * under test.\n */\nexport function loadTopSnapshot(rootDir: string, now = Date.now()): TopSnapshot {\n const root = resolve(rootDir)\n const supervisors: SupervisorView[] = []\n const diagnostics: TopSnapshotDiagnostic[] = []\n let discovered = 0\n const report = (runId: string, sources: readonly SourceDiagnostic[]): void => {\n for (const source of sources) diagnostics.push({ ...source, runId })\n }\n // `.loops` is the pre-rename state dir; runs already on disk there stay visible.\n for (const runsRoot of [supervisorRunsRoot(root), legacySupervisorRunsRoot(root)]) {\n if (!existsSync(runsRoot)) continue\n for (const entry of readdirSync(runsRoot)) {\n const dir = join(runsRoot, entry)\n if (!isDirectory(dir)) continue\n discovered += 1\n const state = readSupervisorState(dir)\n report(entry, state.diagnostics)\n if (!state.value) continue\n const journal = readJournal(dir)\n const progress = readProgressTail(dir, 8)\n const workerEvents = readWorkerEventTails(supervisorWorkersDir(dir), 8)\n report(entry, [...journal.diagnostics, ...progress.diagnostics, ...workerEvents.diagnostics])\n supervisors.push(\n buildSupervisorView(\n state.value,\n dir,\n journal.value,\n progress.value,\n now,\n workerEvents.value,\n ),\n )\n }\n }\n supervisors.sort((a, b) => String(b.startedAt ?? '').localeCompare(String(a.startedAt ?? '')))\n return {\n root,\n generatedAt: now,\n supervisors,\n completeness: diagnostics.length === 0 ? 'complete' : 'partial',\n diagnostics,\n discovered,\n loaded: supervisors.length,\n }\n}\n\n/**\n * The journal file a run dir actually carries. `createFileRunContext` — this repo's own durable\n * writer — names it `spawn-journal.jsonl`; `journal.jsonl` is the retired bare-event file older\n * runs left behind. First existing name wins; a reader that knew only the retired name would show\n * zero workers for every current run.\n */\nconst journalFileNames = ['spawn-journal.jsonl', 'journal.jsonl'] as const\n\nfunction readJournal(eventDir: string): SourceRead<TopJournalEvent[]> {\n const path = journalFileNames.find((candidate) => existsSync(join(eventDir, candidate)))\n if (!path) return { value: [], diagnostics: [] }\n const read = readSourceFile(join(eventDir, path), 'journal', path)\n if (read.value === undefined) return { value: [], diagnostics: read.diagnostics }\n const out: TopJournalEvent[] = []\n let partial = false\n for (const line of read.value.split('\\n')) {\n const trimmed = line.trim()\n if (!trimmed) continue\n try {\n const parsed = JSON.parse(trimmed) as Record<string, unknown>\n const events =\n parsed.kind === 'event' || parsed.kind === 'events'\n ? spawnJournalRecordEvents(parsed)\n : [parsed]\n for (const event of events) if (isSpawnEvent(event)) out.push(event)\n } catch {\n // A corrupt line is expected while the writer is mid-append; keep the lines that parsed.\n partial = true\n }\n }\n return {\n value: out,\n diagnostics: partial ? [{ source: 'journal', path, reason: 'partial-json' }] : [],\n }\n}\n\nfunction buildSupervisorView(\n state: SupervisorState,\n stateDir: string,\n events: readonly TopJournalEvent[],\n progressTail: readonly string[],\n now: number,\n workerEventTails = new Map<string, WorkerEventTail>(),\n): SupervisorView {\n const workers = new Map<string, MutableWorker>()\n let driverSpend = emptySpend\n // `state.json` and the spawn journal are written by DIFFERENT producers, and their ids need not\n // agree: the journal's root is the runtime's `runId`, which defaults to a literal unrelated to\n // the supervisor id the state file records. Recover the journal's own root from its parentless\n // root spawn, and treat EITHER id as the root everywhere. Checking only `state.id` — which the\n // metered/settled/cancelled branches used to do — manufactures a phantom worker named after the\n // runId that never settles, sorts first as RUNNING, and silently captures every steer and cancel.\n const journalRootId = events.find(\n (event) => event.kind === 'spawned' && !event.parent && event.label === 'root',\n )?.id\n const isRoot = (id: string): boolean => id === state.id || id === journalRootId\n\n for (const event of events) {\n if (event.kind === 'spawned') {\n if (isRoot(event.id) || (!event.parent && event.label === 'root')) continue\n const worker = ensureWorker(workers, event.id, event.label ?? event.id)\n worker.label = event.label ?? worker.label\n if (event.parent) worker.parent = event.parent\n if (event.runtime) worker.runtime = event.runtime\n worker.status = 'running'\n if (event.at) worker.startedAt = event.at\n const budget = parseBudget(event.budget)\n if (budget) worker.budget = budget\n continue\n }\n\n if (event.kind === 'settled') {\n if (isRoot(event.id)) continue\n const worker = ensureWorker(workers, event.id, event.id)\n worker.status = event.status === 'down' ? 'down' : 'done'\n if (event.at) worker.endedAt = event.at\n if (event.outRef) worker.outRef = event.outRef\n if (event.infra !== undefined) worker.infra = event.infra\n const verdict = describeVerdict(event.verdict)\n if (verdict) worker.verdict = verdict\n worker.spend = addSpend(worker.spend, parseSpend(event.spent))\n // Live progress is cumulative observation. The terminal spend replaces it, so do not add\n // the two channels or a worker's final cost would be counted twice.\n worker.metered = emptySpend\n continue\n }\n\n if (event.kind === 'cancelled') {\n if (isRoot(event.id)) continue\n const worker = ensureWorker(workers, event.id, event.id)\n worker.status = 'cancelled'\n if (event.at) worker.endedAt = event.at\n if (event.reason) worker.reason = event.reason\n if (event.spent !== undefined) {\n worker.spend = addSpend(worker.spend, parseSpend(event.spent))\n worker.metered = emptySpend\n }\n continue\n }\n\n if (event.kind === 'metered') {\n const spend = parseSpend(event.spend)\n if (isRoot(event.id)) {\n if (event.accountingOnly !== true) driverSpend = addSpend(driverSpend, spend)\n } else {\n const worker = ensureWorker(workers, event.id, event.id)\n if (event.accountingOnly !== true) worker.metered = addSpend(worker.metered, spend)\n }\n continue\n }\n\n if (event.kind === 'progress') {\n if (isRoot(event.id)) continue\n const worker = ensureWorker(workers, event.id, event.id)\n worker.metered = parseSpend(event.spend)\n }\n }\n\n const workerViews = [...workers.values()]\n .map((worker) => {\n // Tails are keyed by file stem, which the writer put through `safeWorkerFile`; a label\n // carrying characters that stem strips would otherwise never find its own events.\n const tail =\n workerEventTails.get(worker.label) ??\n workerEventTails.get(safeWorkerFile(worker.label)) ??\n workerEventTails.get(safeWorkerFile(worker.id)) ??\n workerEventTails.get(worker.id)\n worker.liveTail = tail?.lines ?? []\n if (tail?.file) worker.eventFile = tail.file\n return finalizeWorker(worker, now)\n })\n .sort((a, b) => compareWorker(a, b))\n\n const totals = supervisorTotals(state, workerViews, driverSpend, now)\n return {\n id: state.id,\n stateDir,\n status: state.status,\n task: state.task,\n workspaceDir: state.workspaceDir,\n budget: state.budget,\n ...(state.verifyCmd ? { verifyCmd: state.verifyCmd } : {}),\n ...(state.workerModel ? { workerModel: state.workerModel } : {}),\n ...(state.driverModel ? { driverModel: state.driverModel } : {}),\n ...(state.verdict ? { verdict: state.verdict } : {}),\n ...(state.progress ? { progress: state.progress } : {}),\n ...(state.startedAt ? { startedAt: state.startedAt } : {}),\n ...(state.completedAt ? { completedAt: state.completedAt } : {}),\n ...(state.maxSandboxes !== undefined ? { maxSandboxes: state.maxSandboxes } : {}),\n ...(state.maxLifetimeSeconds !== undefined\n ? { maxLifetimeSeconds: state.maxLifetimeSeconds }\n : {}),\n ...(state.idleTimeoutSeconds !== undefined\n ? { idleTimeoutSeconds: state.idleTimeoutSeconds }\n : {}),\n ...(state.maxUsd !== undefined ? { maxUsd: state.maxUsd } : {}),\n ...(state.maxDepth !== undefined ? { maxDepth: state.maxDepth } : {}),\n ...(state.result?.spentUsd !== undefined ? { resultSpentUsd: state.result.spentUsd } : {}),\n ...(state.result?.spentTokens !== undefined\n ? { resultSpentTokens: state.result.spentTokens }\n : {}),\n workers: workerViews,\n progressTail: [...progressTail],\n journalTail: events.slice(-12),\n driverSpend,\n totals,\n }\n}\n\nfunction ensureWorker(\n workers: Map<string, MutableWorker>,\n id: string,\n label: string,\n): MutableWorker {\n const existing = workers.get(id)\n if (existing) return existing\n const created: MutableWorker = {\n id,\n label,\n status: 'running',\n spend: emptySpend,\n metered: emptySpend,\n liveTail: [],\n }\n workers.set(id, created)\n return created\n}\n\nfunction finalizeWorker(worker: MutableWorker, now: number): WorkerView {\n const startMs = parseTime(worker.startedAt)\n const endMs = parseTime(worker.endedAt) ?? (worker.status === 'running' ? now : startMs)\n const latencyMs = startMs !== undefined && endMs !== undefined ? Math.max(0, endMs - startMs) : 0\n return {\n id: worker.id,\n label: worker.label,\n ...(worker.eventFile ? { eventFile: worker.eventFile } : {}),\n ...(worker.parent ? { parent: worker.parent } : {}),\n ...(worker.runtime ? { runtime: worker.runtime } : {}),\n status: worker.status,\n ...(worker.verdict ? { verdict: worker.verdict } : {}),\n ...(worker.infra !== undefined ? { infra: worker.infra } : {}),\n ...(worker.startedAt ? { startedAt: worker.startedAt } : {}),\n ...(worker.endedAt ? { endedAt: worker.endedAt } : {}),\n latencyMs,\n ...(worker.budget ? { budget: worker.budget } : {}),\n spend: worker.spend,\n metered: worker.metered,\n liveTail: worker.liveTail,\n ...(worker.outRef ? { outRef: worker.outRef } : {}),\n ...(worker.reason ? { reason: worker.reason } : {}),\n }\n}\n\nfunction supervisorTotals(\n state: SupervisorState,\n workers: readonly WorkerView[],\n driverSpend: SpendStats,\n now: number,\n): SupervisorTotals {\n const workerSpends = workers.map(totalSpend)\n const tokenInput = sum(workerSpends.map((spend) => spend.tokensInput)) + driverSpend.tokensInput\n const tokenOutput =\n sum(workerSpends.map((spend) => spend.tokensOutput)) + driverSpend.tokensOutput\n const computedUsd = sum(workerSpends.map((spend) => spend.usd)) + driverSpend.usd\n const usd = computedUsd > 0 ? computedUsd : (state.result?.spentUsd ?? 0)\n const started = parseTime(state.startedAt)\n const completed = parseTime(state.completedAt)\n const latencyMs = started !== undefined ? Math.max(0, (completed ?? now) - started) : 0\n const latencies = workers.map((worker) => worker.latencyMs).filter((ms) => ms > 0)\n return {\n workers: workers.length,\n running: workers.filter((worker) => worker.status === 'running').length,\n done: workers.filter((worker) => worker.status === 'done').length,\n down: workers.filter((worker) => worker.status === 'down').length,\n cancelled: workers.filter((worker) => worker.status === 'cancelled').length,\n inFlight: workers.filter((worker) => worker.status === 'running').length,\n settled: workers.filter((worker) => worker.status !== 'running').length,\n tokensInput: tokenInput,\n tokensOutput: tokenOutput,\n tokensTotal: tokenInput + tokenOutput,\n usd,\n latencyMs,\n workerLatency: distribution(latencies),\n }\n}\n\nexport function aggregateSnapshot(snapshot: TopSnapshot): {\n supervisors: number\n workers: number\n running: number\n done: number\n down: number\n usd: number\n tokensInput: number\n tokensOutput: number\n} {\n return {\n supervisors: snapshot.supervisors.length,\n workers: sum(snapshot.supervisors.map((supervisor) => supervisor.totals.workers)),\n running: sum(snapshot.supervisors.map((supervisor) => supervisor.totals.running)),\n done: sum(snapshot.supervisors.map((supervisor) => supervisor.totals.done)),\n down: sum(snapshot.supervisors.map((supervisor) => supervisor.totals.down)),\n usd: sum(snapshot.supervisors.map((supervisor) => supervisor.totals.usd)),\n tokensInput: sum(snapshot.supervisors.map((supervisor) => supervisor.totals.tokensInput)),\n tokensOutput: sum(snapshot.supervisors.map((supervisor) => supervisor.totals.tokensOutput)),\n }\n}\n\nfunction compareWorker(a: WorkerView, b: WorkerView): number {\n const aStart = parseTime(a.startedAt) ?? 0\n const bStart = parseTime(b.startedAt) ?? 0\n if (a.status === 'running' && b.status !== 'running') return -1\n if (b.status === 'running' && a.status !== 'running') return 1\n return aStart - bStart || a.label.localeCompare(b.label)\n}\n\nexport function totalSpend(worker: WorkerView): SpendStats {\n return addSpend(worker.spend, worker.metered)\n}\n\nfunction addSpend(a: SpendStats, b: SpendStats): SpendStats {\n return {\n iterations: a.iterations + b.iterations,\n tokensInput: a.tokensInput + b.tokensInput,\n tokensOutput: a.tokensOutput + b.tokensOutput,\n usd: a.usd + b.usd,\n ms: a.ms + b.ms,\n }\n}\n\nexport function parseSpend(value: unknown): SpendStats {\n if (!isRecord(value)) return emptySpend\n const tokens = isRecord(value.tokens) ? value.tokens : {}\n return {\n iterations: numberValue(value.iterations),\n tokensInput: numberValue(tokens.input),\n tokensOutput: numberValue(tokens.output),\n usd: numberValue(value.usd),\n ms: numberValue(value.ms),\n }\n}\n\nfunction parseBudget(value: unknown): BudgetStats | undefined {\n if (!isRecord(value)) return undefined\n const budget: BudgetStats = {\n ...(typeof value.maxIterations === 'number' ? { maxIterations: value.maxIterations } : {}),\n ...(typeof value.maxTokens === 'number' ? { maxTokens: value.maxTokens } : {}),\n ...(typeof value.maxUsd === 'number' ? { maxUsd: value.maxUsd } : {}),\n }\n return Object.keys(budget).length ? budget : undefined\n}\n\nfunction describeVerdict(value: unknown): string | undefined {\n if (!isRecord(value)) return undefined\n if (typeof value.valid === 'boolean') return value.valid ? 'valid' : 'invalid'\n if (typeof value.score === 'number') return `score ${value.score.toFixed(2)}`\n return undefined\n}\n\nfunction distribution(values: readonly number[]): Distribution {\n if (values.length === 0) return { n: 0, min: 0, median: 0, p90: 0, max: 0 }\n const sorted = [...values].sort((a, b) => a - b)\n return {\n n: sorted.length,\n min: sorted[0] ?? 0,\n median: percentile(sorted, 0.5),\n p90: percentile(sorted, 0.9),\n max: sorted[sorted.length - 1] ?? 0,\n }\n}\n\nfunction percentile(sorted: readonly number[], p: number): number {\n if (sorted.length === 0) return 0\n const idx = Math.min(sorted.length - 1, Math.max(0, Math.ceil(sorted.length * p) - 1))\n return sorted[idx] ?? 0\n}\n\n/**\n * Read one source file under a run directory. An absent file is not a defect on its own — the\n * writer may not have reached it yet — so it reads as `undefined` with no diagnostic; only a\n * failed read raises one. `path` stays run-relative and never carries file contents.\n */\nfunction readSourceFile(\n file: string,\n source: TopSnapshotDiagnosticSource,\n path: string,\n): SourceRead<string | undefined> {\n if (!existsSync(file)) return { value: undefined, diagnostics: [] }\n try {\n return { value: readFileSync(file, 'utf8'), diagnostics: [] }\n } catch {\n return { value: undefined, diagnostics: [{ source, path, reason: 'unreadable' }] }\n }\n}\n\nfunction tailLines(raw: string | undefined, maxLines: number): string[] {\n if (raw === undefined) return []\n return raw.trim().split('\\n').filter(Boolean).slice(-maxLines)\n}\n\nfunction readProgressTail(dir: string, maxLines: number): SourceRead<string[]> {\n const path = 'progress.ndjson'\n const read = readSourceFile(join(dir, path), 'progress', path)\n return { value: tailLines(read.value, maxLines), diagnostics: read.diagnostics }\n}\n\nfunction readWorkerEventTails(\n dir: string,\n maxLines: number,\n): SourceRead<Map<string, WorkerEventTail>> {\n const out = new Map<string, WorkerEventTail>()\n if (!existsSync(dir)) return { value: out, diagnostics: [] }\n const workersDir = basename(dir)\n let entries: string[]\n try {\n entries = readdirSync(dir)\n } catch {\n return {\n value: out,\n diagnostics: [{ source: 'worker-tail', path: workersDir, reason: 'unreadable' }],\n }\n }\n const diagnostics: SourceDiagnostic[] = []\n for (const entry of entries) {\n // `<label>.inbox.ndjson` is the down-leg steer queue, not this worker's control-event log.\n if (!entry.endsWith('.ndjson') || entry.endsWith('.inbox.ndjson')) continue\n const file = join(dir, entry)\n const read = readSourceFile(file, 'worker-tail', join(workersDir, entry))\n diagnostics.push(...read.diagnostics)\n const lines = tailLines(read.value, maxLines)\n out.set(entry.slice(0, -'.ndjson'.length), { file, lines })\n }\n return { value: out, diagnostics }\n}\n\nfunction readSupervisorState(dir: string): SourceRead<SupervisorState | undefined> {\n const path = 'state.json'\n const read = readSourceFile(join(dir, path), 'supervisor-state', path)\n if (read.diagnostics.length > 0) return { value: undefined, diagnostics: read.diagnostics }\n if (read.value === undefined)\n return {\n value: undefined,\n diagnostics: [{ source: 'supervisor-state', path, reason: 'missing' }],\n }\n let parsed: Partial<SupervisorState>\n try {\n parsed = JSON.parse(read.value) as Partial<SupervisorState>\n } catch {\n return {\n value: undefined,\n diagnostics: [{ source: 'supervisor-state', path, reason: 'partial-json' }],\n }\n }\n if (!isSupervisorState(parsed))\n return {\n value: undefined,\n diagnostics: [{ source: 'supervisor-state', path, reason: 'invalid-state' }],\n }\n return { value: parsed, diagnostics: [] }\n}\n\nfunction isSupervisorState(value: Partial<SupervisorState> | undefined): value is SupervisorState {\n return (\n value !== undefined &&\n typeof value.id === 'string' &&\n typeof value.status === 'string' &&\n typeof value.task === 'string' &&\n typeof value.workspaceDir === 'string' &&\n typeof value.budget === 'number'\n )\n}\n\nfunction isSpawnEvent(value: unknown): value is TopJournalEvent {\n if (!isRecord(value)) return false\n return (\n (value.kind === 'spawned' && typeof value.id === 'string') ||\n (value.kind === 'settled' && typeof value.id === 'string') ||\n (value.kind === 'cancelled' && typeof value.id === 'string') ||\n (value.kind === 'metered' && typeof value.id === 'string') ||\n (value.kind === 'progress' && typeof value.id === 'string')\n )\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null\n}\n\nfunction isDirectory(path: string): boolean {\n try {\n return statSync(path).isDirectory()\n } catch {\n return false\n }\n}\n\nexport function numberValue(value: unknown): number {\n return typeof value === 'number' && Number.isFinite(value) ? value : 0\n}\n\nexport function parseTime(value: string | undefined): number | undefined {\n if (!value) return undefined\n const parsed = Date.parse(value)\n return Number.isFinite(parsed) ? parsed : undefined\n}\n\nfunction sum(values: readonly number[]): number {\n return values.reduce((total, value) => total + value, 0)\n}\n"],"mapp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AO,SAAS,KAAK,IAAI,QAAQ;AACvE;AAEA,SAAgB,UAAU,OAA+C;CACvE,IAAI,CAAC,OAAO,OAAO,KAAA;CACnB,MAAM,SAAS,KAAK,MAAM,KAAK;CAC/B,OAAO,OAAO,SAAS,MAAM,IAAI,SAAS,KAAA;AAC5C;AAEA,SAAS,IAAI,QAAmC;CAC9C,OAAO,OAAO,QAAQ,OAAO,UAAU,QAAQ,OAAO,CAAC;AACzD"}
|
|
1
|
+
{"version":3,"file":"top-snapshot-ChwpTr7A.js","names":[],"sources":["../src/tui/top-snapshot.ts"],"sourcesContent":["/**\n * The snapshot reader for the supervisor-run TUI: turn the on-disk run layout into a `TopSnapshot`.\n * ANSI frame presentation lives in `./top-frame`; this module owns reading and projection.\n *\n * This module never derives a run path itself. Every directory and per-worker file it reads comes\n * from `../runtime/supervise/run-layout` — the same module the writers use — so the reader cannot\n * drift from the layout the way an independently-versioned copy of the contract would.\n *\n * Extracted from the `loops` repo (`src/top-model.ts`), which held a hand-joined copy of the\n * layout. Rendering is deliberately unchanged: raw ANSI, zero dependencies.\n *\n * This is the OPERATOR view: what is on disk right now, for a human watching a workspace. It\n * carries no model-call identity, so its per-supervisor totals cannot be joined with root stream\n * events without double counting. A client that needs one execution's totals reads\n * `projectPursuit` from `../durable` instead.\n *\n * @experimental\n */\n\nimport { existsSync, readdirSync, readFileSync, statSync } from 'node:fs'\nimport { basename, join, resolve } from 'node:path'\nimport { spawnJournalRecordEvents } from '../durable/spawn-journal/record-events'\nimport {\n legacySupervisorRunsRoot,\n safeWorkerFile,\n supervisorRunsRoot,\n supervisorWorkersDir,\n} from '../runtime/supervise/run-layout'\n\nexport interface TopSnapshot {\n readonly root: string\n readonly generatedAt: number\n readonly supervisors: SupervisorView[]\n /** `partial` when at least one discovered source could not be read completely. */\n readonly completeness: TopSnapshotCompleteness\n /** One bounded entry per skipped or partially read source; empty when complete. */\n readonly diagnostics: ReadonlyArray<TopSnapshotDiagnostic>\n /** Run directories found under the runs roots, readable or not. */\n readonly discovered: number\n /** Run directories whose state.json parsed into a valid supervisor view. */\n readonly loaded: number\n}\n\nexport type TopSnapshotCompleteness = 'complete' | 'partial'\n\nexport type TopSnapshotDiagnosticSource =\n | 'supervisor-state'\n | 'journal'\n | 'progress'\n | 'worker-tail'\n\nexport type TopSnapshotDiagnosticReason =\n | 'unreadable'\n | 'partial-json'\n | 'invalid-state'\n | 'missing'\n\n/**\n * One skipped or partially read snapshot source. `path` is relative to the run directory and\n * never carries file contents, so a diagnostic is safe to show or log without leaking run data.\n */\nexport interface TopSnapshotDiagnostic {\n readonly source: TopSnapshotDiagnosticSource\n readonly runId?: string\n readonly path: string\n readonly reason: TopSnapshotDiagnosticReason\n}\n\ninterface SupervisorBase {\n readonly id: string\n readonly status: string\n readonly task: string\n readonly workspaceDir: string\n readonly budget: number\n readonly verifyCmd?: string\n readonly workerModel?: string\n readonly driverModel?: string\n readonly verdict?: string\n readonly progress?: string\n readonly startedAt?: string\n readonly completedAt?: string\n readonly maxSandboxes?: number\n readonly maxLifetimeSeconds?: number\n readonly idleTimeoutSeconds?: number\n readonly maxUsd?: number\n readonly maxDepth?: number\n}\n\nexport interface SupervisorView extends SupervisorBase {\n readonly stateDir: string\n readonly resultSpentUsd?: number\n readonly resultSpentTokens?: number\n readonly workers: WorkerView[]\n readonly progressTail: string[]\n readonly journalTail: TopJournalEvent[]\n readonly driverSpend: SpendStats\n readonly totals: SupervisorTotals\n}\n\nexport interface WorkerView {\n readonly id: string\n readonly label: string\n readonly eventFile?: string\n readonly parent?: string\n readonly runtime?: string\n readonly status: 'running' | 'done' | 'down' | 'cancelled'\n readonly verdict?: string\n readonly infra?: boolean\n readonly startedAt?: string\n readonly endedAt?: string\n readonly latencyMs: number\n readonly budget?: BudgetStats\n readonly spend: SpendStats\n readonly metered: SpendStats\n readonly liveTail: string[]\n readonly outRef?: string\n readonly reason?: string\n}\n\nexport interface SupervisorTotals {\n readonly workers: number\n readonly running: number\n readonly done: number\n readonly down: number\n readonly cancelled: number\n readonly inFlight: number\n readonly settled: number\n readonly tokensInput: number\n readonly tokensOutput: number\n readonly tokensTotal: number\n readonly usd: number\n readonly latencyMs: number\n readonly workerLatency: Distribution\n}\n\nexport interface Distribution {\n readonly n: number\n readonly min: number\n readonly median: number\n readonly p90: number\n readonly max: number\n}\n\nexport interface BudgetStats {\n readonly maxIterations?: number\n readonly maxTokens?: number\n readonly maxUsd?: number\n}\n\nexport interface SpendStats {\n readonly iterations: number\n readonly tokensInput: number\n readonly tokensOutput: number\n readonly usd: number\n readonly ms: number\n}\n\nexport type TopJournalEvent =\n | {\n readonly kind: 'spawned'\n readonly id: string\n readonly parent?: string\n readonly label?: string\n readonly budget?: unknown\n readonly runtime?: string\n readonly seq?: number\n readonly at?: string\n }\n | {\n readonly kind: 'settled'\n readonly id: string\n readonly status?: string\n readonly outRef?: string\n readonly verdict?: unknown\n readonly spent?: unknown\n readonly infra?: boolean\n readonly seq?: number\n readonly at?: string\n }\n | {\n readonly kind: 'cancelled'\n readonly spent?: unknown\n readonly id: string\n readonly reason?: string\n readonly seq?: number\n readonly at?: string\n }\n | {\n readonly kind: 'metered'\n readonly id: string\n readonly spend?: unknown\n readonly accountingOnly?: boolean\n readonly seq?: number\n readonly at?: string\n }\n | {\n readonly kind: 'progress'\n readonly id: string\n readonly spend?: unknown\n readonly seq?: number\n readonly at?: string\n }\n\ninterface SupervisorState extends SupervisorBase {\n readonly result?: {\n readonly spentUsd?: number\n readonly spentTokens?: number\n }\n}\n\ntype MutableWorker = {\n -readonly [Key in keyof Omit<WorkerView, 'latencyMs'>]: WorkerView[Key]\n}\n\ninterface WorkerEventTail {\n readonly file: string\n readonly lines: string[]\n}\n\n/** A diagnostic before its run id is attached; `loadTopSnapshot` adds `runId`. */\ninterface SourceDiagnostic {\n readonly source: TopSnapshotDiagnosticSource\n readonly path: string\n readonly reason: TopSnapshotDiagnosticReason\n}\n\n/**\n * What one snapshot source read produced: the value it could recover, and the bounded diagnostics\n * the read raised. Every reader returns this one shape, so the loader folds them identically.\n */\ninterface SourceRead<T> {\n readonly value: T\n readonly diagnostics: readonly SourceDiagnostic[]\n}\n\nconst emptySpend: SpendStats = { iterations: 0, tokensInput: 0, tokensOutput: 0, usd: 0, ms: 0 }\n\n/**\n * Read every supervisor run under one workspace into a single point-in-time snapshot.\n *\n * Pure with respect to the process: it only reads, and it never throws for a writer mid-append.\n * An unreadable or half-written source is still skipped — an operator view must survive a live\n * writer — but every skip is reported as one bounded `TopSnapshotDiagnostic`, so a client can\n * tell a removed run from a partial read. `now` is injectable so elapsed time is deterministic\n * under test.\n */\nexport function loadTopSnapshot(rootDir: string, now = Date.now()): TopSnapshot {\n const root = resolve(rootDir)\n const supervisors: SupervisorView[] = []\n const diagnostics: TopSnapshotDiagnostic[] = []\n let discovered = 0\n const report = (runId: string, sources: readonly SourceDiagnostic[]): void => {\n for (const source of sources) diagnostics.push({ ...source, runId })\n }\n // `.loops` is the pre-rename state dir; runs already on disk there stay visible.\n for (const runsRoot of [supervisorRunsRoot(root), legacySupervisorRunsRoot(root)]) {\n if (!existsSync(runsRoot)) continue\n for (const entry of readdirSync(runsRoot)) {\n const dir = join(runsRoot, entry)\n if (!isDirectory(dir)) continue\n discovered += 1\n const state = readSupervisorState(dir)\n report(entry, state.diagnostics)\n if (!state.value) continue\n const journal = readJournal(dir)\n const progress = readProgressTail(dir, 8)\n const workerEvents = readWorkerEventTails(supervisorWorkersDir(dir), 8)\n report(entry, [...journal.diagnostics, ...progress.diagnostics, ...workerEvents.diagnostics])\n supervisors.push(\n buildSupervisorView(\n state.value,\n dir,\n journal.value,\n progress.value,\n now,\n workerEvents.value,\n ),\n )\n }\n }\n supervisors.sort((a, b) => String(b.startedAt ?? '').localeCompare(String(a.startedAt ?? '')))\n return {\n root,\n generatedAt: now,\n supervisors,\n completeness: diagnostics.length === 0 ? 'complete' : 'partial',\n diagnostics,\n discovered,\n loaded: supervisors.length,\n }\n}\n\n/**\n * The journal file a run dir actually carries. `createFileRunContext` — this repo's own durable\n * writer — names it `spawn-journal.jsonl`; `journal.jsonl` is the retired bare-event file older\n * runs left behind. First existing name wins; a reader that knew only the retired name would show\n * zero workers for every current run.\n */\nconst journalFileNames = ['spawn-journal.jsonl', 'journal.jsonl'] as const\n\nfunction readJournal(eventDir: string): SourceRead<TopJournalEvent[]> {\n const path = journalFileNames.find((candidate) => existsSync(join(eventDir, candidate)))\n if (!path) return { value: [], diagnostics: [] }\n const read = readSourceFile(join(eventDir, path), 'journal', path)\n if (read.value === undefined) return { value: [], diagnostics: read.diagnostics }\n const out: TopJournalEvent[] = []\n let partial = false\n for (const line of read.value.split('\\n')) {\n const trimmed = line.trim()\n if (!trimmed) continue\n try {\n const parsed = JSON.parse(trimmed) as Record<string, unknown>\n const events =\n parsed.kind === 'event' || parsed.kind === 'events'\n ? spawnJournalRecordEvents(parsed)\n : [parsed]\n for (const event of events) if (isSpawnEvent(event)) out.push(event)\n } catch {\n // A corrupt line is expected while the writer is mid-append; keep the lines that parsed.\n partial = true\n }\n }\n return {\n value: out,\n diagnostics: partial ? [{ source: 'journal', path, reason: 'partial-json' }] : [],\n }\n}\n\nfunction buildSupervisorView(\n state: SupervisorState,\n stateDir: string,\n events: readonly TopJournalEvent[],\n progressTail: readonly string[],\n now: number,\n workerEventTails = new Map<string, WorkerEventTail>(),\n): SupervisorView {\n const workers = new Map<string, MutableWorker>()\n let driverSpend = emptySpend\n // `state.json` and the spawn journal are written by DIFFERENT producers, and their ids need not\n // agree: the journal's root is the runtime's `runId`, which defaults to a literal unrelated to\n // the supervisor id the state file records. Recover the journal's own root from its parentless\n // root spawn, and treat EITHER id as the root everywhere. Checking only `state.id` — which the\n // metered/settled/cancelled branches used to do — manufactures a phantom worker named after the\n // runId that never settles, sorts first as RUNNING, and silently captures every steer and cancel.\n const journalRootId = events.find(\n (event) => event.kind === 'spawned' && !event.parent && event.label === 'root',\n )?.id\n const isRoot = (id: string): boolean => id === state.id || id === journalRootId\n\n for (const event of events) {\n if (event.kind === 'spawned') {\n if (isRoot(event.id) || (!event.parent && event.label === 'root')) continue\n const worker = ensureWorker(workers, event.id, event.label ?? event.id)\n worker.label = event.label ?? worker.label\n if (event.parent) worker.parent = event.parent\n if (event.runtime) worker.runtime = event.runtime\n worker.status = 'running'\n if (event.at) worker.startedAt = event.at\n const budget = parseBudget(event.budget)\n if (budget) worker.budget = budget\n continue\n }\n\n if (event.kind === 'settled') {\n if (isRoot(event.id)) continue\n const worker = ensureWorker(workers, event.id, event.id)\n worker.status = event.status === 'down' ? 'down' : 'done'\n if (event.at) worker.endedAt = event.at\n if (event.outRef) worker.outRef = event.outRef\n if (event.infra !== undefined) worker.infra = event.infra\n const verdict = describeVerdict(event.verdict)\n if (verdict) worker.verdict = verdict\n worker.spend = addSpend(worker.spend, parseSpend(event.spent))\n // Live progress is cumulative observation. The terminal spend replaces it, so do not add\n // the two channels or a worker's final cost would be counted twice.\n worker.metered = emptySpend\n continue\n }\n\n if (event.kind === 'cancelled') {\n if (isRoot(event.id)) continue\n const worker = ensureWorker(workers, event.id, event.id)\n worker.status = 'cancelled'\n if (event.at) worker.endedAt = event.at\n if (event.reason) worker.reason = event.reason\n if (event.spent !== undefined) {\n worker.spend = addSpend(worker.spend, parseSpend(event.spent))\n worker.metered = emptySpend\n }\n continue\n }\n\n if (event.kind === 'metered') {\n const spend = parseSpend(event.spend)\n if (isRoot(event.id)) {\n if (event.accountingOnly !== true) driverSpend = addSpend(driverSpend, spend)\n } else {\n const worker = ensureWorker(workers, event.id, event.id)\n if (event.accountingOnly !== true) worker.metered = addSpend(worker.metered, spend)\n }\n continue\n }\n\n if (event.kind === 'progress') {\n if (isRoot(event.id)) continue\n const worker = ensureWorker(workers, event.id, event.id)\n worker.metered = parseSpend(event.spend)\n }\n }\n\n const workerViews = [...workers.values()]\n .map((worker) => {\n // Tails are keyed by file stem, which the writer put through `safeWorkerFile`; a label\n // carrying characters that stem strips would otherwise never find its own events.\n const tail =\n workerEventTails.get(worker.label) ??\n workerEventTails.get(safeWorkerFile(worker.label)) ??\n workerEventTails.get(safeWorkerFile(worker.id)) ??\n workerEventTails.get(worker.id)\n worker.liveTail = tail?.lines ?? []\n if (tail?.file) worker.eventFile = tail.file\n return finalizeWorker(worker, now)\n })\n .sort((a, b) => compareWorker(a, b))\n\n const totals = supervisorTotals(state, workerViews, driverSpend, now)\n return {\n id: state.id,\n stateDir,\n status: state.status,\n task: state.task,\n workspaceDir: state.workspaceDir,\n budget: state.budget,\n ...(state.verifyCmd ? { verifyCmd: state.verifyCmd } : {}),\n ...(state.workerModel ? { workerModel: state.workerModel } : {}),\n ...(state.driverModel ? { driverModel: state.driverModel } : {}),\n ...(state.verdict ? { verdict: state.verdict } : {}),\n ...(state.progress ? { progress: state.progress } : {}),\n ...(state.startedAt ? { startedAt: state.startedAt } : {}),\n ...(state.completedAt ? { completedAt: state.completedAt } : {}),\n ...(state.maxSandboxes !== undefined ? { maxSandboxes: state.maxSandboxes } : {}),\n ...(state.maxLifetimeSeconds !== undefined\n ? { maxLifetimeSeconds: state.maxLifetimeSeconds }\n : {}),\n ...(state.idleTimeoutSeconds !== undefined\n ? { idleTimeoutSeconds: state.idleTimeoutSeconds }\n : {}),\n ...(state.maxUsd !== undefined ? { maxUsd: state.maxUsd } : {}),\n ...(state.maxDepth !== undefined ? { maxDepth: state.maxDepth } : {}),\n ...(state.result?.spentUsd !== undefined ? { resultSpentUsd: state.result.spentUsd } : {}),\n ...(state.result?.spentTokens !== undefined\n ? { resultSpentTokens: state.result.spentTokens }\n : {}),\n workers: workerViews,\n progressTail: [...progressTail],\n journalTail: events.slice(-12),\n driverSpend,\n totals,\n }\n}\n\nfunction ensureWorker(\n workers: Map<string, MutableWorker>,\n id: string,\n label: string,\n): MutableWorker {\n const existing = workers.get(id)\n if (existing) return existing\n const created: MutableWorker = {\n id,\n label,\n status: 'running',\n spend: emptySpend,\n metered: emptySpend,\n liveTail: [],\n }\n workers.set(id, created)\n return created\n}\n\nfunction finalizeWorker(worker: MutableWorker, now: number): WorkerView {\n const startMs = parseTime(worker.startedAt)\n const endMs = parseTime(worker.endedAt) ?? (worker.status === 'running' ? now : startMs)\n const latencyMs = startMs !== undefined && endMs !== undefined ? Math.max(0, endMs - startMs) : 0\n return {\n id: worker.id,\n label: worker.label,\n ...(worker.eventFile ? { eventFile: worker.eventFile } : {}),\n ...(worker.parent ? { parent: worker.parent } : {}),\n ...(worker.runtime ? { runtime: worker.runtime } : {}),\n status: worker.status,\n ...(worker.verdict ? { verdict: worker.verdict } : {}),\n ...(worker.infra !== undefined ? { infra: worker.infra } : {}),\n ...(worker.startedAt ? { startedAt: worker.startedAt } : {}),\n ...(worker.endedAt ? { endedAt: worker.endedAt } : {}),\n latencyMs,\n ...(worker.budget ? { budget: worker.budget } : {}),\n spend: worker.spend,\n metered: worker.metered,\n liveTail: worker.liveTail,\n ...(worker.outRef ? { outRef: worker.outRef } : {}),\n ...(worker.reason ? { reason: worker.reason } : {}),\n }\n}\n\nfunction supervisorTotals(\n state: SupervisorState,\n workers: readonly WorkerView[],\n driverSpend: SpendStats,\n now: number,\n): SupervisorTotals {\n const workerSpends = workers.map(totalSpend)\n const tokenInput = sum(workerSpends.map((spend) => spend.tokensInput)) + driverSpend.tokensInput\n const tokenOutput =\n sum(workerSpends.map((spend) => spend.tokensOutput)) + driverSpend.tokensOutput\n const computedUsd = sum(workerSpends.map((spend) => spend.usd)) + driverSpend.usd\n const usd = computedUsd > 0 ? computedUsd : (state.result?.spentUsd ?? 0)\n const started = parseTime(state.startedAt)\n const completed = parseTime(state.completedAt)\n const latencyMs = started !== undefined ? Math.max(0, (completed ?? now) - started) : 0\n const latencies = workers.map((worker) => worker.latencyMs).filter((ms) => ms > 0)\n return {\n workers: workers.length,\n running: workers.filter((worker) => worker.status === 'running').length,\n done: workers.filter((worker) => worker.status === 'done').length,\n down: workers.filter((worker) => worker.status === 'down').length,\n cancelled: workers.filter((worker) => worker.status === 'cancelled').length,\n inFlight: workers.filter((worker) => worker.status === 'running').length,\n settled: workers.filter((worker) => worker.status !== 'running').length,\n tokensInput: tokenInput,\n tokensOutput: tokenOutput,\n tokensTotal: tokenInput + tokenOutput,\n usd,\n latencyMs,\n workerLatency: distribution(latencies),\n }\n}\n\nexport function aggregateSnapshot(snapshot: TopSnapshot): {\n supervisors: number\n workers: number\n running: number\n done: number\n down: number\n usd: number\n tokensInput: number\n tokensOutput: number\n} {\n return {\n supervisors: snapshot.supervisors.length,\n workers: sum(snapshot.supervisors.map((supervisor) => supervisor.totals.workers)),\n running: sum(snapshot.supervisors.map((supervisor) => supervisor.totals.running)),\n done: sum(snapshot.supervisors.map((supervisor) => supervisor.totals.done)),\n down: sum(snapshot.supervisors.map((supervisor) => supervisor.totals.down)),\n usd: sum(snapshot.supervisors.map((supervisor) => supervisor.totals.usd)),\n tokensInput: sum(snapshot.supervisors.map((supervisor) => supervisor.totals.tokensInput)),\n tokensOutput: sum(snapshot.supervisors.map((supervisor) => supervisor.totals.tokensOutput)),\n }\n}\n\nfunction compareWorker(a: WorkerView, b: WorkerView): number {\n const aStart = parseTime(a.startedAt) ?? 0\n const bStart = parseTime(b.startedAt) ?? 0\n if (a.status === 'running' && b.status !== 'running') return -1\n if (b.status === 'running' && a.status !== 'running') return 1\n return aStart - bStart || a.label.localeCompare(b.label)\n}\n\nexport function totalSpend(worker: WorkerView): SpendStats {\n return addSpend(worker.spend, worker.metered)\n}\n\nfunction addSpend(a: SpendStats, b: SpendStats): SpendStats {\n return {\n iterations: a.iterations + b.iterations,\n tokensInput: a.tokensInput + b.tokensInput,\n tokensOutput: a.tokensOutput + b.tokensOutput,\n usd: a.usd + b.usd,\n ms: a.ms + b.ms,\n }\n}\n\nexport function parseSpend(value: unknown): SpendStats {\n if (!isRecord(value)) return emptySpend\n const tokens = isRecord(value.tokens) ? value.tokens : {}\n return {\n iterations: numberValue(value.iterations),\n tokensInput: numberValue(tokens.input),\n tokensOutput: numberValue(tokens.output),\n usd: numberValue(value.usd),\n ms: numberValue(value.ms),\n }\n}\n\nfunction parseBudget(value: unknown): BudgetStats | undefined {\n if (!isRecord(value)) return undefined\n const budget: BudgetStats = {\n ...(typeof value.maxIterations === 'number' ? { maxIterations: value.maxIterations } : {}),\n ...(typeof value.maxTokens === 'number' ? { maxTokens: value.maxTokens } : {}),\n ...(typeof value.maxUsd === 'number' ? { maxUsd: value.maxUsd } : {}),\n }\n return Object.keys(budget).length ? budget : undefined\n}\n\nfunction describeVerdict(value: unknown): string | undefined {\n if (!isRecord(value)) return undefined\n if (typeof value.valid === 'boolean') return value.valid ? 'valid' : 'invalid'\n if (typeof value.score === 'number') return `score ${value.score.toFixed(2)}`\n return undefined\n}\n\nfunction distribution(values: readonly number[]): Distribution {\n if (values.length === 0) return { n: 0, min: 0, median: 0, p90: 0, max: 0 }\n const sorted = [...values].sort((a, b) => a - b)\n return {\n n: sorted.length,\n min: sorted[0] ?? 0,\n median: percentile(sorted, 0.5),\n p90: percentile(sorted, 0.9),\n max: sorted[sorted.length - 1] ?? 0,\n }\n}\n\nfunction percentile(sorted: readonly number[], p: number): number {\n if (sorted.length === 0) return 0\n const idx = Math.min(sorted.length - 1, Math.max(0, Math.ceil(sorted.length * p) - 1))\n return sorted[idx] ?? 0\n}\n\n/**\n * Read one source file under a run directory. An absent file is not a defect on its own — the\n * writer may not have reached it yet — so it reads as `undefined` with no diagnostic; only a\n * failed read raises one. `path` stays run-relative and never carries file contents.\n */\nfunction readSourceFile(\n file: string,\n source: TopSnapshotDiagnosticSource,\n path: string,\n): SourceRead<string | undefined> {\n if (!existsSync(file)) return { value: undefined, diagnostics: [] }\n try {\n return { value: readFileSync(file, 'utf8'), diagnostics: [] }\n } catch {\n return { value: undefined, diagnostics: [{ source, path, reason: 'unreadable' }] }\n }\n}\n\nfunction tailLines(raw: string | undefined, maxLines: number): string[] {\n if (raw === undefined) return []\n return raw.trim().split('\\n').filter(Boolean).slice(-maxLines)\n}\n\nfunction readProgressTail(dir: string, maxLines: number): SourceRead<string[]> {\n const path = 'progress.ndjson'\n const read = readSourceFile(join(dir, path), 'progress', path)\n return { value: tailLines(read.value, maxLines), diagnostics: read.diagnostics }\n}\n\nfunction readWorkerEventTails(\n dir: string,\n maxLines: number,\n): SourceRead<Map<string, WorkerEventTail>> {\n const out = new Map<string, WorkerEventTail>()\n if (!existsSync(dir)) return { value: out, diagnostics: [] }\n const workersDir = basename(dir)\n let entries: string[]\n try {\n entries = readdirSync(dir)\n } catch {\n return {\n value: out,\n diagnostics: [{ source: 'worker-tail', path: workersDir, reason: 'unreadable' }],\n }\n }\n const diagnostics: SourceDiagnostic[] = []\n for (const entry of entries) {\n // `<label>.inbox.ndjson` is the down-leg steer queue, not this worker's control-event log.\n if (!entry.endsWith('.ndjson') || entry.endsWith('.inbox.ndjson')) continue\n const file = join(dir, entry)\n const read = readSourceFile(file, 'worker-tail', join(workersDir, entry))\n diagnostics.push(...read.diagnostics)\n const lines = tailLines(read.value, maxLines)\n out.set(entry.slice(0, -'.ndjson'.length), { file, lines })\n }\n return { value: out, diagnostics }\n}\n\nfunction readSupervisorState(dir: string): SourceRead<SupervisorState | undefined> {\n const path = 'state.json'\n const read = readSourceFile(join(dir, path), 'supervisor-state', path)\n if (read.diagnostics.length > 0) return { value: undefined, diagnostics: read.diagnostics }\n if (read.value === undefined)\n return {\n value: undefined,\n diagnostics: [{ source: 'supervisor-state', path, reason: 'missing' }],\n }\n let parsed: Partial<SupervisorState>\n try {\n parsed = JSON.parse(read.value) as Partial<SupervisorState>\n } catch {\n return {\n value: undefined,\n diagnostics: [{ source: 'supervisor-state', path, reason: 'partial-json' }],\n }\n }\n if (!isSupervisorState(parsed))\n return {\n value: undefined,\n diagnostics: [{ source: 'supervisor-state', path, reason: 'invalid-state' }],\n }\n return { value: parsed, diagnostics: [] }\n}\n\nfunction isSupervisorState(value: Partial<SupervisorState> | undefined): value is SupervisorState {\n return (\n value !== undefined &&\n typeof value.id === 'string' &&\n typeof value.status === 'string' &&\n typeof value.task === 'string' &&\n typeof value.workspaceDir === 'string' &&\n typeof value.budget === 'number'\n )\n}\n\nfunction isSpawnEvent(value: unknown): value is TopJournalEvent {\n if (!isRecord(value)) return false\n return (\n (value.kind === 'spawned' && typeof value.id === 'string') ||\n (value.kind === 'settled' && typeof value.id === 'string') ||\n (value.kind === 'cancelled' && typeof value.id === 'string') ||\n (value.kind === 'metered' && typeof value.id === 'string') ||\n (value.kind === 'progress' && typeof value.id === 'string')\n )\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null\n}\n\nfunction isDirectory(path: string): boolean {\n try {\n return statSync(path).isDirectory()\n } catch {\n return false\n }\n}\n\nexport function numberValue(value: unknown): number {\n return typeof value === 'number' && Number.isFinite(value) ? value : 0\n}\n\nexport function parseTime(value: string | undefined): number | undefined {\n if (!value) return undefined\n const parsed = Date.parse(value)\n return Number.isFinite(parsed) ? parsed : undefined\n}\n\nfunction sum(values: readonly number[]): number {\n return values.reduce((total, value) => total + value, 0)\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;AA2OA,MAAM,aAAyB;CAAE,YAAY;CAAG,aAAa;CAAG,cAAc;CAAG,KAAK;CAAG,IAAI;AAAE;;;;;;;;;;AAW/F,SAAgB,gBAAgB,SAAiB,MAAM,KAAK,IAAI,GAAgB;CAC9E,MAAM,OAAO,QAAQ,OAAO;CAC5B,MAAM,cAAgC,CAAC;CACvC,MAAM,cAAuC,CAAC;CAC9C,IAAI,aAAa;CACjB,MAAM,UAAU,OAAe,YAA+C;EAC5E,KAAK,MAAM,UAAU,SAAS,YAAY,KAAK;GAAE,GAAG;GAAQ;EAAM,CAAC;CACrE;CAEA,KAAK,MAAM,YAAY,CAAC,mBAAmB,IAAI,GAAG,yBAAyB,IAAI,CAAC,GAAG;EACjF,IAAI,CAAC,WAAW,QAAQ,GAAG;EAC3B,KAAK,MAAM,SAAS,YAAY,QAAQ,GAAG;GACzC,MAAM,MAAM,KAAK,UAAU,KAAK;GAChC,IAAI,CAAC,YAAY,GAAG,GAAG;GACvB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,SAAS,YACtB,OAAO,MAAM,iBAAiB,YAC9B,OAAO,MAAM,WAAW;AAE5B;AAEA,SAAS,aAAa,OAA0C;CAC9D,IAAI,CAAC,SAAS,KAAK,GAAG,OAAO;CAC7B,OACG,MAAM,SAAS,aAAa,OAAO,MAAM,OAAO,YAChD,MAAM,SAAS,aAAa,OAAO,MAAM,OAAO,YAChD,MAAM,SAAS,eAAe,OAAO,MAAM,OAAO,YAClD,MAAM,SAAS,aAAa,OAAO,MAAM,OAAO,YAChD,MAAM,SAAS,cAAc,OAAO,MAAM,OAAO;AAEtD;AAEA,SAAS,SAAS,OAAkD;CAClE,OAAO,OAAO,UAAU,YAAY,UAAU;AAChD;AAEA,SAAS,YAAY,MAAuB;CAC1C,IAAI;EACF,OAAO,SAAS,IAAI,CAAC,CAAC,YAAY;CACpC,QAAQ;EACN,OAAO;CACT;AACF;AAEA,SAAgB,YAAY,OAAwB;CAClD,OAAO,OAAO,UAAU,YAAY,OAAO,SAAS,KAAK,IAAI,QAAQ;AACvE;AAEA,SAAgB,UAAU,OAA+C;CACvE,IAAI,CAAC,OAAO,OAAO,KAAA;CACnB,MAAM,SAAS,KAAK,MAAM,KAAK;CAC/B,OAAO,OAAO,SAAS,MAAM,IAAI,SAAS,KAAA;AAC5C;AAEA,SAAS,IAAI,QAAmC;CAC9C,OAAO,OAAO,QAAQ,OAAO,UAAU,QAAQ,OAAO,CAAC;AACzD"}
|
package/dist/tui/bin.js
CHANGED
|
@@ -1,11 +1,11 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import { l as cancelWorker, n as cancelRun, w as writeWorkerSteer, y as supervisorRunsRoot } from "../run-cancellation-
|
|
3
|
-
import { a as parseTime, i as parseSpend, n as loadTopSnapshot, o as totalSpend, r as numberValue, t as aggregateSnapshot } from "../top-snapshot-
|
|
2
|
+
import { l as cancelWorker, n as cancelRun, w as writeWorkerSteer, y as supervisorRunsRoot } from "../run-cancellation-BLy_Zz-w.js";
|
|
3
|
+
import { a as parseTime, i as parseSpend, n as loadTopSnapshot, o as totalSpend, r as numberValue, t as aggregateSnapshot } from "../top-snapshot-ChwpTr7A.js";
|
|
4
4
|
import { randomUUID } from "node:crypto";
|
|
5
5
|
import { resolve } from "node:path";
|
|
6
6
|
import { hostname, userInfo } from "node:os";
|
|
7
7
|
import { emitKeypressEvents } from "node:readline";
|
|
8
|
-
|
|
8
|
+
// src/tui/top-frame.ts
|
|
9
9
|
const ansiPattern = /\x1b\[[0-9;?]*[ -/]*[@-~]/g;
|
|
10
10
|
const colors = {
|
|
11
11
|
reset: "\x1B[0m",
|
|
@@ -395,8 +395,7 @@ function fitAnsi(value, width) {
|
|
|
395
395
|
if (out.includes("\x1B[") && !out.endsWith(colors.reset)) out += colors.reset;
|
|
396
396
|
return out;
|
|
397
397
|
}
|
|
398
|
-
|
|
399
|
-
//#region src/tui/top-app.ts
|
|
398
|
+
// src/tui/top-app.ts
|
|
400
399
|
/**
|
|
401
400
|
* The interactive side of the supervisor-run TUI: a keypress/mouse loop over the frames
|
|
402
401
|
* `./top-frame` renders, plus the operator controls that write back to the run — steer a live
|
|
@@ -458,8 +457,9 @@ function runTopApp(options = {}) {
|
|
|
458
457
|
start();
|
|
459
458
|
}
|
|
460
459
|
function initialState(args, cwd) {
|
|
460
|
+
const rootArg = args.find((arg) => !arg.startsWith("-"));
|
|
461
461
|
return {
|
|
462
|
-
root: resolve(
|
|
462
|
+
root: resolve(rootArg ?? cwd),
|
|
463
463
|
color: Boolean(process.stdout.isTTY) && !args.includes("--no-color"),
|
|
464
464
|
focus: args.includes("--detail") ? "workers" : "supervisors",
|
|
465
465
|
mode: args.includes("--log") ? "log" : args.includes("--detail") ? "detail" : "overview",
|
|
@@ -711,8 +711,7 @@ function requestCancel() {
|
|
|
711
711
|
function wrap(value, size) {
|
|
712
712
|
return (value % size + size) % size;
|
|
713
713
|
}
|
|
714
|
-
|
|
715
|
-
//#region src/tui/bin.ts
|
|
714
|
+
// src/tui/bin.ts
|
|
716
715
|
/**
|
|
717
716
|
* `agent-runtime-top` — watch the supervisor runs of one workspace.
|
|
718
717
|
*
|
|
@@ -725,7 +724,6 @@ function wrap(value, size) {
|
|
|
725
724
|
* @experimental
|
|
726
725
|
*/
|
|
727
726
|
runTopApp();
|
|
728
|
-
//#endregion
|
|
729
727
|
export {};
|
|
730
728
|
|
|
731
729
|
//# sourceMappingURL=bin.js.map
|