strands-darwin 0.0.35 → 0.0.36

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 (231) hide show
  1. package/README.md +20 -3
  2. package/README.zh-CN.md +20 -3
  3. package/dist/src/agent/prompt-cache.js +15 -2
  4. package/dist/src/agent/prompt-cache.js.map +1 -1
  5. package/dist/src/agent/rewind.d.ts +2 -0
  6. package/dist/src/agent/rewind.js +4 -1
  7. package/dist/src/agent/rewind.js.map +1 -1
  8. package/dist/src/agent/runtime.d.ts +64 -10
  9. package/dist/src/agent/runtime.js +192 -33
  10. package/dist/src/agent/runtime.js.map +1 -1
  11. package/dist/src/agent/session.d.ts +96 -4
  12. package/dist/src/agent/session.js +249 -9
  13. package/dist/src/agent/session.js.map +1 -1
  14. package/dist/src/agent/stream-idle.d.ts +16 -0
  15. package/dist/src/agent/stream-idle.js +127 -0
  16. package/dist/src/agent/stream-idle.js.map +1 -0
  17. package/dist/src/agent/working-context.d.ts +21 -1
  18. package/dist/src/agent/working-context.js +28 -1
  19. package/dist/src/agent/working-context.js.map +1 -1
  20. package/dist/src/agent/workspace-trust.d.ts +112 -0
  21. package/dist/src/agent/workspace-trust.js +207 -0
  22. package/dist/src/agent/workspace-trust.js.map +1 -0
  23. package/dist/src/agentcore/auto-policy.d.ts +7 -0
  24. package/dist/src/agentcore/auto-policy.js +50 -0
  25. package/dist/src/agentcore/auto-policy.js.map +1 -0
  26. package/dist/src/agentcore/auto-state.d.ts +43 -0
  27. package/dist/src/agentcore/auto-state.js +73 -0
  28. package/dist/src/agentcore/auto-state.js.map +1 -0
  29. package/dist/src/agentcore/cli.d.ts +2 -0
  30. package/dist/src/agentcore/cli.js +38 -0
  31. package/dist/src/agentcore/cli.js.map +1 -0
  32. package/dist/src/agentcore/config.d.ts +48 -0
  33. package/dist/src/agentcore/config.js +44 -0
  34. package/dist/src/agentcore/config.js.map +1 -0
  35. package/dist/src/agentcore/controller.d.ts +105 -0
  36. package/dist/src/agentcore/controller.js +979 -0
  37. package/dist/src/agentcore/controller.js.map +1 -0
  38. package/dist/src/agentcore/projection.d.ts +2 -0
  39. package/dist/src/agentcore/projection.js +8 -0
  40. package/dist/src/agentcore/projection.js.map +1 -0
  41. package/dist/src/agentcore/records.d.ts +41 -0
  42. package/dist/src/agentcore/records.js +149 -0
  43. package/dist/src/agentcore/records.js.map +1 -0
  44. package/dist/src/agentcore/state.d.ts +16 -0
  45. package/dist/src/agentcore/state.js +149 -0
  46. package/dist/src/agentcore/state.js.map +1 -0
  47. package/dist/src/agentcore/tools.d.ts +3 -0
  48. package/dist/src/agentcore/tools.js +11 -0
  49. package/dist/src/agentcore/tools.js.map +1 -0
  50. package/dist/src/agentcore/transport.d.ts +37 -0
  51. package/dist/src/agentcore/transport.js +242 -0
  52. package/dist/src/agentcore/transport.js.map +1 -0
  53. package/dist/src/agentcore/upload-projection.d.ts +208 -0
  54. package/dist/src/agentcore/upload-projection.js +823 -0
  55. package/dist/src/agentcore/upload-projection.js.map +1 -0
  56. package/dist/src/agents/child-recipe.js +4 -1
  57. package/dist/src/agents/child-recipe.js.map +1 -1
  58. package/dist/src/agents/loader.d.ts +12 -0
  59. package/dist/src/agents/loader.js +15 -1
  60. package/dist/src/agents/loader.js.map +1 -1
  61. package/dist/src/agents/subagent-tool.js +2 -4
  62. package/dist/src/agents/subagent-tool.js.map +1 -1
  63. package/dist/src/agents/workflow-tool.js +2 -4
  64. package/dist/src/agents/workflow-tool.js.map +1 -1
  65. package/dist/src/cli-doctor.js +7 -0
  66. package/dist/src/cli-doctor.js.map +1 -1
  67. package/dist/src/cli-import.d.ts +1 -0
  68. package/dist/src/cli-import.js +26 -0
  69. package/dist/src/cli-import.js.map +1 -0
  70. package/dist/src/cli-main.js +60 -10
  71. package/dist/src/cli-main.js.map +1 -1
  72. package/dist/src/cli-permissions.d.ts +2 -0
  73. package/dist/src/cli-permissions.js +20 -0
  74. package/dist/src/cli-permissions.js.map +1 -0
  75. package/dist/src/cli-sessions.js +6 -2
  76. package/dist/src/cli-sessions.js.map +1 -1
  77. package/dist/src/cli-usage.d.ts +9 -1
  78. package/dist/src/cli-usage.js +13 -0
  79. package/dist/src/cli-usage.js.map +1 -1
  80. package/dist/src/cli.js +19 -2
  81. package/dist/src/cli.js.map +1 -1
  82. package/dist/src/commands/custom-commands.d.ts +1 -1
  83. package/dist/src/commands/custom-commands.js +14 -6
  84. package/dist/src/commands/custom-commands.js.map +1 -1
  85. package/dist/src/commands/review-command.d.ts +10 -0
  86. package/dist/src/commands/review-command.js +28 -0
  87. package/dist/src/commands/review-command.js.map +1 -0
  88. package/dist/src/config-file.d.ts +9 -0
  89. package/dist/src/config-file.js +82 -0
  90. package/dist/src/config-file.js.map +1 -0
  91. package/dist/src/config.d.ts +66 -5
  92. package/dist/src/config.js +126 -42
  93. package/dist/src/config.js.map +1 -1
  94. package/dist/src/dev-repl.js +17 -1
  95. package/dist/src/dev-repl.js.map +1 -1
  96. package/dist/src/headless-protocol.d.ts +24 -1
  97. package/dist/src/headless-protocol.js +18 -0
  98. package/dist/src/headless-protocol.js.map +1 -1
  99. package/dist/src/headless-runner.d.ts +8 -0
  100. package/dist/src/headless-runner.js +37 -1
  101. package/dist/src/headless-runner.js.map +1 -1
  102. package/dist/src/hooks/hook-process.js +7 -2
  103. package/dist/src/hooks/hook-process.js.map +1 -1
  104. package/dist/src/hooks/lifecycle-hooks.js +3 -1
  105. package/dist/src/hooks/lifecycle-hooks.js.map +1 -1
  106. package/dist/src/hooks/tool-hooks.js +3 -1
  107. package/dist/src/hooks/tool-hooks.js.map +1 -1
  108. package/dist/src/import-claude-files.d.ts +28 -0
  109. package/dist/src/import-claude-files.js +227 -0
  110. package/dist/src/import-claude-files.js.map +1 -0
  111. package/dist/src/import-claude-snippets.d.ts +2 -0
  112. package/dist/src/import-claude-snippets.js +105 -0
  113. package/dist/src/import-claude-snippets.js.map +1 -0
  114. package/dist/src/import-claude.d.ts +13 -0
  115. package/dist/src/import-claude.js +287 -0
  116. package/dist/src/import-claude.js.map +1 -0
  117. package/dist/src/mcp/registry.d.ts +57 -1
  118. package/dist/src/mcp/registry.js +78 -6
  119. package/dist/src/mcp/registry.js.map +1 -1
  120. package/dist/src/memory/command.d.ts +1 -1
  121. package/dist/src/memory/command.js +89 -4
  122. package/dist/src/memory/command.js.map +1 -1
  123. package/dist/src/memory/controller.d.ts +32 -0
  124. package/dist/src/memory/controller.js +39 -3
  125. package/dist/src/memory/controller.js.map +1 -1
  126. package/dist/src/memory/state.d.ts +6 -0
  127. package/dist/src/memory/state.js +6 -1
  128. package/dist/src/memory/state.js.map +1 -1
  129. package/dist/src/memory/store.d.ts +13 -0
  130. package/dist/src/memory/store.js +38 -2
  131. package/dist/src/memory/store.js.map +1 -1
  132. package/dist/src/memory/tools.d.ts +7 -0
  133. package/dist/src/memory/tools.js +12 -1
  134. package/dist/src/memory/tools.js.map +1 -1
  135. package/dist/src/paths.js +3 -0
  136. package/dist/src/paths.js.map +1 -1
  137. package/dist/src/permissions-test.d.ts +18 -0
  138. package/dist/src/permissions-test.js +207 -0
  139. package/dist/src/permissions-test.js.map +1 -0
  140. package/dist/src/pricing/model-prices.d.ts +8 -5
  141. package/dist/src/pricing/model-prices.js +30 -15
  142. package/dist/src/pricing/model-prices.js.map +1 -1
  143. package/dist/src/project-identity.d.ts +3 -0
  144. package/dist/src/project-identity.js +8 -0
  145. package/dist/src/project-identity.js.map +1 -0
  146. package/dist/src/project-overrides.d.ts +57 -0
  147. package/dist/src/project-overrides.js +79 -0
  148. package/dist/src/project-overrides.js.map +1 -0
  149. package/dist/src/skills/builtin/setup-agentcore-memory/SKILL.md +158 -0
  150. package/dist/src/skills/loader.d.ts +1 -1
  151. package/dist/src/skills/loader.js +4 -1
  152. package/dist/src/skills/loader.js.map +1 -1
  153. package/dist/src/tools/background-bash.d.ts +6 -0
  154. package/dist/src/tools/background-bash.js +26 -0
  155. package/dist/src/tools/background-bash.js.map +1 -1
  156. package/dist/src/tools/shell-env.d.ts +24 -0
  157. package/dist/src/tools/shell-env.js +34 -0
  158. package/dist/src/tools/shell-env.js.map +1 -1
  159. package/dist/src/trajectory/reader.d.ts +1 -1
  160. package/dist/src/trajectory/reader.js +23 -3
  161. package/dist/src/trajectory/reader.js.map +1 -1
  162. package/dist/src/trajectory/resume-recap.d.ts +11 -1
  163. package/dist/src/trajectory/resume-recap.js +10 -1
  164. package/dist/src/trajectory/resume-recap.js.map +1 -1
  165. package/dist/src/trajectory/rewind-history.d.ts +8 -0
  166. package/dist/src/trajectory/rewind-history.js +81 -0
  167. package/dist/src/trajectory/rewind-history.js.map +1 -0
  168. package/dist/src/tui/App.d.ts +5 -1
  169. package/dist/src/tui/App.js +284 -51
  170. package/dist/src/tui/App.js.map +1 -1
  171. package/dist/src/tui/InputBox.d.ts +1 -1
  172. package/dist/src/tui/InputBox.js +1 -1
  173. package/dist/src/tui/MessageList.js +1 -1
  174. package/dist/src/tui/MessageList.js.map +1 -1
  175. package/dist/src/tui/PermissionPrompt.js +5 -3
  176. package/dist/src/tui/PermissionPrompt.js.map +1 -1
  177. package/dist/src/tui/QueuedMessages.js +14 -8
  178. package/dist/src/tui/QueuedMessages.js.map +1 -1
  179. package/dist/src/tui/ToolCallPanel.js +2 -2
  180. package/dist/src/tui/ToolCallPanel.js.map +1 -1
  181. package/dist/src/tui/WorkspaceTrustPrompt.d.ts +8 -0
  182. package/dist/src/tui/WorkspaceTrustPrompt.js +37 -0
  183. package/dist/src/tui/WorkspaceTrustPrompt.js.map +1 -0
  184. package/dist/src/tui/draft-stash.d.ts +25 -0
  185. package/dist/src/tui/draft-stash.js +49 -0
  186. package/dist/src/tui/draft-stash.js.map +1 -0
  187. package/dist/src/tui/frame-budget.d.ts +2 -2
  188. package/dist/src/tui/frame-budget.js +3 -3
  189. package/dist/src/tui/frame-budget.js.map +1 -1
  190. package/dist/src/tui/help-format.d.ts +2 -2
  191. package/dist/src/tui/help-format.js +3 -3
  192. package/dist/src/tui/help-format.js.map +1 -1
  193. package/dist/src/tui/mcp-format.d.ts +9 -0
  194. package/dist/src/tui/mcp-format.js +5 -3
  195. package/dist/src/tui/mcp-format.js.map +1 -1
  196. package/dist/src/tui/permission-rule-preview.d.ts +23 -0
  197. package/dist/src/tui/permission-rule-preview.js +38 -0
  198. package/dist/src/tui/permission-rule-preview.js.map +1 -0
  199. package/dist/src/tui/prompt-editor.d.ts +12 -0
  200. package/dist/src/tui/prompt-editor.js +38 -28
  201. package/dist/src/tui/prompt-editor.js.map +1 -1
  202. package/dist/src/tui/prompt-history-search.js +3 -2
  203. package/dist/src/tui/prompt-history-search.js.map +1 -1
  204. package/dist/src/tui/prompt-queue.d.ts +4 -2
  205. package/dist/src/tui/prompt-queue.js +18 -3
  206. package/dist/src/tui/prompt-queue.js.map +1 -1
  207. package/dist/src/tui/rewind-search.js +4 -3
  208. package/dist/src/tui/rewind-search.js.map +1 -1
  209. package/dist/src/tui/search-preview.d.ts +2 -0
  210. package/dist/src/tui/search-preview.js +9 -0
  211. package/dist/src/tui/search-preview.js.map +1 -0
  212. package/dist/src/tui/shell-command.js +4 -1
  213. package/dist/src/tui/shell-command.js.map +1 -1
  214. package/dist/src/tui/spinner.d.ts +1 -0
  215. package/dist/src/tui/spinner.js +6 -0
  216. package/dist/src/tui/spinner.js.map +1 -0
  217. package/dist/src/tui/status-format.d.ts +9 -0
  218. package/dist/src/tui/status-format.js +37 -2
  219. package/dist/src/tui/status-format.js.map +1 -1
  220. package/dist/src/tui/subagent-format.js +6 -0
  221. package/dist/src/tui/subagent-format.js.map +1 -1
  222. package/dist/src/tui/task-format.d.ts +5 -0
  223. package/dist/src/tui/task-format.js +15 -0
  224. package/dist/src/tui/task-format.js.map +1 -1
  225. package/dist/src/tui/trust-format.d.ts +31 -0
  226. package/dist/src/tui/trust-format.js +102 -0
  227. package/dist/src/tui/trust-format.js.map +1 -0
  228. package/dist/src/tui/turn-state.d.ts +1 -0
  229. package/dist/src/tui/turn-state.js +2 -0
  230. package/dist/src/tui/turn-state.js.map +1 -1
  231. package/package.json +2 -1
@@ -0,0 +1,823 @@
1
+ export const MAX_ACTION_BYTES = 8192;
2
+ // Keep legacy immutable entries readable/sendable at their original bound.
3
+ export const MAX_EVENT_BYTES = 262144;
4
+ export const MAX_EVENT_STATE_BYTES = MAX_EVENT_BYTES + 1024;
5
+ // New evidence only: one event per deterministic Memory session, so cumulative
6
+ // session input cannot grow across turns. Bytes are NOT a service token count.
7
+ export const MAX_NEW_EVENT_BYTES = 98304;
8
+ export const memorySessionId = (token) => `darwin-part-${token}`;
9
+ export const uploadSessionBudget = () => ({ version: 1, maxEvents: 1, maxBytes: MAX_NEW_EVENT_BYTES });
10
+ export const UPLOAD_NOTICE = 'Bounded original public tool content; can include secrets. NOT a confidentiality guarantee. No assistant prose/reasoning, binary/images, child traversal or file/offload/archive hydration. Upstream loss may be undetectable. taskSuccess is not inferred.';
11
+ const MAX_ACTIONS = 64;
12
+ const MAX_SUMMARIES = 96;
13
+ const MAX_SCAN_UNITS = 262144;
14
+ const bytes = (value) => Buffer.byteLength(JSON.stringify(value));
15
+ /** Never encode an unbounded source. Offsets are explicit UTF-16 boundaries, never
16
+ * split a surrogate pair; retained byte counts refer to UTF-8, not JSON escaping. */
17
+ function clipText(text, start, end, cap, tail = false) {
18
+ const split = (at) => at > 0 && at < text.length && /[\uD800-\uDBFF]/.test(text[at - 1]) && /[\uDC00-\uDFFF]/.test(text[at]);
19
+ // Empty ranges must remain empty, including at a lone low surrogate.
20
+ if (start < end) {
21
+ if (split(start))
22
+ start++;
23
+ if (split(end))
24
+ end--;
25
+ }
26
+ let retained = 0;
27
+ let cursor = tail ? end : start;
28
+ // Visit at most cap + one codepoint, not repeated whole-prefix encodings.
29
+ while (tail ? cursor > start : cursor < end) {
30
+ const width = tail ? (split(cursor - 1) ? 2 : 1) : ((text.codePointAt(cursor) ?? 0) > 0xffff ? 2 : 1);
31
+ const point = tail ? text.codePointAt(cursor - width) : text.codePointAt(cursor);
32
+ const size = point <= 0x7f ? 1 : point <= 0x7ff ? 2 : point <= 0xffff ? 3 : 4;
33
+ if (retained + size > cap)
34
+ break;
35
+ retained += size;
36
+ cursor += tail ? -width : width;
37
+ }
38
+ if (tail)
39
+ start = cursor;
40
+ else
41
+ end = cursor;
42
+ // Copy bounded bytes without replacing lone surrogates or retaining source backing.
43
+ return { text: JSON.parse(JSON.stringify(text.slice(start, end))), range: [start, end] };
44
+ }
45
+ export function sliceText(text, limit) {
46
+ const known = text.length <= MAX_SCAN_UNITS;
47
+ const originalBytes = known ? Buffer.byteLength(text) : null;
48
+ const take = (start, end, cap, tail = false) => clipText(text, start, end, cap, tail);
49
+ const full = originalBytes !== null && originalBytes <= limit;
50
+ const head = full ? take(0, text.length, limit) : take(0, Math.min(text.length, Math.floor(limit / 3)), Math.floor(limit / 3));
51
+ const tail = full ? undefined : take(Math.max(head.range[1], text.length - (limit - Math.floor(limit / 3))), text.length, limit - Math.floor(limit / 3), true);
52
+ const pieces = tail === undefined ? [head] : [head, tail];
53
+ return { originalBytes, originalUnits: text.length, retainedBytes: pieces.reduce((n, p) => n + Buffer.byteLength(p.text), 0), ranges: pieces.map(p => p.range), rangeUnit: 'utf16', parts: pieces.map(p => p.text), truncated: !full,
54
+ sourceLoss: known ? [] : ['Original byte length not measured: source exceeds bounded scan; UTF-16 length and retained ranges are exact.'] };
55
+ }
56
+ const semanticFlags = () => ({ sourceUnavailable: false, identityAmbiguous: false, resultUnavailable: false });
57
+ /** These facts are collected before projection/fitting, never inferred from bounded
58
+ * explanatory strings. Deliberate traversal/media/byte omissions are not failures. */
59
+ function sourceOwn(value, key, flags) {
60
+ const property = value !== null && typeof value === 'object' ? Object.getOwnPropertyDescriptor(value, key) : undefined;
61
+ if (!property || !('value' in property)) {
62
+ flags.sourceUnavailable = true;
63
+ return undefined;
64
+ }
65
+ return property.value;
66
+ }
67
+ // Only descriptors: even array indices and SDK block fields can be accessors.
68
+ function own(value, key) {
69
+ if (value === null || typeof value !== 'object')
70
+ return undefined;
71
+ const property = Object.getOwnPropertyDescriptor(value, key);
72
+ return property && 'value' in property ? property.value : undefined;
73
+ }
74
+ function indices(length) {
75
+ return length <= 32 ? Array.from({ length }, (_, i) => i)
76
+ : [...Array.from({ length: 16 }, (_, i) => i), ...Array.from({ length: 16 }, (_, i) => length - 16 + i)];
77
+ }
78
+ const omitted = (reason) => ({ entries: [], losses: [{ path: '', reason }] });
79
+ const childPath = (path, key) => `${path}/${key.replaceAll('~', '~0').replaceAll('/', '~1')}`;
80
+ /** Bounded discovery BEFORE allocation: a long early value cannot starve known
81
+ * short siblings. Never serialize the source, call toJSON or evaluate accessors.
82
+ * The temporary snapshot has <=128 values, depth 8, <=32 entries/container and
83
+ * <=8192 copied UTF-8 bytes/string. No source object or large backing string lives
84
+ * beyond this call. Retained snapshots are pruned to the serialized action cap. */
85
+ function snapshot(value, flags = semanticFlags()) {
86
+ let nodes = 0;
87
+ const visit = (item, depth, ceiling = 128) => {
88
+ if (nodes >= ceiling || depth > 8)
89
+ return omitted('Traversal budget: entire region omitted');
90
+ nodes++;
91
+ if (typeof item === 'string')
92
+ return { text: sliceText(item, MAX_ACTION_BYTES) };
93
+ if (item === null || typeof item === 'boolean' || typeof item === 'number' && Number.isFinite(item))
94
+ return { scalar: item };
95
+ if (typeof item !== 'object' || ArrayBuffer.isView(item) || item instanceof ArrayBuffer)
96
+ return omitted('Binary or non-JSON value omitted');
97
+ const kind = own(item, 'type');
98
+ const sdkMedia = ['imageBlock', 'audioBlock', 'videoBlock', 'documentBlock'].includes(kind) && own(item, 'source') !== undefined;
99
+ const mcpMedia = (kind === 'image' || kind === 'audio') && typeof own(item, 'data') === 'string' && typeof own(item, 'mimeType') === 'string';
100
+ if (sdkMedia || mcpMedia)
101
+ return omitted('Structured media payload omitted');
102
+ const array = Array.isArray(item);
103
+ const length = array ? own(item, 'length') : undefined;
104
+ const keys = [];
105
+ const losses = [];
106
+ if (length !== undefined) {
107
+ keys.push(...indices(length).map(String));
108
+ if (length > 32)
109
+ losses.push({ path: '', reason: `Array middle omitted: indices [16, ${length - 16}); original length ${length}` });
110
+ }
111
+ else {
112
+ for (const key in item) {
113
+ if (!Object.hasOwn(item, key))
114
+ continue;
115
+ if (keys.length === 32) {
116
+ losses.push({ path: '', reason: 'Remaining object properties omitted; count not traversed' });
117
+ break;
118
+ }
119
+ keys.push(key);
120
+ }
121
+ }
122
+ const entries = [];
123
+ // Reserve one visit for each discovered sibling; deeper trees share the rest.
124
+ for (const [index, key] of keys.entries()) {
125
+ const property = Object.getOwnPropertyDescriptor(item, key);
126
+ const unavailable = !property || !('value' in property);
127
+ if (unavailable)
128
+ flags.sourceUnavailable = true;
129
+ if (key.length > 128) {
130
+ losses.push({ path: '', reason: 'Oversized property name and its value omitted' });
131
+ continue;
132
+ }
133
+ entries.push([key, unavailable ? omitted('Accessor or absent own value omitted without evaluation') : visit(property.value, depth + 1, ceiling - (keys.length - index - 1))]);
134
+ }
135
+ return { entries, ...(length === undefined ? {} : { length }), losses };
136
+ };
137
+ return visit(value, 0);
138
+ }
139
+ function project(source) {
140
+ const losses = [];
141
+ let lossBytes = 0;
142
+ let extra = false;
143
+ const loss = (entry) => {
144
+ const bounded = { ...entry, path: sliceText(entry.path, 128).parts.join('') };
145
+ const size = bytes(bounded);
146
+ if (losses.length < 4 && lossBytes + size <= 1200) {
147
+ losses.push(bounded);
148
+ lossBytes += size;
149
+ }
150
+ else
151
+ extra = true;
152
+ };
153
+ const visit = (node, path) => {
154
+ if ('scalar' in node)
155
+ return node.scalar;
156
+ if ('text' in node) {
157
+ const { parts, ...text } = node.text;
158
+ if (text.truncated || text.sourceLoss.length) {
159
+ loss({ path, reason: 'Exact head/tail; middle omitted', text });
160
+ return parts;
161
+ }
162
+ return parts[0];
163
+ }
164
+ for (const entry of node.losses)
165
+ loss({ ...entry, path: path + entry.path });
166
+ if (node.length !== undefined) {
167
+ if (node.entries.length === node.length)
168
+ return node.entries.map(([key, value]) => visit(value, childPath(path, key)));
169
+ return { originalLength: node.length, entries: node.entries.map(([key, value]) => ({ index: Number(key), value: visit(value, childPath(path, key)) })) };
170
+ }
171
+ return Object.fromEntries(node.entries.map(([key, value]) => [key, visit(value, childPath(path, key))]));
172
+ };
173
+ const content = visit(source, '');
174
+ if (extra)
175
+ losses.push({ path: '', reason: 'Additional bounded traversal losses aggregated; no omitted region is represented as complete' });
176
+ return { content, losses };
177
+ }
178
+ /** Re-cut only copied source ranges, mapping them back to the original string.
179
+ * This also allows an input snapshot to release space for a later large result. */
180
+ function shrinkText(source, limit) {
181
+ const parts = [];
182
+ const ranges = [];
183
+ const headBudget = Math.floor(limit / 3);
184
+ const first = source.parts[0];
185
+ const last = source.parts.at(-1);
186
+ const clip = (text, cap, tail) => clipText(text, tail ? Math.max(0, text.length - cap) : 0, tail ? text.length : Math.min(text.length, cap), cap, tail).text;
187
+ const head = clip(first, headBudget, false);
188
+ const tail = clip(last, limit - headBudget, true);
189
+ parts.push(head, tail);
190
+ ranges.push([source.ranges[0][0], source.ranges[0][0] + head.length], [source.ranges.at(-1)[1] - tail.length, source.ranges.at(-1)[1]]);
191
+ return { ...source, parts, ranges, retainedBytes: parts.reduce((n, part) => n + Buffer.byteLength(part), 0), truncated: true };
192
+ }
193
+ function reduceSnapshot(source, excess) {
194
+ const texts = [];
195
+ const containers = [];
196
+ const walk = (node) => {
197
+ if ('text' in node)
198
+ texts.push(node);
199
+ else if ('entries' in node) {
200
+ containers.push(node);
201
+ for (const [, value] of node.entries)
202
+ walk(value);
203
+ }
204
+ };
205
+ walk(source);
206
+ const largest = texts.sort((a, b) => bytes(b.text.parts) - bytes(a.text.parts))[0];
207
+ if (largest && largest.text.retainedBytes > 64) {
208
+ largest.text = shrinkText(largest.text, Math.max(32, largest.text.retainedBytes - Math.max(64, Math.ceil(excess / 6))));
209
+ return true;
210
+ }
211
+ const container = containers.filter(node => node.entries.length).sort((a, b) => bytes(project(b)) - bytes(project(a)))[0];
212
+ if (!container)
213
+ return false;
214
+ const [key] = container.entries.splice(Math.floor(container.entries.length / 2), 1)[0];
215
+ container.losses = [{ path: '', reason: 'Serialized budget: collection entries omitted (retained keys/indices are exact)' }];
216
+ if (container.length === undefined)
217
+ container.losses[0].reason += `; including ${sliceText(key, 64).parts.join('')}`;
218
+ return true;
219
+ }
220
+ function fit(source, budget) {
221
+ let result = project(source);
222
+ // Each step shrinks a string by >=64 bytes or removes an entry. Bound even for
223
+ // escape-heavy/deep trees; final fallback is explicit, never an oversized action.
224
+ for (let i = 0; bytes(result) > budget && i < 512; i++) {
225
+ if (!reduceSnapshot(source, bytes(result) - budget))
226
+ break;
227
+ result = project(source);
228
+ }
229
+ if (bytes(result) > budget) {
230
+ // Release the bounded discovery tree too, not merely its rendered content.
231
+ if ('entries' in source) {
232
+ source.entries = [];
233
+ source.losses = [{ path: '', reason: 'Serialized budget: entire region omitted' }];
234
+ }
235
+ else if ('text' in source)
236
+ source.text = shrinkText(source.text, 0);
237
+ result = project(source);
238
+ }
239
+ return result;
240
+ }
241
+ export function capture(value, budget = MAX_ACTION_BYTES - 1) {
242
+ return fit(snapshot(value), budget);
243
+ }
244
+ function summary(action) {
245
+ return { ordinal: action.ordinal, invocation: action.invocation, invocationScope: action.invocationScope, tool: action.tool, failed: action.failed, recovery: action.recovery, status: 'status' in action.result ? action.result.status : action.result.missing,
246
+ ...('exitCode' in action.result ? { exitCode: action.result.exitCode } : {}), ...(action.original ? { original: action.original } : {}), bodyOmitted: true };
247
+ }
248
+ function priority(action) { return action.failed || action.recovery ? 1 : 0; }
249
+ function comparePriority(a, b) { return priority(a) - priority(b) || a.ordinal - b.ordinal; }
250
+ function toolText(content, flags) {
251
+ const value = [];
252
+ const loss = new Set();
253
+ let exitCode;
254
+ if (!Array.isArray(content)) {
255
+ flags.resultUnavailable = true;
256
+ return { value, loss: ['SDK result content unavailable'] };
257
+ }
258
+ const length = own(content, 'length');
259
+ value.length = length;
260
+ for (const i of indices(length)) {
261
+ // An explicit placeholder for every selected index: deliberately excluded
262
+ // media must not become an absent descriptor when snapshot visits this array.
263
+ value[i] = null;
264
+ const block = sourceOwn(content, String(i), flags);
265
+ const kind = sourceOwn(block, 'type', flags);
266
+ if (kind === 'textBlock') {
267
+ const text = sourceOwn(block, 'text', flags);
268
+ if (typeof text === 'string') {
269
+ value[i] = { text };
270
+ if (/\[.*(?:offload|truncat)|truncated:|retrieve_offloaded_content/i.test(text.slice(0, 1024)))
271
+ loss.add('SDK text signals possible upstream truncation/offload; not hydrated');
272
+ continue;
273
+ }
274
+ flags.resultUnavailable = true;
275
+ }
276
+ else if (kind === 'jsonBlock') {
277
+ const json = sourceOwn(block, 'json', flags);
278
+ value[i] = { json };
279
+ const code = own(json, 'exitCode');
280
+ if (typeof code === 'number' && Number.isInteger(code))
281
+ exitCode = code;
282
+ continue;
283
+ }
284
+ loss.add('Non-text/JSON SDK block or accessor omitted without evaluation (binary/image or unsupported)');
285
+ }
286
+ return { value, loss: [...loss], ...(exitCode === undefined ? {} : { exitCode }) };
287
+ }
288
+ export class UploadTurn {
289
+ turn;
290
+ goal;
291
+ actions = [];
292
+ summaries = [];
293
+ pending = new Map();
294
+ scopes = new WeakMap();
295
+ scopeCount = 0;
296
+ calls = new Map();
297
+ inputs = new WeakMap();
298
+ outputs = new WeakMap();
299
+ flags = semanticFlags();
300
+ obligations = 0;
301
+ completedResults = 0;
302
+ // Untrackable obligations (and, after finish, every remaining ledger obligation).
303
+ sealedUnresolved = 0;
304
+ finished = false;
305
+ lateResults = 0;
306
+ originTurns = new Set();
307
+ lateOriginsOverflow = false;
308
+ get integrity() {
309
+ let unresolvedResults = this.sealedUnresolved;
310
+ for (const call of this.calls.values())
311
+ unresolvedResults += call.unresolved;
312
+ return Object.freeze({ ...this.flags, obligations: this.obligations, completedResults: this.completedResults,
313
+ unresolvedResults, lateResults: this.lateResults, lateOriginsOverflow: this.lateOriginsOverflow });
314
+ }
315
+ /** Controller provenance must check every copied original turn, not the retained
316
+ * action window. Overflow fails closed; this never retains bodies or SDK state. */
317
+ lateOrigins() {
318
+ return { turns: [...this.originTurns], overflow: this.lateOriginsOverflow };
319
+ }
320
+ mergeFlags(flags) {
321
+ this.flags.sourceUnavailable ||= flags.sourceUnavailable;
322
+ this.flags.identityAmbiguous ||= flags.identityAmbiguous;
323
+ this.flags.resultUnavailable ||= flags.resultUnavailable;
324
+ }
325
+ totalActions = 0;
326
+ internalEvents = 0;
327
+ batchEntriesOmitted = 0;
328
+ unmatchedResults = 0;
329
+ resultsWithoutSummary = 0;
330
+ backgroundResultsDropped = 0;
331
+ aggregatedActions = 0;
332
+ observerErrors = 0;
333
+ lastFailed = false;
334
+ key(state, id, create = false) {
335
+ let scope = this.scopes.get(state);
336
+ if (scope === undefined && create) {
337
+ scope = ++this.scopeCount;
338
+ this.scopes.set(state, scope);
339
+ }
340
+ return scope === undefined ? undefined : `${scope}:${id}`;
341
+ }
342
+ /** Bounded batch intent supplies identity/input when cancellation skips BeforeToolCall.
343
+ * A later BeforeToolCall replaces intent with the effective execution input. */
344
+ batch(event) {
345
+ const content = own(event.message, 'content');
346
+ if (!Array.isArray(content))
347
+ return;
348
+ const length = own(content, 'length');
349
+ if (length > 32)
350
+ this.batchEntriesOmitted += length - 32;
351
+ for (const index of indices(length)) {
352
+ const use = own(content, String(index));
353
+ if (own(use, 'type') === 'toolUseBlock')
354
+ this.add(use, event.invocationState, false);
355
+ }
356
+ }
357
+ constructor(turn, goal) {
358
+ this.turn = turn;
359
+ this.goal = sliceText(goal, 8192);
360
+ }
361
+ omit(action) {
362
+ const value = summary(action);
363
+ this.summaries.push(value);
364
+ const record = this.calls.get(`${action.invocationScope}:${action.invocation}`);
365
+ if (record?.action === action) {
366
+ delete record.action;
367
+ record.summary = value;
368
+ }
369
+ if (this.summaries.length > MAX_SUMMARIES) {
370
+ const evicted = this.summaries.shift();
371
+ const old = this.calls.get(`${evicted.invocationScope}:${evicted.invocation}`);
372
+ if (old?.summary === evicted)
373
+ delete old.summary;
374
+ this.aggregatedActions++;
375
+ }
376
+ }
377
+ before(event) { this.add(event.toolUse, event.invocationState, true); }
378
+ add(use, state, started) {
379
+ if (this.finished)
380
+ return;
381
+ const rawId = sourceOwn(use, 'toolUseId', this.flags);
382
+ const name = sourceOwn(use, 'name', this.flags);
383
+ const validId = typeof rawId === 'string' && rawId.length > 0 && rawId.length <= 256;
384
+ const id = validId ? rawId : `unavailable-${this.totalActions + 1}`;
385
+ const key = this.key(state, id, true);
386
+ const prior = validId ? this.calls.get(key) : undefined;
387
+ // Intent is not a second attempt, even after both retention windows evict it.
388
+ // Completed/reused IDs otherwise lack a public attempt token: refuse pairing.
389
+ const intent = started && prior !== undefined && !prior.started && !prior.ambiguous && !prior.observed;
390
+ const retainedIntent = intent ? prior.action : undefined;
391
+ const ordinal = intent ? prior.ordinal : ++this.totalActions;
392
+ if (!intent)
393
+ this.obligations++;
394
+ const input = snapshot(sourceOwn(use, 'input', this.flags), this.flags);
395
+ const action = retainedIntent ?? { ordinal, invocation: id, invocationScope: this.scopes.get(state), attempt: intent ? prior.attempt : (prior?.attempt ?? 0) + 1,
396
+ tool: '', inputSource: '', input: project(input), result: { missing: 'No corresponding result observed (cancelled, incomplete or still pending)' }, failed: false, recovery: this.lastFailed, sourceLoss: [] };
397
+ action.tool = typeof name === 'string' ? sliceText(name, 256).parts.join('') : '(unavailable)';
398
+ action.inputSource = started ? 'BeforeToolCall execution input' : 'BeforeTools requested input; execution not observed';
399
+ action.input = project(input);
400
+ if (!validId)
401
+ action.sourceLoss.push('Oversized/missing SDK identity omitted; corresponding result cannot be matched');
402
+ if (typeof name === 'string' && (name.length > 512 || Buffer.byteLength(name.slice(0, 512)) > 256))
403
+ action.sourceLoss.push('Tool name head/tail truncated to 256 bytes');
404
+ this.lastFailed = false;
405
+ if (!intent && prior) {
406
+ this.flags.identityAmbiguous = true;
407
+ action.sourceLoss.push('SDK ID reused within invocation state; result attribution refused');
408
+ action.result = { missing: 'Ambiguous reused SDK ID; result attribution refused' };
409
+ if (prior.action && 'missing' in prior.action.result)
410
+ prior.action.result.missing = 'Ambiguous reused SDK ID; result attribution refused';
411
+ if (prior.summary && !prior.observed)
412
+ prior.summary.status = 'Ambiguous reused SDK ID; result attribution refused';
413
+ this.pending.delete(key);
414
+ }
415
+ // Keep identity tombstones even for evicted actions. Once full, never forget
416
+ // identities and risk attaching a delayed result to a reused ID.
417
+ const track = validId && (prior !== undefined || this.calls.size < 512);
418
+ if (!track) {
419
+ this.flags.identityAmbiguous = true;
420
+ this.sealedUnresolved++;
421
+ action.sourceLoss.push('Identity ledger unavailable/full (512 keys); results remain unmatched');
422
+ action.result = { missing: 'Identity unavailable/full; observed results cannot be safely attributed' };
423
+ }
424
+ if (track) {
425
+ this.calls.set(key, { action, ordinal, attempt: action.attempt, started, ambiguous: !intent && prior !== undefined || prior?.ambiguous === true,
426
+ unresolved: (prior?.unresolved ?? 0) + (intent ? 0 : 1) });
427
+ if (!this.calls.get(key).ambiguous)
428
+ this.pending.set(key, action);
429
+ }
430
+ if (intent && prior.summary)
431
+ this.summaries.splice(this.summaries.indexOf(prior.summary), 1);
432
+ UploadTurn.fitAction(action, input);
433
+ this.inputs.set(action, input);
434
+ if (!retainedIntent)
435
+ this.actions.push(action);
436
+ this.actions.sort((a, b) => a.ordinal - b.ordinal);
437
+ this.boundActions();
438
+ }
439
+ boundActions() {
440
+ if (this.actions.length > MAX_ACTIONS) {
441
+ const candidates = this.actions.slice(0, -16);
442
+ const victim = candidates.reduce((a, b) => comparePriority(a, b) < 0 ? a : b);
443
+ this.actions.splice(this.actions.indexOf(victim), 1);
444
+ const victimKey = `${victim.invocationScope}:${victim.invocation}`;
445
+ if (this.pending.get(victimKey) === victim)
446
+ this.pending.delete(victimKey);
447
+ this.inputs.delete(victim);
448
+ this.outputs.delete(victim);
449
+ this.omit(victim);
450
+ }
451
+ }
452
+ static fitAction(action, input, result) {
453
+ for (let i = 0; bytes(action) > MAX_ACTION_BYTES && i < 512; i++) {
454
+ const source = result && 'content' in action.result && bytes(action.result.content) > bytes(action.input) ? result : input;
455
+ if (!reduceSnapshot(source, bytes(action) - MAX_ACTION_BYTES))
456
+ break;
457
+ action.input = project(input);
458
+ if (result && 'content' in action.result)
459
+ action.result.content = project(result);
460
+ }
461
+ if (bytes(action) > MAX_ACTION_BYTES) {
462
+ action.input = fit(input, 512);
463
+ if (result && 'content' in action.result)
464
+ action.result.content = fit(result, 512);
465
+ }
466
+ }
467
+ after(event) { this.result(event.invocationState, event.result, 'pre-after-hook execution evidence; not necessarily final model-visible output'); }
468
+ fallback(event) {
469
+ return this.result(event.invocationState, event.result, 'observed public ToolResultEvent fallback; no pre-after-hook snapshot available', true);
470
+ }
471
+ result(state, result, evidence, fallback = false) {
472
+ if (this.finished)
473
+ return;
474
+ const id = sourceOwn(result, 'toolUseId', this.flags);
475
+ const key = typeof id === 'string' && id.length > 0 && id.length <= 256 ? this.key(state, id) : undefined;
476
+ const record = key === undefined ? undefined : this.calls.get(key);
477
+ if (!record || record.ambiguous) {
478
+ this.flags.identityAmbiguous = true;
479
+ this.unmatchedResults++;
480
+ return;
481
+ }
482
+ let action = record.action;
483
+ const flags = semanticFlags();
484
+ const text = toolText(sourceOwn(result, 'content', flags), flags);
485
+ const status = sourceOwn(result, 'status', flags);
486
+ if (status !== 'success' && status !== 'error')
487
+ flags.resultUnavailable = true;
488
+ const failed = status === 'error' || text.exitCode !== undefined && text.exitCode !== 0;
489
+ const ack = fallback && status === 'success' && indices(text.value.length).some(index => {
490
+ const value = own(text.value[index], 'text');
491
+ return typeof value === 'string' && value.startsWith('Background task dispatched.\n\nTask ID: ') && /^Task ID: \S{1,256}$/mu.test(value.slice(0, 1024));
492
+ });
493
+ const retained = action ?? record.summary;
494
+ if (ack) {
495
+ if (record.acknowledged)
496
+ return;
497
+ record.acknowledged = true;
498
+ const captured = snapshot(text.value, flags);
499
+ this.mergeFlags(flags);
500
+ if (!retained) {
501
+ this.resultsWithoutSummary++;
502
+ return;
503
+ }
504
+ if (action && !action.acknowledgement) {
505
+ action.acknowledgement = { status: 'acknowledged', evidence, content: fit(captured, 1024) };
506
+ if (!record.observed)
507
+ action.result = { missing: 'Background acknowledged; final result pending' };
508
+ UploadTurn.fitAction(action, this.inputs.get(action) ?? snapshot(null), this.outputs.get(action));
509
+ }
510
+ else if (record.summary && !record.observed)
511
+ record.summary.status = 'Background acknowledged; final result pending (body omitted)';
512
+ if (!record.observed)
513
+ return { turn: this.turn, ordinal: retained.ordinal, invocation: retained.invocation, invocationScope: retained.invocationScope, tool: retained.tool };
514
+ return;
515
+ }
516
+ if (record.observed)
517
+ return;
518
+ record.observed = true;
519
+ // Traverse even when neither body nor summary survives. A matched arrival
520
+ // resolves its obligation once; unavailable evidence remains a separate flag.
521
+ const captured = snapshot(text.value, flags);
522
+ this.mergeFlags(flags);
523
+ record.unresolved = 0;
524
+ if (status === 'success' || status === 'error')
525
+ this.completedResults++;
526
+ if (record.summary) {
527
+ Object.assign(record.summary, { status: status === 'error' || status === 'success' ? status : 'not reported', failed,
528
+ ...(text.exitCode === undefined ? {} : { exitCode: text.exitCode }) });
529
+ // Recover failure text when the input body was evicted, without pretending
530
+ // the omitted input is still present. Selection may evict another body.
531
+ if (failed) {
532
+ const old = record.summary;
533
+ this.summaries.splice(this.summaries.indexOf(old), 1);
534
+ delete record.summary;
535
+ const { bodyOmitted: _omitted, status: _status, exitCode: _exit, ...identity } = old;
536
+ action = { ...identity, attempt: record.attempt, inputSource: 'Input body evicted before result', input: { content: null, losses: [{ path: '', reason: 'Input body omitted for capacity' }] }, result: { missing: '' }, sourceLoss: ['Input body omitted for capacity before result arrived'] };
537
+ record.action = action;
538
+ this.actions.push(action);
539
+ }
540
+ }
541
+ else if (!action)
542
+ this.resultsWithoutSummary++;
543
+ this.lastFailed = failed;
544
+ this.pending.delete(key);
545
+ if (!action)
546
+ return;
547
+ action.result = { status: status === 'success' || status === 'error' ? status : 'not reported', evidence,
548
+ ...(text.exitCode === undefined ? {} : { exitCode: text.exitCode }), content: project(captured) };
549
+ action.sourceLoss.push(...text.loss);
550
+ action.failed = failed;
551
+ UploadTurn.fitAction(action, this.inputs.get(action) ?? snapshot(null), captured);
552
+ this.outputs.set(action, captured);
553
+ this.actions.sort((a, b) => a.ordinal - b.ordinal);
554
+ this.boundActions();
555
+ }
556
+ static late(original, result) {
557
+ const flags = semanticFlags();
558
+ const text = toolText(sourceOwn(result, 'content', flags), flags);
559
+ const captured = snapshot(text.value, flags);
560
+ const status = sourceOwn(result, 'status', flags);
561
+ if (status !== 'success' && status !== 'error')
562
+ flags.resultUnavailable = true;
563
+ const action = { integrity: Object.freeze(flags), ordinal: Number.MAX_SAFE_INTEGER, invocation: original.invocation, invocationScope: 0, attempt: 1, tool: original.tool,
564
+ original: { ...original }, inputSource: 'Late background result; input belongs to original turn/invocation', input: { content: null, losses: [] },
565
+ result: { status: status === 'success' || status === 'error' ? status : 'not reported', evidence: 'pre-after-hook background execution evidence; received via ordinary parent forwarding', content: project(captured), ...(text.exitCode === undefined ? {} : { exitCode: text.exitCode }) },
566
+ failed: status === 'error' || text.exitCode !== undefined && text.exitCode !== 0, recovery: false, sourceLoss: text.loss };
567
+ UploadTurn.fitAction(action, snapshot(null), captured);
568
+ return action;
569
+ }
570
+ receiveLate(action) {
571
+ if (this.finished)
572
+ return;
573
+ this.mergeFlags(action.integrity);
574
+ this.obligations++;
575
+ this.lateResults++;
576
+ if ('status' in action.result && (action.result.status === 'success' || action.result.status === 'error'))
577
+ this.completedResults++;
578
+ if (action.original && !this.originTurns.has(action.original.turn)) {
579
+ if (this.originTurns.size < 64)
580
+ this.originTurns.add(action.original.turn);
581
+ else
582
+ this.lateOriginsOverflow = true;
583
+ }
584
+ this.actions.push({ ...action, ordinal: ++this.totalActions });
585
+ this.boundActions();
586
+ }
587
+ finish() {
588
+ if (this.finished)
589
+ return;
590
+ this.sealedUnresolved = this.integrity.unresolvedResults;
591
+ this.finished = true;
592
+ this.pending.clear();
593
+ this.calls.clear();
594
+ this.inputs = new WeakMap();
595
+ this.outputs = new WeakMap();
596
+ this.scopes = new WeakMap();
597
+ }
598
+ }
599
+ /** Parent-only pre-after-hook execution capture plus public-result fallback.
600
+ * No I/O, async work, Agent/event serialization, model calls or SDK mutation. */
601
+ export class UploadObserver {
602
+ active;
603
+ turns = new Map();
604
+ invocations = new WeakMap();
605
+ scope = 0;
606
+ // Weak state keys never retain Agent/invocation graphs. Only bounded copied
607
+ // origins (64) and original result bodies (16 x 8KiB) survive a sealed turn.
608
+ background = new Map();
609
+ seenAfter = new WeakSet();
610
+ closed = false;
611
+ cancelledBackground = new Set();
612
+ cancelled = false;
613
+ droppedTurns = 0;
614
+ droppedBackground = 0;
615
+ get retainedTurns() { return this.turns.size; }
616
+ get pendingBackground() { return this.background.size; }
617
+ register(state, turn) {
618
+ if (!this.invocations.has(state))
619
+ this.invocations.set(state, { turn: turn.turn, scope: ++this.scope });
620
+ }
621
+ backgroundKey(state, id) {
622
+ const scope = this.invocations.get(state)?.scope;
623
+ return scope === undefined || typeof id !== 'string' || id.length > 256 ? undefined : `${scope}:${id}`;
624
+ }
625
+ batch(event) { this.safely(turn => { this.register(event.invocationState, turn); turn.batch(event); }); }
626
+ before(event) {
627
+ this.safely(turn => {
628
+ this.register(event.invocationState, turn);
629
+ const key = this.backgroundKey(event.invocationState, own(event.toolUse, 'toolUseId'));
630
+ if (key && this.background.delete(key)) {
631
+ this.droppedBackground++;
632
+ turn.backgroundResultsDropped++;
633
+ }
634
+ turn.before(event);
635
+ });
636
+ }
637
+ fallback(event) {
638
+ this.safely(turn => {
639
+ if (this.invocations.get(event.invocationState)?.turn !== turn.turn) {
640
+ turn.unmatchedResults++;
641
+ return;
642
+ }
643
+ const original = turn.fallback(event);
644
+ const key = this.backgroundKey(event.invocationState, own(event.result, 'toolUseId'));
645
+ if (original && key && !this.background.has(key)) {
646
+ if (this.cancelled || this.background.size >= 64) {
647
+ this.droppedBackground++;
648
+ turn.backgroundResultsDropped++;
649
+ }
650
+ else
651
+ this.background.set(key, { original });
652
+ }
653
+ });
654
+ }
655
+ after(event) {
656
+ if (this.closed || this.seenAfter.has(event))
657
+ return;
658
+ this.seenAfter.add(event);
659
+ try {
660
+ const key = this.backgroundKey(event.invocationState, own(event.result, 'toolUseId'));
661
+ if (key && this.cancelledBackground.has(key))
662
+ return;
663
+ const entry = key === undefined ? undefined : this.background.get(key);
664
+ if (this.active && this.invocations.get(event.invocationState)?.turn === this.active.turn) {
665
+ this.active.after(event);
666
+ if (key)
667
+ this.background.delete(key);
668
+ }
669
+ else if (entry && !entry.ready) {
670
+ if ([...this.background.values()].filter(value => value.ready).length >= 16) {
671
+ this.background.delete(key);
672
+ this.droppedBackground++;
673
+ if (this.active)
674
+ this.active.backgroundResultsDropped++;
675
+ }
676
+ else
677
+ entry.ready = UploadTurn.late(entry.original, event.result);
678
+ }
679
+ else if (!entry && this.active)
680
+ this.active.unmatchedResults++;
681
+ }
682
+ catch {
683
+ if (this.active)
684
+ this.active.observerErrors++;
685
+ else
686
+ this.droppedBackground++;
687
+ }
688
+ }
689
+ /** Called only for ordinary parent-stream After events, including the existing
690
+ * background forwarder. Hook-time capture is original; forwarding authorizes
691
+ * inclusion in this turn, never an idle upload or a synthetic USER goal. */
692
+ forwarded(event) {
693
+ if (this.closed)
694
+ return;
695
+ try {
696
+ const key = this.backgroundKey(event.invocationState, own(event.result, 'toolUseId'));
697
+ const entry = key === undefined ? undefined : this.background.get(key);
698
+ if (!entry?.ready)
699
+ return;
700
+ if (this.active)
701
+ this.active.receiveLate(entry.ready);
702
+ else
703
+ this.droppedBackground++; // A refused collector turn cannot replay forwarding.
704
+ this.background.delete(key);
705
+ }
706
+ catch {
707
+ if (this.active)
708
+ this.active.observerErrors++;
709
+ else
710
+ this.droppedBackground++;
711
+ }
712
+ }
713
+ safely(observe) {
714
+ if (this.closed || !this.active)
715
+ return;
716
+ try {
717
+ observe(this.active);
718
+ }
719
+ catch {
720
+ this.active.observerErrors++;
721
+ }
722
+ }
723
+ begin(turn, goal) {
724
+ if (this.closed)
725
+ return;
726
+ this.end();
727
+ this.cancelled = false;
728
+ this.cancelledBackground.clear();
729
+ if (this.turns.size >= 8) {
730
+ this.droppedTurns++;
731
+ return;
732
+ }
733
+ try {
734
+ this.active = new UploadTurn(turn, goal);
735
+ this.turns.set(turn, this.active);
736
+ }
737
+ catch {
738
+ this.active = undefined;
739
+ }
740
+ }
741
+ internal() { if (this.active)
742
+ this.active.internalEvents++; }
743
+ end() { this.active?.finish(); this.active = undefined; }
744
+ take(turn) {
745
+ const value = this.turns.get(turn);
746
+ this.turns.delete(turn);
747
+ if (this.active === value)
748
+ this.end();
749
+ value?.finish();
750
+ return value;
751
+ }
752
+ cancel() {
753
+ this.droppedBackground += this.background.size;
754
+ if (this.active)
755
+ this.active.backgroundResultsDropped += this.background.size;
756
+ for (const key of this.background.keys())
757
+ this.cancelledBackground.add(key);
758
+ this.background.clear();
759
+ this.cancelled = true;
760
+ }
761
+ clear() { this.end(); this.turns.clear(); this.cancel(); this.invocations = new WeakMap(); this.cancelledBackground.clear(); }
762
+ close() { this.clear(); this.closed = true; }
763
+ }
764
+ const message = (role, text) => ({ conversational: { role, content: { text } } });
765
+ export function uploadBody(envelope, turn, settlement) {
766
+ if (turn.goal.retainedBytes === 0 && turn.actions.length === 0)
767
+ return undefined;
768
+ const selected = [];
769
+ const omitted = [...turn.summaries];
770
+ // Reserve goal + closing/quality metadata independently of action selection.
771
+ const source = {
772
+ format: 'darwin-upload-v2', session: settlement.session, turn: settlement.turn, closingSeq: settlement.seq, at: settlement.at,
773
+ memorySession: uploadSessionBudget(),
774
+ outcome: settlement.failure ? 'failed' : settlement.stopReason === 'cancelled' ? 'cancelled' : settlement.partial || !settlement.stopReason ? 'incomplete' : 'closed',
775
+ stopReason: settlement.stopReason ?? 'not reported', taskSuccess: 'not inferred',
776
+ goal: { ...turn.goal, parts: undefined, present: turn.goal.retainedBytes > 0 },
777
+ omissions: UPLOAD_NOTICE,
778
+ };
779
+ const render = (summaries) => {
780
+ const quality = { integrity: turn.integrity, completeActions: selected.filter(a => 'status' in a.result).length, missingResults: selected.filter(a => 'missing' in a.result).length,
781
+ contentTruncatedActions: selected.filter(a => a.input.losses.length || 'content' in a.result && a.result.content.losses.length).length,
782
+ sourceLimitedActions: selected.filter(a => a.sourceLoss.length || a.input.losses.some(l => l.text?.sourceLoss.length) || 'content' in a.result && a.result.content.losses.some(l => l.text?.sourceLoss.length)).length,
783
+ actionBodiesOmitted: turn.totalActions - selected.length, actionSummariesOmitted: turn.totalActions - selected.length - summaries.length,
784
+ internalEventsExcluded: turn.internalEvents, batchEntriesOmitted: turn.batchEntriesOmitted, unmatchedResults: turn.unmatchedResults, resultsWithoutSummary: turn.resultsWithoutSummary, backgroundResultsDropped: turn.backgroundResultsDropped, observerErrors: turn.observerErrors };
785
+ return { ...envelope, sessionId: memorySessionId(envelope.clientToken), payload: [message('OTHER', JSON.stringify({ ...source, quality, omittedActions: summaries })),
786
+ ...(turn.goal.retainedBytes ? [message('USER', turn.goal.parts.join(''))] : []),
787
+ ...[...selected].sort((a, b) => a.ordinal - b.ordinal).map(a => message('TOOL', JSON.stringify(a)))] };
788
+ };
789
+ // Keep the final observed action first, then failures/recoveries before the
790
+ // remaining recent history. Sixteen large recent bodies could crowd out all
791
+ // failure evidence under the new budget. Output remains chronological.
792
+ const ranked = turn.actions.slice(-1).concat(turn.actions.slice(0, -1).sort((a, b) => comparePriority(b, a)));
793
+ for (const action of ranked) {
794
+ selected.push(action);
795
+ // 16KiB reserved for bounded omitted-action summaries.
796
+ if (bytes(render([])) > MAX_NEW_EVENT_BYTES - 16384 || selected.length > 98) {
797
+ selected.pop();
798
+ omitted.push(summary(action));
799
+ }
800
+ }
801
+ const summaries = [];
802
+ for (const item of omitted.sort((a, b) => b.ordinal - a.ordinal)) {
803
+ summaries.push(item);
804
+ const candidate = render(summaries);
805
+ if (bytes(candidate) > MAX_NEW_EVENT_BYTES || Buffer.byteLength(candidate.payload[0].conversational.content.text) > 100000) {
806
+ summaries.pop();
807
+ break;
808
+ }
809
+ }
810
+ summaries.sort((a, b) => a.ordinal - b.ordinal);
811
+ const body = render(summaries);
812
+ if (bytes(body) > MAX_NEW_EVENT_BYTES)
813
+ throw new Error('Upload session byte budget exceeded; new candidate omitted');
814
+ return body;
815
+ }
816
+ export function uploadQuality(text) {
817
+ const source = JSON.parse(text);
818
+ if (source.format !== 'darwin-upload-v2')
819
+ return 'legacy projection (unchanged)';
820
+ const q = source.quality;
821
+ return `goal ${source.goal.present ? 'present' : 'absent'}${source.goal.truncated ? ' (truncated)' : ''}; ${q.completeActions} complete actions; ${q.missingResults} missing results; ${q.contentTruncatedActions} content-truncated; ${q.actionBodiesOmitted} action bodies omitted; ${q.sourceLimitedActions} source-limited; task success not inferred${source.memorySession ? `; Memory session: one event, ${source.memorySession.maxBytes} byte budget (not tokens)` : ''}${q.integrity ? `; turn integrity ${JSON.stringify(q.integrity)}` : ''}`;
822
+ }
823
+ //# sourceMappingURL=upload-projection.js.map