@caupulican/pi-adaptative 0.81.29 → 0.81.30

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (147) hide show
  1. package/CHANGELOG.md +18 -0
  2. package/dist/bundled-resources/skills/harness-self-adaptation/SKILL.md +327 -0
  3. package/dist/bundled-resources/skills/harness-self-adaptation/references/adaptation-layers.md +89 -0
  4. package/dist/core/agent-session.d.ts +11 -1
  5. package/dist/core/agent-session.d.ts.map +1 -1
  6. package/dist/core/agent-session.js +16 -14
  7. package/dist/core/agent-session.js.map +1 -1
  8. package/dist/core/autonomy/approval-gate.d.ts +1 -1
  9. package/dist/core/autonomy/approval-gate.d.ts.map +1 -1
  10. package/dist/core/autonomy/approval-gate.js +5 -1
  11. package/dist/core/autonomy/approval-gate.js.map +1 -1
  12. package/dist/core/autonomy/lane-tool-surface.d.ts +4 -0
  13. package/dist/core/autonomy/lane-tool-surface.d.ts.map +1 -1
  14. package/dist/core/autonomy/lane-tool-surface.js +31 -4
  15. package/dist/core/autonomy/lane-tool-surface.js.map +1 -1
  16. package/dist/core/autonomy/lane-tracker.d.ts +1 -0
  17. package/dist/core/autonomy/lane-tracker.d.ts.map +1 -1
  18. package/dist/core/autonomy/lane-tracker.js +11 -0
  19. package/dist/core/autonomy/lane-tracker.js.map +1 -1
  20. package/dist/core/autonomy/risk-assessment.d.ts.map +1 -1
  21. package/dist/core/autonomy/risk-assessment.js +1 -1
  22. package/dist/core/autonomy/risk-assessment.js.map +1 -1
  23. package/dist/core/background-lane-controller.d.ts +12 -0
  24. package/dist/core/background-lane-controller.d.ts.map +1 -1
  25. package/dist/core/background-lane-controller.js +114 -19
  26. package/dist/core/background-lane-controller.js.map +1 -1
  27. package/dist/core/context/context-artifacts.d.ts.map +1 -1
  28. package/dist/core/context/context-artifacts.js +7 -6
  29. package/dist/core/context/context-artifacts.js.map +1 -1
  30. package/dist/core/context/context-store-retention.d.ts +12 -0
  31. package/dist/core/context/context-store-retention.d.ts.map +1 -0
  32. package/dist/core/context/context-store-retention.js +161 -0
  33. package/dist/core/context/context-store-retention.js.map +1 -0
  34. package/dist/core/context-gc.d.ts.map +1 -1
  35. package/dist/core/context-gc.js +19 -4
  36. package/dist/core/context-gc.js.map +1 -1
  37. package/dist/core/context-pipeline.d.ts +13 -12
  38. package/dist/core/context-pipeline.d.ts.map +1 -1
  39. package/dist/core/context-pipeline.js +128 -33
  40. package/dist/core/context-pipeline.js.map +1 -1
  41. package/dist/core/cost/cost-summary.d.ts +7 -1
  42. package/dist/core/cost/cost-summary.d.ts.map +1 -1
  43. package/dist/core/cost/cost-summary.js +28 -17
  44. package/dist/core/cost/cost-summary.js.map +1 -1
  45. package/dist/core/cost/daily-usage.d.ts +7 -3
  46. package/dist/core/cost/daily-usage.d.ts.map +1 -1
  47. package/dist/core/cost/daily-usage.js +10 -5
  48. package/dist/core/cost/daily-usage.js.map +1 -1
  49. package/dist/core/delegation/worker-runner.d.ts.map +1 -1
  50. package/dist/core/delegation/worker-runner.js +25 -9
  51. package/dist/core/delegation/worker-runner.js.map +1 -1
  52. package/dist/core/export-html/template.js +2 -1
  53. package/dist/core/extensions/loader.d.ts.map +1 -1
  54. package/dist/core/extensions/loader.js +52 -2
  55. package/dist/core/extensions/loader.js.map +1 -1
  56. package/dist/core/extensions/runner.d.ts.map +1 -1
  57. package/dist/core/extensions/runner.js +21 -19
  58. package/dist/core/extensions/runner.js.map +1 -1
  59. package/dist/core/extensions/types.d.ts +5 -0
  60. package/dist/core/extensions/types.d.ts.map +1 -1
  61. package/dist/core/extensions/types.js.map +1 -1
  62. package/dist/core/failure-corpus.d.ts.map +1 -1
  63. package/dist/core/failure-corpus.js +36 -13
  64. package/dist/core/failure-corpus.js.map +1 -1
  65. package/dist/core/local-runtime-controller.d.ts.map +1 -1
  66. package/dist/core/local-runtime-controller.js +20 -2
  67. package/dist/core/local-runtime-controller.js.map +1 -1
  68. package/dist/core/memory-controller.d.ts +2 -0
  69. package/dist/core/memory-controller.d.ts.map +1 -1
  70. package/dist/core/memory-controller.js +18 -0
  71. package/dist/core/memory-controller.js.map +1 -1
  72. package/dist/core/models/local-runtime.d.ts.map +1 -1
  73. package/dist/core/models/local-runtime.js +15 -10
  74. package/dist/core/models/local-runtime.js.map +1 -1
  75. package/dist/core/reflection-controller.d.ts +3 -1
  76. package/dist/core/reflection-controller.d.ts.map +1 -1
  77. package/dist/core/reflection-controller.js +8 -5
  78. package/dist/core/reflection-controller.js.map +1 -1
  79. package/dist/core/runtime-builder.d.ts +2 -0
  80. package/dist/core/runtime-builder.d.ts.map +1 -1
  81. package/dist/core/runtime-builder.js.map +1 -1
  82. package/dist/core/sdk.d.ts.map +1 -1
  83. package/dist/core/sdk.js +1 -1
  84. package/dist/core/sdk.js.map +1 -1
  85. package/dist/core/session-analytics.d.ts +13 -7
  86. package/dist/core/session-analytics.d.ts.map +1 -1
  87. package/dist/core/session-analytics.js +155 -112
  88. package/dist/core/session-analytics.js.map +1 -1
  89. package/dist/core/tool-recovery-log-records.d.ts.map +1 -1
  90. package/dist/core/tool-recovery-log-records.js +54 -9
  91. package/dist/core/tool-recovery-log-records.js.map +1 -1
  92. package/dist/core/tool-recovery-logger.d.ts +2 -0
  93. package/dist/core/tool-recovery-logger.d.ts.map +1 -1
  94. package/dist/core/tool-recovery-logger.js +32 -13
  95. package/dist/core/tool-recovery-logger.js.map +1 -1
  96. package/dist/core/tool-recovery-stats.d.ts +15 -0
  97. package/dist/core/tool-recovery-stats.d.ts.map +1 -0
  98. package/dist/core/tool-recovery-stats.js +206 -0
  99. package/dist/core/tool-recovery-stats.js.map +1 -0
  100. package/dist/core/tools/delegate-status.d.ts.map +1 -1
  101. package/dist/core/tools/delegate-status.js +15 -6
  102. package/dist/core/tools/delegate-status.js.map +1 -1
  103. package/dist/core/tools/delegate.d.ts +3 -0
  104. package/dist/core/tools/delegate.d.ts.map +1 -1
  105. package/dist/core/tools/delegate.js +7 -2
  106. package/dist/core/tools/delegate.js.map +1 -1
  107. package/dist/main.d.ts.map +1 -1
  108. package/dist/main.js +1 -1
  109. package/dist/main.js.map +1 -1
  110. package/dist/modes/interactive/components/bash-execution.d.ts +2 -1
  111. package/dist/modes/interactive/components/bash-execution.d.ts.map +1 -1
  112. package/dist/modes/interactive/components/bash-execution.js +12 -1
  113. package/dist/modes/interactive/components/bash-execution.js.map +1 -1
  114. package/dist/modes/interactive/components/footer.d.ts +1 -0
  115. package/dist/modes/interactive/components/footer.d.ts.map +1 -1
  116. package/dist/modes/interactive/components/footer.js +19 -9
  117. package/dist/modes/interactive/components/footer.js.map +1 -1
  118. package/dist/modes/interactive/components/tool-execution.d.ts.map +1 -1
  119. package/dist/modes/interactive/components/tool-execution.js +12 -2
  120. package/dist/modes/interactive/components/tool-execution.js.map +1 -1
  121. package/dist/modes/interactive/components/tool-panel-registry.d.ts +1 -0
  122. package/dist/modes/interactive/components/tool-panel-registry.d.ts.map +1 -1
  123. package/dist/modes/interactive/components/tool-panel-registry.js +18 -2
  124. package/dist/modes/interactive/components/tool-panel-registry.js.map +1 -1
  125. package/dist/modes/interactive/interactive-mode.d.ts.map +1 -1
  126. package/dist/modes/interactive/interactive-mode.js +9 -3
  127. package/dist/modes/interactive/interactive-mode.js.map +1 -1
  128. package/dist/modes/rpc/jsonl.d.ts.map +1 -1
  129. package/dist/modes/rpc/jsonl.js +9 -28
  130. package/dist/modes/rpc/jsonl.js.map +1 -1
  131. package/dist/utils/streaming-lines.d.ts +20 -0
  132. package/dist/utils/streaming-lines.d.ts.map +1 -0
  133. package/dist/utils/streaming-lines.js +79 -0
  134. package/dist/utils/streaming-lines.js.map +1 -0
  135. package/docs/extensions.md +2 -0
  136. package/docs/index.md +1 -1
  137. package/docs/self-adaptation.md +7 -0
  138. package/docs/settings.md +5 -1
  139. package/examples/extensions/custom-provider-anthropic/package-lock.json +2 -2
  140. package/examples/extensions/custom-provider-anthropic/package.json +1 -1
  141. package/examples/extensions/custom-provider-gitlab-duo/package.json +1 -1
  142. package/examples/extensions/sandbox/package-lock.json +2 -2
  143. package/examples/extensions/sandbox/package.json +1 -1
  144. package/examples/extensions/with-deps/package-lock.json +2 -2
  145. package/examples/extensions/with-deps/package.json +1 -1
  146. package/npm-shrinkwrap.json +12 -12
  147. package/package.json +4 -4
@@ -6,16 +6,21 @@ function getUsageTotalCost(usage) {
6
6
  const total = usage?.cost?.total;
7
7
  return isFiniteCost(total) ? total : undefined;
8
8
  }
9
- export function aggregateCurrentSessionCostsFromEntries(entries) {
10
- let ownCost = 0;
11
- let subagentCost = 0;
12
- let subagentReports = 0;
13
- const seenSubagentReportIds = new Set();
9
+ export function createCurrentSessionCostAccumulator() {
10
+ return {
11
+ ownCost: 0,
12
+ subagentCost: 0,
13
+ subagentReports: 0,
14
+ currentCost: 0,
15
+ seenSubagentReportIds: new Set(),
16
+ };
17
+ }
18
+ export function accumulateCurrentSessionCostsFromEntries(accumulator, entries) {
14
19
  for (const entry of entries) {
15
20
  if (entry.type === "message" && entry.message.role === "assistant") {
16
21
  const total = getUsageTotalCost(entry.message.usage);
17
22
  if (total !== undefined)
18
- ownCost += total;
23
+ accumulator.ownCost += total;
19
24
  continue;
20
25
  }
21
26
  if (entry.type !== "custom" || entry.customType !== SPAWNED_USAGE_CUSTOM_TYPE)
@@ -25,22 +30,28 @@ export function aggregateCurrentSessionCostsFromEntries(entries) {
25
30
  if (total === undefined)
26
31
  continue;
27
32
  if (report?.reportId) {
28
- if (seenSubagentReportIds.has(report.reportId))
33
+ if (accumulator.seenSubagentReportIds.has(report.reportId))
29
34
  continue;
30
- seenSubagentReportIds.add(report.reportId);
35
+ accumulator.seenSubagentReportIds.add(report.reportId);
31
36
  }
32
- subagentCost += total;
33
- subagentReports += 1;
37
+ accumulator.subagentCost += total;
38
+ accumulator.subagentReports += 1;
34
39
  }
35
- return {
36
- ownCost,
37
- subagentCost,
38
- subagentReports,
39
- currentCost: ownCost + subagentCost,
40
- };
40
+ accumulator.currentCost = accumulator.ownCost + accumulator.subagentCost;
41
+ return accumulator;
42
+ }
43
+ export function aggregateCurrentSessionCostsFromEntries(entries) {
44
+ const { seenSubagentReportIds: _seenSubagentReportIds, ...totals } = accumulateCurrentSessionCostsFromEntries(createCurrentSessionCostAccumulator(), entries);
45
+ return totals;
41
46
  }
42
47
  export function createSessionCostSummary(args) {
43
- const current = aggregateCurrentSessionCostsFromEntries(args.entries);
48
+ const currentSource = args.currentTotals ?? aggregateCurrentSessionCostsFromEntries(args.entries ?? []);
49
+ const current = {
50
+ ownCost: currentSource.ownCost,
51
+ subagentCost: currentSource.subagentCost,
52
+ subagentReports: currentSource.subagentReports,
53
+ currentCost: currentSource.currentCost,
54
+ };
44
55
  return {
45
56
  ...current,
46
57
  todayCost: args.dailyTotals.totalCost,
@@ -1 +1 @@
1
- {"version":3,"file":"cost-summary.js","sourceRoot":"","sources":["../../../src/core/cost/cost-summary.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,yBAAyB,EAA2B,MAAM,qBAAqB,CAAC;AAkBzF,SAAS,YAAY,CAAC,KAAc,EAAmB;IACtD,OAAO,OAAO,KAAK,KAAK,QAAQ,IAAI,MAAM,CAAC,QAAQ,CAAC,KAAK,CAAC,CAAC;AAAA,CAC3D;AAED,SAAS,iBAAiB,CAAC,KAAwB,EAAsB;IACxE,MAAM,KAAK,GAAG,KAAK,EAAE,IAAI,EAAE,KAAK,CAAC;IACjC,OAAO,YAAY,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,SAAS,CAAC;AAAA,CAC/C;AAED,MAAM,UAAU,uCAAuC,CAAC,OAAgC,EAA4B;IACnH,IAAI,OAAO,GAAG,CAAC,CAAC;IAChB,IAAI,YAAY,GAAG,CAAC,CAAC;IACrB,IAAI,eAAe,GAAG,CAAC,CAAC;IACxB,MAAM,qBAAqB,GAAG,IAAI,GAAG,EAAU,CAAC;IAEhD,KAAK,MAAM,KAAK,IAAI,OAAO,EAAE,CAAC;QAC7B,IAAI,KAAK,CAAC,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,OAAO,KAAK,CAAC;AAAA,CACb;AAED,MAAM,UAAU,uBAAuB,CAAC,OAA2B,EAAE,SAAS,GAAG,CAAC,EAAU;IAC3F,MAAM,KAAK,GAAG;QACb,WAAW,UAAU,CAAC,OAAO,CAAC,WAAW,EAAE,SAAS,CAAC,EAAE;QACvD,SAAS,UAAU,CAAC,OAAO,CAAC,SAAS,EAAE,SAAS,CAAC,EAAE;KACnD,CAAC;IACF,IAAI,qBAAqB,CAAC,OAAO,CAAC,EAAE,CAAC;QACpC,KAAK,CAAC,IAAI,CAAC,aAAa,UAAU,CAAC,OAAO,CAAC,YAAY,EAAE,SAAS,CAAC,wBAAwB,CAAC,CAAC;IAC9F,CAAC;IACD,OAAO,KAAK,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;AAAA,CACxB","sourcesContent":["import type { SessionEntry } from \"@caupulican/pi-agent-core/node\";\nimport type { AssistantMessage, Usage } from \"@caupulican/pi-ai\";\nimport { SPAWNED_USAGE_CUSTOM_TYPE, type SpawnedUsageReport } from \"../agent-session.ts\";\nimport type { DailyUsageTotals, DailyUsageWindow } from \"./daily-usage.ts\";\n\nexport interface CurrentSessionCostTotals {\n\townCost: number;\n\tsubagentCost: number;\n\tsubagentReports: number;\n\tcurrentCost: number;\n}\n\nexport interface SessionCostSummary extends CurrentSessionCostTotals {\n\ttodayCost: number;\n\ttodayOwnCost: number;\n\ttodaySubagentCost: number;\n\ttodayWindow: DailyUsageWindow;\n\ttodayRollover: \"local-midnight\";\n}\n\nfunction isFiniteCost(value: unknown): value is number {\n\treturn typeof value === \"number\" && Number.isFinite(value);\n}\n\nfunction getUsageTotalCost(usage: Usage | undefined): number | undefined {\n\tconst total = usage?.cost?.total;\n\treturn isFiniteCost(total) ? total : undefined;\n}\n\nexport function aggregateCurrentSessionCostsFromEntries(entries: readonly SessionEntry[]): CurrentSessionCostTotals {\n\tlet ownCost = 0;\n\tlet subagentCost = 0;\n\tlet subagentReports = 0;\n\tconst seenSubagentReportIds = new Set<string>();\n\n\tfor (const entry of entries) {\n\t\tif (entry.type === \"message\" && entry.message.role === \"assistant\") {\n\t\t\tconst total = getUsageTotalCost((entry.message as AssistantMessage).usage);\n\t\t\tif (total !== undefined) ownCost += total;\n\t\t\tcontinue;\n\t\t}\n\n\t\tif (entry.type !== \"custom\" || entry.customType !== SPAWNED_USAGE_CUSTOM_TYPE) continue;\n\t\tconst report = entry.data as SpawnedUsageReport | undefined;\n\t\tconst total = getUsageTotalCost(report?.usage);\n\t\tif (total === undefined) continue;\n\t\tif (report?.reportId) {\n\t\t\tif (seenSubagentReportIds.has(report.reportId)) continue;\n\t\t\tseenSubagentReportIds.add(report.reportId);\n\t\t}\n\t\tsubagentCost += total;\n\t\tsubagentReports += 1;\n\t}\n\n\treturn {\n\t\townCost,\n\t\tsubagentCost,\n\t\tsubagentReports,\n\t\tcurrentCost: ownCost + subagentCost,\n\t};\n}\n\nexport function createSessionCostSummary(args: {\n\tentries: readonly SessionEntry[];\n\tdailyTotals: DailyUsageTotals;\n\ttodayWindow: DailyUsageWindow;\n}): SessionCostSummary {\n\tconst current = aggregateCurrentSessionCostsFromEntries(args.entries);\n\treturn {\n\t\t...current,\n\t\ttodayCost: args.dailyTotals.totalCost,\n\t\ttodayOwnCost: args.dailyTotals.ownCost,\n\t\ttodaySubagentCost: args.dailyTotals.spawnedCost,\n\t\ttodayWindow: args.todayWindow,\n\t\ttodayRollover: \"local-midnight\",\n\t};\n}\n\nexport function hasCostSummarySignal(summary: SessionCostSummary): boolean {\n\treturn summary.currentCost > 0 || summary.todayCost > 0 || summary.subagentReports > 0;\n}\n\nexport function hasSubagentCostSignal(summary: Pick<SessionCostSummary, \"subagentReports\" | \"subagentCost\">): boolean {\n\treturn summary.subagentReports > 0 || summary.subagentCost > 0;\n}\n\nfunction formatCost(value: number, precision: number): string {\n\treturn `$${value.toFixed(precision)}`;\n}\n\nexport function formatFooterCostParts(\n\tsummary: SessionCostSummary,\n\tprecision = 3,\n\toptions: { subscription?: boolean } = {},\n): string[] {\n\tconst parts: string[] = [];\n\tif (summary.currentCost > 0 || hasSubagentCostSignal(summary) || options.subscription) {\n\t\tparts.push(`CURRENT:${formatCost(summary.currentCost, precision)}${options.subscription ? \" (sub)\" : \"\"}`);\n\t}\n\tif (summary.todayCost > 0) {\n\t\tparts.push(`TODAY:${formatCost(summary.todayCost, precision)}`);\n\t}\n\tif (hasSubagentCostSignal(summary)) {\n\t\tparts.push(`SUBAGENTS:${formatCost(summary.subagentCost, precision)} in CURRENT`);\n\t}\n\treturn parts;\n}\n\nexport function formatStatusCostSummary(summary: SessionCostSummary, precision = 4): string {\n\tconst parts = [\n\t\t`CURRENT ${formatCost(summary.currentCost, precision)}`,\n\t\t`TODAY ${formatCost(summary.todayCost, precision)}`,\n\t];\n\tif (hasSubagentCostSignal(summary)) {\n\t\tparts.push(`SUBAGENTS ${formatCost(summary.subagentCost, precision)} (included in CURRENT)`);\n\t}\n\treturn parts.join(\", \");\n}\n"]}
1
+ {"version":3,"file":"cost-summary.js","sourceRoot":"","sources":["../../../src/core/cost/cost-summary.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,yBAAyB,EAA2B,MAAM,qBAAqB,CAAC;AAsBzF,SAAS,YAAY,CAAC,KAAc,EAAmB;IACtD,OAAO,OAAO,KAAK,KAAK,QAAQ,IAAI,MAAM,CAAC,QAAQ,CAAC,KAAK,CAAC,CAAC;AAAA,CAC3D;AAED,SAAS,iBAAiB,CAAC,KAAwB,EAAsB;IACxE,MAAM,KAAK,GAAG,KAAK,EAAE,IAAI,EAAE,KAAK,CAAC;IACjC,OAAO,YAAY,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,SAAS,CAAC;AAAA,CAC/C;AAED,MAAM,UAAU,mCAAmC,GAAkC;IACpF,OAAO;QACN,OAAO,EAAE,CAAC;QACV,YAAY,EAAE,CAAC;QACf,eAAe,EAAE,CAAC;QAClB,WAAW,EAAE,CAAC;QACd,qBAAqB,EAA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from \"@caupulican/pi-ai\";\nimport { SPAWNED_USAGE_CUSTOM_TYPE, type SpawnedUsageReport } from \"../agent-session.ts\";\nimport type { DailyUsageTotals, DailyUsageWindow } from \"./daily-usage.ts\";\n\nexport interface CurrentSessionCostTotals {\n\townCost: number;\n\tsubagentCost: number;\n\tsubagentReports: number;\n\tcurrentCost: number;\n}\n\nexport interface CurrentSessionCostAccumulator extends CurrentSessionCostTotals {\n\tseenSubagentReportIds: Set<string>;\n}\n\nexport interface SessionCostSummary extends CurrentSessionCostTotals {\n\ttodayCost: number;\n\ttodayOwnCost: number;\n\ttodaySubagentCost: number;\n\ttodayWindow: DailyUsageWindow;\n\ttodayRollover: \"local-midnight\";\n}\n\nfunction isFiniteCost(value: unknown): value is number {\n\treturn typeof value === \"number\" && Number.isFinite(value);\n}\n\nfunction getUsageTotalCost(usage: Usage | undefined): number | undefined {\n\tconst total = usage?.cost?.total;\n\treturn isFiniteCost(total) ? total : undefined;\n}\n\nexport function createCurrentSessionCostAccumulator(): CurrentSessionCostAccumulator {\n\treturn {\n\t\townCost: 0,\n\t\tsubagentCost: 0,\n\t\tsubagentReports: 0,\n\t\tcurrentCost: 0,\n\t\tseenSubagentReportIds: new Set<string>(),\n\t};\n}\n\nexport function accumulateCurrentSessionCostsFromEntries(\n\taccumulator: CurrentSessionCostAccumulator,\n\tentries: readonly SessionEntry[],\n): CurrentSessionCostAccumulator {\n\tfor (const entry of entries) {\n\t\tif (entry.type === \"message\" && entry.message.role === \"assistant\") {\n\t\t\tconst total = getUsageTotalCost((entry.message as AssistantMessage).usage);\n\t\t\tif (total !== undefined) accumulator.ownCost += total;\n\t\t\tcontinue;\n\t\t}\n\n\t\tif (entry.type !== \"custom\" || entry.customType !== SPAWNED_USAGE_CUSTOM_TYPE) continue;\n\t\tconst report = entry.data as SpawnedUsageReport | undefined;\n\t\tconst total = getUsageTotalCost(report?.usage);\n\t\tif (total === undefined) continue;\n\t\tif (report?.reportId) {\n\t\t\tif (accumulator.seenSubagentReportIds.has(report.reportId)) continue;\n\t\t\taccumulator.seenSubagentReportIds.add(report.reportId);\n\t\t}\n\t\taccumulator.subagentCost += total;\n\t\taccumulator.subagentReports += 1;\n\t}\n\taccumulator.currentCost = accumulator.ownCost + accumulator.subagentCost;\n\treturn accumulator;\n}\n\nexport function aggregateCurrentSessionCostsFromEntries(entries: readonly SessionEntry[]): CurrentSessionCostTotals {\n\tconst { seenSubagentReportIds: _seenSubagentReportIds, ...totals } = accumulateCurrentSessionCostsFromEntries(\n\t\tcreateCurrentSessionCostAccumulator(),\n\t\tentries,\n\t);\n\treturn totals;\n}\n\nexport function createSessionCostSummary(args: {\n\tentries?: readonly SessionEntry[];\n\tdailyTotals: DailyUsageTotals;\n\ttodayWindow: DailyUsageWindow;\n\tcurrentTotals?: CurrentSessionCostTotals;\n}): SessionCostSummary {\n\tconst currentSource = args.currentTotals ?? aggregateCurrentSessionCostsFromEntries(args.entries ?? []);\n\tconst current: CurrentSessionCostTotals = {\n\t\townCost: currentSource.ownCost,\n\t\tsubagentCost: currentSource.subagentCost,\n\t\tsubagentReports: currentSource.subagentReports,\n\t\tcurrentCost: currentSource.currentCost,\n\t};\n\treturn {\n\t\t...current,\n\t\ttodayCost: args.dailyTotals.totalCost,\n\t\ttodayOwnCost: args.dailyTotals.ownCost,\n\t\ttodaySubagentCost: args.dailyTotals.spawnedCost,\n\t\ttodayWindow: args.todayWindow,\n\t\ttodayRollover: \"local-midnight\",\n\t};\n}\n\nexport function hasCostSummarySignal(summary: SessionCostSummary): boolean {\n\treturn summary.currentCost > 0 || summary.todayCost > 0 || summary.subagentReports > 0;\n}\n\nexport function hasSubagentCostSignal(summary: Pick<SessionCostSummary, \"subagentReports\" | \"subagentCost\">): boolean {\n\treturn summary.subagentReports > 0 || summary.subagentCost > 0;\n}\n\nfunction formatCost(value: number, precision: number): string {\n\treturn `$${value.toFixed(precision)}`;\n}\n\nexport function formatFooterCostParts(\n\tsummary: SessionCostSummary,\n\tprecision = 3,\n\toptions: { subscription?: boolean } = {},\n): string[] {\n\tconst parts: string[] = [];\n\tif (summary.currentCost > 0 || hasSubagentCostSignal(summary) || options.subscription) {\n\t\tparts.push(`CURRENT:${formatCost(summary.currentCost, precision)}${options.subscription ? \" (sub)\" : \"\"}`);\n\t}\n\tif (summary.todayCost > 0) {\n\t\tparts.push(`TODAY:${formatCost(summary.todayCost, precision)}`);\n\t}\n\tif (hasSubagentCostSignal(summary)) {\n\t\tparts.push(`SUBAGENTS:${formatCost(summary.subagentCost, precision)} in CURRENT`);\n\t}\n\treturn parts;\n}\n\nexport function formatStatusCostSummary(summary: SessionCostSummary, precision = 4): string {\n\tconst parts = [\n\t\t`CURRENT ${formatCost(summary.currentCost, precision)}`,\n\t\t`TODAY ${formatCost(summary.todayCost, precision)}`,\n\t];\n\tif (hasSubagentCostSignal(summary)) {\n\t\tparts.push(`SUBAGENTS ${formatCost(summary.subagentCost, precision)} (included in CURRENT)`);\n\t}\n\treturn parts.join(\", \");\n}\n"]}
@@ -15,9 +15,13 @@ export type DailyUsageTotals = {
15
15
  sessions: number;
16
16
  reports: number;
17
17
  };
18
- export declare function aggregateDailyUsageFromEntries(entries: SessionEntry[], window: DailyUsageWindow): DailyUsageTotals;
19
- export declare function aggregateDailyUsageFromSessionFiles(sessionDir: string, window: DailyUsageWindow): DailyUsageTotals;
20
- export declare function aggregateDailyUsageFromSessionRoot(sessionRoot: string, window: DailyUsageWindow): DailyUsageTotals;
18
+ export declare function aggregateDailyUsageFromEntries(entries: readonly SessionEntry[], window: DailyUsageWindow): DailyUsageTotals;
19
+ export interface LiveSessionDailyUsageSource {
20
+ filePath: string;
21
+ entries: readonly SessionEntry[];
22
+ }
23
+ export declare function aggregateDailyUsageFromSessionFiles(sessionDir: string, window: DailyUsageWindow, liveSession?: LiveSessionDailyUsageSource): DailyUsageTotals;
24
+ export declare function aggregateDailyUsageFromSessionRoot(sessionRoot: string, window: DailyUsageWindow, liveSession?: LiveSessionDailyUsageSource): DailyUsageTotals;
21
25
  export declare function formatDailyUsageBreakdown(totals: DailyUsageTotals, formatLabel?: (label: string) => string): string;
22
26
  export declare function getLocalDayWindow(now?: Date): DailyUsageWindow;
23
27
  //# sourceMappingURL=daily-usage.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"daily-usage.d.ts","sourceRoot":"","sources":["../../../src/core/cost/daily-usage.ts"],"names":[],"mappings":"AAEA,OAAO,EAAuB,KAAK,YAAY,EAAE,MAAM,gCAAgC,CAAC;AAIxF,MAAM,MAAM,gBAAgB,GAAG;IAC9B,OAAO,EAAE,MAAM,CAAC;IAChB,KAAK,EAAE,MAAM,CAAC;CACd,CAAC;AAEF,MAAM,MAAM,gBAAgB,GAAG;IAC9B,OAAO,EAAE,MAAM,CAAC;IAChB,WAAW,EAAE,MAAM,CAAC;IACpB,SAAS,EAAE,MAAM,CAAC;IAClB,KAAK,EAAE,MAAM,CAAC;IACd,MAAM,EAAE,MAAM,CAAC;IACf,SAAS,EAAE,MAAM,CAAC;IAClB,UAAU,EAAE,MAAM,CAAC;IACnB,WAAW,EAAE,MAAM,CAAC;IACpB,QAAQ,EAAE,MAAM,CAAC;IACjB,OAAO,EAAE,MAAM,CAAC;CAChB,CAAC;AA8EF,wBAAgB,8BAA8B,CAAC,OAAO,EAAE,YAAY,EAAE,EAAE,MAAM,EAAE,gBAAgB,GAAG,gBAAgB,CAKlH;AAED,wBAAgB,mCAAmC,CAAC,UAAU,EAAE,MAAM,EAAE,MAAM,EAAE,gBAAgB,GAAG,gBAAgB,CAclH;AAED,wBAAgB,kCAAkC,CAAC,WAAW,EAAE,MAAM,EAAE,MAAM,EAAE,gBAAgB,GAAG,gBAAgB,CAoBlH;AAED,wBAAgB,yBAAyB,CACxC,MAAM,EAAE,gBAAgB,EACxB,WAAW,GAAE,CAAC,KAAK,EAAE,MAAM,KAAK,MAAyB,GACvD,MAAM,CAQR;AAED,wBAAgB,iBAAiB,CAAC,GAAG,OAAa,GAAG,gBAAgB,CAMpE","sourcesContent":["import { existsSync, readdirSync, statSync } from \"node:fs\";\nimport { join } from \"node:path\";\nimport { loadEntriesFromFile, type SessionEntry } from \"@caupulican/pi-agent-core/node\";\nimport type { AssistantMessage, Usage } from \"@caupulican/pi-ai\";\nimport { SPAWNED_USAGE_CUSTOM_TYPE, type SpawnedUsageReport } from \"../agent-session.ts\";\n\nexport type DailyUsageWindow = {\n\tstartMs: number;\n\tendMs: number;\n};\n\nexport type DailyUsageTotals = {\n\townCost: number;\n\tspawnedCost: number;\n\ttotalCost: number;\n\tinput: number;\n\toutput: number;\n\tcacheRead: number;\n\tcacheWrite: number;\n\ttotalTokens: number;\n\tsessions: number;\n\treports: number;\n};\n\nfunction createZeroTotals(): DailyUsageTotals {\n\treturn {\n\t\townCost: 0,\n\t\tspawnedCost: 0,\n\t\ttotalCost: 0,\n\t\tinput: 0,\n\t\toutput: 0,\n\t\tcacheRead: 0,\n\t\tcacheWrite: 0,\n\t\ttotalTokens: 0,\n\t\tsessions: 0,\n\t\treports: 0,\n\t};\n}\n\nfunction isInsideWindow(timestamp: number, window: DailyUsageWindow): boolean {\n\treturn timestamp >= window.startMs && timestamp < window.endMs;\n}\n\nfunction addUsage(\n\ttotals: Pick<DailyUsageTotals, \"input\" | \"output\" | \"cacheRead\" | \"cacheWrite\" | \"totalTokens\">,\n\tusage: Usage,\n): void {\n\ttotals.input += usage.input;\n\ttotals.output += usage.output;\n\ttotals.cacheRead += usage.cacheRead;\n\ttotals.cacheWrite += usage.cacheWrite;\n\ttotals.totalTokens += usage.totalTokens;\n}\n\nfunction addDailyUsageFromEntries(\n\ttotals: DailyUsageTotals,\n\tentries: SessionEntry[],\n\twindow: DailyUsageWindow,\n\tseenSpawnedReportIds: Set<string>,\n): boolean {\n\tlet hasUsage = false;\n\tfor (const entry of entries) {\n\t\tif (!isInsideWindow(Date.parse(entry.timestamp), window)) continue;\n\t\tif (entry.type === \"message\" && entry.message.role === \"assistant\") {\n\t\t\tconst usage = (entry.message as AssistantMessage).usage;\n\t\t\tif (!usage) continue;\n\t\t\ttotals.ownCost += usage.cost.total;\n\t\t\taddUsage(totals, usage);\n\t\t\thasUsage = true;\n\t\t\tcontinue;\n\t\t}\n\t\tif (entry.type === \"custom\" && entry.customType === SPAWNED_USAGE_CUSTOM_TYPE) {\n\t\t\tconst data = entry.data as SpawnedUsageReport | undefined;\n\t\t\tif (!data?.usage) continue;\n\t\t\tif (data.reportId) {\n\t\t\t\tif (seenSpawnedReportIds.has(data.reportId)) continue;\n\t\t\t\tseenSpawnedReportIds.add(data.reportId);\n\t\t\t}\n\t\t\ttotals.spawnedCost += data.usage.cost.total;\n\t\t\ttotals.reports += 1;\n\t\t\taddUsage(totals, data.usage);\n\t\t\thasUsage = true;\n\t\t}\n\t}\n\treturn hasUsage;\n}\n\nfunction finishTotals(totals: DailyUsageTotals): DailyUsageTotals {\n\ttotals.totalCost = totals.ownCost + totals.spawnedCost;\n\treturn totals;\n}\n\nfunction shouldReadSessionFile(filePath: string, window: DailyUsageWindow): boolean {\n\ttry {\n\t\treturn statSync(filePath).mtimeMs >= window.startMs;\n\t} catch {\n\t\treturn false;\n\t}\n}\n\nexport function aggregateDailyUsageFromEntries(entries: SessionEntry[], window: DailyUsageWindow): DailyUsageTotals {\n\tconst totals = createZeroTotals();\n\tconst hasUsage = addDailyUsageFromEntries(totals, entries, window, new Set());\n\ttotals.sessions = hasUsage ? 1 : 0;\n\treturn finishTotals(totals);\n}\n\nexport function aggregateDailyUsageFromSessionFiles(sessionDir: string, window: DailyUsageWindow): DailyUsageTotals {\n\tconst totals = createZeroTotals();\n\tif (!sessionDir || !existsSync(sessionDir)) return totals;\n\tconst seenSpawnedReportIds = new Set<string>();\n\tfor (const name of readdirSync(sessionDir)) {\n\t\tif (!name.endsWith(\".jsonl\")) continue;\n\t\tconst filePath = join(sessionDir, name);\n\t\tif (!shouldReadSessionFile(filePath, window)) continue;\n\t\tconst entries = loadEntriesFromFile(filePath).filter((entry): entry is SessionEntry => entry.type !== \"session\");\n\t\tif (addDailyUsageFromEntries(totals, entries, window, seenSpawnedReportIds)) {\n\t\t\ttotals.sessions += 1;\n\t\t}\n\t}\n\treturn finishTotals(totals);\n}\n\nexport function aggregateDailyUsageFromSessionRoot(sessionRoot: string, window: DailyUsageWindow): DailyUsageTotals {\n\tconst totals = createZeroTotals();\n\tif (!sessionRoot || !existsSync(sessionRoot)) return totals;\n\tconst seenSpawnedReportIds = new Set<string>();\n\tfor (const name of readdirSync(sessionRoot)) {\n\t\tconst dir = join(sessionRoot, name);\n\t\tif (!existsSync(dir) || !statSync(dir).isDirectory()) continue;\n\t\tfor (const fileName of readdirSync(dir)) {\n\t\t\tif (!fileName.endsWith(\".jsonl\")) continue;\n\t\t\tconst filePath = join(dir, fileName);\n\t\t\tif (!shouldReadSessionFile(filePath, window)) continue;\n\t\t\tconst entries = loadEntriesFromFile(filePath).filter(\n\t\t\t\t(entry): entry is SessionEntry => entry.type !== \"session\",\n\t\t\t);\n\t\t\tif (addDailyUsageFromEntries(totals, entries, window, seenSpawnedReportIds)) {\n\t\t\t\ttotals.sessions += 1;\n\t\t\t}\n\t\t}\n\t}\n\treturn finishTotals(totals);\n}\n\nexport function formatDailyUsageBreakdown(\n\ttotals: DailyUsageTotals,\n\tformatLabel: (label: string) => string = (label) => label,\n): string {\n\treturn [\n\t\t`${formatLabel(\"Today:\")} $${totals.totalCost.toFixed(4)}`,\n\t\t`${formatLabel(\"Own/session messages:\")} $${totals.ownCost.toFixed(4)}`,\n\t\t`${formatLabel(\"Spawned/background reports:\")} $${totals.spawnedCost.toFixed(4)}`,\n\t\t`${formatLabel(\"Sessions scanned:\")} ${totals.sessions}`,\n\t\t`${formatLabel(\"Spawned/background report count:\")} ${totals.reports}`,\n\t].join(\"\\n\");\n}\n\nexport function getLocalDayWindow(now = new Date()): DailyUsageWindow {\n\tconst start = new Date(now);\n\tstart.setHours(0, 0, 0, 0);\n\tconst end = new Date(start);\n\tend.setDate(end.getDate() + 1);\n\treturn { startMs: start.getTime(), endMs: end.getTime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Aa,GAAG,gBAAgB,CAMpE","sourcesContent":["import { existsSync, readdirSync, statSync } from \"node:fs\";\nimport { join, resolve } from \"node:path\";\nimport { loadEntriesFromFile, type SessionEntry } from \"@caupulican/pi-agent-core/node\";\nimport type { AssistantMessage, Usage } from \"@caupulican/pi-ai\";\nimport { SPAWNED_USAGE_CUSTOM_TYPE, type SpawnedUsageReport } from \"../agent-session.ts\";\n\nexport type DailyUsageWindow = {\n\tstartMs: number;\n\tendMs: number;\n};\n\nexport type DailyUsageTotals = {\n\townCost: number;\n\tspawnedCost: number;\n\ttotalCost: number;\n\tinput: number;\n\toutput: number;\n\tcacheRead: number;\n\tcacheWrite: number;\n\ttotalTokens: number;\n\tsessions: number;\n\treports: number;\n};\n\nfunction createZeroTotals(): DailyUsageTotals {\n\treturn {\n\t\townCost: 0,\n\t\tspawnedCost: 0,\n\t\ttotalCost: 0,\n\t\tinput: 0,\n\t\toutput: 0,\n\t\tcacheRead: 0,\n\t\tcacheWrite: 0,\n\t\ttotalTokens: 0,\n\t\tsessions: 0,\n\t\treports: 0,\n\t};\n}\n\nfunction isInsideWindow(timestamp: number, window: DailyUsageWindow): boolean {\n\treturn timestamp >= window.startMs && timestamp < window.endMs;\n}\n\nfunction addUsage(\n\ttotals: Pick<DailyUsageTotals, \"input\" | \"output\" | \"cacheRead\" | \"cacheWrite\" | \"totalTokens\">,\n\tusage: Usage,\n): void {\n\ttotals.input += usage.input;\n\ttotals.output += usage.output;\n\ttotals.cacheRead += usage.cacheRead;\n\ttotals.cacheWrite += usage.cacheWrite;\n\ttotals.totalTokens += usage.totalTokens;\n}\n\nfunction addDailyUsageFromEntries(\n\ttotals: DailyUsageTotals,\n\tentries: readonly SessionEntry[],\n\twindow: DailyUsageWindow,\n\tseenSpawnedReportIds: Set<string>,\n): boolean {\n\tlet hasUsage = false;\n\tfor (const entry of entries) {\n\t\tif (!isInsideWindow(Date.parse(entry.timestamp), window)) continue;\n\t\tif (entry.type === \"message\" && entry.message.role === \"assistant\") {\n\t\t\tconst usage = (entry.message as AssistantMessage).usage;\n\t\t\tif (!usage) continue;\n\t\t\ttotals.ownCost += usage.cost.total;\n\t\t\taddUsage(totals, usage);\n\t\t\thasUsage = true;\n\t\t\tcontinue;\n\t\t}\n\t\tif (entry.type === \"custom\" && entry.customType === SPAWNED_USAGE_CUSTOM_TYPE) {\n\t\t\tconst data = entry.data as SpawnedUsageReport | undefined;\n\t\t\tif (!data?.usage) continue;\n\t\t\tif (data.reportId) {\n\t\t\t\tif (seenSpawnedReportIds.has(data.reportId)) continue;\n\t\t\t\tseenSpawnedReportIds.add(data.reportId);\n\t\t\t}\n\t\t\ttotals.spawnedCost += data.usage.cost.total;\n\t\t\ttotals.reports += 1;\n\t\t\taddUsage(totals, data.usage);\n\t\t\thasUsage = true;\n\t\t}\n\t}\n\treturn hasUsage;\n}\n\nfunction finishTotals(totals: DailyUsageTotals): DailyUsageTotals {\n\ttotals.totalCost = totals.ownCost + totals.spawnedCost;\n\treturn totals;\n}\n\nfunction shouldReadSessionFile(filePath: string, window: DailyUsageWindow): boolean {\n\ttry {\n\t\treturn statSync(filePath).mtimeMs >= window.startMs;\n\t} catch {\n\t\treturn false;\n\t}\n}\n\nexport function aggregateDailyUsageFromEntries(\n\tentries: readonly SessionEntry[],\n\twindow: DailyUsageWindow,\n): DailyUsageTotals {\n\tconst totals = createZeroTotals();\n\tconst hasUsage = addDailyUsageFromEntries(totals, entries, window, new Set());\n\ttotals.sessions = hasUsage ? 1 : 0;\n\treturn finishTotals(totals);\n}\n\nexport interface LiveSessionDailyUsageSource {\n\tfilePath: string;\n\tentries: readonly SessionEntry[];\n}\n\nfunction getSessionEntries(\n\tfilePath: string,\n\tliveSession: LiveSessionDailyUsageSource | undefined,\n): readonly SessionEntry[] {\n\tif (liveSession && resolve(filePath) === resolve(liveSession.filePath)) return liveSession.entries;\n\treturn loadEntriesFromFile(filePath).filter((entry): entry is SessionEntry => entry.type !== \"session\");\n}\n\nexport function aggregateDailyUsageFromSessionFiles(\n\tsessionDir: string,\n\twindow: DailyUsageWindow,\n\tliveSession?: LiveSessionDailyUsageSource,\n): DailyUsageTotals {\n\tconst totals = createZeroTotals();\n\tif (!sessionDir || !existsSync(sessionDir)) return totals;\n\tconst seenSpawnedReportIds = new Set<string>();\n\tfor (const name of readdirSync(sessionDir)) {\n\t\tif (!name.endsWith(\".jsonl\")) continue;\n\t\tconst filePath = join(sessionDir, name);\n\t\tif (!shouldReadSessionFile(filePath, window)) continue;\n\t\tconst entries = getSessionEntries(filePath, liveSession);\n\t\tif (addDailyUsageFromEntries(totals, entries, window, seenSpawnedReportIds)) {\n\t\t\ttotals.sessions += 1;\n\t\t}\n\t}\n\treturn finishTotals(totals);\n}\n\nexport function aggregateDailyUsageFromSessionRoot(\n\tsessionRoot: string,\n\twindow: DailyUsageWindow,\n\tliveSession?: LiveSessionDailyUsageSource,\n): DailyUsageTotals {\n\tconst totals = createZeroTotals();\n\tif (!sessionRoot || !existsSync(sessionRoot)) return totals;\n\tconst seenSpawnedReportIds = new Set<string>();\n\tfor (const name of readdirSync(sessionRoot)) {\n\t\tconst dir = join(sessionRoot, name);\n\t\tif (!existsSync(dir) || !statSync(dir).isDirectory()) continue;\n\t\tfor (const fileName of readdirSync(dir)) {\n\t\t\tif (!fileName.endsWith(\".jsonl\")) continue;\n\t\t\tconst filePath = join(dir, fileName);\n\t\t\tif (!shouldReadSessionFile(filePath, window)) continue;\n\t\t\tconst entries = getSessionEntries(filePath, liveSession);\n\t\t\tif (addDailyUsageFromEntries(totals, entries, window, seenSpawnedReportIds)) {\n\t\t\t\ttotals.sessions += 1;\n\t\t\t}\n\t\t}\n\t}\n\treturn finishTotals(totals);\n}\n\nexport function formatDailyUsageBreakdown(\n\ttotals: DailyUsageTotals,\n\tformatLabel: (label: string) => string = (label) => label,\n): string {\n\treturn [\n\t\t`${formatLabel(\"Today:\")} $${totals.totalCost.toFixed(4)}`,\n\t\t`${formatLabel(\"Own/session messages:\")} $${totals.ownCost.toFixed(4)}`,\n\t\t`${formatLabel(\"Spawned/background reports:\")} $${totals.spawnedCost.toFixed(4)}`,\n\t\t`${formatLabel(\"Sessions scanned:\")} ${totals.sessions}`,\n\t\t`${formatLabel(\"Spawned/background report count:\")} ${totals.reports}`,\n\t].join(\"\\n\");\n}\n\nexport function getLocalDayWindow(now = new Date()): DailyUsageWindow {\n\tconst start = new Date(now);\n\tstart.setHours(0, 0, 0, 0);\n\tconst end = new Date(start);\n\tend.setDate(end.getDate() + 1);\n\treturn { startMs: start.getTime(), endMs: end.getTime() };\n}\n"]}
@@ -1,5 +1,5 @@
1
1
  import { existsSync, readdirSync, statSync } from "node:fs";
2
- import { join } from "node:path";
2
+ import { join, resolve } from "node:path";
3
3
  import { loadEntriesFromFile } from "@caupulican/pi-agent-core/node";
4
4
  import { SPAWNED_USAGE_CUSTOM_TYPE } from "../agent-session.js";
5
5
  function createZeroTotals() {
@@ -75,7 +75,12 @@ export function aggregateDailyUsageFromEntries(entries, window) {
75
75
  totals.sessions = hasUsage ? 1 : 0;
76
76
  return finishTotals(totals);
77
77
  }
78
- export function aggregateDailyUsageFromSessionFiles(sessionDir, window) {
78
+ function getSessionEntries(filePath, liveSession) {
79
+ if (liveSession && resolve(filePath) === resolve(liveSession.filePath))
80
+ return liveSession.entries;
81
+ return loadEntriesFromFile(filePath).filter((entry) => entry.type !== "session");
82
+ }
83
+ export function aggregateDailyUsageFromSessionFiles(sessionDir, window, liveSession) {
79
84
  const totals = createZeroTotals();
80
85
  if (!sessionDir || !existsSync(sessionDir))
81
86
  return totals;
@@ -86,14 +91,14 @@ export function aggregateDailyUsageFromSessionFiles(sessionDir, window) {
86
91
  const filePath = join(sessionDir, name);
87
92
  if (!shouldReadSessionFile(filePath, window))
88
93
  continue;
89
- const entries = loadEntriesFromFile(filePath).filter((entry) => entry.type !== "session");
94
+ const entries = getSessionEntries(filePath, liveSession);
90
95
  if (addDailyUsageFromEntries(totals, entries, window, seenSpawnedReportIds)) {
91
96
  totals.sessions += 1;
92
97
  }
93
98
  }
94
99
  return finishTotals(totals);
95
100
  }
96
- export function aggregateDailyUsageFromSessionRoot(sessionRoot, window) {
101
+ export function aggregateDailyUsageFromSessionRoot(sessionRoot, window, liveSession) {
97
102
  const totals = createZeroTotals();
98
103
  if (!sessionRoot || !existsSync(sessionRoot))
99
104
  return totals;
@@ -108,7 +113,7 @@ export function aggregateDailyUsageFromSessionRoot(sessionRoot, window) {
108
113
  const filePath = join(dir, fileName);
109
114
  if (!shouldReadSessionFile(filePath, window))
110
115
  continue;
111
- const entries = loadEntriesFromFile(filePath).filter((entry) => entry.type !== "session");
116
+ const entries = getSessionEntries(filePath, liveSession);
112
117
  if (addDailyUsageFromEntries(totals, entries, window, seenSpawnedReportIds)) {
113
118
  totals.sessions += 1;
114
119
  }
@@ -1 +1 @@
1
- {"version":3,"file":"daily-usage.js","sourceRoot":"","sources":["../../../src/core/cost/daily-usage.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,WAAW,EAAE,QAAQ,EAAE,MAAM,SAAS,CAAC;AAC5D,OAAO,EAAE,IAAI,EAAE,MAAM,WAAW,CAAC;AACjC,OAAO,EAAE,mBAAmB,EAAqB,MAAM,gCAAgC,CAAC;AAExF,OAAO,EAAE,yBAAyB,EAA2B,MAAM,qBAAqB,CAAC;AAoBzF,SAAS,gBAAgB,GAAqB;IAC7C,OAAO;QACN,OAAO,EAAE,CAAC;QACV,WAAW,EAAE,CAAC;QACd,SAAS,EAAE,CAAC;QACZ,KAAK,EAAE,CAAC;QACR,MAAM,EAAE,CAAC;QACT,SAAS,EAAE,CAAC;QACZ,UAAU,EAAE,CAAC;QACb,WAAW,EAAE,CAAC;QACd,QAAQ,EAAE,CAAC;QACX,OAAO,EAAE,CAAC;KACV,CAAC;AAAA,CACF;AAED,SAAS,cAAc,CAAC,SAAiB,EAAE,MAAwB,EAAW;IAC7E,OAAO,SAAS,IAAI,MAAM,CAAC,OAAO,IAAI,SAAS,GAAG,MAAM,CAAC,KA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,OAAO,EAAE;KACtE,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;AAAA,CACb;AAED,MAAM,UAAU,iBAAiB,CAAC,GAAG,GAAG,IAAI,IAAI,EAAE,EAAoB;IACrE,MAAM,KAAK,GAAG,IAAI,IAAI,CAAC,GAAG,CAAC,CAAC;IAC5B,KAAK,CAAC,QAAQ,CAAC,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,CAAC,CAAC;IAC3B,MAAM,GAAG,GAAG,IAAI,IAAI,CAAC,KAAK,CAAC,CAAC;IAC5B,GAAG,CAAC,OAAO,CAAC,GAAG,CAAC,OAAO,EAAE,GAAG,CAAC,CAAC,CAAC;IAC/B,OAAO,EAAE,OAAO,EAAE,KAAK,CAAC,OAAO,EAAE,EAAE,KAAK,EAAE,GAAG,CAAC,OAAO,EAAE,EAAE,CAAC;AAAA,CAC1D","sourcesContent":["import { existsSync, readdirSync, statSync } from \"node:fs\";\nimport { join } from \"node:path\";\nimport { loadEntriesFromFile, type SessionEntry } from \"@caupulican/pi-agent-core/node\";\nimport type { AssistantMessage, Usage } from \"@caupulican/pi-ai\";\nimport { SPAWNED_USAGE_CUSTOM_TYPE, type SpawnedUsageReport } from \"../agent-session.ts\";\n\nexport type DailyUsageWindow = {\n\tstartMs: number;\n\tendMs: number;\n};\n\nexport type DailyUsageTotals = {\n\townCost: number;\n\tspawnedCost: number;\n\ttotalCost: number;\n\tinput: number;\n\toutput: number;\n\tcacheRead: number;\n\tcacheWrite: number;\n\ttotalTokens: number;\n\tsessions: number;\n\treports: number;\n};\n\nfunction createZeroTotals(): DailyUsageTotals {\n\treturn {\n\t\townCost: 0,\n\t\tspawnedCost: 0,\n\t\ttotalCost: 0,\n\t\tinput: 0,\n\t\toutput: 0,\n\t\tcacheRead: 0,\n\t\tcacheWrite: 0,\n\t\ttotalTokens: 0,\n\t\tsessions: 0,\n\t\treports: 0,\n\t};\n}\n\nfunction isInsideWindow(timestamp: number, window: DailyUsageWindow): boolean {\n\treturn timestamp >= window.startMs && timestamp < window.endMs;\n}\n\nfunction addUsage(\n\ttotals: Pick<DailyUsageTotals, \"input\" | \"output\" | \"cacheRead\" | \"cacheWrite\" | \"totalTokens\">,\n\tusage: Usage,\n): void {\n\ttotals.input += usage.input;\n\ttotals.output += usage.output;\n\ttotals.cacheRead += usage.cacheRead;\n\ttotals.cacheWrite += usage.cacheWrite;\n\ttotals.totalTokens += usage.totalTokens;\n}\n\nfunction addDailyUsageFromEntries(\n\ttotals: DailyUsageTotals,\n\tentries: SessionEntry[],\n\twindow: DailyUsageWindow,\n\tseenSpawnedReportIds: Set<string>,\n): boolean {\n\tlet hasUsage = false;\n\tfor (const entry of entries) {\n\t\tif (!isInsideWindow(Date.parse(entry.timestamp), window)) continue;\n\t\tif (entry.type === \"message\" && entry.message.role === \"assistant\") {\n\t\t\tconst usage = (entry.message as AssistantMessage).usage;\n\t\t\tif (!usage) continue;\n\t\t\ttotals.ownCost += usage.cost.total;\n\t\t\taddUsage(totals, usage);\n\t\t\thasUsage = true;\n\t\t\tcontinue;\n\t\t}\n\t\tif (entry.type === \"custom\" && entry.customType === SPAWNED_USAGE_CUSTOM_TYPE) {\n\t\t\tconst data = entry.data as SpawnedUsageReport | undefined;\n\t\t\tif (!data?.usage) continue;\n\t\t\tif (data.reportId) {\n\t\t\t\tif (seenSpawnedReportIds.has(data.reportId)) continue;\n\t\t\t\tseenSpawnedReportIds.add(data.reportId);\n\t\t\t}\n\t\t\ttotals.spawnedCost += data.usage.cost.total;\n\t\t\ttotals.reports += 1;\n\t\t\taddUsage(totals, data.usage);\n\t\t\thasUsage = true;\n\t\t}\n\t}\n\treturn hasUsage;\n}\n\nfunction finishTotals(totals: DailyUsageTotals): DailyUsageTotals {\n\ttotals.totalCost = totals.ownCost + totals.spawnedCost;\n\treturn totals;\n}\n\nfunction shouldReadSessionFile(filePath: string, window: DailyUsageWindow): boolean {\n\ttry {\n\t\treturn statSync(filePath).mtimeMs >= window.startMs;\n\t} catch {\n\t\treturn false;\n\t}\n}\n\nexport function aggregateDailyUsageFromEntries(entries: SessionEntry[], window: DailyUsageWindow): DailyUsageTotals {\n\tconst totals = createZeroTotals();\n\tconst hasUsage = addDailyUsageFromEntries(totals, entries, window, new Set());\n\ttotals.sessions = hasUsage ? 1 : 0;\n\treturn finishTotals(totals);\n}\n\nexport function aggregateDailyUsageFromSessionFiles(sessionDir: string, window: DailyUsageWindow): DailyUsageTotals {\n\tconst totals = createZeroTotals();\n\tif (!sessionDir || !existsSync(sessionDir)) return totals;\n\tconst seenSpawnedReportIds = new Set<string>();\n\tfor (const name of readdirSync(sessionDir)) {\n\t\tif (!name.endsWith(\".jsonl\")) continue;\n\t\tconst filePath = join(sessionDir, name);\n\t\tif (!shouldReadSessionFile(filePath, window)) continue;\n\t\tconst entries = loadEntriesFromFile(filePath).filter((entry): entry is SessionEntry => entry.type !== \"session\");\n\t\tif (addDailyUsageFromEntries(totals, entries, window, seenSpawnedReportIds)) {\n\t\t\ttotals.sessions += 1;\n\t\t}\n\t}\n\treturn finishTotals(totals);\n}\n\nexport function aggregateDailyUsageFromSessionRoot(sessionRoot: string, window: DailyUsageWindow): DailyUsageTotals {\n\tconst totals = createZeroTotals();\n\tif (!sessionRoot || !existsSync(sessionRoot)) return totals;\n\tconst seenSpawnedReportIds = new Set<string>();\n\tfor (const name of readdirSync(sessionRoot)) {\n\t\tconst dir = join(sessionRoot, name);\n\t\tif (!existsSync(dir) || !statSync(dir).isDirectory()) continue;\n\t\tfor (const fileName of readdirSync(dir)) {\n\t\t\tif (!fileName.endsWith(\".jsonl\")) continue;\n\t\t\tconst filePath = join(dir, fileName);\n\t\t\tif (!shouldReadSessionFile(filePath, window)) continue;\n\t\t\tconst entries = loadEntriesFromFile(filePath).filter(\n\t\t\t\t(entry): entry is SessionEntry => entry.type !== \"session\",\n\t\t\t);\n\t\t\tif (addDailyUsageFromEntries(totals, entries, window, seenSpawnedReportIds)) {\n\t\t\t\ttotals.sessions += 1;\n\t\t\t}\n\t\t}\n\t}\n\treturn finishTotals(totals);\n}\n\nexport function formatDailyUsageBreakdown(\n\ttotals: DailyUsageTotals,\n\tformatLabel: (label: string) => string = (label) => label,\n): string {\n\treturn [\n\t\t`${formatLabel(\"Today:\")} $${totals.totalCost.toFixed(4)}`,\n\t\t`${formatLabel(\"Own/session messages:\")} $${totals.ownCost.toFixed(4)}`,\n\t\t`${formatLabel(\"Spawned/background reports:\")} $${totals.spawnedCost.toFixed(4)}`,\n\t\t`${formatLabel(\"Sessions scanned:\")} ${totals.sessions}`,\n\t\t`${formatLabel(\"Spawned/background report count:\")} ${totals.reports}`,\n\t].join(\"\\n\");\n}\n\nexport function getLocalDayWindow(now = new Date()): DailyUsageWindow {\n\tconst start = new Date(now);\n\tstart.setHours(0, 0, 0, 0);\n\tconst end = new Date(start);\n\tend.setDate(end.getDate() + 1);\n\treturn { startMs: start.getTime(), endMs: end.getTime() };\n}\n"]}
1
+ {"version":3,"file":"daily-usage.js","sourceRoot":"","sources":["../../../src/core/cost/daily-usage.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,WAAW,EAAE,QAAQ,EAAE,MAAM,SAAS,CAAC;AAC5D,OAAO,EAAE,IAAI,EAAE,OAAO,EAAE,MAAM,WAAW,CAAC;AAC1C,OAAO,EAAE,mBAAmB,EAAqB,MAAM,gCAAgC,CAAC;AAExF,OAAO,EAAE,yBAAyB,EAA2B,MAAM,qBAAqB,CAAC;AAoBzF,SAAS,gBAAgB,GAAqB;IAC7C,OAAO;QACN,OAAO,EAAE,CAAC;QACV,WAAW,EAAE,CAAC;QACd,SAAS,EAAE,CAAC;QACZ,KAAK,EAAE,CAAC;QACR,MAAM,EAAE,CAAC;QACT,SAAS,EAAE,CAAC;QACZ,UAAU,EAAE,CAAC;QACb,WAAW,EAAE,CAAC;QACd,QAAQ,EAAE,CAAC;QACX,OAAO,EAAE,CAAC;KACV,CAAC;AAAA,CACF;AAED,SAAS,cAAc,CAAC,SAAiB,EAAE,MA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CAAC,KAAK,MAAM,CAAC,OAAO,CAAC,OAAO,CAAC,CAAC,CAAC,EAAE;QACvE,GAAG,WAAW,CAAC,6BAA6B,CAAC,KAAK,MAAM,CAAC,WAAW,CAAC,OAAO,CAAC,CAAC,CAAC,EAAE;QACjF,GAAG,WAAW,CAAC,mBAAmB,CAAC,IAAI,MAAM,CAAC,QAAQ,EAAE;QACxD,GAAG,WAAW,CAAC,kCAAkC,CAAC,IAAI,MAAM,CAAC,OAAO,EAAE;KACtE,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;AAAA,CACb;AAED,MAAM,UAAU,iBAAiB,CAAC,GAAG,GAAG,IAAI,IAAI,EAAE,EAAoB;IACrE,MAAM,KAAK,GAAG,IAAI,IAAI,CAAC,GAAG,CAAC,CAAC;IAC5B,KAAK,CAAC,QAAQ,CAAC,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,CAAC,CAAC;IAC3B,MAAM,GAAG,GAAG,IAAI,IAAI,CAAC,KAAK,CAAC,CAAC;IAC5B,GAAG,CAAC,OAAO,CAAC,GAAG,CAAC,OAAO,EAAE,GAAG,CAAC,CAAC,CAAC;IAC/B,OAAO,EAAE,OAAO,EAAE,KAAK,CAAC,OAAO,EAAE,EAAE,KAAK,EAAE,GAAG,CAAC,OAAO,EAAE,EAAE,CAAC;AAAA,CAC1D","sourcesContent":["import { existsSync, readdirSync, statSync } from \"node:fs\";\nimport { join, resolve } from \"node:path\";\nimport { loadEntriesFromFile, type SessionEntry } from \"@caupulican/pi-agent-core/node\";\nimport type { AssistantMessage, Usage } from \"@caupulican/pi-ai\";\nimport { SPAWNED_USAGE_CUSTOM_TYPE, type SpawnedUsageReport } from \"../agent-session.ts\";\n\nexport type DailyUsageWindow = {\n\tstartMs: number;\n\tendMs: number;\n};\n\nexport type DailyUsageTotals = {\n\townCost: number;\n\tspawnedCost: number;\n\ttotalCost: number;\n\tinput: number;\n\toutput: number;\n\tcacheRead: number;\n\tcacheWrite: number;\n\ttotalTokens: number;\n\tsessions: number;\n\treports: number;\n};\n\nfunction createZeroTotals(): DailyUsageTotals {\n\treturn {\n\t\townCost: 0,\n\t\tspawnedCost: 0,\n\t\ttotalCost: 0,\n\t\tinput: 0,\n\t\toutput: 0,\n\t\tcacheRead: 0,\n\t\tcacheWrite: 0,\n\t\ttotalTokens: 0,\n\t\tsessions: 0,\n\t\treports: 0,\n\t};\n}\n\nfunction isInsideWindow(timestamp: number, window: DailyUsageWindow): boolean {\n\treturn timestamp >= window.startMs && timestamp < window.endMs;\n}\n\nfunction addUsage(\n\ttotals: Pick<DailyUsageTotals, \"input\" | \"output\" | \"cacheRead\" | \"cacheWrite\" | \"totalTokens\">,\n\tusage: Usage,\n): void {\n\ttotals.input += usage.input;\n\ttotals.output += usage.output;\n\ttotals.cacheRead += usage.cacheRead;\n\ttotals.cacheWrite += usage.cacheWrite;\n\ttotals.totalTokens += usage.totalTokens;\n}\n\nfunction addDailyUsageFromEntries(\n\ttotals: DailyUsageTotals,\n\tentries: readonly SessionEntry[],\n\twindow: DailyUsageWindow,\n\tseenSpawnedReportIds: Set<string>,\n): boolean {\n\tlet hasUsage = false;\n\tfor (const entry of entries) {\n\t\tif (!isInsideWindow(Date.parse(entry.timestamp), window)) continue;\n\t\tif (entry.type === \"message\" && entry.message.role === \"assistant\") {\n\t\t\tconst usage = (entry.message as AssistantMessage).usage;\n\t\t\tif (!usage) continue;\n\t\t\ttotals.ownCost += usage.cost.total;\n\t\t\taddUsage(totals, usage);\n\t\t\thasUsage = true;\n\t\t\tcontinue;\n\t\t}\n\t\tif (entry.type === \"custom\" && entry.customType === SPAWNED_USAGE_CUSTOM_TYPE) {\n\t\t\tconst data = entry.data as SpawnedUsageReport | undefined;\n\t\t\tif (!data?.usage) continue;\n\t\t\tif (data.reportId) {\n\t\t\t\tif (seenSpawnedReportIds.has(data.reportId)) continue;\n\t\t\t\tseenSpawnedReportIds.add(data.reportId);\n\t\t\t}\n\t\t\ttotals.spawnedCost += data.usage.cost.total;\n\t\t\ttotals.reports += 1;\n\t\t\taddUsage(totals, data.usage);\n\t\t\thasUsage = true;\n\t\t}\n\t}\n\treturn hasUsage;\n}\n\nfunction finishTotals(totals: DailyUsageTotals): DailyUsageTotals {\n\ttotals.totalCost = totals.ownCost + totals.spawnedCost;\n\treturn totals;\n}\n\nfunction shouldReadSessionFile(filePath: string, window: DailyUsageWindow): boolean {\n\ttry {\n\t\treturn statSync(filePath).mtimeMs >= window.startMs;\n\t} catch {\n\t\treturn false;\n\t}\n}\n\nexport function aggregateDailyUsageFromEntries(\n\tentries: readonly SessionEntry[],\n\twindow: DailyUsageWindow,\n): DailyUsageTotals {\n\tconst totals = createZeroTotals();\n\tconst hasUsage = addDailyUsageFromEntries(totals, entries, window, new Set());\n\ttotals.sessions = hasUsage ? 1 : 0;\n\treturn finishTotals(totals);\n}\n\nexport interface LiveSessionDailyUsageSource {\n\tfilePath: string;\n\tentries: readonly SessionEntry[];\n}\n\nfunction getSessionEntries(\n\tfilePath: string,\n\tliveSession: LiveSessionDailyUsageSource | undefined,\n): readonly SessionEntry[] {\n\tif (liveSession && resolve(filePath) === resolve(liveSession.filePath)) return liveSession.entries;\n\treturn loadEntriesFromFile(filePath).filter((entry): entry is SessionEntry => entry.type !== \"session\");\n}\n\nexport function aggregateDailyUsageFromSessionFiles(\n\tsessionDir: string,\n\twindow: DailyUsageWindow,\n\tliveSession?: LiveSessionDailyUsageSource,\n): DailyUsageTotals {\n\tconst totals = createZeroTotals();\n\tif (!sessionDir || !existsSync(sessionDir)) return totals;\n\tconst seenSpawnedReportIds = new Set<string>();\n\tfor (const name of readdirSync(sessionDir)) {\n\t\tif (!name.endsWith(\".jsonl\")) continue;\n\t\tconst filePath = join(sessionDir, name);\n\t\tif (!shouldReadSessionFile(filePath, window)) continue;\n\t\tconst entries = getSessionEntries(filePath, liveSession);\n\t\tif (addDailyUsageFromEntries(totals, entries, window, seenSpawnedReportIds)) {\n\t\t\ttotals.sessions += 1;\n\t\t}\n\t}\n\treturn finishTotals(totals);\n}\n\nexport function aggregateDailyUsageFromSessionRoot(\n\tsessionRoot: string,\n\twindow: DailyUsageWindow,\n\tliveSession?: LiveSessionDailyUsageSource,\n): DailyUsageTotals {\n\tconst totals = createZeroTotals();\n\tif (!sessionRoot || !existsSync(sessionRoot)) return totals;\n\tconst seenSpawnedReportIds = new Set<string>();\n\tfor (const name of readdirSync(sessionRoot)) {\n\t\tconst dir = join(sessionRoot, name);\n\t\tif (!existsSync(dir) || !statSync(dir).isDirectory()) continue;\n\t\tfor (const fileName of readdirSync(dir)) {\n\t\t\tif (!fileName.endsWith(\".jsonl\")) continue;\n\t\t\tconst filePath = join(dir, fileName);\n\t\t\tif (!shouldReadSessionFile(filePath, window)) continue;\n\t\t\tconst entries = getSessionEntries(filePath, liveSession);\n\t\t\tif (addDailyUsageFromEntries(totals, entries, window, seenSpawnedReportIds)) {\n\t\t\t\ttotals.sessions += 1;\n\t\t\t}\n\t\t}\n\t}\n\treturn finishTotals(totals);\n}\n\nexport function formatDailyUsageBreakdown(\n\ttotals: DailyUsageTotals,\n\tformatLabel: (label: string) => string = (label) => label,\n): string {\n\treturn [\n\t\t`${formatLabel(\"Today:\")} $${totals.totalCost.toFixed(4)}`,\n\t\t`${formatLabel(\"Own/session messages:\")} $${totals.ownCost.toFixed(4)}`,\n\t\t`${formatLabel(\"Spawned/background reports:\")} $${totals.spawnedCost.toFixed(4)}`,\n\t\t`${formatLabel(\"Sessions scanned:\")} ${totals.sessions}`,\n\t\t`${formatLabel(\"Spawned/background report count:\")} ${totals.reports}`,\n\t].join(\"\\n\");\n}\n\nexport function getLocalDayWindow(now = new Date()): DailyUsageWindow {\n\tconst start = new Date(now);\n\tstart.setHours(0, 0, 0, 0);\n\tconst end = new Date(start);\n\tend.setDate(end.getDate() + 1);\n\treturn { startMs: start.getTime(), endMs: end.getTime() };\n}\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"worker-runner.d.ts","sourceRoot":"","sources":["../../../src/core/delegation/worker-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E;gDAC4C;IAC5C,GAAG,CAAC,EAAE,MAAM,CAAC;CACb;AAED,MAAM,WAAW,gBAAgB;IAChC,MAAM,EAAE,YAAY,CAAC;IACrB,8FAA8F;IAC9F,UAAU,EAAE,WAAW,CAAC;IACxB,QAAQ,EAAE,OAAO,CAAC;IAClB,UAAU,EAAE,kBAAkB,CAAC;IAC/B,UAAU,EAAE,MAAM,CAAC;IACnB,OAAO,EAAE,MAAM,CAAC;CAChB;AAED,wBAAgB,qBAAqB,CAAC,OAAO,EAAE,aAAa,GAAG,MAAM,CAEpE;AAED,MAAM,WAAW,kBAAkB;IAClC,OAAO,EAAE,MAAM,CAAC;IAChB,MAAM,EAAE,WAAW,GAAG,SAAS,CAAC;IAChC,QAAQ,EAAE,MAAM,EAAE,CAAC;IACnB,QAAQ,EAAE,KAAK,CAAC;QAAE,OAAO,EAAE,MAAM,CAAC;QAAC,UAAU,CAAC,EAAE,MAAM,CAAA;KAAE,CAAC,CAAC;IAC1D,OAAO,EAAE,YAAY,EAAE,CAAC;CACxB;AA8BD,wBAAgB,iBAAiB,CAAC,IAAI,EAAE,MAAM,GAAG,kBAAkB,GAAG,SAAS,CAwC9E;AAiDD,wBAAsB,SAAS,CAAC,OAAO,EAAE,mBAAmB,GAAG,OAAO,CAAC,gBAAgB,CAAC,CAgJvF","sourcesContent":["import { runBoundedCompletion } from \"../autonomy/bounded-completion.ts\";\nimport type { EvidenceRef, Finding, GateOutcome, WorkerRequest, WorkerResult } from \"../autonomy/contracts.ts\";\nimport type { LaneTerminalStatus } from \"../autonomy/lane-tracker.ts\";\nimport { createEvidenceBundle } from \"../research/evidence-bundle.ts\";\nimport { type AppliedActionsReport, parseWorkerActions, type WorkerAction } from \"./worker-actions.ts\";\nimport { validateWorkerResult } from \"./worker-result.ts\";\n\n/**\n * Pure orchestration for one bounded scout-worker delegation: bounded isolated completion ->\n * parse -> `WorkerResult` -> parent validation via {@link validateWorkerResult}.\n *\n * The injected completion may be a bounded child tool loop. Its tool surface is built and gated by\n * the host; this module keeps the structured-output contract and treats every result as untrusted\n * until parent validation succeeds.\n */\n\n/** Static across calls so callers can use `cacheRetention: \"short\"`. */\nexport const WORKER_LANE_SYSTEM_PROMPT = [\n\t\"You are a bounded read-only scout worker delegated one task by a coding agent.\",\n\t\"Use only the read-only tools provided to inspect the workspace. You cannot change files or delegate more workers.\",\n\t\"Respond with STRICT JSON only - no prose, no markdown fences:\",\n\t'{\"summary\":\"<what you concluded>\",\"status\":\"completed\"|\"blocked\",\"blockers\":[\"<why you are stuck>\"],\"findings\":[{\"summary\":\"<one concrete finding>\",\"confidence\":<0..1>}]}',\n\t'Use status \"blocked\" with blockers only when the task cannot be answered from the provided context.',\n\t\"Never invent file paths, APIs, or facts.\",\n].join(\"\\n\");\n\n/** Write-capable variant (G2): direct tools are execution-gated and reported; structured actions\n * remain as a fallback for models without a native tool channel and use the same path scope. */\nexport const WORKER_WRITE_LANE_SYSTEM_PROMPT = [\n\t\"You are a bounded code-writing worker delegated one task by a coding agent.\",\n\t\"Use only the provided read tools and path-scoped write/edit tools. You cannot run shell commands or delegate workers.\",\n\t\"Respond with STRICT JSON only - no prose, no markdown fences:\",\n\t'{\"summary\":\"<what you did>\",\"status\":\"completed\"|\"blocked\",\"blockers\":[],\"findings\":[{\"summary\":\"<finding>\",\"confidence\":<0..1>}],\"actions\":[{\"op\":\"write\",\"path\":\"<relative path>\",\"content\":\"<full file content>\"},{\"op\":\"edit\",\"path\":\"<relative path>\",\"old\":\"<exact text>\",\"new\":\"<replacement>\"}]}',\n\t\"Only touch paths inside your delegated scope. Keep edits minimal and exact.\",\n\t\"If you changed a file with a provided tool, do not repeat that change in actions; actions are for changes not already applied.\",\n\t'Use status \"blocked\" with blockers when the task cannot be done from the provided context.',\n\t\"Never invent file paths, APIs, or facts.\",\n].join(\"\\n\");\n\nexport interface WorkerCompletion {\n\ttext: string;\n\tcostUsd: number;\n\tstopReason: string;\n\t/** Files successfully changed by the child tool loop before it produced the final JSON. */\n\tchangedFiles?: readonly string[];\n\t/** Capability refusals or execution failures observed inside the child tool loop. */\n\tblockers?: readonly string[];\n}\n\nexport interface WorkerRunnerOptions {\n\trequest: WorkerRequest;\n\t/** Budget for this delegation; a post-hoc breach marks the lane budget_exhausted. */\n\tmaxUsd: number;\n\t/** Wall-clock budget in milliseconds; 0 disables. */\n\tmaxWallClockMs: number;\n\t/**\n\t * Pre-allocated spawned-usage report id. Always stamped on the result so parent validation can\n\t * enforce the cost-visibility invariant (a completed result without a usage report is blocked).\n\t */\n\tusageReportId: string;\n\tcomplete: (args: { systemPrompt: string; userPrompt: string; signal?: AbortSignal }) => Promise<WorkerCompletion>;\n\t/** Live successful child-tool mutations, including writes completed before timeout/cancellation. */\n\tgetChangedFiles?: () => readonly string[];\n\tsignal?: AbortSignal;\n\tnow?: () => string;\n\t/** Enables the WRITE lane: only honored when the request envelope grants \"write_files\". The\n\t * runner applies the worker's structured actions through the envelope path scope; refusals\n\t * and failures become blockers, never silent drops. */\n\tapplyActions?: (actions: readonly WorkerAction[]) => AppliedActionsReport;\n\t/** Session cwd — the baseline for relative changed-file and envelope paths in parent\n\t * validation. Defaults to process.cwd(). */\n\tcwd?: string;\n}\n\nexport interface WorkerRunOutcome {\n\tresult: WorkerResult;\n\t/** Parent-review verdict from {@link validateWorkerResult}; worker output stays untrusted. */\n\tacceptance: GateOutcome;\n\taccepted: boolean;\n\tlaneStatus: LaneTerminalStatus;\n\treasonCode: string;\n\tcostUsd: number;\n}\n\nexport function buildWorkerUserPrompt(request: WorkerRequest): string {\n\treturn `Delegated task: ${request.instructions}`;\n}\n\nexport interface ParsedWorkerOutput {\n\tsummary: string;\n\tstatus: \"completed\" | \"blocked\";\n\tblockers: string[];\n\tfindings: Array<{ summary: string; confidence?: number }>;\n\tactions: WorkerAction[];\n}\n\nfunction balancedObjectCandidates(text: string): string[] {\n\tconst candidates: string[] = [];\n\tfor (let start = 0; start < text.length; start++) {\n\t\tif (text[start] !== \"{\") continue;\n\t\tlet depth = 0;\n\t\tlet inString = false;\n\t\tlet escaped = false;\n\t\tfor (let index = start; index < text.length; index++) {\n\t\t\tconst character = text[index];\n\t\t\tif (inString) {\n\t\t\t\tif (escaped) escaped = false;\n\t\t\t\telse if (character === \"\\\\\") escaped = true;\n\t\t\t\telse if (character === '\"') inString = false;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (character === '\"') {\n\t\t\t\tinString = true;\n\t\t\t} else if (character === \"{\") {\n\t\t\t\tdepth++;\n\t\t\t} else if (character === \"}\" && --depth === 0) {\n\t\t\t\tcandidates.push(text.slice(start, index + 1));\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t}\n\treturn candidates;\n}\n\nexport function parseWorkerOutput(text: string): ParsedWorkerOutput | undefined {\n\tconst trimmed = text.trim();\n\tconst candidates: string[] = [trimmed];\n\tconst fenced = /```(?:json)?\\s*([\\s\\S]*?)```/.exec(trimmed);\n\tif (fenced?.[1]) candidates.push(fenced[1].trim());\n\tcandidates.push(...balancedObjectCandidates(trimmed));\n\n\tfor (const candidate of candidates) {\n\t\tlet parsed: unknown;\n\t\ttry {\n\t\t\tparsed = JSON.parse(candidate);\n\t\t} catch {\n\t\t\tcontinue;\n\t\t}\n\t\tif (!parsed || typeof parsed !== \"object\" || Array.isArray(parsed)) continue;\n\t\tconst record = parsed as Record<string, unknown>;\n\t\tconst summary = record.summary;\n\t\tif (typeof summary !== \"string\" || summary.trim().length === 0) continue;\n\n\t\tconst status = record.status === \"blocked\" ? \"blocked\" : \"completed\";\n\t\tconst blockers = Array.isArray(record.blockers)\n\t\t\t? record.blockers.filter((blocker): blocker is string => typeof blocker === \"string\" && blocker.length > 0)\n\t\t\t: [];\n\t\tconst findings: Array<{ summary: string; confidence?: number }> = [];\n\t\tif (Array.isArray(record.findings)) {\n\t\t\tfor (const item of record.findings) {\n\t\t\t\tif (!item || typeof item !== \"object\" || Array.isArray(item)) continue;\n\t\t\t\tconst findingSummary = (item as { summary?: unknown }).summary;\n\t\t\t\tif (typeof findingSummary !== \"string\" || findingSummary.trim().length === 0) continue;\n\t\t\t\tconst confidenceRaw = (item as { confidence?: unknown }).confidence;\n\t\t\t\tconst confidence =\n\t\t\t\t\ttypeof confidenceRaw === \"number\" && Number.isFinite(confidenceRaw)\n\t\t\t\t\t\t? Math.min(Math.max(confidenceRaw, 0), 1)\n\t\t\t\t\t\t: undefined;\n\t\t\t\tfindings.push({ summary: findingSummary.trim(), confidence });\n\t\t\t}\n\t\t}\n\t\treturn { summary: summary.trim(), status, blockers, findings, actions: parseWorkerActions(record.actions) };\n\t}\n\treturn undefined;\n}\n\nfunction buildWorkerEvidence(request: WorkerRequest, findings: ParsedWorkerOutput[\"findings\"]) {\n\tif (findings.length === 0) return undefined;\n\tconst instructionsRef: EvidenceRef = {\n\t\tid: \"src-instructions\",\n\t\tkind: \"user\",\n\t\ttitle: \"Delegated task instructions\",\n\t\ttrusted: true,\n\t\texcerpt: request.instructions.slice(0, 2000),\n\t};\n\tconst synthesisRef: EvidenceRef = {\n\t\tid: \"src-worker\",\n\t\tkind: \"tool\",\n\t\ttitle: \"Scout-worker synthesis\",\n\t\ttrusted: false,\n\t};\n\tconst bundleFindings: Finding[] = findings.map((finding, index) => ({\n\t\tid: `finding-${index + 1}`,\n\t\tsummary: finding.summary,\n\t\tevidenceIds: [synthesisRef.id],\n\t\t...(finding.confidence !== undefined ? { confidence: finding.confidence } : {}),\n\t}));\n\treturn createEvidenceBundle({\n\t\tquery: `worker:${request.id}`,\n\t\tsources: [instructionsRef, synthesisRef],\n\t\tfindings: bundleFindings,\n\t});\n}\n\nfunction finishOutcome(args: {\n\trequest: WorkerRequest;\n\tresult: WorkerResult;\n\tlaneStatus: LaneTerminalStatus;\n\treasonCode: string;\n\tcostUsd: number;\n\tcwd?: string;\n}): WorkerRunOutcome {\n\tconst acceptance = validateWorkerResult({ request: args.request, result: args.result, cwd: args.cwd });\n\treturn {\n\t\tresult: args.result,\n\t\tacceptance,\n\t\taccepted: acceptance.outcome === \"allow\",\n\t\tlaneStatus: args.laneStatus,\n\t\treasonCode: args.reasonCode,\n\t\tcostUsd: args.costUsd,\n\t};\n}\n\nexport async function runWorker(options: WorkerRunnerOptions): Promise<WorkerRunOutcome> {\n\tconst now = options.now ?? (() => new Date().toISOString());\n\tconst baseResult = {\n\t\trequestId: options.request.id,\n\t\tchangedFiles: [] as string[],\n\t\tusageReportId: options.usageReportId,\n\t\tcreatedAt: now(),\n\t};\n\n\t// The WRITE lane requires BOTH the envelope grant and a caller-supplied applier — either\n\t// alone keeps the read-only scout contract byte-for-byte.\n\tconst writeCapable =\n\t\toptions.request.envelope.capabilities.includes(\"write_files\") && options.applyActions !== undefined;\n\n\tconst bounded = await runBoundedCompletion({\n\t\tmaxWallClockMs: options.maxWallClockMs,\n\t\tsignal: options.signal,\n\t\texecute: (signal) =>\n\t\t\toptions.complete({\n\t\t\t\tsystemPrompt: writeCapable ? WORKER_WRITE_LANE_SYSTEM_PROMPT : WORKER_LANE_SYSTEM_PROMPT,\n\t\t\t\tuserPrompt: buildWorkerUserPrompt(options.request),\n\t\t\t\tsignal,\n\t\t\t}),\n\t});\n\tconst costUsd = bounded.completion?.costUsd ?? 0;\n\tconst liveChangedFiles = [...new Set(options.getChangedFiles?.() ?? [])];\n\n\tif (bounded.failure) {\n\t\tconst cancelled = bounded.failure.status === \"canceled\" || bounded.failure.status === \"timeout\";\n\t\treturn finishOutcome({\n\t\t\trequest: options.request,\n\t\t\tcwd: options.cwd,\n\t\t\tresult: {\n\t\t\t\t...baseResult,\n\t\t\t\tchangedFiles: liveChangedFiles,\n\t\t\t\tstatus: cancelled ? \"cancelled\" : \"failed\",\n\t\t\t\tsummary: `Worker did not complete: ${bounded.failure.reasonCode}`,\n\t\t\t},\n\t\t\tlaneStatus: bounded.failure.status,\n\t\t\treasonCode: bounded.failure.reasonCode,\n\t\t\tcostUsd,\n\t\t});\n\t}\n\n\tconst completion = bounded.completion as WorkerCompletion | undefined;\n\tconst completionChangedFiles = [...new Set([...liveChangedFiles, ...(completion?.changedFiles ?? [])])];\n\tconst completionBaseResult = { ...baseResult, changedFiles: completionChangedFiles };\n\tif (!completion || completion.stopReason === \"error\" || completion.stopReason === \"aborted\") {\n\t\treturn finishOutcome({\n\t\t\trequest: options.request,\n\t\t\tcwd: options.cwd,\n\t\t\tresult: { ...completionBaseResult, status: \"failed\", summary: \"Worker model call failed.\" },\n\t\t\tlaneStatus: \"failed\",\n\t\t\treasonCode: \"model_error\",\n\t\t\tcostUsd,\n\t\t});\n\t}\n\n\tconst parsed = parseWorkerOutput(completion.text);\n\tif (!parsed) {\n\t\tconst readOnlyPlainText =\n\t\t\t!writeCapable &&\n\t\t\tcompletion.stopReason === \"stop\" &&\n\t\t\tcompletion.text.trim().length > 0 &&\n\t\t\tcompletionChangedFiles.length === 0;\n\t\tif (readOnlyPlainText) {\n\t\t\treturn finishOutcome({\n\t\t\t\trequest: options.request,\n\t\t\t\tcwd: options.cwd,\n\t\t\t\tresult: {\n\t\t\t\t\t...completionBaseResult,\n\t\t\t\t\tstatus: \"completed\",\n\t\t\t\t\toutputFormat: \"plain_text\",\n\t\t\t\t\tsummary: completion.text.trim().slice(0, 8000),\n\t\t\t\t},\n\t\t\t\tlaneStatus: \"succeeded\",\n\t\t\t\treasonCode: \"worker_completed_plain_text\",\n\t\t\t\tcostUsd,\n\t\t\t});\n\t\t}\n\t\treturn finishOutcome({\n\t\t\trequest: options.request,\n\t\t\tcwd: options.cwd,\n\t\t\tresult: {\n\t\t\t\t...completionBaseResult,\n\t\t\t\tstatus: \"failed\",\n\t\t\t\tsummary: \"Worker output was not valid structured JSON.\",\n\t\t\t},\n\t\t\tlaneStatus: \"failed\",\n\t\t\treasonCode: \"unparseable_output\",\n\t\t\tcostUsd,\n\t\t});\n\t}\n\n\tconst evidence = buildWorkerEvidence(options.request, parsed.findings);\n\tlet changedFiles: string[] = [...completionChangedFiles];\n\tconst actionBlockers: string[] = [...(completion.blockers ?? [])];\n\tif (!writeCapable && completionChangedFiles.length > 0) {\n\t\tactionBlockers.push(\"worker reported file changes without a write_files envelope grant\");\n\t}\n\tif (writeCapable && parsed.status !== \"blocked\" && parsed.actions.length > 0 && options.applyActions) {\n\t\t// Runner-side application through the envelope path scope: refusals and failures are\n\t\t// surfaced as blockers so a partially-applied change can never look like clean success.\n\t\tconst applied = options.applyActions(parsed.actions);\n\t\tchangedFiles = [...new Set([...changedFiles, ...applied.changedFiles])];\n\t\tfor (const refusal of applied.refused) {\n\t\t\tactionBlockers.push(`action refused (${refusal.path}): ${refusal.reason}`);\n\t\t}\n\t\tfor (const failure of applied.failed) {\n\t\t\tactionBlockers.push(`action failed (${failure.path}): ${failure.reason}`);\n\t\t}\n\t} else if (!writeCapable && parsed.actions.length > 0) {\n\t\tactionBlockers.push(\"worker emitted file actions without a write_files envelope grant; nothing was applied\");\n\t}\n\tconst allBlockers = [...parsed.blockers, ...actionBlockers];\n\tconst result: WorkerResult = {\n\t\t...baseResult,\n\t\tchangedFiles,\n\t\tstatus: parsed.status === \"blocked\" || allBlockers.length > 0 ? \"blocked\" : \"completed\",\n\t\tsummary: parsed.summary,\n\t\t...(allBlockers.length > 0 ? { blockers: allBlockers } : {}),\n\t\t...(evidence ? { evidence } : {}),\n\t};\n\n\tif (result.status === \"blocked\") {\n\t\treturn finishOutcome({\n\t\t\trequest: options.request,\n\t\t\tcwd: options.cwd,\n\t\t\tresult,\n\t\t\tlaneStatus: \"failed\",\n\t\t\treasonCode: \"worker_blocked\",\n\t\t\tcostUsd,\n\t\t});\n\t}\n\n\tconst overBudget = options.maxUsd > 0 && costUsd > options.maxUsd;\n\treturn finishOutcome({\n\t\trequest: options.request,\n\t\tcwd: options.cwd,\n\t\tresult,\n\t\tlaneStatus: overBudget ? \"budget_exhausted\" : \"succeeded\",\n\t\treasonCode: overBudget ? \"cost_budget_exceeded\" : \"worker_completed\",\n\t\tcostUsd,\n\t});\n}\n"]}
1
+ {"version":3,"file":"worker-runner.d.ts","sourceRoot":"","sources":["../../../src/core/delegation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IAC1E;gDAC4C;IAC5C,GAAG,CAAC,EAAE,MAAM,CAAC;CACb;AAED,MAAM,WAAW,gBAAgB;IAChC,MAAM,EAAE,YAAY,CAAC;IACrB,8FAA8F;IAC9F,UAAU,EAAE,WAAW,CAAC;IACxB,QAAQ,EAAE,OAAO,CAAC;IAClB,UAAU,EAAE,kBAAkB,CAAC;IAC/B,UAAU,EAAE,MAAM,CAAC;IACnB,OAAO,EAAE,MAAM,CAAC;CAChB;AAED,wBAAgB,qBAAqB,CAAC,OAAO,EAAE,aAAa,GAAG,MAAM,CAUpE;AAED,MAAM,WAAW,kBAAkB;IAClC,OAAO,EAAE,MAAM,CAAC;IAChB,MAAM,EAAE,WAAW,GAAG,SAAS,CAAC;IAChC,QAAQ,EAAE,MAAM,EAAE,CAAC;IACnB,QAAQ,EAAE,KAAK,CAAC;QAAE,OAAO,EAAE,MAAM,CAAC;QAAC,UAAU,CAAC,EAAE,MAAM,CAAA;KAAE,CAAC,CAAC;IAC1D,OAAO,EAAE,YAAY,EAAE,CAAC;CACxB;AA8BD,wBAAgB,iBAAiB,CAAC,IAAI,EAAE,MAAM,GAAG,kBAAkB,GAAG,SAAS,CAwC9E;AAiDD,wBAAsB,SAAS,CAAC,OAAO,EAAE,mBAAmB,GAAG,OAAO,CAAC,gBAAgB,CAAC,CAyJvF","sourcesContent":["import { runBoundedCompletion } from \"../autonomy/bounded-completion.ts\";\nimport type { EvidenceRef, Finding, GateOutcome, WorkerRequest, WorkerResult } from \"../autonomy/contracts.ts\";\nimport type { LaneTerminalStatus } from \"../autonomy/lane-tracker.ts\";\nimport { createEvidenceBundle } from \"../research/evidence-bundle.ts\";\nimport { type AppliedActionsReport, parseWorkerActions, type WorkerAction } from \"./worker-actions.ts\";\nimport { validateWorkerResult } from \"./worker-result.ts\";\n\n/**\n * Pure orchestration for one bounded scout-worker delegation: bounded isolated completion ->\n * parse -> `WorkerResult` -> parent validation via {@link validateWorkerResult}.\n *\n * The injected completion may be a bounded child tool loop. Its tool surface is built and gated by\n * the host; this module keeps the structured-output contract and treats every result as untrusted\n * until parent validation succeeds.\n */\n\n/** Static across calls so callers can use `cacheRetention: \"short\"`. */\nexport const WORKER_LANE_SYSTEM_PROMPT = [\n\t\"You are a bounded read-only scout worker delegated one task by a coding agent.\",\n\t\"Use only the read-only tools provided to inspect the workspace. You cannot change files or delegate more workers.\",\n\t\"Respond with STRICT JSON only - no prose, no markdown fences:\",\n\t'{\"summary\":\"<what you concluded>\",\"status\":\"completed\"|\"blocked\",\"blockers\":[\"<why you are stuck>\"],\"findings\":[{\"summary\":\"<one concrete finding>\",\"confidence\":<0..1>}]}',\n\t'Use status \"blocked\" with blockers only when the task cannot be answered from the provided context.',\n\t\"Never invent file paths, APIs, or facts.\",\n].join(\"\\n\");\n\n/** Write-capable variant (G2): direct tools are execution-gated and reported; structured actions\n * remain as a fallback for models without a native tool channel and use the same path scope. */\nexport const WORKER_WRITE_LANE_SYSTEM_PROMPT = [\n\t\"You are a bounded code-writing worker delegated one task by a coding agent.\",\n\t\"Use only the provided read tools and path-scoped write/edit tools. You cannot run shell commands or delegate workers.\",\n\t\"Respond with STRICT JSON only - no prose, no markdown fences:\",\n\t'{\"summary\":\"<what you did>\",\"status\":\"completed\"|\"blocked\",\"blockers\":[],\"findings\":[{\"summary\":\"<finding>\",\"confidence\":<0..1>}],\"actions\":[{\"op\":\"write\",\"path\":\"<relative path>\",\"content\":\"<full file content>\"},{\"op\":\"edit\",\"path\":\"<relative path>\",\"old\":\"<exact text>\",\"new\":\"<replacement>\"}]}',\n\t\"Only touch paths inside your delegated scope. Keep edits minimal and exact.\",\n\t\"If you changed a file with a provided tool, do not repeat that change in actions; actions are for changes not already applied.\",\n\t'Use status \"blocked\" with blockers when the task cannot be done from the provided context.',\n\t\"Never invent file paths, APIs, or facts.\",\n].join(\"\\n\");\n\nexport interface WorkerCompletion {\n\ttext: string;\n\tcostUsd: number;\n\tstopReason: string;\n\t/** Files successfully changed by the child tool loop before it produced the final JSON. */\n\tchangedFiles?: readonly string[];\n\t/** Capability refusals or execution failures observed inside the child tool loop. */\n\tblockers?: readonly string[];\n}\n\nexport interface WorkerRunnerOptions {\n\trequest: WorkerRequest;\n\t/** Budget for this delegation; a post-hoc breach marks the lane budget_exhausted. */\n\tmaxUsd: number;\n\t/** Wall-clock budget in milliseconds; 0 disables. */\n\tmaxWallClockMs: number;\n\t/**\n\t * Pre-allocated spawned-usage report id. Always stamped on the result so parent validation can\n\t * enforce the cost-visibility invariant (a completed result without a usage report is blocked).\n\t */\n\tusageReportId: string;\n\tcomplete: (args: { systemPrompt: string; userPrompt: string; signal?: AbortSignal }) => Promise<WorkerCompletion>;\n\t/** Live successful child-tool mutations, including writes completed before timeout/cancellation. */\n\tgetChangedFiles?: () => readonly string[];\n\tsignal?: AbortSignal;\n\tnow?: () => string;\n\t/** Enables the WRITE lane: only honored when the request envelope grants \"write_files\". The\n\t * runner applies the worker's structured actions through the envelope path scope; refusals\n\t * and failures become blockers, never silent drops. */\n\tapplyActions?: (actions: readonly WorkerAction[]) => AppliedActionsReport;\n\t/** Session cwd — the baseline for relative changed-file and envelope paths in parent\n\t * validation. Defaults to process.cwd(). */\n\tcwd?: string;\n}\n\nexport interface WorkerRunOutcome {\n\tresult: WorkerResult;\n\t/** Parent-review verdict from {@link validateWorkerResult}; worker output stays untrusted. */\n\tacceptance: GateOutcome;\n\taccepted: boolean;\n\tlaneStatus: LaneTerminalStatus;\n\treasonCode: string;\n\tcostUsd: number;\n}\n\nexport function buildWorkerUserPrompt(request: WorkerRequest): string {\n\treturn [\n\t\t\"Delegated task:\",\n\t\t\"<task>\",\n\t\trequest.instructions,\n\t\t\"</task>\",\n\t\t\"\",\n\t\t\"The task may request a custom output format. Do not replace the worker result envelope.\",\n\t\t'Always return the JSON object required by the system prompt; put requested details inside \"summary\" and \"findings\".',\n\t].join(\"\\n\");\n}\n\nexport interface ParsedWorkerOutput {\n\tsummary: string;\n\tstatus: \"completed\" | \"blocked\";\n\tblockers: string[];\n\tfindings: Array<{ summary: string; confidence?: number }>;\n\tactions: WorkerAction[];\n}\n\nfunction balancedObjectCandidates(text: string): string[] {\n\tconst candidates: string[] = [];\n\tfor (let start = 0; start < text.length; start++) {\n\t\tif (text[start] !== \"{\") continue;\n\t\tlet depth = 0;\n\t\tlet inString = false;\n\t\tlet escaped = false;\n\t\tfor (let index = start; index < text.length; index++) {\n\t\t\tconst character = text[index];\n\t\t\tif (inString) {\n\t\t\t\tif (escaped) escaped = false;\n\t\t\t\telse if (character === \"\\\\\") escaped = true;\n\t\t\t\telse if (character === '\"') inString = false;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (character === '\"') {\n\t\t\t\tinString = true;\n\t\t\t} else if (character === \"{\") {\n\t\t\t\tdepth++;\n\t\t\t} else if (character === \"}\" && --depth === 0) {\n\t\t\t\tcandidates.push(text.slice(start, index + 1));\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t}\n\treturn candidates;\n}\n\nexport function parseWorkerOutput(text: string): ParsedWorkerOutput | undefined {\n\tconst trimmed = text.trim();\n\tconst candidates: string[] = [trimmed];\n\tconst fenced = /```(?:json)?\\s*([\\s\\S]*?)```/.exec(trimmed);\n\tif (fenced?.[1]) candidates.push(fenced[1].trim());\n\tcandidates.push(...balancedObjectCandidates(trimmed));\n\n\tfor (const candidate of candidates) {\n\t\tlet parsed: unknown;\n\t\ttry {\n\t\t\tparsed = JSON.parse(candidate);\n\t\t} catch {\n\t\t\tcontinue;\n\t\t}\n\t\tif (!parsed || typeof parsed !== \"object\" || Array.isArray(parsed)) continue;\n\t\tconst record = parsed as Record<string, unknown>;\n\t\tconst summary = record.summary;\n\t\tif (typeof summary !== \"string\" || summary.trim().length === 0) continue;\n\n\t\tconst status = record.status === \"blocked\" ? \"blocked\" : \"completed\";\n\t\tconst blockers = Array.isArray(record.blockers)\n\t\t\t? record.blockers.filter((blocker): blocker is string => typeof blocker === \"string\" && blocker.length > 0)\n\t\t\t: [];\n\t\tconst findings: Array<{ summary: string; confidence?: number }> = [];\n\t\tif (Array.isArray(record.findings)) {\n\t\t\tfor (const item of record.findings) {\n\t\t\t\tif (!item || typeof item !== \"object\" || Array.isArray(item)) continue;\n\t\t\t\tconst findingSummary = (item as { summary?: unknown }).summary;\n\t\t\t\tif (typeof findingSummary !== \"string\" || findingSummary.trim().length === 0) continue;\n\t\t\t\tconst confidenceRaw = (item as { confidence?: unknown }).confidence;\n\t\t\t\tconst confidence =\n\t\t\t\t\ttypeof confidenceRaw === \"number\" && Number.isFinite(confidenceRaw)\n\t\t\t\t\t\t? Math.min(Math.max(confidenceRaw, 0), 1)\n\t\t\t\t\t\t: undefined;\n\t\t\t\tfindings.push({ summary: findingSummary.trim(), confidence });\n\t\t\t}\n\t\t}\n\t\treturn { summary: summary.trim(), status, blockers, findings, actions: parseWorkerActions(record.actions) };\n\t}\n\treturn undefined;\n}\n\nfunction buildWorkerEvidence(request: WorkerRequest, findings: ParsedWorkerOutput[\"findings\"]) {\n\tif (findings.length === 0) return undefined;\n\tconst instructionsRef: EvidenceRef = {\n\t\tid: \"src-instructions\",\n\t\tkind: \"user\",\n\t\ttitle: \"Delegated task instructions\",\n\t\ttrusted: true,\n\t\texcerpt: request.instructions.slice(0, 2000),\n\t};\n\tconst synthesisRef: EvidenceRef = {\n\t\tid: \"src-worker\",\n\t\tkind: \"tool\",\n\t\ttitle: \"Scout-worker synthesis\",\n\t\ttrusted: false,\n\t};\n\tconst bundleFindings: Finding[] = findings.map((finding, index) => ({\n\t\tid: `finding-${index + 1}`,\n\t\tsummary: finding.summary,\n\t\tevidenceIds: [synthesisRef.id],\n\t\t...(finding.confidence !== undefined ? { confidence: finding.confidence } : {}),\n\t}));\n\treturn createEvidenceBundle({\n\t\tquery: `worker:${request.id}`,\n\t\tsources: [instructionsRef, synthesisRef],\n\t\tfindings: bundleFindings,\n\t});\n}\n\nfunction finishOutcome(args: {\n\trequest: WorkerRequest;\n\tresult: WorkerResult;\n\tlaneStatus: LaneTerminalStatus;\n\treasonCode: string;\n\tcostUsd: number;\n\tcwd?: string;\n}): WorkerRunOutcome {\n\tconst acceptance = validateWorkerResult({ request: args.request, result: args.result, cwd: args.cwd });\n\treturn {\n\t\tresult: args.result,\n\t\tacceptance,\n\t\taccepted: acceptance.outcome === \"allow\",\n\t\tlaneStatus: args.laneStatus,\n\t\treasonCode: args.reasonCode,\n\t\tcostUsd: args.costUsd,\n\t};\n}\n\nexport async function runWorker(options: WorkerRunnerOptions): Promise<WorkerRunOutcome> {\n\tconst now = options.now ?? (() => new Date().toISOString());\n\tconst baseResult = {\n\t\trequestId: options.request.id,\n\t\tchangedFiles: [] as string[],\n\t\tusageReportId: options.usageReportId,\n\t\tcreatedAt: now(),\n\t};\n\n\t// The WRITE lane requires BOTH the envelope grant and a caller-supplied applier — either\n\t// alone keeps the read-only scout contract byte-for-byte.\n\tconst writeCapable =\n\t\toptions.request.envelope.capabilities.includes(\"write_files\") && options.applyActions !== undefined;\n\n\tconst bounded = await runBoundedCompletion({\n\t\tmaxWallClockMs: options.maxWallClockMs,\n\t\tsignal: options.signal,\n\t\texecute: (signal) =>\n\t\t\toptions.complete({\n\t\t\t\tsystemPrompt: writeCapable ? WORKER_WRITE_LANE_SYSTEM_PROMPT : WORKER_LANE_SYSTEM_PROMPT,\n\t\t\t\tuserPrompt: buildWorkerUserPrompt(options.request),\n\t\t\t\tsignal,\n\t\t\t}),\n\t});\n\tconst costUsd = bounded.completion?.costUsd ?? 0;\n\tconst liveChangedFiles = [...new Set(options.getChangedFiles?.() ?? [])];\n\n\tif (bounded.failure) {\n\t\tconst cancelled = bounded.failure.status === \"canceled\" || bounded.failure.status === \"timeout\";\n\t\treturn finishOutcome({\n\t\t\trequest: options.request,\n\t\t\tcwd: options.cwd,\n\t\t\tresult: {\n\t\t\t\t...baseResult,\n\t\t\t\tchangedFiles: liveChangedFiles,\n\t\t\t\tstatus: cancelled ? \"cancelled\" : \"failed\",\n\t\t\t\tsummary: `Worker did not complete: ${bounded.failure.reasonCode}`,\n\t\t\t},\n\t\t\tlaneStatus: bounded.failure.status,\n\t\t\treasonCode: bounded.failure.reasonCode,\n\t\t\tcostUsd,\n\t\t});\n\t}\n\n\tconst completion = bounded.completion as WorkerCompletion | undefined;\n\tconst completionChangedFiles = [...new Set([...liveChangedFiles, ...(completion?.changedFiles ?? [])])];\n\tconst completionBaseResult = { ...baseResult, changedFiles: completionChangedFiles };\n\tif (!completion || completion.stopReason === \"error\" || completion.stopReason === \"aborted\") {\n\t\treturn finishOutcome({\n\t\t\trequest: options.request,\n\t\t\tcwd: options.cwd,\n\t\t\tresult: { ...completionBaseResult, status: \"failed\", summary: \"Worker model call failed.\" },\n\t\t\tlaneStatus: \"failed\",\n\t\t\treasonCode: \"model_error\",\n\t\t\tcostUsd,\n\t\t});\n\t}\n\n\tconst parsed = parseWorkerOutput(completion.text);\n\tif (!parsed) {\n\t\tconst readOnlyPlainText =\n\t\t\t!writeCapable && completion.text.trim().length > 0 && completionChangedFiles.length === 0;\n\t\tif (readOnlyPlainText) {\n\t\t\tconst completionBlockers = [...(completion.blockers ?? [])];\n\t\t\tconst incompleteNote =\n\t\t\t\tcompletion.stopReason === \"stop\"\n\t\t\t\t\t? \"\"\n\t\t\t\t\t: `\\n\\n[Worker output ended with stop reason '${completion.stopReason}'; verify completeness.]`;\n\t\t\tconst summary = `${completion.text.trim().slice(0, Math.max(0, 8000 - incompleteNote.length))}${incompleteNote}`;\n\t\t\tconst blocked = completionBlockers.length > 0;\n\t\t\treturn finishOutcome({\n\t\t\t\trequest: options.request,\n\t\t\t\tcwd: options.cwd,\n\t\t\t\tresult: {\n\t\t\t\t\t...completionBaseResult,\n\t\t\t\t\tstatus: blocked ? \"blocked\" : \"completed\",\n\t\t\t\t\toutputFormat: \"plain_text\",\n\t\t\t\t\tsummary,\n\t\t\t\t\t...(blocked ? { blockers: completionBlockers } : {}),\n\t\t\t\t},\n\t\t\t\tlaneStatus: blocked ? \"failed\" : \"succeeded\",\n\t\t\t\treasonCode: blocked\n\t\t\t\t\t? \"worker_blocked\"\n\t\t\t\t\t: completion.stopReason === \"stop\"\n\t\t\t\t\t\t? \"worker_completed_plain_text\"\n\t\t\t\t\t\t: \"worker_completed_plain_text_incomplete\",\n\t\t\t\tcostUsd,\n\t\t\t});\n\t\t}\n\t\treturn finishOutcome({\n\t\t\trequest: options.request,\n\t\t\tcwd: options.cwd,\n\t\t\tresult: {\n\t\t\t\t...completionBaseResult,\n\t\t\t\tstatus: \"failed\",\n\t\t\t\tsummary: \"Worker output was not valid structured JSON.\",\n\t\t\t},\n\t\t\tlaneStatus: \"failed\",\n\t\t\treasonCode: \"unparseable_output\",\n\t\t\tcostUsd,\n\t\t});\n\t}\n\n\tconst evidence = buildWorkerEvidence(options.request, parsed.findings);\n\tlet changedFiles: string[] = [...completionChangedFiles];\n\tconst actionBlockers: string[] = [...(completion.blockers ?? [])];\n\tif (!writeCapable && completionChangedFiles.length > 0) {\n\t\tactionBlockers.push(\"worker reported file changes without a write_files envelope grant\");\n\t}\n\tif (writeCapable && parsed.status !== \"blocked\" && parsed.actions.length > 0 && options.applyActions) {\n\t\t// Runner-side application through the envelope path scope: refusals and failures are\n\t\t// surfaced as blockers so a partially-applied change can never look like clean success.\n\t\tconst applied = options.applyActions(parsed.actions);\n\t\tchangedFiles = [...new Set([...changedFiles, ...applied.changedFiles])];\n\t\tfor (const refusal of applied.refused) {\n\t\t\tactionBlockers.push(`action refused (${refusal.path}): ${refusal.reason}`);\n\t\t}\n\t\tfor (const failure of applied.failed) {\n\t\t\tactionBlockers.push(`action failed (${failure.path}): ${failure.reason}`);\n\t\t}\n\t} else if (!writeCapable && parsed.actions.length > 0) {\n\t\tactionBlockers.push(\"worker emitted file actions without a write_files envelope grant; nothing was applied\");\n\t}\n\tconst allBlockers = [...parsed.blockers, ...actionBlockers];\n\tconst result: WorkerResult = {\n\t\t...baseResult,\n\t\tchangedFiles,\n\t\tstatus: parsed.status === \"blocked\" || allBlockers.length > 0 ? \"blocked\" : \"completed\",\n\t\tsummary: parsed.summary,\n\t\t...(allBlockers.length > 0 ? { blockers: allBlockers } : {}),\n\t\t...(evidence ? { evidence } : {}),\n\t};\n\n\tif (result.status === \"blocked\") {\n\t\treturn finishOutcome({\n\t\t\trequest: options.request,\n\t\t\tcwd: options.cwd,\n\t\t\tresult,\n\t\t\tlaneStatus: \"failed\",\n\t\t\treasonCode: \"worker_blocked\",\n\t\t\tcostUsd,\n\t\t});\n\t}\n\n\tconst overBudget = options.maxUsd > 0 && costUsd > options.maxUsd;\n\treturn finishOutcome({\n\t\trequest: options.request,\n\t\tcwd: options.cwd,\n\t\tresult,\n\t\tlaneStatus: overBudget ? \"budget_exhausted\" : \"succeeded\",\n\t\treasonCode: overBudget ? \"cost_budget_exceeded\" : \"worker_completed\",\n\t\tcostUsd,\n\t});\n}\n"]}
@@ -32,7 +32,15 @@ export const WORKER_WRITE_LANE_SYSTEM_PROMPT = [
32
32
  "Never invent file paths, APIs, or facts.",
33
33
  ].join("\n");
34
34
  export function buildWorkerUserPrompt(request) {
35
- return `Delegated task: ${request.instructions}`;
35
+ return [
36
+ "Delegated task:",
37
+ "<task>",
38
+ request.instructions,
39
+ "</task>",
40
+ "",
41
+ "The task may request a custom output format. Do not replace the worker result envelope.",
42
+ 'Always return the JSON object required by the system prompt; put requested details inside "summary" and "findings".',
43
+ ].join("\n");
36
44
  }
37
45
  function balancedObjectCandidates(text) {
38
46
  const candidates = [];
@@ -203,22 +211,30 @@ export async function runWorker(options) {
203
211
  }
204
212
  const parsed = parseWorkerOutput(completion.text);
205
213
  if (!parsed) {
206
- const readOnlyPlainText = !writeCapable &&
207
- completion.stopReason === "stop" &&
208
- completion.text.trim().length > 0 &&
209
- completionChangedFiles.length === 0;
214
+ const readOnlyPlainText = !writeCapable && completion.text.trim().length > 0 && completionChangedFiles.length === 0;
210
215
  if (readOnlyPlainText) {
216
+ const completionBlockers = [...(completion.blockers ?? [])];
217
+ const incompleteNote = completion.stopReason === "stop"
218
+ ? ""
219
+ : `\n\n[Worker output ended with stop reason '${completion.stopReason}'; verify completeness.]`;
220
+ const summary = `${completion.text.trim().slice(0, Math.max(0, 8000 - incompleteNote.length))}${incompleteNote}`;
221
+ const blocked = completionBlockers.length > 0;
211
222
  return finishOutcome({
212
223
  request: options.request,
213
224
  cwd: options.cwd,
214
225
  result: {
215
226
  ...completionBaseResult,
216
- status: "completed",
227
+ status: blocked ? "blocked" : "completed",
217
228
  outputFormat: "plain_text",
218
- summary: completion.text.trim().slice(0, 8000),
229
+ summary,
230
+ ...(blocked ? { blockers: completionBlockers } : {}),
219
231
  },
220
- laneStatus: "succeeded",
221
- reasonCode: "worker_completed_plain_text",
232
+ laneStatus: blocked ? "failed" : "succeeded",
233
+ reasonCode: blocked
234
+ ? "worker_blocked"
235
+ : completion.stopReason === "stop"
236
+ ? "worker_completed_plain_text"
237
+ : "worker_completed_plain_text_incomplete",
222
238
  costUsd,
223
239
  });
224
240
  }
@@ -1 +1 @@
1
- {"version":3,"file":"worker-runner.js","sourceRoot":"","sources":["../../../src/core/delegation/worker-runner.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,oBAAoB,EAAE,MAAM,mCAAmC,CAAC;AAGzE,OAAO,EAAE,oBAAoB,EAAE,MAAM,gCAAgC,CAAC;AACtE,OAAO,EAA6B,kBAAkB,EAAqB,MAAM,qBAAqB,CAAC;AACvG,OAAO,EAAE,oBAAoB,EAAE,MAAM,oBAAoB,CAAC;AAE1D;;;;;;;GAOG;AAEH,wEAAwE;AACxE,MAAM,CAAC,MAAM,yBAAyB,GAAG;IACxC,gFAAgF;IAChF,mHAAmH;IACnH,+DAA+D;IAC/D,4KAA4K;IAC5K,qGAAqG;IACrG,0CAA0C;CAC1C,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;AAEb;gGACgG;AAChG,MAAM,CAAC,MAAM,+BAA+B,GAAG;IAC9C,6EAA6E;IAC7E,uHAAuH;IACvH,+DAA+D;IAC/D,0SAA0S;IAC1S,6EAA6E;IAC7E,gIA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GAAG,cAAc,CAAC,CAAC;IAC5D,MAAM,MAAM,GAAiB;QAC5B,GAAG,UAAU;QACb,YAAY;QACZ,MAAM,EAAE,MAAM,CAAC,MAAM,KAAK,SAAS,IAAI,WAAW,CAAC,MAAM,GAAG,CAAC,CAAC,CAAC,CAAC,SAAS,CAAC,CAAC,CAAC,WAAW;QACvF,OAAO,EAAE,MAAM,CAAC,OAAO;QACvB,GAAG,CAAC,WAAW,CAAC,MAAM,GAAG,CAAC,CAAC,CAAC,CAAC,EAAE,QAAQ,EAAE,WAAW,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC;QAC5D,GAAG,CAAC,QAAQ,CAAC,CAAC,CAAC,EAAE,QAAQ,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC;KACjC,CAAC;IAEF,IAAI,MAAM,CAAC,MAAM,KAAK,SAAS,EAAE,CAAC;QACjC,OAAO,aAAa,CAAC;YACpB,OAAO,EAAE,OAAO,CAAC,OAAO;YACxB,GAAG,EAAE,OAAO,CAAC,GAAG;YAChB,MAAM;YACN,UAAU,EAAE,QAAQ;YACpB,UAAU,EAAE,gBAAgB;YAC5B,OAAO;SACP,CAAC,CAAC;IACJ,CAAC;IAED,MAAM,UAAU,GAAG,OAAO,CAAC,MAAM,GAAG,CAAC,IAAI,OAAO,GAAG,OAAO,CAAC,MAAM,CAAC;IAClE,OAAO,aAAa,CAAC;QACpB,OAAO,EAAE,OAAO,CAAC,OAAO;QACxB,GAAG,EAAE,OAAO,CAAC,GAAG;QAChB,MAAM;QACN,UAAU,EAAE,UAAU,CAAC,CAAC,CAAC,kBAAkB,CAAC,CAAC,CAAC,WAAW;QACzD,UAAU,EAAE,UAAU,CAAC,CAAC,CAAC,sBAAsB,CAAC,CAAC,CAAC,kBAAkB;QACpE,OAAO;KACP,CAAC,CAAC;AAAA,CACH","sourcesContent":["import { runBoundedCompletion } from \"../autonomy/bounded-completion.ts\";\nimport type { EvidenceRef, Finding, GateOutcome, WorkerRequest, WorkerResult } from \"../autonomy/contracts.ts\";\nimport type { LaneTerminalStatus } from \"../autonomy/lane-tracker.ts\";\nimport { createEvidenceBundle } from \"../research/evidence-bundle.ts\";\nimport { type AppliedActionsReport, parseWorkerActions, type WorkerAction } from \"./worker-actions.ts\";\nimport { validateWorkerResult } from \"./worker-result.ts\";\n\n/**\n * Pure orchestration for one bounded scout-worker delegation: bounded isolated completion ->\n * parse -> `WorkerResult` -> parent validation via {@link validateWorkerResult}.\n *\n * The injected completion may be a bounded child tool loop. Its tool surface is built and gated by\n * the host; this module keeps the structured-output contract and treats every result as untrusted\n * until parent validation succeeds.\n */\n\n/** Static across calls so callers can use `cacheRetention: \"short\"`. */\nexport const WORKER_LANE_SYSTEM_PROMPT = [\n\t\"You are a bounded read-only scout worker delegated one task by a coding agent.\",\n\t\"Use only the read-only tools provided to inspect the workspace. You cannot change files or delegate more workers.\",\n\t\"Respond with STRICT JSON only - no prose, no markdown fences:\",\n\t'{\"summary\":\"<what you concluded>\",\"status\":\"completed\"|\"blocked\",\"blockers\":[\"<why you are stuck>\"],\"findings\":[{\"summary\":\"<one concrete finding>\",\"confidence\":<0..1>}]}',\n\t'Use status \"blocked\" with blockers only when the task cannot be answered from the provided context.',\n\t\"Never invent file paths, APIs, or facts.\",\n].join(\"\\n\");\n\n/** Write-capable variant (G2): direct tools are execution-gated and reported; structured actions\n * remain as a fallback for models without a native tool channel and use the same path scope. */\nexport const WORKER_WRITE_LANE_SYSTEM_PROMPT = [\n\t\"You are a bounded code-writing worker delegated one task by a coding agent.\",\n\t\"Use only the provided read tools and path-scoped write/edit tools. You cannot run shell commands or delegate workers.\",\n\t\"Respond with STRICT JSON only - no prose, no markdown fences:\",\n\t'{\"summary\":\"<what you did>\",\"status\":\"completed\"|\"blocked\",\"blockers\":[],\"findings\":[{\"summary\":\"<finding>\",\"confidence\":<0..1>}],\"actions\":[{\"op\":\"write\",\"path\":\"<relative path>\",\"content\":\"<full file content>\"},{\"op\":\"edit\",\"path\":\"<relative path>\",\"old\":\"<exact text>\",\"new\":\"<replacement>\"}]}',\n\t\"Only touch paths inside your delegated scope. Keep edits minimal and exact.\",\n\t\"If you changed a file with a provided tool, do not repeat that change in actions; actions are for changes not already applied.\",\n\t'Use status \"blocked\" with blockers when the task cannot be done from the provided context.',\n\t\"Never invent file paths, APIs, or facts.\",\n].join(\"\\n\");\n\nexport interface WorkerCompletion {\n\ttext: string;\n\tcostUsd: number;\n\tstopReason: string;\n\t/** Files successfully changed by the child tool loop before it produced the final JSON. */\n\tchangedFiles?: readonly string[];\n\t/** Capability refusals or execution failures observed inside the child tool loop. */\n\tblockers?: readonly string[];\n}\n\nexport interface WorkerRunnerOptions {\n\trequest: WorkerRequest;\n\t/** Budget for this delegation; a post-hoc breach marks the lane budget_exhausted. */\n\tmaxUsd: number;\n\t/** Wall-clock budget in milliseconds; 0 disables. */\n\tmaxWallClockMs: number;\n\t/**\n\t * Pre-allocated spawned-usage report id. Always stamped on the result so parent validation can\n\t * enforce the cost-visibility invariant (a completed result without a usage report is blocked).\n\t */\n\tusageReportId: string;\n\tcomplete: (args: { systemPrompt: string; userPrompt: string; signal?: AbortSignal }) => Promise<WorkerCompletion>;\n\t/** Live successful child-tool mutations, including writes completed before timeout/cancellation. */\n\tgetChangedFiles?: () => readonly string[];\n\tsignal?: AbortSignal;\n\tnow?: () => string;\n\t/** Enables the WRITE lane: only honored when the request envelope grants \"write_files\". The\n\t * runner applies the worker's structured actions through the envelope path scope; refusals\n\t * and failures become blockers, never silent drops. */\n\tapplyActions?: (actions: readonly WorkerAction[]) => AppliedActionsReport;\n\t/** Session cwd — the baseline for relative changed-file and envelope paths in parent\n\t * validation. Defaults to process.cwd(). */\n\tcwd?: string;\n}\n\nexport interface WorkerRunOutcome {\n\tresult: WorkerResult;\n\t/** Parent-review verdict from {@link validateWorkerResult}; worker output stays untrusted. */\n\tacceptance: GateOutcome;\n\taccepted: boolean;\n\tlaneStatus: LaneTerminalStatus;\n\treasonCode: string;\n\tcostUsd: number;\n}\n\nexport function buildWorkerUserPrompt(request: WorkerRequest): string {\n\treturn `Delegated task: ${request.instructions}`;\n}\n\nexport interface ParsedWorkerOutput {\n\tsummary: string;\n\tstatus: \"completed\" | \"blocked\";\n\tblockers: string[];\n\tfindings: Array<{ summary: string; confidence?: number }>;\n\tactions: WorkerAction[];\n}\n\nfunction balancedObjectCandidates(text: string): string[] {\n\tconst candidates: string[] = [];\n\tfor (let start = 0; start < text.length; start++) {\n\t\tif (text[start] !== \"{\") continue;\n\t\tlet depth = 0;\n\t\tlet inString = false;\n\t\tlet escaped = false;\n\t\tfor (let index = start; index < text.length; index++) {\n\t\t\tconst character = text[index];\n\t\t\tif (inString) {\n\t\t\t\tif (escaped) escaped = false;\n\t\t\t\telse if (character === \"\\\\\") escaped = true;\n\t\t\t\telse if (character === '\"') inString = false;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (character === '\"') {\n\t\t\t\tinString = true;\n\t\t\t} else if (character === \"{\") {\n\t\t\t\tdepth++;\n\t\t\t} else if (character === \"}\" && --depth === 0) {\n\t\t\t\tcandidates.push(text.slice(start, index + 1));\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t}\n\treturn candidates;\n}\n\nexport function parseWorkerOutput(text: string): ParsedWorkerOutput | undefined {\n\tconst trimmed = text.trim();\n\tconst candidates: string[] = [trimmed];\n\tconst fenced = /```(?:json)?\\s*([\\s\\S]*?)```/.exec(trimmed);\n\tif (fenced?.[1]) candidates.push(fenced[1].trim());\n\tcandidates.push(...balancedObjectCandidates(trimmed));\n\n\tfor (const candidate of candidates) {\n\t\tlet parsed: unknown;\n\t\ttry {\n\t\t\tparsed = JSON.parse(candidate);\n\t\t} catch {\n\t\t\tcontinue;\n\t\t}\n\t\tif (!parsed || typeof parsed !== \"object\" || Array.isArray(parsed)) continue;\n\t\tconst record = parsed as Record<string, unknown>;\n\t\tconst summary = record.summary;\n\t\tif (typeof summary !== \"string\" || summary.trim().length === 0) continue;\n\n\t\tconst status = record.status === \"blocked\" ? \"blocked\" : \"completed\";\n\t\tconst blockers = Array.isArray(record.blockers)\n\t\t\t? record.blockers.filter((blocker): blocker is string => typeof blocker === \"string\" && blocker.length > 0)\n\t\t\t: [];\n\t\tconst findings: Array<{ summary: string; confidence?: number }> = [];\n\t\tif (Array.isArray(record.findings)) {\n\t\t\tfor (const item of record.findings) {\n\t\t\t\tif (!item || typeof item !== \"object\" || Array.isArray(item)) continue;\n\t\t\t\tconst findingSummary = (item as { summary?: unknown }).summary;\n\t\t\t\tif (typeof findingSummary !== \"string\" || findingSummary.trim().length === 0) continue;\n\t\t\t\tconst confidenceRaw = (item as { confidence?: unknown }).confidence;\n\t\t\t\tconst confidence =\n\t\t\t\t\ttypeof confidenceRaw === \"number\" && Number.isFinite(confidenceRaw)\n\t\t\t\t\t\t? Math.min(Math.max(confidenceRaw, 0), 1)\n\t\t\t\t\t\t: undefined;\n\t\t\t\tfindings.push({ summary: findingSummary.trim(), confidence });\n\t\t\t}\n\t\t}\n\t\treturn { summary: summary.trim(), status, blockers, findings, actions: parseWorkerActions(record.actions) };\n\t}\n\treturn undefined;\n}\n\nfunction buildWorkerEvidence(request: WorkerRequest, findings: ParsedWorkerOutput[\"findings\"]) {\n\tif (findings.length === 0) return undefined;\n\tconst instructionsRef: EvidenceRef = {\n\t\tid: \"src-instructions\",\n\t\tkind: \"user\",\n\t\ttitle: \"Delegated task instructions\",\n\t\ttrusted: true,\n\t\texcerpt: request.instructions.slice(0, 2000),\n\t};\n\tconst synthesisRef: EvidenceRef = {\n\t\tid: \"src-worker\",\n\t\tkind: \"tool\",\n\t\ttitle: \"Scout-worker synthesis\",\n\t\ttrusted: false,\n\t};\n\tconst bundleFindings: Finding[] = findings.map((finding, index) => ({\n\t\tid: `finding-${index + 1}`,\n\t\tsummary: finding.summary,\n\t\tevidenceIds: [synthesisRef.id],\n\t\t...(finding.confidence !== undefined ? { confidence: finding.confidence } : {}),\n\t}));\n\treturn createEvidenceBundle({\n\t\tquery: `worker:${request.id}`,\n\t\tsources: [instructionsRef, synthesisRef],\n\t\tfindings: bundleFindings,\n\t});\n}\n\nfunction finishOutcome(args: {\n\trequest: WorkerRequest;\n\tresult: WorkerResult;\n\tlaneStatus: LaneTerminalStatus;\n\treasonCode: string;\n\tcostUsd: number;\n\tcwd?: string;\n}): WorkerRunOutcome {\n\tconst acceptance = validateWorkerResult({ request: args.request, result: args.result, cwd: args.cwd });\n\treturn {\n\t\tresult: args.result,\n\t\tacceptance,\n\t\taccepted: acceptance.outcome === \"allow\",\n\t\tlaneStatus: args.laneStatus,\n\t\treasonCode: args.reasonCode,\n\t\tcostUsd: args.costUsd,\n\t};\n}\n\nexport async function runWorker(options: WorkerRunnerOptions): Promise<WorkerRunOutcome> {\n\tconst now = options.now ?? (() => new Date().toISOString());\n\tconst baseResult = {\n\t\trequestId: options.request.id,\n\t\tchangedFiles: [] as string[],\n\t\tusageReportId: options.usageReportId,\n\t\tcreatedAt: now(),\n\t};\n\n\t// The WRITE lane requires BOTH the envelope grant and a caller-supplied applier — either\n\t// alone keeps the read-only scout contract byte-for-byte.\n\tconst writeCapable =\n\t\toptions.request.envelope.capabilities.includes(\"write_files\") && options.applyActions !== undefined;\n\n\tconst bounded = await runBoundedCompletion({\n\t\tmaxWallClockMs: options.maxWallClockMs,\n\t\tsignal: options.signal,\n\t\texecute: (signal) =>\n\t\t\toptions.complete({\n\t\t\t\tsystemPrompt: writeCapable ? WORKER_WRITE_LANE_SYSTEM_PROMPT : WORKER_LANE_SYSTEM_PROMPT,\n\t\t\t\tuserPrompt: buildWorkerUserPrompt(options.request),\n\t\t\t\tsignal,\n\t\t\t}),\n\t});\n\tconst costUsd = bounded.completion?.costUsd ?? 0;\n\tconst liveChangedFiles = [...new Set(options.getChangedFiles?.() ?? [])];\n\n\tif (bounded.failure) {\n\t\tconst cancelled = bounded.failure.status === \"canceled\" || bounded.failure.status === \"timeout\";\n\t\treturn finishOutcome({\n\t\t\trequest: options.request,\n\t\t\tcwd: options.cwd,\n\t\t\tresult: {\n\t\t\t\t...baseResult,\n\t\t\t\tchangedFiles: liveChangedFiles,\n\t\t\t\tstatus: cancelled ? \"cancelled\" : \"failed\",\n\t\t\t\tsummary: `Worker did not complete: ${bounded.failure.reasonCode}`,\n\t\t\t},\n\t\t\tlaneStatus: bounded.failure.status,\n\t\t\treasonCode: bounded.failure.reasonCode,\n\t\t\tcostUsd,\n\t\t});\n\t}\n\n\tconst completion = bounded.completion as WorkerCompletion | undefined;\n\tconst completionChangedFiles = [...new Set([...liveChangedFiles, ...(completion?.changedFiles ?? [])])];\n\tconst completionBaseResult = { ...baseResult, changedFiles: completionChangedFiles };\n\tif (!completion || completion.stopReason === \"error\" || completion.stopReason === \"aborted\") {\n\t\treturn finishOutcome({\n\t\t\trequest: options.request,\n\t\t\tcwd: options.cwd,\n\t\t\tresult: { ...completionBaseResult, status: \"failed\", summary: \"Worker model call failed.\" },\n\t\t\tlaneStatus: \"failed\",\n\t\t\treasonCode: \"model_error\",\n\t\t\tcostUsd,\n\t\t});\n\t}\n\n\tconst parsed = parseWorkerOutput(completion.text);\n\tif (!parsed) {\n\t\tconst readOnlyPlainText =\n\t\t\t!writeCapable &&\n\t\t\tcompletion.stopReason === \"stop\" &&\n\t\t\tcompletion.text.trim().length > 0 &&\n\t\t\tcompletionChangedFiles.length === 0;\n\t\tif (readOnlyPlainText) {\n\t\t\treturn finishOutcome({\n\t\t\t\trequest: options.request,\n\t\t\t\tcwd: options.cwd,\n\t\t\t\tresult: {\n\t\t\t\t\t...completionBaseResult,\n\t\t\t\t\tstatus: \"completed\",\n\t\t\t\t\toutputFormat: \"plain_text\",\n\t\t\t\t\tsummary: completion.text.trim().slice(0, 8000),\n\t\t\t\t},\n\t\t\t\tlaneStatus: \"succeeded\",\n\t\t\t\treasonCode: \"worker_completed_plain_text\",\n\t\t\t\tcostUsd,\n\t\t\t});\n\t\t}\n\t\treturn finishOutcome({\n\t\t\trequest: options.request,\n\t\t\tcwd: options.cwd,\n\t\t\tresult: {\n\t\t\t\t...completionBaseResult,\n\t\t\t\tstatus: \"failed\",\n\t\t\t\tsummary: \"Worker output was not valid structured JSON.\",\n\t\t\t},\n\t\t\tlaneStatus: \"failed\",\n\t\t\treasonCode: \"unparseable_output\",\n\t\t\tcostUsd,\n\t\t});\n\t}\n\n\tconst evidence = buildWorkerEvidence(options.request, parsed.findings);\n\tlet changedFiles: string[] = [...completionChangedFiles];\n\tconst actionBlockers: string[] = [...(completion.blockers ?? [])];\n\tif (!writeCapable && completionChangedFiles.length > 0) {\n\t\tactionBlockers.push(\"worker reported file changes without a write_files envelope grant\");\n\t}\n\tif (writeCapable && parsed.status !== \"blocked\" && parsed.actions.length > 0 && options.applyActions) {\n\t\t// Runner-side application through the envelope path scope: refusals and failures are\n\t\t// surfaced as blockers so a partially-applied change can never look like clean success.\n\t\tconst applied = options.applyActions(parsed.actions);\n\t\tchangedFiles = [...new Set([...changedFiles, ...applied.changedFiles])];\n\t\tfor (const refusal of applied.refused) {\n\t\t\tactionBlockers.push(`action refused (${refusal.path}): ${refusal.reason}`);\n\t\t}\n\t\tfor (const failure of applied.failed) {\n\t\t\tactionBlockers.push(`action failed (${failure.path}): ${failure.reason}`);\n\t\t}\n\t} else if (!writeCapable && parsed.actions.length > 0) {\n\t\tactionBlockers.push(\"worker emitted file actions without a write_files envelope grant; nothing was applied\");\n\t}\n\tconst allBlockers = [...parsed.blockers, ...actionBlockers];\n\tconst result: WorkerResult = {\n\t\t...baseResult,\n\t\tchangedFiles,\n\t\tstatus: parsed.status === \"blocked\" || allBlockers.length > 0 ? \"blocked\" : \"completed\",\n\t\tsummary: parsed.summary,\n\t\t...(allBlockers.length > 0 ? { blockers: allBlockers } : {}),\n\t\t...(evidence ? { evidence } : {}),\n\t};\n\n\tif (result.status === \"blocked\") {\n\t\treturn finishOutcome({\n\t\t\trequest: options.request,\n\t\t\tcwd: options.cwd,\n\t\t\tresult,\n\t\t\tlaneStatus: \"failed\",\n\t\t\treasonCode: \"worker_blocked\",\n\t\t\tcostUsd,\n\t\t});\n\t}\n\n\tconst overBudget = options.maxUsd > 0 && costUsd > options.maxUsd;\n\treturn finishOutcome({\n\t\trequest: options.request,\n\t\tcwd: options.cwd,\n\t\tresult,\n\t\tlaneStatus: overBudget ? \"budget_exhausted\" : \"succeeded\",\n\t\treasonCode: overBudget ? \"cost_budget_exceeded\" : \"worker_completed\",\n\t\tcostUsd,\n\t});\n}\n"]}
1
+ {"version":3,"file":"worker-runner.js","sourceRoot":"","sources":["../../../src/core/delegation/worker-runner.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,oBAAoB,EAAE,MAAM,mCAAmC,CAAC;AAGzE,OAAO,EAAE,oBAAoB,EAAE,MAAM,gCAAgC,CAAC;AACtE,OAAO,EAA6B,kBAAkB,EAAqB,MAAM,qBAAqB,CAAC;AACvG,OAAO,EAAE,oBAAoB,EAAE,MAAM,oBAAoB,CAAC;AAE1D;;;;;;;GAOG;AAEH,wEAAwE;AACxE,MAAM,CAAC,MAAM,yBAAyB,GAAG;IACxC,gFAAgF;IAChF,mHAAmH;IACnH,+DAA+D;IAC/D,4KAA4K;IAC5K,qGAAqG;IACrG,0CAA0C;CAC1C,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;AAEb;gGACgG;AAChG,MAAM,CAAC,MAAM,+BAA+B,GAAG;IAC9C,6EAA6E;IAC7E,uHAAuH;IACvH,+DAA+D;IAC/D,0SAA0S;IAC1S,6EAA6E;IAC7E,gIAAgI;IAChI,4FAA4F;IAC5F,0CAA0C;CAC1C,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;AA+Cb,MAAM,UAAU,qBAAqB,CAAC,OAAsB,EAAU;IACrE,OAAO;QACN,iBAAiB;QACjB,QAAQ;QACR,OAAO,CAAC,YAAY;QACpB,SAAS;QACT,EAAE;QACF,yFAAyF;QACzF,qHAAqH;KACrH,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;AAAA,CACb;AAUD,SAAS,wBAAwB,CAAC,IAAY,EAAY;IACz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,UAAU,GAAG,OAAO,CAAC,MAAM,GAAG,CAAC,IAAI,OAAO,GAAG,OAAO,CAAC,MAAM,CAAC;IAClE,OAAO,aAAa,CAAC;QACpB,OAAO,EAAE,OAAO,CAAC,OAAO;QACxB,GAAG,EAAE,OAAO,CAAC,GAAG;QAChB,MAAM;QACN,UAAU,EAAE,UAAU,CAAC,CAAC,CAAC,kBAAkB,CAAC,CAAC,CAAC,WAAW;QACzD,UAAU,EAAE,UAAU,CAAC,CAAC,CAAC,sBAAsB,CAAC,CAAC,CAAC,kBAAkB;QACpE,OAAO;KACP,CAAC,CAAC;AAAA,CACH","sourcesContent":["import { runBoundedCompletion } from \"../autonomy/bounded-completion.ts\";\nimport type { EvidenceRef, Finding, GateOutcome, WorkerRequest, WorkerResult } from \"../autonomy/contracts.ts\";\nimport type { LaneTerminalStatus } from \"../autonomy/lane-tracker.ts\";\nimport { createEvidenceBundle } from \"../research/evidence-bundle.ts\";\nimport { type AppliedActionsReport, parseWorkerActions, type WorkerAction } from \"./worker-actions.ts\";\nimport { validateWorkerResult } from \"./worker-result.ts\";\n\n/**\n * Pure orchestration for one bounded scout-worker delegation: bounded isolated completion ->\n * parse -> `WorkerResult` -> parent validation via {@link validateWorkerResult}.\n *\n * The injected completion may be a bounded child tool loop. Its tool surface is built and gated by\n * the host; this module keeps the structured-output contract and treats every result as untrusted\n * until parent validation succeeds.\n */\n\n/** Static across calls so callers can use `cacheRetention: \"short\"`. */\nexport const WORKER_LANE_SYSTEM_PROMPT = [\n\t\"You are a bounded read-only scout worker delegated one task by a coding agent.\",\n\t\"Use only the read-only tools provided to inspect the workspace. You cannot change files or delegate more workers.\",\n\t\"Respond with STRICT JSON only - no prose, no markdown fences:\",\n\t'{\"summary\":\"<what you concluded>\",\"status\":\"completed\"|\"blocked\",\"blockers\":[\"<why you are stuck>\"],\"findings\":[{\"summary\":\"<one concrete finding>\",\"confidence\":<0..1>}]}',\n\t'Use status \"blocked\" with blockers only when the task cannot be answered from the provided context.',\n\t\"Never invent file paths, APIs, or facts.\",\n].join(\"\\n\");\n\n/** Write-capable variant (G2): direct tools are execution-gated and reported; structured actions\n * remain as a fallback for models without a native tool channel and use the same path scope. */\nexport const WORKER_WRITE_LANE_SYSTEM_PROMPT = [\n\t\"You are a bounded code-writing worker delegated one task by a coding agent.\",\n\t\"Use only the provided read tools and path-scoped write/edit tools. You cannot run shell commands or delegate workers.\",\n\t\"Respond with STRICT JSON only - no prose, no markdown fences:\",\n\t'{\"summary\":\"<what you did>\",\"status\":\"completed\"|\"blocked\",\"blockers\":[],\"findings\":[{\"summary\":\"<finding>\",\"confidence\":<0..1>}],\"actions\":[{\"op\":\"write\",\"path\":\"<relative path>\",\"content\":\"<full file content>\"},{\"op\":\"edit\",\"path\":\"<relative path>\",\"old\":\"<exact text>\",\"new\":\"<replacement>\"}]}',\n\t\"Only touch paths inside your delegated scope. Keep edits minimal and exact.\",\n\t\"If you changed a file with a provided tool, do not repeat that change in actions; actions are for changes not already applied.\",\n\t'Use status \"blocked\" with blockers when the task cannot be done from the provided context.',\n\t\"Never invent file paths, APIs, or facts.\",\n].join(\"\\n\");\n\nexport interface WorkerCompletion {\n\ttext: string;\n\tcostUsd: number;\n\tstopReason: string;\n\t/** Files successfully changed by the child tool loop before it produced the final JSON. */\n\tchangedFiles?: readonly string[];\n\t/** Capability refusals or execution failures observed inside the child tool loop. */\n\tblockers?: readonly string[];\n}\n\nexport interface WorkerRunnerOptions {\n\trequest: WorkerRequest;\n\t/** Budget for this delegation; a post-hoc breach marks the lane budget_exhausted. */\n\tmaxUsd: number;\n\t/** Wall-clock budget in milliseconds; 0 disables. */\n\tmaxWallClockMs: number;\n\t/**\n\t * Pre-allocated spawned-usage report id. Always stamped on the result so parent validation can\n\t * enforce the cost-visibility invariant (a completed result without a usage report is blocked).\n\t */\n\tusageReportId: string;\n\tcomplete: (args: { systemPrompt: string; userPrompt: string; signal?: AbortSignal }) => Promise<WorkerCompletion>;\n\t/** Live successful child-tool mutations, including writes completed before timeout/cancellation. */\n\tgetChangedFiles?: () => readonly string[];\n\tsignal?: AbortSignal;\n\tnow?: () => string;\n\t/** Enables the WRITE lane: only honored when the request envelope grants \"write_files\". The\n\t * runner applies the worker's structured actions through the envelope path scope; refusals\n\t * and failures become blockers, never silent drops. */\n\tapplyActions?: (actions: readonly WorkerAction[]) => AppliedActionsReport;\n\t/** Session cwd — the baseline for relative changed-file and envelope paths in parent\n\t * validation. Defaults to process.cwd(). */\n\tcwd?: string;\n}\n\nexport interface WorkerRunOutcome {\n\tresult: WorkerResult;\n\t/** Parent-review verdict from {@link validateWorkerResult}; worker output stays untrusted. */\n\tacceptance: GateOutcome;\n\taccepted: boolean;\n\tlaneStatus: LaneTerminalStatus;\n\treasonCode: string;\n\tcostUsd: number;\n}\n\nexport function buildWorkerUserPrompt(request: WorkerRequest): string {\n\treturn [\n\t\t\"Delegated task:\",\n\t\t\"<task>\",\n\t\trequest.instructions,\n\t\t\"</task>\",\n\t\t\"\",\n\t\t\"The task may request a custom output format. Do not replace the worker result envelope.\",\n\t\t'Always return the JSON object required by the system prompt; put requested details inside \"summary\" and \"findings\".',\n\t].join(\"\\n\");\n}\n\nexport interface ParsedWorkerOutput {\n\tsummary: string;\n\tstatus: \"completed\" | \"blocked\";\n\tblockers: string[];\n\tfindings: Array<{ summary: string; confidence?: number }>;\n\tactions: WorkerAction[];\n}\n\nfunction balancedObjectCandidates(text: string): string[] {\n\tconst candidates: string[] = [];\n\tfor (let start = 0; start < text.length; start++) {\n\t\tif (text[start] !== \"{\") continue;\n\t\tlet depth = 0;\n\t\tlet inString = false;\n\t\tlet escaped = false;\n\t\tfor (let index = start; index < text.length; index++) {\n\t\t\tconst character = text[index];\n\t\t\tif (inString) {\n\t\t\t\tif (escaped) escaped = false;\n\t\t\t\telse if (character === \"\\\\\") escaped = true;\n\t\t\t\telse if (character === '\"') inString = false;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (character === '\"') {\n\t\t\t\tinString = true;\n\t\t\t} else if (character === \"{\") {\n\t\t\t\tdepth++;\n\t\t\t} else if (character === \"}\" && --depth === 0) {\n\t\t\t\tcandidates.push(text.slice(start, index + 1));\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t}\n\treturn candidates;\n}\n\nexport function parseWorkerOutput(text: string): ParsedWorkerOutput | undefined {\n\tconst trimmed = text.trim();\n\tconst candidates: string[] = [trimmed];\n\tconst fenced = /```(?:json)?\\s*([\\s\\S]*?)```/.exec(trimmed);\n\tif (fenced?.[1]) candidates.push(fenced[1].trim());\n\tcandidates.push(...balancedObjectCandidates(trimmed));\n\n\tfor (const candidate of candidates) {\n\t\tlet parsed: unknown;\n\t\ttry {\n\t\t\tparsed = JSON.parse(candidate);\n\t\t} catch {\n\t\t\tcontinue;\n\t\t}\n\t\tif (!parsed || typeof parsed !== \"object\" || Array.isArray(parsed)) continue;\n\t\tconst record = parsed as Record<string, unknown>;\n\t\tconst summary = record.summary;\n\t\tif (typeof summary !== \"string\" || summary.trim().length === 0) continue;\n\n\t\tconst status = record.status === \"blocked\" ? \"blocked\" : \"completed\";\n\t\tconst blockers = Array.isArray(record.blockers)\n\t\t\t? record.blockers.filter((blocker): blocker is string => typeof blocker === \"string\" && blocker.length > 0)\n\t\t\t: [];\n\t\tconst findings: Array<{ summary: string; confidence?: number }> = [];\n\t\tif (Array.isArray(record.findings)) {\n\t\t\tfor (const item of record.findings) {\n\t\t\t\tif (!item || typeof item !== \"object\" || Array.isArray(item)) continue;\n\t\t\t\tconst findingSummary = (item as { summary?: unknown }).summary;\n\t\t\t\tif (typeof findingSummary !== \"string\" || findingSummary.trim().length === 0) continue;\n\t\t\t\tconst confidenceRaw = (item as { confidence?: unknown }).confidence;\n\t\t\t\tconst confidence =\n\t\t\t\t\ttypeof confidenceRaw === \"number\" && Number.isFinite(confidenceRaw)\n\t\t\t\t\t\t? Math.min(Math.max(confidenceRaw, 0), 1)\n\t\t\t\t\t\t: undefined;\n\t\t\t\tfindings.push({ summary: findingSummary.trim(), confidence });\n\t\t\t}\n\t\t}\n\t\treturn { summary: summary.trim(), status, blockers, findings, actions: parseWorkerActions(record.actions) };\n\t}\n\treturn undefined;\n}\n\nfunction buildWorkerEvidence(request: WorkerRequest, findings: ParsedWorkerOutput[\"findings\"]) {\n\tif (findings.length === 0) return undefined;\n\tconst instructionsRef: EvidenceRef = {\n\t\tid: \"src-instructions\",\n\t\tkind: \"user\",\n\t\ttitle: \"Delegated task instructions\",\n\t\ttrusted: true,\n\t\texcerpt: request.instructions.slice(0, 2000),\n\t};\n\tconst synthesisRef: EvidenceRef = {\n\t\tid: \"src-worker\",\n\t\tkind: \"tool\",\n\t\ttitle: \"Scout-worker synthesis\",\n\t\ttrusted: false,\n\t};\n\tconst bundleFindings: Finding[] = findings.map((finding, index) => ({\n\t\tid: `finding-${index + 1}`,\n\t\tsummary: finding.summary,\n\t\tevidenceIds: [synthesisRef.id],\n\t\t...(finding.confidence !== undefined ? { confidence: finding.confidence } : {}),\n\t}));\n\treturn createEvidenceBundle({\n\t\tquery: `worker:${request.id}`,\n\t\tsources: [instructionsRef, synthesisRef],\n\t\tfindings: bundleFindings,\n\t});\n}\n\nfunction finishOutcome(args: {\n\trequest: WorkerRequest;\n\tresult: WorkerResult;\n\tlaneStatus: LaneTerminalStatus;\n\treasonCode: string;\n\tcostUsd: number;\n\tcwd?: string;\n}): WorkerRunOutcome {\n\tconst acceptance = validateWorkerResult({ request: args.request, result: args.result, cwd: args.cwd });\n\treturn {\n\t\tresult: args.result,\n\t\tacceptance,\n\t\taccepted: acceptance.outcome === \"allow\",\n\t\tlaneStatus: args.laneStatus,\n\t\treasonCode: args.reasonCode,\n\t\tcostUsd: args.costUsd,\n\t};\n}\n\nexport async function runWorker(options: WorkerRunnerOptions): Promise<WorkerRunOutcome> {\n\tconst now = options.now ?? (() => new Date().toISOString());\n\tconst baseResult = {\n\t\trequestId: options.request.id,\n\t\tchangedFiles: [] as string[],\n\t\tusageReportId: options.usageReportId,\n\t\tcreatedAt: now(),\n\t};\n\n\t// The WRITE lane requires BOTH the envelope grant and a caller-supplied applier — either\n\t// alone keeps the read-only scout contract byte-for-byte.\n\tconst writeCapable =\n\t\toptions.request.envelope.capabilities.includes(\"write_files\") && options.applyActions !== undefined;\n\n\tconst bounded = await runBoundedCompletion({\n\t\tmaxWallClockMs: options.maxWallClockMs,\n\t\tsignal: options.signal,\n\t\texecute: (signal) =>\n\t\t\toptions.complete({\n\t\t\t\tsystemPrompt: writeCapable ? WORKER_WRITE_LANE_SYSTEM_PROMPT : WORKER_LANE_SYSTEM_PROMPT,\n\t\t\t\tuserPrompt: buildWorkerUserPrompt(options.request),\n\t\t\t\tsignal,\n\t\t\t}),\n\t});\n\tconst costUsd = bounded.completion?.costUsd ?? 0;\n\tconst liveChangedFiles = [...new Set(options.getChangedFiles?.() ?? [])];\n\n\tif (bounded.failure) {\n\t\tconst cancelled = bounded.failure.status === \"canceled\" || bounded.failure.status === \"timeout\";\n\t\treturn finishOutcome({\n\t\t\trequest: options.request,\n\t\t\tcwd: options.cwd,\n\t\t\tresult: {\n\t\t\t\t...baseResult,\n\t\t\t\tchangedFiles: liveChangedFiles,\n\t\t\t\tstatus: cancelled ? \"cancelled\" : \"failed\",\n\t\t\t\tsummary: `Worker did not complete: ${bounded.failure.reasonCode}`,\n\t\t\t},\n\t\t\tlaneStatus: bounded.failure.status,\n\t\t\treasonCode: bounded.failure.reasonCode,\n\t\t\tcostUsd,\n\t\t});\n\t}\n\n\tconst completion = bounded.completion as WorkerCompletion | undefined;\n\tconst completionChangedFiles = [...new Set([...liveChangedFiles, ...(completion?.changedFiles ?? [])])];\n\tconst completionBaseResult = { ...baseResult, changedFiles: completionChangedFiles };\n\tif (!completion || completion.stopReason === \"error\" || completion.stopReason === \"aborted\") {\n\t\treturn finishOutcome({\n\t\t\trequest: options.request,\n\t\t\tcwd: options.cwd,\n\t\t\tresult: { ...completionBaseResult, status: \"failed\", summary: \"Worker model call failed.\" },\n\t\t\tlaneStatus: \"failed\",\n\t\t\treasonCode: \"model_error\",\n\t\t\tcostUsd,\n\t\t});\n\t}\n\n\tconst parsed = parseWorkerOutput(completion.text);\n\tif (!parsed) {\n\t\tconst readOnlyPlainText =\n\t\t\t!writeCapable && completion.text.trim().length > 0 && completionChangedFiles.length === 0;\n\t\tif (readOnlyPlainText) {\n\t\t\tconst completionBlockers = [...(completion.blockers ?? [])];\n\t\t\tconst incompleteNote =\n\t\t\t\tcompletion.stopReason === \"stop\"\n\t\t\t\t\t? \"\"\n\t\t\t\t\t: `\\n\\n[Worker output ended with stop reason '${completion.stopReason}'; verify completeness.]`;\n\t\t\tconst summary = `${completion.text.trim().slice(0, Math.max(0, 8000 - incompleteNote.length))}${incompleteNote}`;\n\t\t\tconst blocked = completionBlockers.length > 0;\n\t\t\treturn finishOutcome({\n\t\t\t\trequest: options.request,\n\t\t\t\tcwd: options.cwd,\n\t\t\t\tresult: {\n\t\t\t\t\t...completionBaseResult,\n\t\t\t\t\tstatus: blocked ? \"blocked\" : \"completed\",\n\t\t\t\t\toutputFormat: \"plain_text\",\n\t\t\t\t\tsummary,\n\t\t\t\t\t...(blocked ? { blockers: completionBlockers } : {}),\n\t\t\t\t},\n\t\t\t\tlaneStatus: blocked ? \"failed\" : \"succeeded\",\n\t\t\t\treasonCode: blocked\n\t\t\t\t\t? \"worker_blocked\"\n\t\t\t\t\t: completion.stopReason === \"stop\"\n\t\t\t\t\t\t? \"worker_completed_plain_text\"\n\t\t\t\t\t\t: \"worker_completed_plain_text_incomplete\",\n\t\t\t\tcostUsd,\n\t\t\t});\n\t\t}\n\t\treturn finishOutcome({\n\t\t\trequest: options.request,\n\t\t\tcwd: options.cwd,\n\t\t\tresult: {\n\t\t\t\t...completionBaseResult,\n\t\t\t\tstatus: \"failed\",\n\t\t\t\tsummary: \"Worker output was not valid structured JSON.\",\n\t\t\t},\n\t\t\tlaneStatus: \"failed\",\n\t\t\treasonCode: \"unparseable_output\",\n\t\t\tcostUsd,\n\t\t});\n\t}\n\n\tconst evidence = buildWorkerEvidence(options.request, parsed.findings);\n\tlet changedFiles: string[] = [...completionChangedFiles];\n\tconst actionBlockers: string[] = [...(completion.blockers ?? [])];\n\tif (!writeCapable && completionChangedFiles.length > 0) {\n\t\tactionBlockers.push(\"worker reported file changes without a write_files envelope grant\");\n\t}\n\tif (writeCapable && parsed.status !== \"blocked\" && parsed.actions.length > 0 && options.applyActions) {\n\t\t// Runner-side application through the envelope path scope: refusals and failures are\n\t\t// surfaced as blockers so a partially-applied change can never look like clean success.\n\t\tconst applied = options.applyActions(parsed.actions);\n\t\tchangedFiles = [...new Set([...changedFiles, ...applied.changedFiles])];\n\t\tfor (const refusal of applied.refused) {\n\t\t\tactionBlockers.push(`action refused (${refusal.path}): ${refusal.reason}`);\n\t\t}\n\t\tfor (const failure of applied.failed) {\n\t\t\tactionBlockers.push(`action failed (${failure.path}): ${failure.reason}`);\n\t\t}\n\t} else if (!writeCapable && parsed.actions.length > 0) {\n\t\tactionBlockers.push(\"worker emitted file actions without a write_files envelope grant; nothing was applied\");\n\t}\n\tconst allBlockers = [...parsed.blockers, ...actionBlockers];\n\tconst result: WorkerResult = {\n\t\t...baseResult,\n\t\tchangedFiles,\n\t\tstatus: parsed.status === \"blocked\" || allBlockers.length > 0 ? \"blocked\" : \"completed\",\n\t\tsummary: parsed.summary,\n\t\t...(allBlockers.length > 0 ? { blockers: allBlockers } : {}),\n\t\t...(evidence ? { evidence } : {}),\n\t};\n\n\tif (result.status === \"blocked\") {\n\t\treturn finishOutcome({\n\t\t\trequest: options.request,\n\t\t\tcwd: options.cwd,\n\t\t\tresult,\n\t\t\tlaneStatus: \"failed\",\n\t\t\treasonCode: \"worker_blocked\",\n\t\t\tcostUsd,\n\t\t});\n\t}\n\n\tconst overBudget = options.maxUsd > 0 && costUsd > options.maxUsd;\n\treturn finishOutcome({\n\t\trequest: options.request,\n\t\tcwd: options.cwd,\n\t\tresult,\n\t\tlaneStatus: overBudget ? \"budget_exhausted\" : \"succeeded\",\n\t\treasonCode: overBudget ? \"cost_budget_exceeded\" : \"worker_completed\",\n\t\tcostUsd,\n\t});\n}\n"]}
@@ -134,13 +134,14 @@
134
134
  const path = [];
135
135
  let current = byId.get(targetId);
136
136
  while (current) {
137
- path.unshift(current);
137
+ path.push(current);
138
138
  // Stop if no parent or self-referencing (root)
139
139
  if (!current.parentId || current.parentId === current.id) {
140
140
  break;
141
141
  }
142
142
  current = byId.get(current.parentId);
143
143
  }
144
+ path.reverse();
144
145
  return path;
145
146
  }
146
147