dal-code 1.0.45 → 1.0.47

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 (400) hide show
  1. package/CHANGELOG.md +83 -0
  2. package/NOTICE +49 -1
  3. package/PRIVACY.md +18 -11
  4. package/dal-docs/extensions.md +16 -4
  5. package/dist/cli/args.js +2 -2
  6. package/dist/cli/auth-check.js +1 -1
  7. package/dist/cli/auth-command.js +6 -5
  8. package/dist/cli/list-models.js +2 -2
  9. package/dist/cli/piped-stdin.js +2 -0
  10. package/dist/cli/startup-diagnostics.js +1 -0
  11. package/dist/core/agent-log.d.ts +6 -0
  12. package/dist/core/agent-log.js +3 -0
  13. package/dist/core/agent-session-services.d.ts +0 -1
  14. package/dist/core/agent-session-services.js +1 -1
  15. package/dist/core/agent-session.d.ts +19 -2
  16. package/dist/core/agent-session.js +8 -8
  17. package/dist/core/client-identity.js +1 -0
  18. package/dist/core/compaction/branch-summarization.js +3 -3
  19. package/dist/core/compaction/compaction.d.ts +2 -2
  20. package/dist/core/compaction/compaction.js +11 -9
  21. package/dist/core/compaction-backoff.js +1 -0
  22. package/dist/core/dal-session-headers.js +1 -0
  23. package/dist/core/export-html/index.js +2 -2
  24. package/dist/core/export-html/template.html +1 -0
  25. package/dist/core/export-html/template.js +6 -6
  26. package/dist/core/export-html/vendor/marked-cjk-friendly.min.js +6 -0
  27. package/dist/core/export-html/vendor/marked.min.js +30 -29
  28. package/dist/core/extensions/engine-specifiers.js +1 -0
  29. package/dist/core/extensions/errors.d.ts +12 -0
  30. package/dist/core/extensions/errors.js +1 -0
  31. package/dist/core/extensions/index.d.ts +1 -0
  32. package/dist/core/extensions/index.js +1 -1
  33. package/dist/core/extensions/loader.js +1 -1
  34. package/dist/core/extensions/runner.d.ts +7 -1
  35. package/dist/core/extensions/runner.js +1 -1
  36. package/dist/core/extensions/types.d.ts +4 -0
  37. package/dist/core/extensions/virtual-modules.js +1 -1
  38. package/dist/core/http-dispatcher.js +1 -1
  39. package/dist/core/model-config.d.ts +984 -0
  40. package/dist/core/model-config.js +5 -5
  41. package/dist/core/model-identity.js +2 -0
  42. package/dist/core/model-resolver.js +1 -1
  43. package/dist/core/model-runtime.d.ts +2 -0
  44. package/dist/core/model-runtime.js +2 -2
  45. package/dist/core/package-manager.d.ts +2 -0
  46. package/dist/core/package-manager.js +2 -2
  47. package/dist/core/provider-composer.d.ts +2 -1
  48. package/dist/core/provider-composer.js +1 -1
  49. package/dist/core/sandbox/bwrap-placeholders.js +1 -1
  50. package/dist/core/sandbox/index.d.ts +1 -1
  51. package/dist/core/sandbox/index.js +1 -1
  52. package/dist/core/sandbox/policy.d.ts +4 -0
  53. package/dist/core/sandbox/policy.js +1 -1
  54. package/dist/core/sandbox/runtime.d.ts +2 -0
  55. package/dist/core/sandbox/runtime.js +1 -1
  56. package/dist/core/sandbox/shell-sandbox.d.ts +2 -0
  57. package/dist/core/sandbox/shell-sandbox.js +6 -6
  58. package/dist/core/sdk.js +1 -1
  59. package/dist/core/session-stall-monitor.d.ts +41 -0
  60. package/dist/core/session-stall-monitor.js +2 -0
  61. package/dist/core/settings-manager.d.ts +4 -0
  62. package/dist/core/settings-manager.js +1 -1
  63. package/dist/core/settings-schema.d.ts +2 -0
  64. package/dist/core/settings-schema.js +1 -1
  65. package/dist/core/stall-watchdog.d.ts +55 -0
  66. package/dist/core/stall-watchdog.js +1 -0
  67. package/dist/core/system-prompt.js +10 -10
  68. package/dist/core/tools/bash.d.ts +1 -0
  69. package/dist/core/tools/bash.js +14 -14
  70. package/dist/core/tools/edit.d.ts +1 -1
  71. package/dist/core/tools/edit.js +3 -3
  72. package/dist/core/tools/grep.js +1 -1
  73. package/dist/core/tools/path-utils.d.ts +1 -0
  74. package/dist/core/tools/path-utils.js +1 -1
  75. package/dist/dal/builtins.js +2 -2
  76. package/dist/dal/manifest.d.ts +1 -0
  77. package/dist/dal/manifest.js +1 -1
  78. package/dist/dal/safety-net.js +3 -1
  79. package/dist/extensions/codemode/execute.js +22 -16
  80. package/dist/extensions/mcp/config.js +2 -2
  81. package/dist/extensions/mcp/oauth.js +2 -2
  82. package/dist/index.d.ts +5 -4
  83. package/dist/index.js +1 -1
  84. package/dist/main.js +4 -4
  85. package/dist/migrations.js +3 -5
  86. package/dist/modes/index.d.ts +2 -2
  87. package/dist/modes/index.js +1 -1
  88. package/dist/modes/interactive/external-editor.js +1 -1
  89. package/dist/modes/interactive/interactive-mode.d.ts +7 -7
  90. package/dist/modes/interactive/interactive-mode.js +25 -25
  91. package/dist/modes/interactive/session-share.js +1 -1
  92. package/dist/modes/print-mode.d.ts +1 -0
  93. package/dist/modes/print-mode.js +8 -7
  94. package/dist/modes/rpc/rpc-client.d.ts +13 -1
  95. package/dist/modes/rpc/rpc-client.js +3 -3
  96. package/dist/modes/rpc/rpc-mode.js +1 -1
  97. package/dist/modes/rpc/rpc-types.d.ts +14 -0
  98. package/dist/node_modules/@dalcode/dal-advisor/package.json +3 -3
  99. package/dist/node_modules/@dalcode/dal-awake/package.json +2 -2
  100. package/dist/node_modules/@dalcode/dal-bridge/package.json +2 -2
  101. package/dist/node_modules/@dalcode/dal-capabilities/package.json +4 -4
  102. package/dist/node_modules/@dalcode/dal-capabilities/src/catalogue.js +1 -1
  103. package/dist/node_modules/@dalcode/dal-capabilities/src/index.js +10 -10
  104. package/dist/node_modules/@dalcode/dal-capabilities/src/match.js +1 -1
  105. package/dist/node_modules/@dalcode/dal-capabilities/src/state.js +3 -3
  106. package/dist/node_modules/@dalcode/dal-codeindex/package.json +2 -2
  107. package/dist/node_modules/@dalcode/dal-codeindex/src/index.js +4 -4
  108. package/dist/node_modules/@dalcode/dal-compat/package.json +2 -2
  109. package/dist/node_modules/@dalcode/dal-dap/package.json +2 -2
  110. package/dist/node_modules/@dalcode/dal-dap/src/install.js +2 -2
  111. package/dist/node_modules/@dalcode/dal-gateway/package.json +2 -2
  112. package/dist/node_modules/@dalcode/dal-goal/package.json +3 -3
  113. package/dist/node_modules/@dalcode/dal-guard/package.json +5 -4
  114. package/dist/node_modules/@dalcode/dal-guard/src/credentials.js +7 -1
  115. package/dist/node_modules/@dalcode/dal-guard/src/edit-anchor-core.js +25 -23
  116. package/dist/node_modules/@dalcode/dal-guard/src/edit-anchor.js +4 -4
  117. package/dist/node_modules/@dalcode/dal-guard/src/index.js +4 -4
  118. package/dist/node_modules/@dalcode/dal-guard/src/policy.js +1 -1
  119. package/dist/node_modules/@dalcode/dal-guard/src/session-files.js +1 -0
  120. package/dist/node_modules/@dalcode/dal-guard/src/suspicion.js +1 -0
  121. package/dist/node_modules/@dalcode/dal-guard/src/workspace.js +2 -2
  122. package/dist/node_modules/@dalcode/dal-halo/package.json +1 -1
  123. package/dist/node_modules/@dalcode/dal-interactive/package.json +2 -2
  124. package/dist/node_modules/@dalcode/dal-lang/package.json +3 -3
  125. package/dist/node_modules/@dalcode/dal-learn/package.json +4 -2
  126. package/dist/node_modules/@dalcode/dal-learn/src/engine.js +4 -4
  127. package/dist/node_modules/@dalcode/dal-learn/src/index.js +15 -14
  128. package/dist/node_modules/@dalcode/dal-learn/src/revisions.js +3 -0
  129. package/dist/node_modules/@dalcode/dal-learn/src/safety.js +1 -1
  130. package/dist/node_modules/@dalcode/dal-learn/src/skill-evolution.js +14 -14
  131. package/dist/node_modules/@dalcode/dal-lsp/package.json +5 -3
  132. package/dist/node_modules/@dalcode/dal-lsp/src/config.js +1 -1
  133. package/dist/node_modules/@dalcode/dal-lsp/src/index.js +14 -13
  134. package/dist/node_modules/@dalcode/dal-lsp/src/managed.js +1 -0
  135. package/dist/node_modules/@dalcode/dal-mcp/package.json +7 -6
  136. package/dist/node_modules/@dalcode/dal-mcp/src/child-env.js +3 -0
  137. package/dist/node_modules/@dalcode/dal-mcp/src/stdio-client.d.ts +1 -0
  138. package/dist/node_modules/@dalcode/dal-mcp/src/stdio-client.js +3 -3
  139. package/dist/node_modules/@dalcode/dal-office/package.json +3 -2
  140. package/dist/node_modules/@dalcode/dal-office/src/extract/cell.js +1 -0
  141. package/dist/node_modules/@dalcode/dal-office/src/extract/index.js +2 -2
  142. package/dist/node_modules/@dalcode/dal-office/src/extract/ooxml.js +4 -4
  143. package/dist/node_modules/@dalcode/dal-office/src/extract/pdf.js +4 -4
  144. package/dist/node_modules/@dalcode/dal-office/src/facts.d.ts +15 -0
  145. package/dist/node_modules/@dalcode/dal-office/src/facts.js +4 -0
  146. package/dist/node_modules/@dalcode/dal-office/src/index.js +1 -1
  147. package/dist/node_modules/@dalcode/dal-office/src/lazy.js +1 -0
  148. package/dist/node_modules/@dalcode/dal-office/src/{index.d.ts → office.d.ts} +2 -3
  149. package/dist/node_modules/@dalcode/dal-office/src/office.js +1 -0
  150. package/dist/node_modules/@dalcode/dal-office/src/render/capture.d.ts +21 -0
  151. package/dist/node_modules/@dalcode/dal-office/src/render/capture.js +13 -0
  152. package/dist/node_modules/@dalcode/dal-office/src/render/chart.d.ts +15 -0
  153. package/dist/node_modules/@dalcode/dal-office/src/render/chart.js +3 -3
  154. package/dist/node_modules/@dalcode/dal-office/src/render/docx.d.ts +4 -0
  155. package/dist/node_modules/@dalcode/dal-office/src/render/docx.js +1 -1
  156. package/dist/node_modules/@dalcode/dal-office/src/render/pptx.d.ts +2 -0
  157. package/dist/node_modules/@dalcode/dal-office/src/render/pptx.js +4 -3
  158. package/dist/node_modules/@dalcode/dal-office/src/render/table-layout.js +1 -0
  159. package/dist/node_modules/@dalcode/dal-office/src/render/xlsx-chart.d.ts +24 -0
  160. package/dist/node_modules/@dalcode/dal-office/src/render/xlsx-chart.js +1 -0
  161. package/dist/node_modules/@dalcode/dal-office/src/render/xlsx.d.ts +9 -0
  162. package/dist/node_modules/@dalcode/dal-office/src/render/xlsx.js +1 -1
  163. package/dist/node_modules/@dalcode/dal-office/src/scratchpad.d.ts +2 -0
  164. package/dist/node_modules/@dalcode/dal-office/src/scratchpad.js +1 -1
  165. package/dist/node_modules/@dalcode/dal-office/src/table-stats.js +2 -0
  166. package/dist/node_modules/@dalcode/dal-office/src/tools/chart-generate.js +4 -3
  167. package/dist/node_modules/@dalcode/dal-office/src/tools/doc-generate.js +2 -3
  168. package/dist/node_modules/@dalcode/dal-office/src/tools/docx-edit.js +5 -5
  169. package/dist/node_modules/@dalcode/dal-office/src/tools/drawio-generate.js +2 -3
  170. package/dist/node_modules/@dalcode/dal-office/src/tools/md-generate.js +2 -3
  171. package/dist/node_modules/@dalcode/dal-office/src/tools/ppt-generate.js +5 -3
  172. package/dist/node_modules/@dalcode/dal-office/src/tools/ppt-plan.js +4 -2
  173. package/dist/node_modules/@dalcode/dal-office/src/tools/pptx-edit.js +5 -5
  174. package/dist/node_modules/@dalcode/dal-office/src/tools/read-file.js +4 -3
  175. package/dist/node_modules/@dalcode/dal-office/src/tools/render-page.js +4 -0
  176. package/dist/node_modules/@dalcode/dal-office/src/tools/sheet-generate.js +3 -3
  177. package/dist/node_modules/@dalcode/dal-office/src/tools/xlsx-edit.js +3 -3
  178. package/dist/node_modules/@dalcode/dal-pi-kit/dist/i18n.js +15 -15
  179. package/dist/node_modules/@dalcode/dal-pi-kit/dist/index.js +1 -1
  180. package/dist/node_modules/@dalcode/dal-pi-kit/dist/project-size.js +1 -0
  181. package/dist/node_modules/@dalcode/dal-pi-kit/package.json +1 -1
  182. package/dist/node_modules/@dalcode/dal-pi-kit/src/i18n.js +15 -15
  183. package/dist/node_modules/@dalcode/dal-pi-kit/src/index.js +1 -1
  184. package/dist/node_modules/@dalcode/dal-pi-kit/src/project-size.js +1 -0
  185. package/dist/node_modules/@dalcode/dal-plugins/package.json +4 -5
  186. package/dist/node_modules/@dalcode/dal-plugins/src/index.js +11 -11
  187. package/dist/node_modules/@dalcode/dal-plugins/src/manage.js +7 -7
  188. package/dist/node_modules/@dalcode/dal-recall/package.json +2 -2
  189. package/dist/node_modules/@dalcode/dal-recall/src/index.js +1 -1
  190. package/dist/node_modules/@dalcode/dal-remote/package.json +2 -2
  191. package/dist/node_modules/@dalcode/dal-review/package.json +3 -3
  192. package/dist/node_modules/@dalcode/dal-rewind/package.json +2 -2
  193. package/dist/node_modules/@dalcode/dal-rewind/src/commands.js +1 -1
  194. package/dist/node_modules/@dalcode/dal-rewind/src/core.d.ts +2 -0
  195. package/dist/node_modules/@dalcode/dal-rewind/src/core.js +6 -6
  196. package/dist/node_modules/@dalcode/dal-rewind/src/index.js +1 -1
  197. package/dist/node_modules/@dalcode/dal-rewind/src/state.js +1 -1
  198. package/dist/node_modules/@dalcode/dal-router/package.json +9 -9
  199. package/dist/node_modules/@dalcode/dal-router/src/commands.js +8 -9
  200. package/dist/node_modules/@dalcode/dal-router/src/config.d.ts +4 -36
  201. package/dist/node_modules/@dalcode/dal-router/src/config.js +2 -2
  202. package/dist/node_modules/@dalcode/dal-router/src/index.js +2 -4
  203. package/dist/node_modules/@dalcode/dal-router/src/notice.js +1 -0
  204. package/dist/node_modules/@dalcode/dal-router/src/roles/deliverables.js +4 -0
  205. package/dist/node_modules/@dalcode/dal-router/src/roles/index.js +10 -8
  206. package/dist/node_modules/@dalcode/dal-router/src/roles/planner.js +5 -0
  207. package/dist/node_modules/@dalcode/dal-router/src/roles/prompts.js +28 -17
  208. package/dist/node_modules/@dalcode/dal-router/src/roles/signals.js +2 -2
  209. package/dist/node_modules/@dalcode/dal-router/src/runtime.d.ts +0 -13
  210. package/dist/node_modules/@dalcode/dal-router/src/runtime.js +1 -1
  211. package/dist/node_modules/@dalcode/dal-router/src/subagent.js +1 -1
  212. package/dist/node_modules/@dalcode/dal-router/src/task-shape.d.ts +8 -0
  213. package/dist/node_modules/@dalcode/dal-router/src/task-shape.js +1 -0
  214. package/dist/node_modules/@dalcode/dal-rtk/package.json +2 -2
  215. package/dist/node_modules/@dalcode/dal-skills/package.json +4 -3
  216. package/dist/node_modules/@dalcode/dal-skills/src/bundled/chart-design/SKILL.md +35 -0
  217. package/dist/node_modules/@dalcode/dal-skills/src/bundled/dal-slides/SKILL.md +17 -9
  218. package/dist/node_modules/@dalcode/dal-skills/src/bundled/diagram-design/SKILL.md +7 -5
  219. package/dist/node_modules/@dalcode/dal-skills/src/bundled/poster-design/SKILL.md +8 -6
  220. package/dist/node_modules/@dalcode/dal-skills/src/bundled/print-design/SKILL.md +21 -8
  221. package/dist/node_modules/@dalcode/dal-skills/src/bundled/visual-kit/diagram.html +1 -1
  222. package/dist/node_modules/@dalcode/dal-skills/src/bundled/visual-kit/mindmap.html +1 -1
  223. package/dist/node_modules/@dalcode/dal-skills/src/bundled/visual-kit/posters/event-poster.html +1 -1
  224. package/dist/node_modules/@dalcode/dal-skills/src/bundled/visual-kit/posters/poster.css +1 -1
  225. package/dist/node_modules/@dalcode/dal-skills/src/bundled/visual-kit/posters/square-card.html +1 -1
  226. package/dist/node_modules/@dalcode/dal-skills/src/bundled/visual-kit/posters/wechat-cover.html +1 -1
  227. package/dist/node_modules/@dalcode/dal-skills/src/bundled/visual-kit/posters/xhs-card.html +1 -1
  228. package/dist/node_modules/@dalcode/dal-skills/src/bundled/visual-kit/posters/xhs-cover.html +8 -5
  229. package/dist/node_modules/@dalcode/dal-skills/src/bundled/visual-kit/print/letter.html +1 -1
  230. package/dist/node_modules/@dalcode/dal-skills/src/bundled/visual-kit/print/report.html +1 -1
  231. package/dist/node_modules/@dalcode/dal-skills/src/bundled/visual-kit/print/resume.html +7 -3
  232. package/dist/node_modules/@dalcode/dal-skills/src/bundled/web-design/SKILL.md +4 -4
  233. package/dist/node_modules/@dalcode/dal-skills/src/bundled.js +1 -1
  234. package/dist/node_modules/@dalcode/dal-skills/src/catalog.js +3 -2
  235. package/dist/node_modules/@dalcode/dal-skills/src/hint.js +1 -0
  236. package/dist/node_modules/@dalcode/dal-skills/src/index.js +13 -14
  237. package/dist/node_modules/@dalcode/dal-skills/src/search.js +1 -1
  238. package/dist/node_modules/@dalcode/dal-statusline/package.json +2 -2
  239. package/dist/node_modules/@dalcode/dal-structured/package.json +2 -2
  240. package/dist/node_modules/@dalcode/dal-subagent/package.json +5 -5
  241. package/dist/node_modules/@dalcode/dal-subagent/src/background.js +10 -10
  242. package/dist/node_modules/@dalcode/dal-subagent/src/index.js +18 -20
  243. package/dist/node_modules/@dalcode/dal-sync/LICENSE +21 -0
  244. package/dist/node_modules/@dalcode/dal-sync/package.json +35 -0
  245. package/dist/node_modules/@dalcode/dal-sync/src/client.js +1 -0
  246. package/dist/node_modules/@dalcode/dal-sync/src/core.js +2 -0
  247. package/dist/node_modules/@dalcode/dal-sync/src/index.js +4 -0
  248. package/dist/node_modules/@dalcode/dal-telemetry/package.json +4 -3
  249. package/dist/node_modules/@dalcode/dal-telemetry/src/config.js +3 -3
  250. package/dist/node_modules/@dalcode/dal-telemetry/src/failure-queue.js +3 -3
  251. package/dist/node_modules/@dalcode/dal-telemetry/src/failure-reporting.js +3 -5
  252. package/dist/node_modules/@dalcode/dal-terminal/package.json +2 -2
  253. package/dist/node_modules/@dalcode/dal-tool-catalog/package.json +3 -2
  254. package/dist/node_modules/@dalcode/dal-tool-catalog/src/groups.js +1 -1
  255. package/dist/node_modules/@dalcode/dal-tool-catalog/src/index.js +4 -4
  256. package/dist/node_modules/@dalcode/dal-tool-catalog/src/repair-hook.js +2 -2
  257. package/dist/node_modules/@dalcode/dal-tool-catalog/src/repair.js +2 -2
  258. package/dist/node_modules/@dalcode/dal-usage/package.json +2 -2
  259. package/dist/node_modules/@dalcode/dal-web/package.json +3 -3
  260. package/dist/node_modules/@dalcode/dal-workflow/package.json +2 -2
  261. package/dist/node_modules/@dalcode/dal-workflow/src/announce-check.js +3 -1
  262. package/dist/node_modules/@dalcode/dal-workflow/src/deliverable-scope.js +1 -0
  263. package/dist/node_modules/@dalcode/dal-workflow/src/index.js +4 -4
  264. package/dist/node_modules/@dalcode/dal-workflow/src/test-proof-note.js +3 -0
  265. package/dist/node_modules/@dalcode/dal-workflow/src/todo-snapshot.js +2 -2
  266. package/dist/node_modules/@dalcode/dal-workflow/src/todo.js +4 -4
  267. package/dist/node_modules/@dalcode/dal-workflow/src/truncation-check.js +1 -0
  268. package/dist/node_modules/@dalcode/dal-workflow/src/working-contract.js +1 -1
  269. package/dist/node_modules/@dalcode/deepailab/package.json +3 -3
  270. package/dist/node_modules/@dalcode/deepailab/src/index.js +3 -3
  271. package/dist/node_modules/@earendil-works/pi-agent-core/README.md +5 -0
  272. package/dist/node_modules/@earendil-works/pi-agent-core/dist/agent-loop.d.ts +2 -1
  273. package/dist/node_modules/@earendil-works/pi-agent-core/dist/agent-loop.js +1 -1
  274. package/dist/node_modules/@earendil-works/pi-agent-core/dist/agent.d.ts +3 -1
  275. package/dist/node_modules/@earendil-works/pi-agent-core/dist/agent.js +1 -1
  276. package/dist/node_modules/@earendil-works/pi-agent-core/dist/types.d.ts +2 -0
  277. package/dist/node_modules/@earendil-works/pi-agent-core/package.json +2 -2
  278. package/dist/node_modules/@earendil-works/pi-ai/README.md +78 -3
  279. package/dist/node_modules/@earendil-works/pi-ai/dist/api/anthropic-messages.js +5 -5
  280. package/dist/node_modules/@earendil-works/pi-ai/dist/api/azure-openai-responses.js +1 -1
  281. package/dist/node_modules/@earendil-works/pi-ai/dist/api/bedrock-converse-stream.js +1 -1
  282. package/dist/node_modules/@earendil-works/pi-ai/dist/api/classifier-shared.js +1 -1
  283. package/dist/node_modules/@earendil-works/pi-ai/dist/api/cloudflare-workers-ai-system-one.js +1 -1
  284. package/dist/node_modules/@earendil-works/pi-ai/dist/api/google-generative-ai.js +1 -1
  285. package/dist/node_modules/@earendil-works/pi-ai/dist/api/google-shared.js +1 -1
  286. package/dist/node_modules/@earendil-works/pi-ai/dist/api/google-vertex.js +1 -1
  287. package/dist/node_modules/@earendil-works/pi-ai/dist/api/lazy.d.ts +6 -2
  288. package/dist/node_modules/@earendil-works/pi-ai/dist/api/lazy.js +1 -1
  289. package/dist/node_modules/@earendil-works/pi-ai/dist/api/llama-cpp-classify.js +5 -5
  290. package/dist/node_modules/@earendil-works/pi-ai/dist/api/mistral-conversations.js +2 -2
  291. package/dist/node_modules/@earendil-works/pi-ai/dist/api/openai-codex-responses.js +6 -6
  292. package/dist/node_modules/@earendil-works/pi-ai/dist/api/openai-completions.js +5 -5
  293. package/dist/node_modules/@earendil-works/pi-ai/dist/api/openai-responses-shared.js +10 -5
  294. package/dist/node_modules/@earendil-works/pi-ai/dist/api/openai-responses.js +3 -2
  295. package/dist/node_modules/@earendil-works/pi-ai/dist/api/openrouter-images.js +1 -1
  296. package/dist/node_modules/@earendil-works/pi-ai/dist/api/pi-messages.js +4 -4
  297. package/dist/node_modules/@earendil-works/pi-ai/dist/api/simple-options.js +1 -1
  298. package/dist/node_modules/@earendil-works/pi-ai/dist/api/system-one-shared.js +1 -1
  299. package/dist/node_modules/@earendil-works/pi-ai/dist/api/typesafe-system-one.js +1 -1
  300. package/dist/node_modules/@earendil-works/pi-ai/dist/cli.js +0 -0
  301. package/dist/node_modules/@earendil-works/pi-ai/dist/index.d.ts +2 -0
  302. package/dist/node_modules/@earendil-works/pi-ai/dist/index.js +1 -1
  303. package/dist/node_modules/@earendil-works/pi-ai/dist/models.d.ts +4 -0
  304. package/dist/node_modules/@earendil-works/pi-ai/dist/models.js +1 -1
  305. package/dist/node_modules/@earendil-works/pi-ai/dist/providers/compat-schema.d.ts +180 -0
  306. package/dist/node_modules/@earendil-works/pi-ai/dist/providers/compat-schema.js +1 -1
  307. package/dist/node_modules/@earendil-works/pi-ai/dist/providers/data/.manifest.json +1 -1
  308. package/dist/node_modules/@earendil-works/pi-ai/dist/providers/data/cloudflare-workers-ai.json +1 -1
  309. package/dist/node_modules/@earendil-works/pi-ai/dist/providers/data/fireworks.json +1 -1
  310. package/dist/node_modules/@earendil-works/pi-ai/dist/providers/data/huggingface.json +1 -1
  311. package/dist/node_modules/@earendil-works/pi-ai/dist/providers/data/kimi-coding.json +1 -1
  312. package/dist/node_modules/@earendil-works/pi-ai/dist/providers/data/minimax-cn.json +1 -1
  313. package/dist/node_modules/@earendil-works/pi-ai/dist/providers/data/minimax.json +1 -1
  314. package/dist/node_modules/@earendil-works/pi-ai/dist/providers/data/mistral.json +1 -1
  315. package/dist/node_modules/@earendil-works/pi-ai/dist/providers/data/moonshotai-cn.json +1 -1
  316. package/dist/node_modules/@earendil-works/pi-ai/dist/providers/data/moonshotai.json +1 -1
  317. package/dist/node_modules/@earendil-works/pi-ai/dist/providers/data/nvidia.json +1 -1
  318. package/dist/node_modules/@earendil-works/pi-ai/dist/providers/data/openai-codex.json +1 -1
  319. package/dist/node_modules/@earendil-works/pi-ai/dist/providers/data/opencode-go.json +1 -1
  320. package/dist/node_modules/@earendil-works/pi-ai/dist/providers/data/opencode.json +1 -1
  321. package/dist/node_modules/@earendil-works/pi-ai/dist/providers/data/openrouter.json +1 -1
  322. package/dist/node_modules/@earendil-works/pi-ai/dist/providers/data/typesafe.json +1 -1
  323. package/dist/node_modules/@earendil-works/pi-ai/dist/providers/data/vercel-ai-gateway.json +1 -1
  324. package/dist/node_modules/@earendil-works/pi-ai/dist/providers/model-schema.js +1 -1
  325. package/dist/node_modules/@earendil-works/pi-ai/dist/telemetry.d.ts +286 -0
  326. package/dist/node_modules/@earendil-works/pi-ai/dist/telemetry.js +1 -0
  327. package/dist/node_modules/@earendil-works/pi-ai/dist/types.d.ts +20 -4
  328. package/dist/node_modules/@earendil-works/pi-ai/dist/utils/event-stream.d.ts +4 -0
  329. package/dist/node_modules/@earendil-works/pi-ai/dist/utils/event-stream.js +1 -1
  330. package/dist/node_modules/@earendil-works/pi-ai/dist/utils/identity.d.ts +27 -0
  331. package/dist/node_modules/@earendil-works/pi-ai/dist/utils/identity.js +1 -0
  332. package/dist/node_modules/@earendil-works/pi-ai/dist/utils/overflow.js +1 -1
  333. package/dist/node_modules/@earendil-works/pi-ai/dist/utils/provider-retry.js +1 -1
  334. package/dist/node_modules/@earendil-works/pi-ai/dist/utils/retry.js +1 -1
  335. package/dist/node_modules/@earendil-works/pi-ai/dist/utils/transcript.d.ts +3 -2
  336. package/dist/node_modules/@earendil-works/pi-ai/dist/utils/transcript.js +2 -2
  337. package/dist/node_modules/@earendil-works/pi-ai/dist/utils/version.d.ts +1 -0
  338. package/dist/node_modules/@earendil-works/pi-ai/dist/utils/version.js +1 -0
  339. package/dist/node_modules/@earendil-works/pi-ai/package.json +2 -2
  340. package/dist/node_modules/@earendil-works/pi-codemode/package.json +1 -1
  341. package/dist/node_modules/@earendil-works/pi-coding-agent/package.json +1 -1
  342. package/dist/node_modules/@earendil-works/pi-mcp/CHANGELOG.md +2 -0
  343. package/dist/node_modules/@earendil-works/pi-mcp/package.json +1 -1
  344. package/dist/node_modules/@earendil-works/pi-telemetry/README.md +167 -21
  345. package/dist/node_modules/@earendil-works/pi-telemetry/dist/index.d.ts +77 -2
  346. package/dist/node_modules/@earendil-works/pi-telemetry/dist/index.js +1 -1
  347. package/dist/node_modules/@earendil-works/pi-telemetry/dist/memory.d.ts +35 -2
  348. package/dist/node_modules/@earendil-works/pi-telemetry/dist/memory.js +1 -1
  349. package/dist/node_modules/@earendil-works/pi-telemetry/dist/metrics.d.ts +70 -0
  350. package/dist/node_modules/@earendil-works/pi-telemetry/dist/metrics.js +1 -0
  351. package/dist/node_modules/@earendil-works/pi-telemetry/dist/noop.d.ts +5 -2
  352. package/dist/node_modules/@earendil-works/pi-telemetry/dist/noop.js +1 -1
  353. package/dist/node_modules/@earendil-works/pi-telemetry/dist/render.js +2 -0
  354. package/dist/node_modules/@earendil-works/pi-telemetry/dist/testing/conformance.js +1 -1
  355. package/dist/node_modules/@earendil-works/pi-telemetry/package.json +6 -1
  356. package/dist/node_modules/@earendil-works/pi-tui/dist/autocomplete.js +2 -2
  357. package/dist/node_modules/@earendil-works/pi-tui/dist/components/markdown.js +8 -7
  358. package/dist/node_modules/@earendil-works/pi-tui/dist/stdin-buffer.d.ts +3 -0
  359. package/dist/node_modules/@earendil-works/pi-tui/dist/stdin-buffer.js +1 -1
  360. package/dist/node_modules/@earendil-works/pi-tui/dist/terminal-image.js +1 -1
  361. package/dist/node_modules/@earendil-works/pi-tui/dist/terminal.d.ts +3 -0
  362. package/dist/node_modules/@earendil-works/pi-tui/dist/terminal.js +1 -1
  363. package/dist/node_modules/@earendil-works/pi-tui/dist/tui-alt-screen.d.ts +2 -0
  364. package/dist/node_modules/@earendil-works/pi-tui/dist/tui-alt-screen.js +4 -4
  365. package/dist/node_modules/@earendil-works/pi-tui/dist/tui.d.ts +3 -0
  366. package/dist/node_modules/@earendil-works/pi-tui/dist/tui.js +2 -2
  367. package/dist/node_modules/@earendil-works/pi-tui/package.json +3 -2
  368. package/dist/package-manager-cli.js +9 -9
  369. package/dist/sdk/index.d.ts +2 -2
  370. package/dist/sdk/index.js +1 -1
  371. package/dist/sdk/office.d.ts +1 -1
  372. package/dist/sdk/office.js +1 -1
  373. package/dist/sdk/router.d.ts +4 -4
  374. package/dist/sdk/router.js +1 -1
  375. package/dist/utils/clipboard-command.js +1 -1
  376. package/dist/utils/pi-user-agent.js +1 -1
  377. package/dist/utils/shell.js +2 -2
  378. package/dist/utils/tools-manager.js +1 -1
  379. package/examples/extensions/custom-provider-gitlab-duo/package.json +1 -1
  380. package/examples/extensions/gondolin/package-lock.json +2 -2
  381. package/examples/extensions/gondolin/package.json +1 -1
  382. package/examples/extensions/sandbox/package-lock.json +2 -2
  383. package/examples/extensions/sandbox/package.json +1 -1
  384. package/examples/extensions/with-deps/package-lock.json +2 -2
  385. package/examples/extensions/with-deps/package.json +1 -1
  386. package/npm-shrinkwrap.json +15 -2
  387. package/package.json +6 -2
  388. package/dist/core/provider-attribution.js +0 -1
  389. package/dist/node_modules/@dalcode/dal-guard/src/review.js +0 -3
  390. package/dist/node_modules/@dalcode/dal-office/src/scenes.js +0 -1
  391. package/dist/node_modules/@dalcode/dal-plugins/src/rank.js +0 -4
  392. package/dist/node_modules/@dalcode/dal-router/src/assist.js +0 -4
  393. package/dist/node_modules/@dalcode/dal-router/src/compact-defer.js +0 -3
  394. package/dist/node_modules/@dalcode/dal-router/src/jev.d.ts +0 -52
  395. package/dist/node_modules/@dalcode/dal-router/src/jev.js +0 -5
  396. package/dist/node_modules/@dalcode/dal-router/src/router.d.ts +0 -32
  397. package/dist/node_modules/@dalcode/dal-router/src/router.js +0 -1
  398. package/dist/node_modules/@dalcode/dal-router/src/services.js +0 -1
  399. package/dist/node_modules/@dalcode/dal-subagent/src/role-pick.js +0 -2
  400. package/dist/node_modules/@earendil-works/pi-ai/dist/utils/pi-user-agent.js +0 -1
@@ -6,6 +6,8 @@ This package provides:
6
6
 
7
7
  - an explicit, callback-based `TelemetryContext` / `TelemetrySpan` contract;
8
8
  - a shared `NOOP_TELEMETRY_CONTEXT`;
9
+ - opaque cross-process propagation and span links;
10
+ - counters, up-down counters, histograms, and typed metric schemas;
9
11
  - a reference `InMemoryTelemetryContext` implementation;
10
12
  - serializable schema definitions with inferred TypeScript types;
11
13
  - no exporter, global current-span state, or dependency on a telemetry backend.
@@ -18,8 +20,11 @@ Applications can use the in-memory reference or provide an adapter for OpenTelem
18
20
  - [Telemetry Concepts](#telemetry-concepts)
19
21
  - [Core Context API](#core-context-api)
20
22
  - [Adapter Contract](#adapter-contract)
23
+ - [Propagation and Span Links](#propagation-and-span-links)
24
+ - [Metrics](#metrics)
21
25
  - [No-op Context](#no-op-context)
22
26
  - [In-Memory Reference Adapter](#in-memory-reference-adapter)
27
+ - [Stored Telemetry](#stored-telemetry)
23
28
  - [Adapter Conformance](#adapter-conformance)
24
29
  - [Typed Schemas](#typed-schemas)
25
30
  - [Start and Completion Attributes](#start-and-completion-attributes)
@@ -59,11 +64,11 @@ example.account.load span
59
64
  └─ status: ok final outcome
60
65
  ```
61
66
 
62
- A span is diagnostic data, not business state. Recording it must not change whether the account load runs, succeeds, fails, or is persisted. An adapter translates these generic concepts into the corresponding concepts used by OpenTelemetry, Sentry, logs, or another backend.
67
+ A span is diagnostic data, not business state. An adapter translates these generic concepts into the corresponding concepts used by OpenTelemetry, Sentry, logs, or another backend.
63
68
 
64
69
  ## Core Context API
65
70
 
66
- A `TelemetryContext` starts a span around a callback. The callback receives a `TelemetrySpan`, which is also the explicit parent context for child spans.
71
+ A `TelemetryContext` starts a span around a callback. The callback receives a `TelemetrySpan`, which is also the explicit parent context for child spans. Contexts optionally expose their adapter's `metrics?: TelemetryMetrics` and `propagation?: TelemetryPropagation` capabilities; child spans and extracted parents carry the same capabilities. A `TelemetryContext` adapter starts root spans; hosts retain this adapter. Invocation contexts and pi-ai request options carry a `TelemetrySpan`, never the adapter. A tracing adapter that only implements `startSpan()` is still valid.
67
72
 
68
73
  ```typescript
69
74
  import {
@@ -117,20 +122,121 @@ return telemetryContext.startSpan({ name: 'example.save' }, async (span) => {
117
122
 
118
123
  ## Adapter Contract
119
124
 
120
- An adapter implements `TelemetryContext` and bridges the generic API to its backend. It must:
125
+ An adapter implements `TelemetryContext` and bridges the generic API to its backend. Typed inputs are trusted; malformed inputs have unspecified behavior. Adapters are not required to validate inputs or suppress adapter/backend failures.
126
+
127
+ The callback and recording contract is:
121
128
 
122
129
  - create a child span and invoke the callback synchronously, exactly once;
130
+ - expose optional metric and propagation capabilities on its contexts, child spans, and extracted parents, including inert fallback spans;
123
131
  - preserve the callback's returned value and rejection value, returning a promise rejected with the same value after a synchronous throw;
124
132
  - keep the native span open until a returned promise settles;
125
133
  - treat normal completion as `ok` and throws/rejections as errors unless an explicit status was set;
126
134
  - make repeated `setStatus()` calls last-write-wins;
127
135
  - merge `setAttributes()` calls, with later defined values replacing earlier values and `undefined` ignored;
128
- - make recording methods synchronous, passive, and non-throwing;
129
- - ignore calls made after settlement;
130
- - ignore a failed recording call atomically, suppress backend failures, and still execute the business callback exactly once.
136
+ - make recording methods synchronous;
137
+ - ignore calls made after settlement.
131
138
 
132
139
  Adapters may activate backend-native ambient context internally for automatic instrumentation, but pi code always propagates the parent through `TelemetryContext` arguments. Exporter buffering, flushing, sampling, backend IDs, and backend-specific context objects belong to the adapter. Use the [adapter conformance suite](#adapter-conformance) to check these observable semantics.
133
140
 
141
+ ## Propagation and Span Links
142
+
143
+ An adapter may also implement `TelemetryPropagation`. Expose it through `context.propagation` so code can inject or extract using the context it already has. The root, spans, and extracted parents share the adapter's capability object:
144
+
145
+ ```typescript
146
+ interface TelemetryPropagation {
147
+ inject(context: TelemetryContext): TelemetryCarrier | undefined;
148
+ extract(carrier: TelemetryCarrier | undefined): TelemetryContext;
149
+ }
150
+ type TelemetryCarrier = Record<string, string>;
151
+ ```
152
+
153
+ A carrier is an opaque JSON-safe string map. Adapters own its format; W3C `traceparent` and `tracestate` fit without requiring them. Transport code sends only the carrier, never a context or span:
154
+
155
+ ```typescript
156
+ const caller = new InMemoryTelemetryContext();
157
+ const provider = new InMemoryTelemetryContext();
158
+ await caller.startSpan({ name: 'rpc.client' }, async (span) => {
159
+ const wire = JSON.stringify(caller.inject(span));
160
+ await provider.extract(JSON.parse(wire)).startSpan(
161
+ { name: 'rpc.server' },
162
+ (serverSpan) => handleRequest(serverSpan),
163
+ );
164
+ });
165
+ ```
166
+
167
+ Injection returns a detached carrier or `undefined` for roots, no-op contexts, and unsupported contexts. Extraction returns a receiver-owned parent. Absent or unknown carriers fall back to the adapter's root. Extraction checks only that required carrier keys contain strings; identifiers are opaque and need no format validation. Both methods are synchronous. Trace metadata is diagnostics, never authorization. Transport boundaries own carrier size limits.
168
+
169
+ A link relates work without changing its parent. Use `SpanOptions.links` when the target is known at creation, or `span.addLink()` after the span has started:
170
+
171
+ ```typescript
172
+ await telemetry.startSpan(
173
+ { name: 'activation', links: [{ context: firstGetter, attributes: { reason: 'trigger' } }] },
174
+ async (activation) => {
175
+ laterGetter.addLink({ context: activation });
176
+ await activate();
177
+ },
178
+ );
179
+ ```
180
+
181
+ Link targets are `TelemetryContext` handles, including spans and extracted remote parents. For a remote link, first call `adapter.extract(carrier)`. A settled target remains linkable and injectable; a settled source ignores `addLink()`. Links append in order, copy attributes, and ignore root, no-op, or unsupported contexts. The typed span starter's callback also supports `addLink()`; initial links use the low-level `startSpan()` API.
182
+
183
+ `NOOP_TELEMETRY_PROPAGATION` ignores its arguments: injection returns `undefined`, extraction returns `NOOP_TELEMETRY_CONTEXT`.
184
+
185
+ ## Metrics
186
+
187
+ An adapter may implement `TelemetryMetrics` alongside `TelemetryContext` and `TelemetryPropagation`. Applications configure one adapter, not separate backends for each capability. Expose the shared capability through `context.metrics`; child spans retain it, so nested model calls can record metrics without a separate configuration option. The in-memory adapter also implements the factory methods directly:
188
+
189
+ ```typescript
190
+ const bytes = telemetry.counter('network.bytes', {
191
+ description: 'Encoded WebSocket bytes', unit: 'By',
192
+ });
193
+ bytes.add(encodedSize, { direction: 'out' });
194
+
195
+ const active = telemetry.upDownCounter('calls.active');
196
+ active.add(1);
197
+ active.add(-1);
198
+
199
+ const duration = telemetry.histogram('call.duration', {
200
+ unit: 'ms', boundaries: [1, 10, 100, 1000],
201
+ });
202
+ duration.record(elapsedMs, { method: 'read' }, currentSpan);
203
+ ```
204
+
205
+ Factories take an instrument name and optional `InstrumentOptions` (`description`, `unit`). Histograms additionally accept `HistogramOptions.boundaries`: callers supply finite, strictly increasing bucket hints. Backends own aggregation and may translate these hints. Callers are responsible for finite measurements and non-negative counter increments; up-down counters and histograms may use signed values. Histogram `record(value, attributes?, context?)` optionally correlates a measurement with a span, called an exemplar. Counter `add(value, attributes?)` has no context argument.
206
+
207
+ Factories and recording methods are synchronous and trust typed inputs. Adapters need not validate measurement values, metadata, attributes, or boundaries; malformed inputs have unspecified behavior. `NOOP_TELEMETRY_METRICS` returns shared frozen instruments that discard measurements. Record only values already available to business code; do not serialize or measure extra data for telemetry.
208
+
209
+ Use only low-cardinality attributes: bounded values such as direction or method, not request IDs, user IDs, prompts, or arbitrary paths. The low-level attribute bag remains open; instrumentation owns this policy, not backend-specific heuristics.
210
+
211
+ ### Typed metric schemas
212
+
213
+ `TelemetrySchemaDefinition.metrics` optionally declares instrument names, kinds, metadata, and required/optional attributes. `createTypedMetrics()` combines one or more schemas and rejects duplicate metric names, incorrect instrument kinds, unknown attributes, and missing required attributes at compile time:
214
+
215
+ ```typescript
216
+ const schema = defineTelemetrySchema({
217
+ version: 1,
218
+ spans: {},
219
+ metrics: {
220
+ 'network.bytes': {
221
+ kind: 'counter', description: 'Encoded bytes', unit: 'By',
222
+ attributes: {
223
+ direction: {
224
+ type: 'string', required: true, values: ['in', 'out'],
225
+ description: 'Direction', cardinality: 'low',
226
+ },
227
+ },
228
+ },
229
+ },
230
+ } as const);
231
+
232
+ const metrics = createTypedMetrics(telemetry, [schema]);
233
+ metrics.counter('network.bytes').add(encodedSize, { direction: 'out' });
234
+ ```
235
+
236
+ Metric definitions use `kind: 'counter' | 'upDownCounter' | 'histogram'`; only histograms may declare `boundaries`. Metric attributes use the same scalar/array definitions as spans, but reject `cardinality: 'high'`. Omitting the cardinality annotation does not waive the low-cardinality policy. Unlike the typed span starter, the metric helper reads and retains schema instrument metadata at runtime. It performs no runtime attribute validation.
237
+
238
+ `InMemoryTelemetryContext.getMetrics()` returns ordered, detached `RecordedTelemetryMeasurement` snapshots: `kind`, `name`, optional `description`/`unit`/`boundaries`, `value`, copied `attributes`, and a carrier-shaped exemplar `context` or `null`. This is a measurement log, not aggregated counters or buckets; storage is unbounded. Measurement times are retained privately for store queries, not exposed in these snapshots.
239
+
134
240
  ## No-op Context
135
241
 
136
242
  Use `NOOP_TELEMETRY_CONTEXT` when telemetry is optional:
@@ -149,6 +255,7 @@ The no-op context:
149
255
  - invokes callbacks synchronously;
150
256
  - preserves returned values and asynchronous rejections, and converts a synchronous throw to a promise rejected with the same value;
151
257
  - uses one shared frozen inert span, including for nested spans;
258
+ - exposes `NOOP_TELEMETRY_METRICS` and `NOOP_TELEMETRY_PROPAGATION` on its root and spans;
152
259
  - does not inspect or retain names, attributes, events, or statuses.
153
260
 
154
261
  ## In-Memory Reference Adapter
@@ -171,10 +278,35 @@ await telemetry.startSpan(
171
278
  console.log(telemetry.getSpans());
172
279
  ```
173
280
 
174
- `getSpans()` returns detached snapshots in span-start order. Each `RecordedTelemetrySpan` contains a deterministic numeric ID, parent ID, merged attributes, ordered events, final status, settlement state, and deterministic end sequence. It records no timestamps.
281
+ `getSpans()` returns detached snapshots in span-start order. Each `RecordedTelemetrySpan` contains a deterministic numeric ID, local parent ID, carrier-shaped `context` and `parentContext` snapshots, ordered `links`, merged attributes, ordered events, final status, settlement state, and deterministic end sequence. These normalized snapshots expose no timestamps. A remote parent has `parentId: null` but a non-null `parentContext`; a root has both null. A `RecordedTelemetryLink` contains a target carrier and copied attributes.
282
+
283
+ The adapter implements `TelemetryPropagation` with its own small carrier codec: a unique recorder scope, a deterministic numeric span ID, and an inherited trace ID. The carrier survives JSON round trips and works across independent processes without a shared registry. Its keys are an implementation detail, not a public wire format for other adapters.
175
284
 
176
285
  The adapter is safe to use as an ordinary `TelemetryContext`, but storage is unbounded and process-local. Create a fresh instance to isolate tests or recording scopes, and do not capture sensitive attributes unless the caller's data policy allows them.
177
286
 
287
+ ## Stored Telemetry
288
+
289
+ `TelemetryStore` separates querying from recording. Both `InMemoryTelemetryContext` and `@earendil-works/chord/telemetry-sqlite` implement it:
290
+
291
+ - `findTraces(query?)` returns complete locally stored traces, newest trace start first. Filters include the earliest stored span's `name`, inclusive `startMin`/`startMax`, `errors: true`, and scalar `attributes`. All requested attributes must match one span, anywhere in the trace. Pages default to 20 traces; pass the returned opaque `cursor` with the same filters to continue. Equal start times are ordered by trace ID.
292
+ - `getTrace(traceId)` returns a trace or `undefined`.
293
+ - `findMetrics({ name, startMin?, startMax?, attributes? })` returns metric rows with count, sum, minimum, and maximum. Time bounds are inclusive interval-start times. The in-memory adapter maps each raw measurement to a count-one row in its ten-second interval; SQLite aggregates measurements per series and interval.
294
+
295
+ Only settled spans are returned. A trace ID is the root's globally unique span ID (`<recorder UUID>:<counter>`) and propagates with the parent identity. Stores return the spans available locally: remote or expired parents can be absent, and a child can appear before its parent settles. Pagination is not a snapshot across requests; late settlements and retention can change a trace's earliest stored span. SQLite reads committed rows without implicitly flushing.
296
+
297
+ `StoredSpan` includes epoch-millisecond `startedMs`/`endedMs`, event offsets in `timeMs`, and links carrying both target `traceId` and `spanId`. Duration uses a monotonic clock; wall clocks across processes may disagree. Merge spans from several stores by trace ID; parent relationships, not timestamp containment, define the tree.
298
+
299
+ Rendering is a separate subpath, kept out of the root entry graph:
300
+
301
+ ```typescript
302
+ import { renderTrace } from '@earendil-works/pi-telemetry/render';
303
+
304
+ const page = await telemetry.findTraces({ errors: true, limit: 10 });
305
+ for (const trace of page.traces) console.log(renderTrace(trace.spans));
306
+ ```
307
+
308
+ `renderTrace()` accepts stored spans, deduplicates IDs, treats absent parents as roots, and prints attributes, durations, statuses, event offsets, and cross-trace links. It never follows links or queries a store.
309
+
178
310
  ## Adapter Conformance
179
311
 
180
312
  `@earendil-works/pi-telemetry/testing` exports a runner-independent conformance suite modeled as grouped cases. A fixture supplies a fresh context and converts its backend's finished spans into normalized `RecordedTelemetrySpan` snapshots:
@@ -206,7 +338,7 @@ for (const group of new Set(conformance.map((testCase) => testCase.group))) {
206
338
  }
207
339
  ```
208
340
 
209
- The suite checks synchronous single admission, result and rejection identity, automatic and explicit status, attribute merging, event ordering, inert post-settlement calls, nested and concurrent parentage, and suppression of unreadable telemetry payload failures. `getSpans()` may flush an asynchronous exporter before returning. The testing subpath uses Node's assertion APIs; the root telemetry package remains runtime-neutral.
341
+ The suite checks capability identity on roots, child spans, extracted parents and inert spans, synchronous single admission, result and rejection identity, automatic and explicit status, attribute merging, event ordering, inert post-settlement calls, nested and concurrent parentage, and links. Fixtures may supply `propagation` to additionally check JSON round trips, multiple adapter hops, and root fallback for absent or unknown carriers. Fixtures may also supply `metrics` and `getMetrics()` to check ordered measurements, histogram exemplars, and input copying. It does not test malformed inputs or require suppression of adapter/backend failures. `getSpans()` may flush an asynchronous exporter before returning. The testing subpath uses Node's assertion APIs; the root telemetry package remains runtime-neutral.
210
342
 
211
343
  ## Typed Schemas
212
344
 
@@ -367,24 +499,20 @@ Adapters do not need to understand schema objects. Instrumentation helpers and t
367
499
  Package ownership is intentionally split:
368
500
 
369
501
  - `@earendil-works/pi-telemetry` owns the vendor-neutral contract, no-op and in-memory reference contexts, schema utilities, and adapter conformance suite;
370
- - `@earendil-works/pi-ai` accepts and propagates `telemetryContext` in provider request options but owns no telemetry schema;
371
- - `@earendil-works/pi-agent-core` owns and exports the pi AI-request and harness schemas, their combined readonly schema tuple, and typed span helpers.
502
+ - `@earendil-works/pi-ai` accepts a parent `TelemetrySpan` through `telemetry` in provider request options and exports `AI_TELEMETRY_SCHEMA` from its root and `./models` entry points;
503
+ - `@earendil-works/pi-durable` exports `DURABLE_TELEMETRY_SCHEMA` for short task-handler and submission spans, events, and metrics;
504
+ - `@earendil-works/pi-agent-core` retains its existing agent-loop and session instrumentation and schemas.
372
505
 
373
506
  ```typescript
374
- import {
375
- AGENT_TELEMETRY_SCHEMAS,
376
- AI_TELEMETRY_SCHEMA,
377
- HARNESS_TELEMETRY_SCHEMA,
378
- startAiSpan,
379
- startHarnessSpan,
380
- } from '@earendil-works/pi-agent-core';
507
+ import { AI_TELEMETRY_SCHEMA } from '@earendil-works/pi-ai/models';
508
+ import { DURABLE_TELEMETRY_SCHEMA } from '@earendil-works/pi-durable';
381
509
  ```
382
510
 
383
- The pi schemas use pi-owned `pi.ai.*`, `pi.harness.*`, and `pi.session.*` names. Adapters may translate them to backend conventions without changing the emitted pi vocabulary.
511
+ The AI and Durable schemas use pi-owned `pi.ai.*` and `pi.durable.*` names. Adapters may translate them to backend conventions without changing the emitted pi vocabulary.
384
512
 
385
513
  ## Security and Portability
386
514
 
387
- Telemetry is process-local diagnostics, not durable application state. Do not persist a `TelemetryContext`, `TelemetrySpan`, or backend-native trace object in records, messages, snapshots, or deferred handles.
515
+ Telemetry is diagnostics, not durable application state. Do not persist a `TelemetryContext`, `TelemetrySpan`, or backend-native trace object in records, messages, snapshots, or deferred handles. An injected `TelemetryCarrier` may cross a transport or be stored as optional diagnostic correlation data. Changing adapters may lose correlation; carriers are not application state.
388
516
 
389
517
  Attribute values are intentionally limited to primitive scalars and arrays. Domain instrumentation should avoid prompts, completions, tool arguments or output, file contents, provider payloads, headers, credentials, and free-form error details unless its schema and data policy explicitly allow them.
390
518
 
@@ -396,15 +524,30 @@ The package does not use `AsyncLocalStorage` or another runtime-specific ambient
396
524
 
397
525
  | Export | Purpose |
398
526
  |---|---|
399
- | `TelemetryContext` | Starts callback-managed child spans |
527
+ | `TelemetryContext` | Starts callback-managed child spans and optionally exposes adapter metrics/propagation |
400
528
  | `TelemetrySpan` | Records attributes, events, and status; also acts as a child context |
401
- | `SpanOptions` | Span name and optional start attributes |
529
+ | `SpanOptions` | Span name, optional start attributes and links |
530
+ | `SpanLink` | Context target and optional link attributes |
531
+ | `TelemetryCarrier` | Opaque JSON-safe string map |
532
+ | `TelemetryPropagation` | Optional adapter injection and extraction capability |
533
+ | `NOOP_TELEMETRY_PROPAGATION` | Shared passive propagation for disabled telemetry |
534
+ | `TelemetryMetrics` | Optional adapter instrument factories |
535
+ | `TelemetryCounter` / `TelemetryUpDownCounter` | Instruments with `add()` |
536
+ | `TelemetryHistogram` | Instrument with `record()` and optional exemplar context |
537
+ | `InstrumentOptions` / `HistogramOptions` | Description, unit, and histogram boundary hints |
538
+ | `NOOP_TELEMETRY_METRICS` | Shared passive metric instruments |
539
+ | `RecordedTelemetryMeasurement` | Captured measurement and optional exemplar |
402
540
  | `SpanAttributes` / `AttributeValue` | Open adapter-level attribute bag and supported values |
403
541
  | `SpanStatus` | Explicit `ok` or `error` status |
404
542
  | `NOOP_TELEMETRY_CONTEXT` | Shared passive context for disabled telemetry |
405
543
  | `InMemoryTelemetryContext` | Reference adapter with deterministic process-local recording |
406
544
  | `RecordedTelemetrySpan` | Normalized captured span snapshot |
407
545
  | `RecordedTelemetryEvent` | Normalized captured event snapshot |
546
+ | `RecordedTelemetryLink` | Captured target carrier and link attributes |
547
+ | `TelemetryStore` | Settled trace discovery, trace retrieval, and metric queries |
548
+ | `StoredSpan` / `StoredTrace` | Backend-independent timed span and trace snapshots |
549
+ | `TraceQuery` / `MetricQuery` | Trace filters, pagination, and metric filters |
550
+ | `StoredMetric` | Metric interval row with count, sum, minimum, and maximum |
408
551
 
409
552
  ### Schema definitions and inference
410
553
 
@@ -412,6 +555,9 @@ The package does not use `AsyncLocalStorage` or another runtime-specific ambient
412
555
  |---|---|
413
556
  | `defineTelemetrySchema()` | Typed identity helper for serializable schema data |
414
557
  | `createTypedSpanStarter()` | Binds a parent context to one or more schema vocabularies |
558
+ | `createTypedMetrics()` / `TypedTelemetryMetrics` | Binds metric names, kinds, metadata, and attributes to schemas |
559
+ | `TelemetryMetricDefinition` / `TelemetryMetricAttributeDefinition` | Serializable instrument metadata and low-cardinality attribute definitions |
560
+ | `SchemaTelemetryCounter` / `SchemaTelemetryHistogram` | Schema-constrained recording methods |
415
561
  | `TypedSpanStarter` | Exact starter type with recursively child-bound callbacks |
416
562
  | `TelemetrySchemaDefinition` | Top-level schema shape |
417
563
  | `TelemetrySpanDefinition` | Span metadata, parents, attributes, events, and status rule |
@@ -1,10 +1,21 @@
1
+ import type { TelemetryMetricDefinition, TelemetryMetrics } from "./metrics.ts";
1
2
  export type AttributeValue = string | number | boolean | readonly string[] | readonly number[] | readonly boolean[];
2
3
  export interface SpanAttributes {
3
4
  [name: string]: AttributeValue | undefined;
4
5
  }
6
+ export type TelemetryCarrier = Record<string, string>;
7
+ export interface TelemetryPropagation {
8
+ inject(context: TelemetryContext): TelemetryCarrier | undefined;
9
+ extract(carrier: TelemetryCarrier | undefined): TelemetryContext;
10
+ }
11
+ export interface SpanLink {
12
+ context: TelemetryContext;
13
+ attributes?: SpanAttributes;
14
+ }
5
15
  export interface SpanOptions {
6
16
  name: string;
7
17
  attributes?: SpanAttributes;
18
+ links?: readonly SpanLink[];
8
19
  }
9
20
  export type SpanStatus = {
10
21
  status: "ok";
@@ -15,15 +26,78 @@ export type SpanStatus = {
15
26
  message: string;
16
27
  };
17
28
  };
29
+ export interface StoredSpan {
30
+ readonly id: string;
31
+ readonly traceId: string;
32
+ readonly parentId?: string;
33
+ readonly name: string;
34
+ readonly startedMs: number;
35
+ readonly endedMs: number;
36
+ readonly attributes: SpanAttributes;
37
+ readonly events: readonly {
38
+ readonly name: string;
39
+ readonly timeMs: number;
40
+ readonly attributes: SpanAttributes;
41
+ }[];
42
+ readonly links: readonly {
43
+ readonly traceId: string;
44
+ readonly spanId: string;
45
+ readonly attributes?: SpanAttributes;
46
+ }[];
47
+ readonly status: SpanStatus;
48
+ }
49
+ export interface StoredTrace {
50
+ readonly traceId: string;
51
+ readonly spans: readonly StoredSpan[];
52
+ }
53
+ export interface TraceQuery {
54
+ readonly name?: string;
55
+ readonly attributes?: Readonly<Record<string, string | number | boolean>>;
56
+ readonly errors?: true;
57
+ readonly startMin?: number;
58
+ readonly startMax?: number;
59
+ readonly limit?: number;
60
+ readonly cursor?: string;
61
+ }
62
+ export interface MetricQuery {
63
+ readonly name: string;
64
+ readonly startMin?: number;
65
+ readonly startMax?: number;
66
+ readonly attributes?: Readonly<Record<string, string | number | boolean>>;
67
+ }
68
+ export interface StoredMetric {
69
+ readonly intervalMs: number;
70
+ readonly name: string;
71
+ readonly kind: "counter" | "upDownCounter" | "histogram";
72
+ readonly unit?: string;
73
+ readonly attributes: SpanAttributes;
74
+ readonly count: number;
75
+ readonly sum: number;
76
+ readonly min: number;
77
+ readonly max: number;
78
+ }
79
+ export interface TelemetryStore {
80
+ findTraces(query?: TraceQuery): Promise<{
81
+ traces: readonly StoredTrace[];
82
+ cursor?: string;
83
+ }>;
84
+ getTrace(traceId: string): Promise<StoredTrace | undefined>;
85
+ findMetrics(query: MetricQuery): Promise<readonly StoredMetric[]>;
86
+ }
18
87
  export interface TelemetryContext {
88
+ readonly metrics?: TelemetryMetrics;
89
+ readonly propagation?: TelemetryPropagation;
19
90
  startSpan<T>(options: SpanOptions, callback: (span: TelemetrySpan) => T | Promise<T>): Promise<T>;
20
91
  }
21
92
  export interface TelemetrySpan extends TelemetryContext {
93
+ addLink(link: SpanLink): void;
22
94
  addEvent(name: string, attributes?: SpanAttributes): void;
23
95
  setAttributes(attributes: SpanAttributes): void;
24
96
  setStatus(status: SpanStatus): void;
25
97
  }
26
- export { NOOP_TELEMETRY_CONTEXT } from "./noop.ts";
98
+ export type { HistogramOptions, InstrumentOptions, SchemaTelemetryCounter, SchemaTelemetryHistogram, TelemetryCounter, TelemetryHistogram, TelemetryMetricAttributeDefinition, TelemetryMetricDefinition, TelemetryMetrics, TelemetryUpDownCounter, TypedTelemetryMetrics, } from "./metrics.ts";
99
+ export { createTypedMetrics } from "./metrics.ts";
100
+ export { NOOP_TELEMETRY_CONTEXT, NOOP_TELEMETRY_METRICS, NOOP_TELEMETRY_PROPAGATION } from "./noop.ts";
27
101
  export type TelemetryAttributeType = "string" | "number" | "boolean" | "string[]" | "number[]" | "boolean[]";
28
102
  export interface TelemetryAttributeMetadata {
29
103
  description: string;
@@ -87,6 +161,7 @@ export interface TelemetrySpanDefinition {
87
161
  export interface TelemetrySchemaDefinition {
88
162
  version: number;
89
163
  spans: Record<string, TelemetrySpanDefinition>;
164
+ metrics?: Record<string, TelemetryMetricDefinition>;
90
165
  }
91
166
  export declare function defineTelemetrySchema<const T extends TelemetrySchemaDefinition>(schema: T): T;
92
167
  type AttributeDefinitionValue<Definition extends TelemetryAttributeDefinition> = Definition extends {
@@ -183,5 +258,5 @@ export type TypedSpanStarter<Schemas extends TelemetrySchemaTuple> = UnionToInte
183
258
  [Name in SpanNameInSchemas<Schemas>]: TypedSpanStarterForName<Schemas, Name>;
184
259
  }[SpanNameInSchemas<Schemas>]>;
185
260
  export declare function createTypedSpanStarter<const Schemas extends TelemetrySchemaTuple>(telemetryContext: TelemetryContext, _schemas: Schemas & UniqueTelemetrySchemas<Schemas>): TypedSpanStarter<Schemas>;
186
- export type { RecordedTelemetryEvent, RecordedTelemetrySpan } from "./memory.ts";
261
+ export type { RecordedTelemetryEvent, RecordedTelemetryLink, RecordedTelemetryMeasurement, RecordedTelemetrySpan, } from "./memory.ts";
187
262
  export { InMemoryTelemetryContext } from "./memory.ts";
@@ -1 +1 @@
1
- var T=Object.defineProperty;var e=(t,r)=>T(t,"name",{value:r,configurable:!0});import{NOOP_TELEMETRY_CONTEXT as s}from"./noop.js";function m(t){return t}e(m,"defineTelemetrySchema");function a(t){return e((o,p,S)=>t.startSpan({name:o,attributes:p},n=>S(n,a(n))),"startSpan")}e(a,"bindTypedSpanStarter");function f(t,r){return a(t)}e(f,"createTypedSpanStarter");import{InMemoryTelemetryContext as y}from"./memory.js";export{y as InMemoryTelemetryContext,s as NOOP_TELEMETRY_CONTEXT,f as createTypedSpanStarter,m as defineTelemetrySchema};
1
+ var E=Object.defineProperty;var t=(e,r)=>E(e,"name",{value:r,configurable:!0});import{createTypedMetrics as _}from"./metrics.js";import{NOOP_TELEMETRY_CONTEXT as s,NOOP_TELEMETRY_METRICS as u,NOOP_TELEMETRY_PROPAGATION as x}from"./noop.js";function O(e){return e}t(O,"defineTelemetrySchema");function T(e){return t((o,a,p)=>e.startSpan({name:o,attributes:a},n=>p(n,T(n))),"startSpan")}t(T,"bindTypedSpanStarter");function S(e,r){return T(e)}t(S,"createTypedSpanStarter");import{InMemoryTelemetryContext as M}from"./memory.js";export{M as InMemoryTelemetryContext,s as NOOP_TELEMETRY_CONTEXT,u as NOOP_TELEMETRY_METRICS,x as NOOP_TELEMETRY_PROPAGATION,_ as createTypedMetrics,S as createTypedSpanStarter,O as defineTelemetrySchema};
@@ -1,11 +1,19 @@
1
- import type { SpanAttributes, SpanOptions, SpanStatus, TelemetryContext, TelemetrySpan } from "./index.ts";
1
+ import type { MetricQuery, SpanAttributes, SpanOptions, SpanStatus, StoredMetric, StoredTrace, TelemetryCarrier, TelemetryContext, TelemetryPropagation, TelemetrySpan, TelemetryStore, TraceQuery } from "./index.ts";
2
+ import type { HistogramOptions, InstrumentOptions, TelemetryCounter, TelemetryHistogram, TelemetryMetrics, TelemetryUpDownCounter } from "./metrics.ts";
2
3
  export interface RecordedTelemetryEvent {
3
4
  readonly name: string;
4
5
  readonly attributes: Readonly<SpanAttributes>;
5
6
  }
7
+ export interface RecordedTelemetryLink {
8
+ readonly context: Readonly<TelemetryCarrier>;
9
+ readonly attributes: Readonly<SpanAttributes>;
10
+ }
6
11
  export interface RecordedTelemetrySpan {
7
12
  readonly id: number;
8
13
  readonly parentId: number | null;
14
+ readonly context: Readonly<TelemetryCarrier>;
15
+ readonly parentContext: Readonly<TelemetryCarrier> | null;
16
+ readonly links: readonly RecordedTelemetryLink[];
9
17
  readonly name: string;
10
18
  readonly attributes: Readonly<SpanAttributes>;
11
19
  readonly events: readonly RecordedTelemetryEvent[];
@@ -13,8 +21,33 @@ export interface RecordedTelemetrySpan {
13
21
  readonly settled: boolean;
14
22
  readonly endSequence?: number;
15
23
  }
16
- export declare class InMemoryTelemetryContext implements TelemetryContext {
24
+ export interface RecordedTelemetryMeasurement {
25
+ readonly kind: "counter" | "upDownCounter" | "histogram";
26
+ readonly name: string;
27
+ readonly description?: string;
28
+ readonly unit?: string;
29
+ readonly boundaries?: readonly number[];
30
+ readonly value: number;
31
+ readonly attributes: Readonly<SpanAttributes>;
32
+ readonly context: Readonly<TelemetryCarrier> | null;
33
+ }
34
+ export declare class InMemoryTelemetryContext implements TelemetryContext, TelemetryPropagation, TelemetryMetrics, TelemetryStore {
35
+ readonly metrics: TelemetryMetrics;
36
+ readonly propagation: TelemetryPropagation;
17
37
  private readonly state;
18
38
  startSpan<T>(options: SpanOptions, callback: (span: TelemetrySpan) => T | Promise<T>): Promise<T>;
39
+ inject(context: TelemetryContext): TelemetryCarrier | undefined;
40
+ extract(carrier: TelemetryCarrier | undefined): TelemetryContext;
41
+ counter(name: string, options?: InstrumentOptions): TelemetryCounter;
42
+ upDownCounter(name: string, options?: InstrumentOptions): TelemetryUpDownCounter;
43
+ histogram(name: string, options?: HistogramOptions): TelemetryHistogram;
44
+ private storedSpans;
45
+ getTrace(traceId: string): Promise<StoredTrace | undefined>;
46
+ findTraces(query?: TraceQuery): Promise<{
47
+ traces: readonly StoredTrace[];
48
+ cursor?: string;
49
+ }>;
50
+ findMetrics(query: MetricQuery): Promise<readonly StoredMetric[]>;
51
+ getMetrics(): readonly RecordedTelemetryMeasurement[];
19
52
  getSpans(): readonly RecordedTelemetrySpan[];
20
53
  }
@@ -1 +1 @@
1
- var y=Object.defineProperty;var a=(t,e)=>y(t,"name",{value:e,configurable:!0});import{NOOP_TELEMETRY_CONTEXT as f}from"./noop.js";function m(t){return Array.isArray(t)?[...t]:t}a(m,"copyAttributeValue");function i(t){const e={};if(!t)return e;for(const[n,u]of Object.entries(t))u!==void 0&&(e[n]=m(u));return e}a(i,"copyAttributes");function b(t,e){const n=i(t);for(const[u,r]of Object.entries(e))r!==void 0&&(n[u]=m(r));return n}a(b,"mergeAttributes");function S(t){return t.status==="ok"?{status:"ok"}:t.error?{status:"error",error:{name:t.error.name,message:t.error.message}}:{status:"error"}}a(S,"copyStatus");function h(t){try{if(t instanceof Error)return{status:"error",error:{name:t.name,message:t.message}}}catch{}return{status:"error"}}a(h,"automaticErrorStatus");function o(t,e,n,u){e.settled||(n&&!e.explicitStatus&&(e.status=h(u)),e.settled=!0,e.endSequence=t.nextEndSequence++)}a(o,"settleSpan");function x(t,e,n){const u=n.name,r=i(n.attributes);return{id:t.nextSpanId++,parentId:e?.id??null,name:u,attributes:r,events:[],status:{status:"ok"},explicitStatus:!1,settled:!1}}a(x,"createSpan");function l(t,e,n,u){if(e?.settled)return f.startSpan(n,u);let r;try{r=x(t,e,n),t.spans.push(r)}catch{return f.startSpan(n,u)}const p={startSpan:a((s,c)=>l(t,r,s,c),"startSpan"),addEvent(s,c){if(!r.settled)try{r.events.push({name:s,attributes:i(c)})}catch{}},setAttributes(s){if(!r.settled)try{r.attributes=b(r.attributes,s)}catch{}},setStatus(s){if(!r.settled)try{r.status=S(s),r.explicitStatus=!0}catch{}}};let d;try{d=u(p)}catch(s){return o(t,r,!0,s),Promise.reject(s)}return Promise.resolve(d).then(s=>(o(t,r,!1),s),s=>{throw o(t,r,!0,s),s})}a(l,"startInMemorySpan");class I{static{a(this,"InMemoryTelemetryContext")}state={spans:[],nextSpanId:1,nextEndSequence:1};startSpan(e,n){return l(this.state,void 0,e,n)}getSpans(){return this.state.spans.map(e=>({id:e.id,parentId:e.parentId,name:e.name,attributes:i(e.attributes),events:e.events.map(n=>({name:n.name,attributes:i(n.attributes)})),status:S(e.status),settled:e.settled,...e.endSequence===void 0?{}:{endSequence:e.endSequence}}))}}export{I as InMemoryTelemetryContext};
1
+ var y=Object.defineProperty;var u=(r,t)=>y(r,"name",{value:t,configurable:!0});import{NOOP_TELEMETRY_CONTEXT as k}from"./noop.js";function x(r){return`${r["pi-memory-scope"]}:${r["pi-memory-span"]}`}u(x,"carrierId");const f=new WeakMap;function p(r){return Object.fromEntries(Object.entries(r??{}).filter(([,t])=>t!==void 0).map(([t,e])=>[t,Array.isArray(e)?[...e]:e]))}u(p,"copyAttributes");function g(r){const t=f.get(r.context);return t?{context:{...t},attributes:p(r.attributes)}:void 0}u(g,"copyLink");function b(r){return r.status==="ok"?{status:"ok"}:r.error?{status:"error",error:{name:r.error.name,message:r.error.message}}:{status:"error"}}u(b,"copyStatus");function w(r,t,e){const s=e.name,n=p(e.attributes),o=[];for(const d of e.links??[]){const i=g(d);i&&o.push(i)}const a=r.nextSpanId++;return{startedMs:Date.now(),clock:performance.now(),id:a,parentId:t?.localId??null,context:{"pi-memory-scope":r.scope,"pi-memory-span":String(a),"pi-memory-trace":t?.context["pi-memory-trace"]??`${r.scope}:${a}`},parentContext:t?{...t.context}:null,links:o,name:s,attributes:n,events:[],status:{status:"ok"},explicitStatus:!1,settled:!1}}u(w,"createSpan");function S(r,t,e){return k.startSpan(t,s=>e({...s,metrics:r.metrics,propagation:r.propagation,startSpan:u((n,o)=>S(r,n,o),"startSpan")}))}u(S,"startInertSpan");async function M(r,t,e,s){if(t?.span?.settled)return S(r,e,s);const n=w(r,t,e);r.spans.push(n);const o={metrics:r.metrics,propagation:r.propagation,startSpan:u((a,d)=>M(r,{context:n.context,localId:n.id,span:n},a,d),"startSpan"),addLink(a){if(n.settled)return;const d=g(a);d&&n.links.push(d)},addEvent(a,d){n.settled||n.events.push({name:a,timeMs:performance.now()-n.clock,attributes:p(d)})},setAttributes(a){n.settled||(n.attributes={...n.attributes,...p(a)})},setStatus(a){n.settled||(n.status=b(a),n.explicitStatus=!0)}};f.set(o,n.context);try{return await s(o)}catch(a){throw n.explicitStatus||(n.status=a instanceof Error?{status:"error",error:{name:a.name,message:a.message}}:{status:"error"}),a}finally{n.settled=!0,n.endedMs=n.startedMs+performance.now()-n.clock,n.endSequence=r.nextEndSequence++}}u(M,"startInMemorySpan");function h(r,t,e,s){const n=s?.description,o=s?.unit,a=t==="histogram"&&s?.boundaries!==void 0?[...s.boundaries]:void 0,d={kind:t,name:e,...n===void 0?{}:{description:n},...o===void 0?{}:{unit:o},...a===void 0?{}:{boundaries:a}};return(i,c,m)=>{const l=m===void 0?void 0:f.get(m);r.measurements.push({intervalMs:Math.floor(Date.now()/1e4)*1e4,measurement:{...d,value:i,attributes:p(c),context:l?{...l}:null}})}}u(h,"createMeasurementRecorder");class O{static{u(this,"InMemoryTelemetryContext")}metrics=this;propagation=this;state={metrics:this,propagation:this,scope:crypto.randomUUID(),spans:[],measurements:[],nextSpanId:1,nextEndSequence:1};startSpan(t,e){return M(this.state,void 0,t,e)}inject(t){const e=f.get(t);return e?{...e}:void 0}extract(t){const e=t?.["pi-memory-scope"],s=t?.["pi-memory-span"],n=t?.["pi-memory-trace"];if(typeof e!="string"||typeof s!="string"||typeof n!="string")return this;const o={"pi-memory-scope":e,"pi-memory-span":s,"pi-memory-trace":n},a=e===this.state.scope?Number(s):null,d={metrics:this,propagation:this,startSpan:u((i,c)=>M(this.state,{context:o,localId:a},i,c),"startSpan")};return f.set(d,o),d}counter(t,e){return{add:h(this.state,"counter",t,e)}}upDownCounter(t,e){return{add:h(this.state,"upDownCounter",t,e)}}histogram(t,e){return{record:h(this.state,"histogram",t,e)}}storedSpans(){return this.state.spans.filter(t=>t.settled).map(t=>({id:x(t.context),traceId:t.context["pi-memory-trace"],...t.parentContext?{parentId:x(t.parentContext)}:{},name:t.name,startedMs:t.startedMs,endedMs:t.endedMs,attributes:p(t.attributes),events:t.events.map(e=>({name:e.name,timeMs:e.timeMs,attributes:p(e.attributes)})),links:t.links.map(e=>({traceId:e.context["pi-memory-trace"],spanId:x(e.context),attributes:p(e.attributes)})),status:b(t.status)})).sort((t,e)=>t.startedMs-e.startedMs||(t.id<e.id?-1:t.id>e.id?1:0))}async getTrace(t){const e=this.storedSpans().filter(s=>s.traceId===t);return e.length?{traceId:t,spans:e}:void 0}async findTraces(t={}){const e=t.limit??20,s=t.cursor===void 0?void 0:JSON.parse(t.cursor),n=new Map;for(const i of this.storedSpans()){let c=n.get(i.traceId);c||(c={traceId:i.traceId,spans:[]},n.set(i.traceId,c)),c.spans.push(i)}const o=[...n.values()].filter(i=>{const c=i.spans[0];return(t.name===void 0||c.name===t.name)&&(t.startMin===void 0||c.startedMs>=t.startMin)&&(t.startMax===void 0||c.startedMs<=t.startMax)&&(!s||c.startedMs<s[0]||c.startedMs===s[0]&&i.traceId>s[1])&&(!t.errors||i.spans.some(m=>m.status.status==="error"))&&(!t.attributes||i.spans.some(m=>Object.entries(t.attributes).every(([l,I])=>m.attributes[l]===I)))}).sort((i,c)=>c.spans[0].startedMs-i.spans[0].startedMs||(i.traceId<c.traceId?-1:i.traceId>c.traceId?1:0)),a=o.slice(0,e),d=a.at(-1);return{traces:a,...o.length>e?{cursor:JSON.stringify([d.spans[0].startedMs,d.traceId])}:{}}}async findMetrics(t){return this.state.measurements.filter(({intervalMs:e,measurement:s})=>s.name===t.name&&(t.startMin===void 0||e>=t.startMin)&&(t.startMax===void 0||e<=t.startMax)&&Object.entries(t.attributes??{}).every(([n,o])=>s.attributes[n]===o)).map(({intervalMs:e,measurement:s})=>({intervalMs:e,name:s.name,kind:s.kind,...s.unit===void 0?{}:{unit:s.unit},attributes:p(s.attributes),count:1,sum:s.value,min:s.value,max:s.value}))}getMetrics(){return this.state.measurements.map(({measurement:t})=>({...t,...t.boundaries===void 0?{}:{boundaries:[...t.boundaries]},attributes:p(t.attributes),context:t.context?{...t.context}:null}))}getSpans(){return this.state.spans.map(t=>({id:t.id,parentId:t.parentId,context:{...t.context},parentContext:t.parentContext?{...t.parentContext}:null,links:t.links.map(e=>({context:{...e.context},attributes:p(e.attributes)})),name:t.name,attributes:p(t.attributes),events:t.events.map(e=>({name:e.name,attributes:p(e.attributes)})),status:b(t.status),settled:t.settled,...t.endSequence===void 0?{}:{endSequence:t.endSequence}}))}}export{O as InMemoryTelemetryContext};
@@ -0,0 +1,70 @@
1
+ import type { ExactTelemetryAttributes, InferRequiredAndOptionalAttributes, SpanAttributes, TelemetryContext, TelemetrySchemaDefinition, TelemetryStartAttributeDefinition } from "./index.ts";
2
+ export interface InstrumentOptions {
3
+ description?: string;
4
+ unit?: string;
5
+ }
6
+ export interface HistogramOptions extends InstrumentOptions {
7
+ boundaries?: readonly number[];
8
+ }
9
+ export interface TelemetryCounter {
10
+ add(value: number, attributes?: SpanAttributes): void;
11
+ }
12
+ export interface TelemetryUpDownCounter {
13
+ add(value: number, attributes?: SpanAttributes): void;
14
+ }
15
+ export interface TelemetryHistogram {
16
+ record(value: number, attributes?: SpanAttributes, context?: TelemetryContext): void;
17
+ }
18
+ export interface TelemetryMetrics {
19
+ counter(name: string, options?: InstrumentOptions): TelemetryCounter;
20
+ upDownCounter(name: string, options?: InstrumentOptions): TelemetryUpDownCounter;
21
+ histogram(name: string, options?: HistogramOptions): TelemetryHistogram;
22
+ }
23
+ export type TelemetryMetricAttributeDefinition = TelemetryStartAttributeDefinition & {
24
+ cardinality?: "low";
25
+ };
26
+ export type TelemetryMetricDefinition = {
27
+ description: string;
28
+ unit?: string;
29
+ attributes: Record<string, TelemetryMetricAttributeDefinition>;
30
+ } & ({
31
+ kind: "counter" | "upDownCounter";
32
+ boundaries?: never;
33
+ } | {
34
+ kind: "histogram";
35
+ boundaries?: readonly number[];
36
+ });
37
+ type MetricKind = TelemetryMetricDefinition["kind"];
38
+ type MetricSchemas = readonly [TelemetrySchemaDefinition, ...TelemetrySchemaDefinition[]];
39
+ type MetricsOf<Schema extends TelemetrySchemaDefinition> = Schema extends {
40
+ metrics: infer Metrics extends Record<string, TelemetryMetricDefinition>;
41
+ } ? Metrics : Record<never, never>;
42
+ type MetricNames<Schema extends TelemetrySchemaDefinition, Kind extends MetricKind> = Schema extends TelemetrySchemaDefinition ? {
43
+ [Name in keyof MetricsOf<Schema>]: MetricsOf<Schema>[Name] extends {
44
+ kind: Kind;
45
+ } ? Name : never;
46
+ }[keyof MetricsOf<Schema>] & string : never;
47
+ type MetricByName<Schema extends TelemetrySchemaDefinition, Name extends string> = Schema extends TelemetrySchemaDefinition ? Name extends keyof MetricsOf<Schema> ? MetricsOf<Schema>[Name] : never : never;
48
+ type DuplicateMetricNames<Schemas extends readonly TelemetrySchemaDefinition[], Seen extends string = never> = Schemas extends readonly [
49
+ infer Schema extends TelemetrySchemaDefinition,
50
+ ...infer Rest extends readonly TelemetrySchemaDefinition[]
51
+ ] ? Extract<keyof MetricsOf<Schema>, Seen> | DuplicateMetricNames<Rest, Seen | (keyof MetricsOf<Schema> & string)> : never;
52
+ type MetricAttributes<Definition extends TelemetryMetricDefinition> = InferRequiredAndOptionalAttributes<Definition["attributes"]>;
53
+ type MeasurementArguments<Definition extends TelemetryMetricDefinition, Attributes extends MetricAttributes<Definition>> = {
54
+ [Name in keyof Definition["attributes"]]: Definition["attributes"][Name]["required"] extends true ? Name : never;
55
+ }[keyof Definition["attributes"]] extends never ? [attributes?: ExactTelemetryAttributes<MetricAttributes<Definition>, Attributes>] : [attributes: ExactTelemetryAttributes<MetricAttributes<Definition>, Attributes>];
56
+ export type SchemaTelemetryCounter<Definition extends TelemetryMetricDefinition> = {
57
+ add<const Attributes extends MetricAttributes<Definition> = MetricAttributes<Definition>>(value: number, ...args: MeasurementArguments<Definition, Attributes>): void;
58
+ };
59
+ export type SchemaTelemetryHistogram<Definition extends TelemetryMetricDefinition> = {
60
+ record<const Attributes extends MetricAttributes<Definition> = MetricAttributes<Definition>>(value: number, ...args: [...MeasurementArguments<Definition, Attributes>, context?: TelemetryContext]): void;
61
+ };
62
+ export interface TypedTelemetryMetrics<Schemas extends MetricSchemas> {
63
+ counter<Name extends MetricNames<Schemas[number], "counter">>(name: Name): SchemaTelemetryCounter<MetricByName<Schemas[number], Name>>;
64
+ upDownCounter<Name extends MetricNames<Schemas[number], "upDownCounter">>(name: Name): SchemaTelemetryCounter<MetricByName<Schemas[number], Name>>;
65
+ histogram<Name extends MetricNames<Schemas[number], "histogram">>(name: Name): SchemaTelemetryHistogram<MetricByName<Schemas[number], Name>>;
66
+ }
67
+ export declare function createTypedMetrics<const Schemas extends MetricSchemas>(metrics: TelemetryMetrics, schemas: Schemas & ([DuplicateMetricNames<Schemas>] extends [never] ? unknown : {
68
+ readonly "duplicate telemetry metric names": DuplicateMetricNames<Schemas>;
69
+ })): TypedTelemetryMetrics<Schemas>;
70
+ export {};
@@ -0,0 +1 @@
1
+ var s=Object.defineProperty;var e=(o,r)=>s(o,"name",{value:r,configurable:!0});function f(o,r){const n=new Map;for(const t of r)for(const[i,c]of Object.entries(t.metrics??{}))n.set(i,c);return{counter:e(t=>o.counter(t,n.get(t)),"counter"),upDownCounter:e(t=>o.upDownCounter(t,n.get(t)),"upDownCounter"),histogram:e(t=>o.histogram(t,n.get(t)),"histogram")}}e(f,"createTypedMetrics");export{f as createTypedMetrics};
@@ -1,2 +1,5 @@
1
- import type { TelemetryContext } from "./index.ts";
2
- export declare const NOOP_TELEMETRY_CONTEXT: TelemetryContext;
1
+ import type { TelemetryPropagation, TelemetrySpan } from "./index.ts";
2
+ import type { TelemetryMetrics } from "./metrics.ts";
3
+ export declare const NOOP_TELEMETRY_METRICS: TelemetryMetrics;
4
+ export declare const NOOP_TELEMETRY_PROPAGATION: TelemetryPropagation;
5
+ export declare const NOOP_TELEMETRY_CONTEXT: TelemetrySpan;
@@ -1 +1 @@
1
- var s=Object.defineProperty;var t=(o,e)=>s(o,"name",{value:e,configurable:!0});function a(o,e){try{return Promise.resolve(e(r))}catch(n){return Promise.reject(n)}}t(a,"startNoopSpan");const r={startSpan:a,addEvent:t(()=>{},"addEvent"),setAttributes:t(()=>{},"setAttributes"),setStatus:t(()=>{},"setStatus")};Object.freeze(r);const p=r;export{p as NOOP_TELEMETRY_CONTEXT};
1
+ var r=Object.defineProperty;var e=(n,t)=>r(n,"name",{value:t,configurable:!0});async function c(n,t){return t(o)}e(c,"startNoopSpan");const s=Object.freeze({add:e(()=>{},"add")}),a=Object.freeze({add:e(()=>{},"add")}),p=Object.freeze({record:e(()=>{},"record")}),O=Object.freeze({counter:e(()=>s,"counter"),upDownCounter:e(()=>a,"upDownCounter"),histogram:e(()=>p,"histogram")}),E=Object.freeze({inject:e(()=>{},"inject"),extract:e(()=>d,"extract")}),o={metrics:O,propagation:E,startSpan:c,addLink:e(()=>{},"addLink"),addEvent:e(()=>{},"addEvent"),setAttributes:e(()=>{},"setAttributes"),setStatus:e(()=>{},"setStatus")};Object.freeze(o);const d=o;export{d as NOOP_TELEMETRY_CONTEXT,O as NOOP_TELEMETRY_METRICS,E as NOOP_TELEMETRY_PROPAGATION};
@@ -0,0 +1,2 @@
1
+ var h=Object.defineProperty;var c=(r,n)=>h(r,"name",{value:n,configurable:!0});function f(r={}){return Object.entries(r).map(([n,o])=>` ${n}=${JSON.stringify(o)}`).join("")}c(f,"formatAttributes");function m(r){const n=new Map(r.map(e=>[e.id,e])),o=[],d=new Map;for(const e of[...n.values()].sort((s,a)=>s.startedMs-a.startedMs))if(e.parentId===void 0||!n.has(e.parentId))o.push(e);else{const s=d.get(e.parentId);s===void 0?d.set(e.parentId,[e]):s.push(e)}const i=[],p=o.reverse().map(e=>({span:e,depth:0}));for(;p.length>0;){const{span:e,depth:s}=p.pop(),a=" ".repeat(s);let u="";e.status.status==="error"&&(u=" error",e.status.error!==void 0&&(u+=` ${e.status.error.name}: ${e.status.error.message}`)),i.push(`${a}${e.name}${f(e.attributes)} (${e.endedMs-e.startedMs}ms)${u}`);for(const t of e.events)i.push(`${a} \xB7 ${t.name}${f(t.attributes)} (+${t.timeMs}ms)`);for(const t of e.links)i.push(`${a} \u2192 link trace ${t.traceId} span ${t.spanId}${f(t.attributes)}`);const $=d.get(e.id)??[];for(let t=$.length-1;t>=0;t--)p.push({span:$[t],depth:s+1})}return i.join(`
2
+ `)}c(m,"renderTrace");export{m as renderTrace};