@asyra/ai-agent-runtime 0.5.1 → 0.6.0

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 (262) hide show
  1. package/CHANGELOG.md +73 -0
  2. package/README.md +9 -5
  3. package/dist/action-batch.d.ts.map +1 -1
  4. package/dist/action-batch.js.map +1 -1
  5. package/dist/action-registry.d.ts +2 -2
  6. package/dist/action-registry.d.ts.map +1 -1
  7. package/dist/action-registry.js +100 -65
  8. package/dist/action-registry.js.map +1 -1
  9. package/dist/audit.d.ts.map +1 -1
  10. package/dist/audit.js.map +1 -1
  11. package/dist/batch-exchange-types.d.ts +21 -0
  12. package/dist/batch-exchange-types.d.ts.map +1 -0
  13. package/dist/batch-exchange-types.js +2 -0
  14. package/dist/batch-exchange-types.js.map +1 -0
  15. package/dist/capability-search.d.ts +46 -0
  16. package/dist/capability-search.d.ts.map +1 -0
  17. package/dist/capability-search.js +210 -0
  18. package/dist/capability-search.js.map +1 -0
  19. package/dist/index.d.ts +37 -4
  20. package/dist/index.d.ts.map +1 -1
  21. package/dist/index.js +28 -2
  22. package/dist/index.js.map +1 -1
  23. package/dist/invocation.d.ts +46 -0
  24. package/dist/invocation.d.ts.map +1 -0
  25. package/dist/invocation.js +71 -0
  26. package/dist/invocation.js.map +1 -0
  27. package/dist/json-value.d.ts +3 -0
  28. package/dist/json-value.d.ts.map +1 -0
  29. package/dist/json-value.js +50 -0
  30. package/dist/json-value.js.map +1 -0
  31. package/dist/knowledge-types.d.ts +81 -0
  32. package/dist/knowledge-types.d.ts.map +1 -0
  33. package/dist/knowledge-types.js +2 -0
  34. package/dist/knowledge-types.js.map +1 -0
  35. package/dist/knowledge.d.ts +17 -0
  36. package/dist/knowledge.d.ts.map +1 -0
  37. package/dist/knowledge.js +585 -0
  38. package/dist/knowledge.js.map +1 -0
  39. package/dist/named-result-inputs.d.ts +9 -0
  40. package/dist/named-result-inputs.d.ts.map +1 -0
  41. package/dist/named-result-inputs.js +94 -0
  42. package/dist/named-result-inputs.js.map +1 -0
  43. package/dist/node/action-observation.d.ts +15 -0
  44. package/dist/node/action-observation.d.ts.map +1 -0
  45. package/dist/node/action-observation.js +126 -0
  46. package/dist/node/action-observation.js.map +1 -0
  47. package/dist/node/batch-exchange.d.ts +19 -0
  48. package/dist/node/batch-exchange.d.ts.map +1 -0
  49. package/dist/node/batch-exchange.js +105 -0
  50. package/dist/node/batch-exchange.js.map +1 -0
  51. package/dist/node/file-record-collector.d.ts +11 -0
  52. package/dist/node/file-record-collector.d.ts.map +1 -0
  53. package/dist/node/file-record-collector.js +142 -0
  54. package/dist/node/file-record-collector.js.map +1 -0
  55. package/dist/node/index.d.ts +22 -0
  56. package/dist/node/index.d.ts.map +1 -0
  57. package/dist/node/index.js +22 -0
  58. package/dist/node/index.js.map +1 -0
  59. package/dist/node/information-delivery.d.ts +90 -0
  60. package/dist/node/information-delivery.d.ts.map +1 -0
  61. package/dist/node/information-delivery.js +144 -0
  62. package/dist/node/information-delivery.js.map +1 -0
  63. package/dist/node/knowledge-file.d.ts +22 -0
  64. package/dist/node/knowledge-file.d.ts.map +1 -0
  65. package/dist/node/knowledge-file.js +106 -0
  66. package/dist/node/knowledge-file.js.map +1 -0
  67. package/dist/node/native-provider-config.d.ts +12 -0
  68. package/dist/node/native-provider-config.d.ts.map +1 -0
  69. package/dist/node/native-provider-config.js +58 -0
  70. package/dist/node/native-provider-config.js.map +1 -0
  71. package/dist/node/native-provider.d.ts +36 -0
  72. package/dist/node/native-provider.d.ts.map +1 -0
  73. package/dist/node/native-provider.js +209 -0
  74. package/dist/node/native-provider.js.map +1 -0
  75. package/dist/node/native-rpc-transport.d.ts +39 -0
  76. package/dist/node/native-rpc-transport.d.ts.map +1 -0
  77. package/dist/node/native-rpc-transport.js +171 -0
  78. package/dist/node/native-rpc-transport.js.map +1 -0
  79. package/dist/node/native-session.d.ts +50 -0
  80. package/dist/node/native-session.d.ts.map +1 -0
  81. package/dist/node/native-session.js +200 -0
  82. package/dist/node/native-session.js.map +1 -0
  83. package/dist/node/payload.d.ts +12 -0
  84. package/dist/node/payload.d.ts.map +1 -0
  85. package/dist/node/payload.js +69 -0
  86. package/dist/node/payload.js.map +1 -0
  87. package/dist/node/provider-content.d.ts +9 -0
  88. package/dist/node/provider-content.d.ts.map +1 -0
  89. package/dist/node/provider-content.js +2 -0
  90. package/dist/node/provider-content.js.map +1 -0
  91. package/dist/node/provider-conversations.d.ts +21 -0
  92. package/dist/node/provider-conversations.d.ts.map +1 -0
  93. package/dist/node/provider-conversations.js +98 -0
  94. package/dist/node/provider-conversations.js.map +1 -0
  95. package/dist/node/record-collector.d.ts +27 -0
  96. package/dist/node/record-collector.d.ts.map +1 -0
  97. package/dist/node/record-collector.js +175 -0
  98. package/dist/node/record-collector.js.map +1 -0
  99. package/dist/node/record-sink.d.ts +4 -0
  100. package/dist/node/record-sink.d.ts.map +1 -0
  101. package/dist/node/record-sink.js +218 -0
  102. package/dist/node/record-sink.js.map +1 -0
  103. package/dist/node/report-cli.d.ts +21 -0
  104. package/dist/node/report-cli.d.ts.map +1 -0
  105. package/dist/node/report-cli.js +285 -0
  106. package/dist/node/report-cli.js.map +1 -0
  107. package/dist/node/responses-provider.d.ts +53 -0
  108. package/dist/node/responses-provider.d.ts.map +1 -0
  109. package/dist/node/responses-provider.js +542 -0
  110. package/dist/node/responses-provider.js.map +1 -0
  111. package/dist/node/responses-tool-search.d.ts +74 -0
  112. package/dist/node/responses-tool-search.d.ts.map +1 -0
  113. package/dist/node/responses-tool-search.js +100 -0
  114. package/dist/node/responses-tool-search.js.map +1 -0
  115. package/dist/node/source-identity.d.ts +10 -0
  116. package/dist/node/source-identity.d.ts.map +1 -0
  117. package/dist/node/source-identity.js +85 -0
  118. package/dist/node/source-identity.js.map +1 -0
  119. package/dist/node/sqlite-tool-store.d.ts +18 -0
  120. package/dist/node/sqlite-tool-store.d.ts.map +1 -0
  121. package/dist/node/sqlite-tool-store.js +198 -0
  122. package/dist/node/sqlite-tool-store.js.map +1 -0
  123. package/dist/node/tool-host-library.d.ts +97 -0
  124. package/dist/node/tool-host-library.d.ts.map +1 -0
  125. package/dist/node/tool-host-library.js +368 -0
  126. package/dist/node/tool-host-library.js.map +1 -0
  127. package/dist/node/tool-provider.d.ts +65 -0
  128. package/dist/node/tool-provider.d.ts.map +1 -0
  129. package/dist/node/tool-provider.js +2 -0
  130. package/dist/node/tool-provider.js.map +1 -0
  131. package/dist/profiler/assessment.d.ts +30 -0
  132. package/dist/profiler/assessment.d.ts.map +1 -0
  133. package/dist/profiler/assessment.js +111 -0
  134. package/dist/profiler/assessment.js.map +1 -0
  135. package/dist/profiler/evaluation.d.ts +288 -0
  136. package/dist/profiler/evaluation.d.ts.map +1 -0
  137. package/dist/profiler/evaluation.js +513 -0
  138. package/dist/profiler/evaluation.js.map +1 -0
  139. package/dist/profiler/record-delivery.d.ts +20 -0
  140. package/dist/profiler/record-delivery.d.ts.map +1 -0
  141. package/dist/profiler/record-delivery.js +279 -0
  142. package/dist/profiler/record-delivery.js.map +1 -0
  143. package/dist/profiler/record-outbox.d.ts +48 -0
  144. package/dist/profiler/record-outbox.d.ts.map +1 -0
  145. package/dist/profiler/record-outbox.js +126 -0
  146. package/dist/profiler/record-outbox.js.map +1 -0
  147. package/dist/profiler/recorder.d.ts +35 -0
  148. package/dist/profiler/recorder.d.ts.map +1 -0
  149. package/dist/profiler/recorder.js +864 -0
  150. package/dist/profiler/recorder.js.map +1 -0
  151. package/dist/profiler/records.d.ts +89 -0
  152. package/dist/profiler/records.d.ts.map +1 -0
  153. package/dist/profiler/records.js +216 -0
  154. package/dist/profiler/records.js.map +1 -0
  155. package/dist/profiler/timing.d.ts +21 -0
  156. package/dist/profiler/timing.d.ts.map +1 -0
  157. package/dist/profiler/timing.js +197 -0
  158. package/dist/profiler/timing.js.map +1 -0
  159. package/dist/profiler/trace.d.ts +31 -0
  160. package/dist/profiler/trace.d.ts.map +1 -0
  161. package/dist/profiler/trace.js +66 -0
  162. package/dist/profiler/trace.js.map +1 -0
  163. package/dist/provider-retry.d.ts.map +1 -1
  164. package/dist/provider-retry.js +1 -0
  165. package/dist/provider-retry.js.map +1 -1
  166. package/dist/provider.d.ts +46 -1
  167. package/dist/provider.d.ts.map +1 -1
  168. package/dist/provider.js +34 -0
  169. package/dist/provider.js.map +1 -1
  170. package/dist/providers/exchange-provider.d.ts +32 -0
  171. package/dist/providers/exchange-provider.d.ts.map +1 -0
  172. package/dist/providers/exchange-provider.js +348 -0
  173. package/dist/providers/exchange-provider.js.map +1 -0
  174. package/dist/providers/generic-http.d.ts +2 -1
  175. package/dist/providers/generic-http.d.ts.map +1 -1
  176. package/dist/providers/generic-http.js +12 -5
  177. package/dist/providers/generic-http.js.map +1 -1
  178. package/dist/recipe-admission.d.ts +5 -0
  179. package/dist/recipe-admission.d.ts.map +1 -0
  180. package/dist/recipe-admission.js +533 -0
  181. package/dist/recipe-admission.js.map +1 -0
  182. package/dist/recipe-execution.d.ts +93 -0
  183. package/dist/recipe-execution.d.ts.map +1 -0
  184. package/dist/recipe-execution.js +562 -0
  185. package/dist/recipe-execution.js.map +1 -0
  186. package/dist/recipe-format.d.ts +18 -0
  187. package/dist/recipe-format.d.ts.map +1 -0
  188. package/dist/recipe-format.js +94 -0
  189. package/dist/recipe-format.js.map +1 -0
  190. package/dist/recipe-schema.d.ts +67 -0
  191. package/dist/recipe-schema.d.ts.map +1 -0
  192. package/dist/recipe-schema.js +959 -0
  193. package/dist/recipe-schema.js.map +1 -0
  194. package/dist/recipe-types.d.ts +86 -0
  195. package/dist/recipe-types.d.ts.map +1 -0
  196. package/dist/recipe-types.js +2 -0
  197. package/dist/recipe-types.js.map +1 -0
  198. package/dist/redaction.d.ts.map +1 -1
  199. package/dist/redaction.js.map +1 -1
  200. package/dist/result-context.d.ts +70 -0
  201. package/dist/result-context.d.ts.map +1 -0
  202. package/dist/result-context.js +186 -0
  203. package/dist/result-context.js.map +1 -0
  204. package/dist/result-delivery.d.ts +64 -0
  205. package/dist/result-delivery.d.ts.map +1 -0
  206. package/dist/result-delivery.js +212 -0
  207. package/dist/result-delivery.js.map +1 -0
  208. package/dist/result-media.d.ts +8 -0
  209. package/dist/result-media.d.ts.map +1 -0
  210. package/dist/result-media.js +14 -0
  211. package/dist/result-media.js.map +1 -0
  212. package/dist/runtime.d.ts +70 -10
  213. package/dist/runtime.d.ts.map +1 -1
  214. package/dist/runtime.js +811 -162
  215. package/dist/runtime.js.map +1 -1
  216. package/dist/schema/index.d.ts +6 -0
  217. package/dist/schema/index.d.ts.map +1 -0
  218. package/dist/schema/index.js +6 -0
  219. package/dist/schema/index.js.map +1 -0
  220. package/dist/schema/native-input.d.ts +2 -0
  221. package/dist/schema/native-input.d.ts.map +1 -0
  222. package/dist/schema/native-input.js +170 -0
  223. package/dist/schema/native-input.js.map +1 -0
  224. package/dist/schema/owner-invocation.d.ts +19 -0
  225. package/dist/schema/owner-invocation.d.ts.map +1 -0
  226. package/dist/schema/owner-invocation.js +40 -0
  227. package/dist/schema/owner-invocation.js.map +1 -0
  228. package/dist/schema/result-delivery.d.ts +57 -0
  229. package/dist/schema/result-delivery.d.ts.map +1 -0
  230. package/dist/schema/result-delivery.js +380 -0
  231. package/dist/schema/result-delivery.js.map +1 -0
  232. package/dist/schema/tool-leases.d.ts +63 -0
  233. package/dist/schema/tool-leases.d.ts.map +1 -0
  234. package/dist/schema/tool-leases.js +439 -0
  235. package/dist/schema/tool-leases.js.map +1 -0
  236. package/dist/schema/validation.d.ts +19 -0
  237. package/dist/schema/validation.d.ts.map +1 -0
  238. package/dist/schema/validation.js +502 -0
  239. package/dist/schema/validation.js.map +1 -0
  240. package/dist/tool-contract.d.ts +105 -0
  241. package/dist/tool-contract.d.ts.map +1 -0
  242. package/dist/tool-contract.js +318 -0
  243. package/dist/tool-contract.js.map +1 -0
  244. package/dist/tool-input-error.d.ts +8 -0
  245. package/dist/tool-input-error.d.ts.map +1 -0
  246. package/dist/tool-input-error.js +10 -0
  247. package/dist/tool-input-error.js.map +1 -0
  248. package/dist/tool-library.d.ts +43 -0
  249. package/dist/tool-library.d.ts.map +1 -0
  250. package/dist/tool-library.js +204 -0
  251. package/dist/tool-library.js.map +1 -0
  252. package/dist/tool-scheduler.d.ts +10 -0
  253. package/dist/tool-scheduler.d.ts.map +1 -0
  254. package/dist/tool-scheduler.js +46 -0
  255. package/dist/tool-scheduler.js.map +1 -0
  256. package/dist/tool-store.d.ts +109 -0
  257. package/dist/tool-store.d.ts.map +1 -0
  258. package/dist/tool-store.js +536 -0
  259. package/dist/tool-store.js.map +1 -0
  260. package/dist/types.d.ts +45 -8
  261. package/dist/types.d.ts.map +1 -1
  262. package/package.json +33 -3
@@ -0,0 +1,864 @@
1
+ const tokenFields = [
2
+ 'inputTokens',
3
+ 'cachedInputTokens',
4
+ 'outputTokens',
5
+ 'reasoningOutputTokens',
6
+ 'totalTokens'
7
+ ];
8
+ const isRecord = (value) => typeof value === 'object' && value !== null && !Array.isArray(value);
9
+ const correlationId = (value) => typeof value === 'string' && /^[a-zA-Z0-9:_-]{1,160}$/.test(value)
10
+ ? value
11
+ : undefined;
12
+ // Evidence is deliberately allowlisted: never retain raw prompts, provider events,
13
+ // credentials, bitmap bytes, SVG/path coordinates or complete document payloads.
14
+ const numericTokenKeys = new Set([
15
+ ...tokenFields,
16
+ 'cacheWriteTokens',
17
+ 'cacheWrite30mTokens',
18
+ 'cacheWrite12hTokens'
19
+ ]);
20
+ const evidenceKeys = new Set([
21
+ 'activity',
22
+ 'sourceWork',
23
+ 'preparationInput',
24
+ 'retainedDraft',
25
+ 'draftId',
26
+ 'sourceBytes',
27
+ 'replacementCount',
28
+ 'reuse',
29
+ 'fillOccurrences',
30
+ 'compiledFillDefinitions',
31
+ 'fillTemplateUses',
32
+ 'constructionMs',
33
+ 'compilationMs',
34
+ 'expansionWork',
35
+ 'identityWork',
36
+ 'batches',
37
+ 'nodes',
38
+ 'pathCommands',
39
+ 'projectionCalls',
40
+ 'largestBatchNodes',
41
+ 'largestBatchPathCommands',
42
+ 'definition',
43
+ 'coverage',
44
+ 'requestedCoverage',
45
+ 'availableInResponse',
46
+ 'deliveryReason',
47
+ 'state',
48
+ 'schemaPaths',
49
+ 'decision',
50
+ 'reason',
51
+ 'phase',
52
+ 'sequence',
53
+ 'kind',
54
+ 'observation',
55
+ 'actor',
56
+ 'documentId',
57
+ 'documentGeneration',
58
+ 'firstSequence',
59
+ 'lastSequence',
60
+ 'durableSequence',
61
+ 'targetSequence',
62
+ 'snapshotId',
63
+ 'revision',
64
+ 'recipeStep',
65
+ 'iteration',
66
+ 'reused',
67
+ 'coordinateSpace',
68
+ 'selectionExecutions',
69
+ 'candidateCount',
70
+ 'matchedCount',
71
+ 'metadataReadCount',
72
+ 'computedReadCount',
73
+ 'retainedRows',
74
+ 'retryOf',
75
+ 'direction',
76
+ 'bytes',
77
+ 'asset',
78
+ 'sha256',
79
+ 'path',
80
+ 'attachmentIndex',
81
+ 'contentIndex',
82
+ 'mediaType',
83
+ 'stream',
84
+ 'executor',
85
+ 'channel',
86
+ 'terminal',
87
+ 'parentCallId',
88
+ 'part',
89
+ 'nativeThreadId',
90
+ 'nativeTurnId',
91
+ 'nativeItemId',
92
+ 'batchId',
93
+ 'actionId',
94
+ 'purpose',
95
+ 'purposeSource',
96
+ 'expectedResult',
97
+ 'expectationSource',
98
+ 'contractDigest',
99
+ 'timingScope',
100
+ 'actionObservation',
101
+ 'handlerMs',
102
+ 'executionMs',
103
+ 'settlement',
104
+ 'notificationCounts',
105
+ 'notification',
106
+ 'diagnostic',
107
+ 'server',
108
+ 'failureReason',
109
+ 'willRetry',
110
+ 'rpcCode',
111
+ 'httpStatusCode',
112
+ 'detailOmitted',
113
+ 'occurrences',
114
+ 'value',
115
+ 'acknowledgedActions',
116
+ 'tool',
117
+ 'namespace',
118
+ 'names',
119
+ 'operations',
120
+ 'scope',
121
+ 'parentId',
122
+ 'offset',
123
+ 'limit',
124
+ 'count',
125
+ 'catalogSize',
126
+ 'fields',
127
+ 'keyPrefix',
128
+ 'keys',
129
+ 'field',
130
+ 'target',
131
+ 'callId',
132
+ 'arguments',
133
+ 'updates',
134
+ 'style',
135
+ 'fillColor',
136
+ 'strokeColor',
137
+ 'geometry',
138
+ 'scaleX',
139
+ 'scaleY',
140
+ 'properties',
141
+ 'facts',
142
+ 'factBindings',
143
+ 'criterionId',
144
+ 'factId',
145
+ 'factIds',
146
+ 'final',
147
+ 'statement',
148
+ 'sources',
149
+ 'verification',
150
+ 'dependencies',
151
+ 'dependencyChanges',
152
+ 'invalidatedBy',
153
+ 'key',
154
+ 'version',
155
+ 'structureCriteria',
156
+ 'readyForDetail',
157
+ 'recovery',
158
+ 'nextTool',
159
+ 'deferredDetails',
160
+ 'deferredChecks',
161
+ 'pendingDetails',
162
+ 'description',
163
+ 'regressions',
164
+ 'previousEvidence',
165
+ 'currentEvidence',
166
+ 'plan',
167
+ 'draft',
168
+ 'type',
169
+ 'children',
170
+ 'projection',
171
+ 'result',
172
+ 'actionResults',
173
+ 'batchSummary',
174
+ 'operationCount',
175
+ 'actionCount',
176
+ 'followupActionCount',
177
+ 'actionName',
178
+ 'status',
179
+ 'available',
180
+ 'current',
181
+ 'complete',
182
+ 'outcome',
183
+ 'toolOutcome',
184
+ 'issues',
185
+ 'code',
186
+ 'durationMs',
187
+ 'queueMs',
188
+ 'requestBytes',
189
+ 'toolCount',
190
+ 'toolDefinitionBytes',
191
+ 'eagerToolCount',
192
+ 'eagerToolDefinitionBytes',
193
+ 'executionMs',
194
+ 'responseTextBytes',
195
+ 'imageCount',
196
+ 'timing',
197
+ 'admissionMs',
198
+ 'createMs',
199
+ 'cooperativePaintMs',
200
+ 'cooperativeYieldMs',
201
+ 'totalMs',
202
+ 'sliceCount',
203
+ 'artifactId',
204
+ 'imageArtifactId',
205
+ 'analysisId',
206
+ 'elementId',
207
+ 'compositionId',
208
+ 'elementIds',
209
+ 'elementCount',
210
+ 'pathCount',
211
+ 'pointCount',
212
+ 'width',
213
+ 'height',
214
+ 'url',
215
+ 'sourceUrl',
216
+ 'title',
217
+ 'sources',
218
+ 'references',
219
+ 'method',
220
+ 'strategy',
221
+ 'brief',
222
+ 'viewpoint',
223
+ 'assumptions',
224
+ 'checks',
225
+ 'findings',
226
+ 'kind',
227
+ 'property',
228
+ 'expected',
229
+ 'actual',
230
+ 'tolerance',
231
+ 'applicable',
232
+ 'layoutReview',
233
+ 'review',
234
+ 'phase',
235
+ 'criteria',
236
+ 'requirement',
237
+ 'evidence',
238
+ 'limitations',
239
+ 'inspection',
240
+ 'inspectionDeferred',
241
+ 'inspectionIds',
242
+ 'inspectionId',
243
+ 'revision',
244
+ 'detailRequired',
245
+ 'id',
246
+ 'actions',
247
+ 'name',
248
+ 'message',
249
+ 'accepted',
250
+ 'queries',
251
+ 'images',
252
+ 'image',
253
+ 'candidates',
254
+ 'candidateId',
255
+ 'referenceId',
256
+ 'source',
257
+ 'reviewEvidence',
258
+ 'reason',
259
+ 'error',
260
+ 'query',
261
+ 'action',
262
+ 'truncated',
263
+ 'elementsTruncated',
264
+ 'imageScope',
265
+ 'partial',
266
+ 'bounds',
267
+ 'x',
268
+ 'y',
269
+ 'view',
270
+ 'region'
271
+ ]);
272
+ const summarizeEvidence = (value, depth = 0, budget = { nodes: 128 }) => {
273
+ if (--budget.nodes < 0) {
274
+ return '[evidence budget exhausted]';
275
+ }
276
+ if (depth > 6) {
277
+ return '[nested evidence omitted]';
278
+ }
279
+ if (typeof value === 'string') {
280
+ if (/data:|base64|<svg|Bearer\s/i.test(value)) {
281
+ return '[payload omitted]';
282
+ }
283
+ return (value
284
+ .replace(/https?:\/\/[^\s"<>]+/g, (address) => {
285
+ try {
286
+ const url = new URL(address);
287
+ return url.origin + url.pathname;
288
+ }
289
+ catch {
290
+ return '[invalid URL]';
291
+ }
292
+ })
293
+ .slice(0, 500) + (value.length > 500 ? ' [truncated]' : ''));
294
+ }
295
+ if (typeof value === 'boolean' ||
296
+ typeof value === 'number' ||
297
+ value === null) {
298
+ return value;
299
+ }
300
+ if (Array.isArray(value)) {
301
+ return {
302
+ count: value.length,
303
+ items: value
304
+ .slice(0, 12)
305
+ .map((item) => summarizeEvidence(item, depth + 1, budget)),
306
+ truncated: value.length > 12
307
+ };
308
+ }
309
+ if (!isRecord(value)) {
310
+ return undefined;
311
+ }
312
+ return Object.fromEntries(Object.entries(value)
313
+ .filter(([key]) => evidenceKeys.has(key))
314
+ .map(([key, item]) => {
315
+ if (key === 'part' && isRecord(item)) {
316
+ return [
317
+ key,
318
+ {
319
+ key: summarizeEvidence(item.key, depth + 1, budget),
320
+ index: typeof item.index === 'number' &&
321
+ Number.isSafeInteger(item.index) &&
322
+ item.index >= 0
323
+ ? item.index
324
+ : null
325
+ }
326
+ ];
327
+ }
328
+ return [
329
+ key,
330
+ ['fillColor', 'strokeColor'].includes(key) &&
331
+ typeof item === 'string' &&
332
+ !/^#[0-9a-f]{6,8}$/i.test(item)
333
+ ? '[invalid color value]'
334
+ : summarizeEvidence(key === 'criteria' && isRecord(item)
335
+ ? Object.entries(item).map(([id, criterion]) => ({
336
+ criterionId: id,
337
+ ...(isRecord(criterion) ? criterion : {})
338
+ }))
339
+ : item, depth + 1, budget)
340
+ ];
341
+ }));
342
+ };
343
+ // Persist the structured diagnostic projection, not echoed briefs or arbitrary
344
+ // exception text. Console compatibility remains separate from local retention.
345
+ const persistedEvidence = (value) => {
346
+ if (Array.isArray(value)) {
347
+ return value.map(persistedEvidence);
348
+ }
349
+ if (!isRecord(value)) {
350
+ return value;
351
+ }
352
+ return Object.fromEntries(Object.entries(value).map(([key, item]) => [
353
+ key,
354
+ ['brief', 'message', 'error'].includes(key) && typeof item === 'string'
355
+ ? '[free text omitted]'
356
+ : persistedEvidence(item)
357
+ ]));
358
+ };
359
+ const payloadShape = (value) => {
360
+ if (Array.isArray(value)) {
361
+ return 'array';
362
+ }
363
+ if (value === null) {
364
+ return 'null';
365
+ }
366
+ return typeof value;
367
+ };
368
+ const diagnosticSummary = (value) => {
369
+ const summary = persistedEvidence(summarizeEvidence(value));
370
+ if (JSON.stringify(summary ?? null).length > 4000) {
371
+ return {
372
+ truncated: true,
373
+ reason: 'Diagnostic summary exceeds its display budget; inspect the local payload reference.'
374
+ };
375
+ }
376
+ return summary;
377
+ };
378
+ // Shape and omissions are explicit; this is not a raw-payload recorder.
379
+ const payloadDiagnostic = (value) => ({
380
+ shape: payloadShape(value),
381
+ summary: diagnosticSummary(value),
382
+ omittedFields: isRecord(value)
383
+ ? Object.keys(value)
384
+ .filter((key) => !evidenceKeys.has(key))
385
+ .slice(0, 24)
386
+ .map((key) => /secret|password|token|credential|authorization|key/i.test(key)
387
+ ? '[sensitive field]'
388
+ : key)
389
+ : [],
390
+ policy: 'bounded-allowlist'
391
+ });
392
+ const outputDiagnostic = (value, failed, reason) => {
393
+ const result = isRecord(value) ? value : {};
394
+ const receipts = Array.isArray(result.actionResults)
395
+ ? result.actionResults
396
+ .filter(isRecord)
397
+ .map((entry) => (isRecord(entry.result) ? entry.result : {}))
398
+ : [];
399
+ const observations = [result, ...receipts];
400
+ let usability = 'unknown';
401
+ let basis = 'No explicit output-availability contract was returned.';
402
+ const outcome = isRecord(result.toolOutcome) ? result.toolOutcome : {};
403
+ if (!failed &&
404
+ [
405
+ 'success',
406
+ 'failed',
407
+ 'unknown',
408
+ 'usable',
409
+ 'unavailable',
410
+ 'partial'
411
+ ].includes(String(outcome.status))) {
412
+ usability = String(outcome.status);
413
+ if (outcome.status === 'unavailable' || outcome.status === 'failed') {
414
+ usability = 'unusable';
415
+ }
416
+ else if (outcome.status === 'success') {
417
+ usability = 'usable';
418
+ }
419
+ basis =
420
+ 'The App invocation owner classified execution output; this does not certify visual correctness.';
421
+ }
422
+ else if (failed ||
423
+ observations.some((item) => item.available === false ||
424
+ item.applicable === false ||
425
+ item.status === 'failed')) {
426
+ usability = 'unusable';
427
+ basis = failed
428
+ ? 'Tool raised an execution or admission error.'
429
+ : 'Receipt explicitly rejected or could not provide the requested output.';
430
+ }
431
+ else if (observations.some((item) => item.partial === true ||
432
+ item.complete === false ||
433
+ item.accepted === false ||
434
+ item.readyForDetail === false)) {
435
+ usability = 'partial';
436
+ basis = 'Receipt reports incomplete coverage or unmet review criteria.';
437
+ }
438
+ else if (observations.some((item) => item.available === true ||
439
+ item.complete === true ||
440
+ item.accepted === true ||
441
+ item.status === 'complete' ||
442
+ item.status === 'no-change') ||
443
+ (isRecord(result.batchSummary) &&
444
+ Number(result.batchSummary.actionCount) > 0)) {
445
+ usability = 'usable';
446
+ basis =
447
+ 'Receipt acknowledges output or operations; this does not certify visual correctness.';
448
+ }
449
+ const issue = Array.isArray(outcome.issues)
450
+ ? outcome.issues.find((item) => isRecord(item) && typeof item.message === 'string')
451
+ : undefined;
452
+ const feedback = reason ??
453
+ (isRecord(issue) ? issue.message : undefined) ??
454
+ (usability === 'unusable' || usability === 'partial'
455
+ ? observations.find((item) => typeof item.message === 'string')?.message
456
+ : undefined);
457
+ let correctness = {
458
+ status: 'unverified',
459
+ source: 'none',
460
+ reason: 'Execution receipt alone does not verify the requested result.'
461
+ };
462
+ const checks = result.checks;
463
+ if (Array.isArray(checks) &&
464
+ checks.length > 0 &&
465
+ checks.every((check) => isRecord(check) &&
466
+ ['pass', 'fail', 'unverified'].includes(String(check.status)) &&
467
+ typeof check.evidence === 'string')) {
468
+ let status = 'unverified';
469
+ if (checks.some((check) => check.status === 'fail')) {
470
+ status = 'failed';
471
+ }
472
+ else if (checks.every((check) => check.status === 'pass')) {
473
+ status = 'passed';
474
+ }
475
+ correctness = {
476
+ status,
477
+ source: 'model-review',
478
+ reason: 'Recorded criterion judgments only; see each check and its evidence. This is not independent verification of the artwork.'
479
+ };
480
+ }
481
+ let executionStatus = usability;
482
+ if (usability === 'unusable') {
483
+ executionStatus =
484
+ result.settlement === 'not-started' &&
485
+ (result.stage === 'admission' || result.code === 'TOOL_INPUT_INVALID')
486
+ ? 'rejected'
487
+ : 'failed';
488
+ }
489
+ if (failed) {
490
+ executionStatus = 'failed';
491
+ }
492
+ return {
493
+ ...payloadDiagnostic(value),
494
+ correctness,
495
+ usability,
496
+ execution: {
497
+ status: executionStatus,
498
+ stage: typeof result.stage === 'string' ? result.stage.slice(0, 128) : null,
499
+ code: typeof result.code === 'string' ? result.code.slice(0, 128) : null,
500
+ settlement: typeof result.settlement === 'string'
501
+ ? result.settlement.slice(0, 128)
502
+ : null
503
+ },
504
+ basis,
505
+ feedback: typeof feedback === 'string' ? summarizeEvidence(feedback) : null
506
+ };
507
+ };
508
+ /** One bounded accumulator per provider invocation; provider totals are snapshots, not deltas. */
509
+ export const createAiExecutionProfiler = (input, model, options = {}) => {
510
+ const now = options.now ?? (() => performance.now());
511
+ // Assessment CLI stdout is the report payload; keep diagnostics separate.
512
+ const log = options.log ?? (() => undefined);
513
+ const requestId = globalThis.crypto.randomUUID();
514
+ const startedAt = now();
515
+ const metadata = isRecord(input.metadata) ? input.metadata : {};
516
+ const conversationId = correlationId(metadata.conversationId);
517
+ const turnId = correlationId(metadata.turnId);
518
+ const replyToTurnId = isRecord(metadata.replyTo)
519
+ ? correlationId(metadata.replyTo.turnId)
520
+ : undefined;
521
+ let tokens = null;
522
+ let invalidSnapshot = false;
523
+ let finished = false;
524
+ let sequence = 0;
525
+ const transport = { sentBytes: 0, receivedBytes: 0 };
526
+ const activeIntervals = new Set();
527
+ let intervalStartedAt = 0;
528
+ let observedToolAndResearchMs = 0;
529
+ let recordingFailures = 0;
530
+ const persist = (record) => {
531
+ try {
532
+ options.sink?.write({
533
+ ...record,
534
+ evidence: persistedEvidence(record.evidence)
535
+ });
536
+ }
537
+ catch {
538
+ recordingFailures++;
539
+ // A diagnostic sink cannot change execution.
540
+ }
541
+ };
542
+ persist({
543
+ event: 'ai_request_started',
544
+ schemaVersion: 2,
545
+ profilerVersion: 1,
546
+ requestId,
547
+ sequence: 0,
548
+ startedAt: new Date().toISOString(),
549
+ model,
550
+ effort: options.effort ?? null,
551
+ provider: options.provider ?? null,
552
+ sourceRevision: correlationId(options.sourceRevision) ?? null,
553
+ sourceFingerprint: /^[a-f0-9]{64}$/.test(options.sourceFingerprint ?? '')
554
+ ? options.sourceFingerprint
555
+ : null,
556
+ sourceIdentityStatus: options.sourceIdentityStatus ??
557
+ (options.sourceRevision ? 'configured' : 'unavailable'),
558
+ conversationId,
559
+ turnId,
560
+ replyToTurnId,
561
+ purpose: options.purpose ?? 'execution',
562
+ sourceRequestId: correlationId(options.sourceRequestId) ?? null,
563
+ parentCallId: correlationId(options.parentCallId) ?? null,
564
+ sourceSpanId: correlationId(options.sourceSpanId) ?? null,
565
+ ...(options.lifecycle ? { lifecycleVersion: 1 } : {})
566
+ });
567
+ const lifecycle = (stage, evidence, elapsedMs = Math.max(0, now() - startedAt)) => {
568
+ const record = {
569
+ event: 'ai_request_trace',
570
+ schemaVersion: 2,
571
+ requestId,
572
+ sequence: ++sequence,
573
+ stage,
574
+ callId: evidence.callId,
575
+ elapsedMs,
576
+ recordedAt: new Date().toISOString(),
577
+ evidence
578
+ };
579
+ persist(record);
580
+ try {
581
+ log(JSON.stringify(record));
582
+ }
583
+ catch {
584
+ /* Diagnostics cannot fail work. */
585
+ }
586
+ };
587
+ const root = {
588
+ callId: 'request-lifecycle',
589
+ owner: 'app',
590
+ purpose: options.purpose ?? 'Compose, execute and settle this provider invocation'
591
+ };
592
+ if (options.lifecycle) {
593
+ lifecycle('lifecycle_started', root, 0);
594
+ }
595
+ return {
596
+ requestId,
597
+ span(evidence) {
598
+ if (finished) {
599
+ return () => undefined;
600
+ }
601
+ lifecycle('lifecycle_started', evidence);
602
+ let closed = false;
603
+ return () => {
604
+ if (closed || finished) {
605
+ return;
606
+ }
607
+ closed = true;
608
+ lifecycle('lifecycle_completed', evidence);
609
+ };
610
+ },
611
+ recordTransport(direction, bytes, stream = 'protocol') {
612
+ if (finished || !Number.isSafeInteger(bytes) || bytes < 0) {
613
+ return;
614
+ }
615
+ const key = direction === 'sent' ? 'sentBytes' : 'receivedBytes';
616
+ if (stream === 'protocol') {
617
+ transport[key] += bytes;
618
+ }
619
+ persist({
620
+ event: 'ai_request_trace',
621
+ schemaVersion: 2,
622
+ requestId,
623
+ sequence: ++sequence,
624
+ stage: 'transport_chunk',
625
+ elapsedMs: Math.max(0, now() - startedAt),
626
+ recordedAt: new Date().toISOString(),
627
+ evidence: { direction, bytes, stream }
628
+ });
629
+ },
630
+ trace(stage, evidence) {
631
+ if (finished) {
632
+ return;
633
+ }
634
+ const observedElapsedMs = Math.max(0, now() - startedAt);
635
+ try {
636
+ if (isRecord(evidence) && typeof evidence.callId === 'string') {
637
+ const research = stage.startsWith('research_');
638
+ const key = `${research ? 'research' : 'tool'}:${evidence.callId}`;
639
+ if (stage === 'tool_started' || stage === 'research_started') {
640
+ if (!activeIntervals.size) {
641
+ intervalStartedAt = now();
642
+ }
643
+ activeIntervals.add(key);
644
+ }
645
+ else if (stage === 'tool_completed' ||
646
+ stage === 'tool_failed' ||
647
+ stage === 'research_completed') {
648
+ if (activeIntervals.delete(key) && !activeIntervals.size) {
649
+ observedToolAndResearchMs += Math.max(0, now() - intervalStartedAt);
650
+ }
651
+ }
652
+ }
653
+ let diagnostic;
654
+ if (isRecord(evidence) && typeof evidence.callId === 'string') {
655
+ const payload = (phase, value) => options.sink?.writePayload?.(requestId, evidence.callId, phase, value) ?? { status: 'unavailable', path: null };
656
+ if (stage === 'research_started' || stage === 'research_completed') {
657
+ const phase = stage === 'research_started' ? 'input' : 'output';
658
+ // Native item metadata is not the upstream request/response payload.
659
+ diagnostic = {
660
+ [phase]: {
661
+ payload: {
662
+ status: 'unavailable',
663
+ reason: 'upstream-not-exposed',
664
+ path: null
665
+ }
666
+ }
667
+ };
668
+ }
669
+ if ((stage === 'provider_item_completed' ||
670
+ stage === 'provider_notification' ||
671
+ stage === 'orchestration_completed') &&
672
+ isRecord(evidence.nativeOutput)) {
673
+ try {
674
+ diagnostic = {
675
+ output: { payload: payload('output', evidence.nativeOutput) }
676
+ };
677
+ }
678
+ catch {
679
+ diagnostic = {
680
+ output: { payload: { status: 'failed', path: null } }
681
+ };
682
+ }
683
+ }
684
+ if (stage === 'visual_assessment_context') {
685
+ diagnostic = {
686
+ input: { payload: payload('input', evidence.arguments) }
687
+ };
688
+ }
689
+ if (stage === 'provider_notifications') {
690
+ diagnostic = {
691
+ output: {
692
+ payload: payload('output', evidence.notificationCounts)
693
+ }
694
+ };
695
+ }
696
+ if (stage === 'capabilities_advertised') {
697
+ diagnostic = { contracts: payload('input', evidence.definitions) };
698
+ }
699
+ if (stage === 'tool_started' || stage === 'action_started') {
700
+ diagnostic = {
701
+ attribution: {
702
+ actor: evidence.actor ?? null,
703
+ executor: evidence.executor ?? null,
704
+ parentCallId: correlationId(evidence.parentCallId) ?? null,
705
+ retryOf: correlationId(evidence.retryOf) ?? null,
706
+ nativeThreadId: correlationId(evidence.nativeThreadId) ?? null,
707
+ nativeTurnId: correlationId(evidence.nativeTurnId) ?? null,
708
+ contractDigest: evidence.contractDigest ?? null,
709
+ purpose: summarizeEvidence(evidence.purpose) ?? null,
710
+ purposeSource: evidence.purposeSource ?? 'unavailable',
711
+ expectedResult: summarizeEvidence(evidence.expectedResult) ?? null,
712
+ expectationSource: evidence.expectationSource ?? 'unavailable',
713
+ timingScope: evidence.timingScope ?? 'unavailable'
714
+ },
715
+ input: {
716
+ ...payloadDiagnostic(evidence.arguments),
717
+ payload: payload('input', evidence.arguments)
718
+ }
719
+ };
720
+ }
721
+ if ([
722
+ 'tool_completed',
723
+ 'tool_failed',
724
+ 'action_completed',
725
+ 'action_failed'
726
+ ].includes(stage)) {
727
+ const output = evidence.result ?? {
728
+ code: evidence.code,
729
+ reason: evidence.reason
730
+ };
731
+ diagnostic = {
732
+ output: {
733
+ ...outputDiagnostic(evidence.result, stage.endsWith('_failed'), evidence.reason),
734
+ payload: payload('output', output)
735
+ }
736
+ };
737
+ }
738
+ }
739
+ const summarized = summarizeEvidence(isRecord(evidence) && 'nativeOutput' in evidence
740
+ ? Object.fromEntries(Object.entries(evidence).filter(([key]) => key !== 'nativeOutput'))
741
+ : evidence);
742
+ if (stage === 'provider_transport_event' &&
743
+ isRecord(evidence) &&
744
+ evidence.part === 'response-usage' &&
745
+ isRecord(summarized)) {
746
+ for (const key of numericTokenKeys) {
747
+ const value = evidence[key];
748
+ if (typeof value === 'number' &&
749
+ Number.isSafeInteger(value) &&
750
+ value >= 0) {
751
+ summarized[key] = value;
752
+ }
753
+ }
754
+ }
755
+ const serialized = JSON.stringify(summarized);
756
+ const record = {
757
+ event: 'ai_request_trace',
758
+ diagnostic,
759
+ schemaVersion: 2,
760
+ requestId,
761
+ conversationId,
762
+ turnId,
763
+ sequence: ++sequence,
764
+ stage,
765
+ tool: isRecord(evidence)
766
+ ? summarizeEvidence(evidence.tool)
767
+ : undefined,
768
+ callId: isRecord(evidence)
769
+ ? summarizeEvidence(evidence.callId)
770
+ : undefined,
771
+ elapsedMs: observedElapsedMs,
772
+ recordedAt: new Date().toISOString(),
773
+ evidence: serialized.length <= 6000
774
+ ? summarized
775
+ : {
776
+ truncated: true,
777
+ reason: 'Evidence exceeded the per-event log budget.'
778
+ }
779
+ };
780
+ persist(record);
781
+ log(JSON.stringify(record));
782
+ }
783
+ catch {
784
+ // A diagnostic sink must not alter execution or settlement.
785
+ }
786
+ },
787
+ update(value) {
788
+ if (finished) {
789
+ return;
790
+ }
791
+ const total = isRecord(value) ? value.total : undefined;
792
+ if (!isRecord(total) ||
793
+ !tokenFields.every((field) => Number.isSafeInteger(total[field]) && total[field] >= 0)) {
794
+ invalidSnapshot = true;
795
+ return;
796
+ }
797
+ const snapshot = Object.fromEntries(tokenFields.map((field) => [field, total[field]]));
798
+ if (snapshot.cachedInputTokens > snapshot.inputTokens ||
799
+ snapshot.reasoningOutputTokens > snapshot.outputTokens ||
800
+ !Number.isSafeInteger(snapshot.inputTokens + snapshot.outputTokens) ||
801
+ snapshot.totalTokens !== snapshot.inputTokens + snapshot.outputTokens) {
802
+ invalidSnapshot = true;
803
+ return;
804
+ }
805
+ const previous = tokens;
806
+ if (previous &&
807
+ tokenFields.some((field) => snapshot[field] < previous[field])) {
808
+ return;
809
+ }
810
+ tokens = snapshot;
811
+ },
812
+ finish(outcome) {
813
+ if (finished) {
814
+ return;
815
+ }
816
+ finished = true;
817
+ let usageStatus = 'unavailable';
818
+ if (tokens !== null) {
819
+ usageStatus =
820
+ outcome === 'completed' && !invalidSnapshot ? 'reported' : 'partial';
821
+ }
822
+ const durationMs = Math.max(0, now() - startedAt);
823
+ if (options.lifecycle) {
824
+ lifecycle('lifecycle_completed', root, durationMs);
825
+ }
826
+ const observedMs = Math.min(durationMs, observedToolAndResearchMs +
827
+ (activeIntervals.size ? Math.max(0, now() - intervalStartedAt) : 0));
828
+ const report = {
829
+ event: 'ai_request_usage',
830
+ schemaVersion: 2,
831
+ requestId,
832
+ sequence: ++sequence,
833
+ provider: options.provider ?? null,
834
+ model,
835
+ conversationId,
836
+ turnId,
837
+ replyToTurnId,
838
+ attempt: Number.isSafeInteger(input.attempt) && input.attempt > 0
839
+ ? input.attempt
840
+ : undefined,
841
+ finishedAt: new Date().toISOString(),
842
+ durationMs,
843
+ timing: {
844
+ observedToolAndResearchMs: observedMs,
845
+ outsideToolAndResearchMs: durationMs - observedMs
846
+ },
847
+ transport: { ...transport },
848
+ recordingFailures,
849
+ outcome,
850
+ usageStatus,
851
+ tokens
852
+ };
853
+ // Diagnostics must never change the drawing request's settlement.
854
+ persist(report);
855
+ try {
856
+ log(JSON.stringify(report));
857
+ }
858
+ catch {
859
+ // The process log sink may already be closed during shutdown.
860
+ }
861
+ }
862
+ };
863
+ };
864
+ //# sourceMappingURL=recorder.js.map