@dxos/compute 0.16.0 → 0.17.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 (136) hide show
  1. package/dist/lib/AiMetering.mjs +1 -0
  2. package/dist/lib/Hook.mjs +1 -0
  3. package/dist/lib/Operation.mjs +3 -3
  4. package/dist/lib/Process.mjs +2 -2
  5. package/dist/lib/Trace.mjs +1 -1
  6. package/dist/lib/chunk-AgentIdentity.mjs +1 -1
  7. package/dist/lib/chunk-AgentService.mjs.map +1 -1
  8. package/dist/lib/chunk-AiMetering.mjs +77 -0
  9. package/dist/lib/chunk-AiMetering.mjs.map +1 -0
  10. package/dist/lib/chunk-Cancellation.mjs +1 -1
  11. package/dist/lib/chunk-Hook.mjs +78 -0
  12. package/dist/lib/chunk-Hook.mjs.map +1 -0
  13. package/dist/lib/chunk-Instructions.mjs +1 -1
  14. package/dist/lib/chunk-Operation.mjs +169 -5
  15. package/dist/lib/chunk-Operation.mjs.map +1 -1
  16. package/dist/lib/chunk-OperationHandlerSet.mjs +1 -1
  17. package/dist/lib/chunk-OperationRegistry.mjs +1 -1
  18. package/dist/lib/chunk-OperationRegistry.mjs.map +1 -1
  19. package/dist/lib/chunk-Process.mjs +18 -10
  20. package/dist/lib/chunk-Process.mjs.map +1 -1
  21. package/dist/lib/chunk-Project.mjs +52 -24
  22. package/dist/lib/chunk-Project.mjs.map +1 -1
  23. package/dist/lib/chunk-Reducer.mjs +827 -0
  24. package/dist/lib/chunk-Reducer.mjs.map +1 -0
  25. package/dist/lib/chunk-Routine.mjs +1 -1
  26. package/dist/lib/chunk-Runnable.mjs +1 -1
  27. package/dist/lib/chunk-ServiceResolver.mjs +1 -1
  28. package/dist/lib/chunk-Skill.mjs +10 -47
  29. package/dist/lib/chunk-Skill.mjs.map +1 -1
  30. package/dist/lib/chunk-Spec.mjs +49 -0
  31. package/dist/lib/chunk-Spec.mjs.map +1 -0
  32. package/dist/lib/chunk-SpecReview.mjs +98 -0
  33. package/dist/lib/chunk-SpecReview.mjs.map +1 -0
  34. package/dist/lib/chunk-SqlService.mjs.map +1 -1
  35. package/dist/lib/chunk-StorageService.mjs +1 -1
  36. package/dist/lib/chunk-Template.mjs +2 -2
  37. package/dist/lib/chunk-Trace.mjs +97 -13
  38. package/dist/lib/chunk-Trace.mjs.map +1 -1
  39. package/dist/lib/chunk-Trajectory.mjs +326 -0
  40. package/dist/lib/chunk-Trajectory.mjs.map +1 -0
  41. package/dist/lib/chunk-Transcript.mjs +84 -0
  42. package/dist/lib/chunk-Transcript.mjs.map +1 -0
  43. package/dist/lib/chunk-definitions.mjs +1 -1
  44. package/dist/lib/errors.mjs +3 -1
  45. package/dist/lib/errors.mjs.map +1 -1
  46. package/dist/lib/index.mjs +14 -8
  47. package/dist/lib/testing.mjs +2 -2
  48. package/dist/lib/trajectory/Reducer.mjs +1 -0
  49. package/dist/lib/trajectory/Trajectory.mjs +1 -0
  50. package/dist/lib/trajectory/Transcript.mjs +1 -0
  51. package/dist/lib/types/Project.mjs +1 -1
  52. package/dist/lib/types/Skill.mjs +1 -1
  53. package/dist/lib/types/Spec.mjs +1 -0
  54. package/dist/lib/types/SpecReview.mjs +1 -0
  55. package/dist/types/src/AgentService.d.ts +9 -0
  56. package/dist/types/src/AgentService.d.ts.map +1 -1
  57. package/dist/types/src/AiMetering.d.ts +23 -0
  58. package/dist/types/src/AiMetering.d.ts.map +1 -0
  59. package/dist/types/src/AiMetering.test.d.ts +2 -0
  60. package/dist/types/src/AiMetering.test.d.ts.map +1 -0
  61. package/dist/types/src/Hook.d.ts +84 -0
  62. package/dist/types/src/Hook.d.ts.map +1 -0
  63. package/dist/types/src/Hook.test.d.ts +2 -0
  64. package/dist/types/src/Hook.test.d.ts.map +1 -0
  65. package/dist/types/src/Operation.d.ts +276 -2
  66. package/dist/types/src/Operation.d.ts.map +1 -1
  67. package/dist/types/src/Process.d.ts +26 -4
  68. package/dist/types/src/Process.d.ts.map +1 -1
  69. package/dist/types/src/Script.test.d.ts +2 -0
  70. package/dist/types/src/Script.test.d.ts.map +1 -0
  71. package/dist/types/src/Trace.d.ts +103 -1
  72. package/dist/types/src/Trace.d.ts.map +1 -1
  73. package/dist/types/src/errors.d.ts +30 -0
  74. package/dist/types/src/errors.d.ts.map +1 -1
  75. package/dist/types/src/index.d.ts +3 -1
  76. package/dist/types/src/index.d.ts.map +1 -1
  77. package/dist/types/src/trajectory/Reducer.d.ts +191 -0
  78. package/dist/types/src/trajectory/Reducer.d.ts.map +1 -0
  79. package/dist/types/src/trajectory/Reducer.test.d.ts +2 -0
  80. package/dist/types/src/trajectory/Reducer.test.d.ts.map +1 -0
  81. package/dist/types/src/trajectory/Trajectory.d.ts +3211 -0
  82. package/dist/types/src/trajectory/Trajectory.d.ts.map +1 -0
  83. package/dist/types/src/trajectory/Trajectory.test.d.ts +2 -0
  84. package/dist/types/src/trajectory/Trajectory.test.d.ts.map +1 -0
  85. package/dist/types/src/trajectory/Transcript.d.ts +40 -0
  86. package/dist/types/src/trajectory/Transcript.d.ts.map +1 -0
  87. package/dist/types/src/trajectory/index.d.ts +4 -0
  88. package/dist/types/src/trajectory/index.d.ts.map +1 -0
  89. package/dist/types/src/trajectory/light-threads.test.d.ts +2 -0
  90. package/dist/types/src/trajectory/light-threads.test.d.ts.map +1 -0
  91. package/dist/types/src/trajectory/samples.test.d.ts +2 -0
  92. package/dist/types/src/trajectory/samples.test.d.ts.map +1 -0
  93. package/dist/types/src/types/Project.d.ts +11 -12
  94. package/dist/types/src/types/Project.d.ts.map +1 -1
  95. package/dist/types/src/types/Skill.d.ts +6 -51
  96. package/dist/types/src/types/Skill.d.ts.map +1 -1
  97. package/dist/types/src/types/Spec.d.ts +26 -0
  98. package/dist/types/src/types/Spec.d.ts.map +1 -0
  99. package/dist/types/src/types/SpecReview.d.ts +76 -0
  100. package/dist/types/src/types/SpecReview.d.ts.map +1 -0
  101. package/dist/types/src/types/index.d.ts +2 -0
  102. package/dist/types/src/types/index.d.ts.map +1 -1
  103. package/dist/types/tsconfig.tsbuildinfo +1 -1
  104. package/package.json +59 -26
  105. package/src/AgentService.ts +9 -0
  106. package/src/AiMetering.test.ts +89 -0
  107. package/src/AiMetering.ts +93 -0
  108. package/src/Hook.test.ts +75 -0
  109. package/src/Hook.ts +154 -0
  110. package/src/Operation.test.ts +23 -0
  111. package/src/Operation.ts +334 -0
  112. package/src/Process.ts +33 -6
  113. package/src/Script.test.ts +74 -0
  114. package/src/Trace.ts +97 -4
  115. package/src/errors.ts +3 -0
  116. package/src/index.ts +3 -1
  117. package/src/trajectory/Reducer.test.ts +575 -0
  118. package/src/trajectory/Reducer.ts +1026 -0
  119. package/src/trajectory/Trajectory.test.ts +114 -0
  120. package/src/trajectory/Trajectory.ts +440 -0
  121. package/src/trajectory/Transcript.ts +113 -0
  122. package/src/trajectory/index.ts +7 -0
  123. package/src/trajectory/light-threads.test.ts +310 -0
  124. package/src/trajectory/samples.test.ts +285 -0
  125. package/src/types/Project.test.ts +2 -1
  126. package/src/types/Project.ts +43 -27
  127. package/src/types/Skill.ts +6 -61
  128. package/src/types/Spec.ts +68 -0
  129. package/src/types/SpecReview.ts +98 -0
  130. package/src/types/index.ts +2 -0
  131. package/dist/lib/McpServer.mjs +0 -1
  132. package/dist/lib/chunk-McpServer.mjs +0 -124
  133. package/dist/lib/chunk-McpServer.mjs.map +0 -1
  134. package/dist/types/src/McpServer.d.ts +0 -113
  135. package/dist/types/src/McpServer.d.ts.map +0 -1
  136. package/src/McpServer.ts +0 -142
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@dxos/compute",
3
- "version": "0.16.0",
3
+ "version": "0.17.0",
4
4
  "description": "Umbrella package for AI-aware DXOS compute primitives.",
5
5
  "homepage": "https://dxos.org",
6
6
  "bugs": "https://github.com/dxos/dxos/issues",
@@ -18,6 +18,11 @@
18
18
  "types": "./dist/types/src/index.d.ts",
19
19
  "import": "./dist/lib/index.mjs"
20
20
  },
21
+ "./AiMetering": {
22
+ "source": "./src/AiMetering.ts",
23
+ "types": "./dist/types/src/AiMetering.d.ts",
24
+ "import": "./dist/lib/AiMetering.mjs"
25
+ },
21
26
  "./AgentIdentity": {
22
27
  "source": "./src/AgentIdentity.ts",
23
28
  "types": "./dist/types/src/AgentIdentity.d.ts",
@@ -48,6 +53,11 @@
48
53
  "types": "./dist/types/src/Header.d.ts",
49
54
  "import": "./dist/lib/Header.mjs"
50
55
  },
56
+ "./Hook": {
57
+ "source": "./src/Hook.ts",
58
+ "types": "./dist/types/src/Hook.d.ts",
59
+ "import": "./dist/lib/Hook.mjs"
60
+ },
51
61
  "./Instructions": {
52
62
  "source": "./src/types/Instructions.ts",
53
63
  "types": "./dist/types/src/types/Instructions.d.ts",
@@ -58,11 +68,6 @@
58
68
  "types": "./dist/types/src/LayerSpec.d.ts",
59
69
  "import": "./dist/lib/LayerSpec.mjs"
60
70
  },
61
- "./McpServer": {
62
- "source": "./src/McpServer.ts",
63
- "types": "./dist/types/src/McpServer.d.ts",
64
- "import": "./dist/lib/McpServer.mjs"
65
- },
66
71
  "./Operation": {
67
72
  "source": "./src/Operation.ts",
68
73
  "types": "./dist/types/src/Operation.d.ts",
@@ -89,11 +94,26 @@
89
94
  "types": "./dist/types/src/types/Project.d.ts",
90
95
  "import": "./dist/lib/types/Project.mjs"
91
96
  },
97
+ "./Reducer": {
98
+ "source": "./src/trajectory/Reducer.ts",
99
+ "types": "./dist/types/src/trajectory/Reducer.d.ts",
100
+ "import": "./dist/lib/trajectory/Reducer.mjs"
101
+ },
92
102
  "./Routine": {
93
103
  "source": "./src/types/Routine.ts",
94
104
  "types": "./dist/types/src/types/Routine.d.ts",
95
105
  "import": "./dist/lib/types/Routine.mjs"
96
106
  },
107
+ "./Spec": {
108
+ "source": "./src/types/Spec.ts",
109
+ "types": "./dist/types/src/types/Spec.d.ts",
110
+ "import": "./dist/lib/types/Spec.mjs"
111
+ },
112
+ "./SpecReview": {
113
+ "source": "./src/types/SpecReview.ts",
114
+ "types": "./dist/types/src/types/SpecReview.d.ts",
115
+ "import": "./dist/lib/types/SpecReview.mjs"
116
+ },
97
117
  "./Runnable": {
98
118
  "source": "./src/Runnable.ts",
99
119
  "types": "./dist/types/src/Runnable.d.ts",
@@ -109,16 +129,16 @@
109
129
  "types": "./dist/types/src/ServiceResolver.d.ts",
110
130
  "import": "./dist/lib/ServiceResolver.mjs"
111
131
  },
112
- "./Skill": {
113
- "source": "./src/types/Skill.ts",
114
- "types": "./dist/types/src/types/Skill.d.ts",
115
- "import": "./dist/lib/types/Skill.mjs"
116
- },
117
132
  "./ShellService": {
118
133
  "source": "./src/ShellService.ts",
119
134
  "types": "./dist/types/src/ShellService.d.ts",
120
135
  "import": "./dist/lib/ShellService.mjs"
121
136
  },
137
+ "./Skill": {
138
+ "source": "./src/types/Skill.ts",
139
+ "types": "./dist/types/src/types/Skill.d.ts",
140
+ "import": "./dist/lib/types/Skill.mjs"
141
+ },
122
142
  "./SqlService": {
123
143
  "source": "./src/SqlService.ts",
124
144
  "types": "./dist/types/src/SqlService.d.ts",
@@ -144,6 +164,16 @@
144
164
  "types": "./dist/types/src/Trace.d.ts",
145
165
  "import": "./dist/lib/Trace.mjs"
146
166
  },
167
+ "./Trajectory": {
168
+ "source": "./src/trajectory/Trajectory.ts",
169
+ "types": "./dist/types/src/trajectory/Trajectory.d.ts",
170
+ "import": "./dist/lib/trajectory/Trajectory.mjs"
171
+ },
172
+ "./Transcript": {
173
+ "source": "./src/trajectory/Transcript.ts",
174
+ "types": "./dist/types/src/trajectory/Transcript.d.ts",
175
+ "import": "./dist/lib/trajectory/Transcript.mjs"
176
+ },
147
177
  "./Trigger": {
148
178
  "source": "./src/types/Trigger.ts",
149
179
  "types": "./dist/types/src/types/Trigger.d.ts",
@@ -161,29 +191,32 @@
161
191
  "src"
162
192
  ],
163
193
  "dependencies": {
164
- "@dxos/ai": "0.16.0",
165
- "@dxos/echo": "0.16.0",
166
- "@dxos/effect": "0.16.0",
167
- "@dxos/errors": "0.16.0",
168
- "@dxos/keys": "0.16.0",
169
- "@dxos/invariant": "0.16.0",
170
- "@dxos/link": "0.16.0",
171
- "@dxos/log": "0.16.0",
172
- "@dxos/protocols": "0.16.0",
173
- "@dxos/schema": "0.16.0",
174
- "@dxos/types": "0.16.0",
175
- "@dxos/vendor-kbn-handlebars": "0.16.0"
194
+ "@dxos/ai": "0.17.0",
195
+ "@dxos/echo": "0.17.0",
196
+ "@dxos/effect": "0.17.0",
197
+ "@dxos/errors": "0.17.0",
198
+ "@dxos/invariant": "0.17.0",
199
+ "@dxos/keys": "0.17.0",
200
+ "@dxos/log": "0.17.0",
201
+ "@dxos/protocols": "0.17.0",
202
+ "@dxos/schema": "0.17.0",
203
+ "@dxos/types": "0.17.0",
204
+ "@dxos/vendor-kbn-handlebars": "0.17.0"
176
205
  },
177
206
  "devDependencies": {
207
+ "@dxos/echo-client": "0.17.0",
208
+ "@dxos/sql-sqlite": "0.17.0",
178
209
  "effect": "4.0.4",
179
- "vitest": "4.1.10",
180
- "@dxos/echo-client": "0.16.0",
181
- "@dxos/sql-sqlite": "0.16.0"
210
+ "typedoc": "0.28.1",
211
+ "vitest": "4.1.10"
182
212
  },
183
213
  "peerDependencies": {
184
214
  "effect": "4.0.4"
185
215
  },
186
216
  "publishConfig": {
187
217
  "access": "public"
218
+ },
219
+ "scripts": {
220
+ "typedoc": "typedoc --out typedoc"
188
221
  }
189
222
  }
@@ -16,6 +16,7 @@ import type { ContentBlock } from '@dxos/types';
16
16
 
17
17
  import type * as Process from './Process.ts';
18
18
  import type * as Trace from './Trace.ts';
19
+ import type * as Trajectory from './trajectory/Trajectory.ts';
19
20
  import { Instructions } from './types/index.ts';
20
21
 
21
22
  /**
@@ -66,6 +67,8 @@ export type PromptSender = {
66
67
  export type SubmitPromptOptions = {
67
68
  /** Recorded on the appended user message; a named sender is shown to the model as the speaker. */
68
69
  readonly sender?: PromptSender;
70
+ /** The fork to send the prompt into; main when absent. */
71
+ readonly thread?: Trajectory.ThreadId;
69
72
  };
70
73
 
71
74
  /**
@@ -145,6 +148,12 @@ export interface GetSessionOptions {
145
148
  * @default 'local'
146
149
  */
147
150
  readonly location?: AgentLocation;
151
+ /**
152
+ * Admits the operations the agent and its tool calls invoke that declare requirements
153
+ * (`Process.SpawnOptions.guard`). Bound at spawn, so a session asked for with a different guard
154
+ * runs on a fresh process. A guard is a closure and never reaches an `edge` process.
155
+ */
156
+ readonly guard?: Process.Guard;
148
157
  }
149
158
 
150
159
  export type AgentLocation = 'local' | 'edge';
@@ -0,0 +1,89 @@
1
+ //
2
+ // Copyright 2026 DXOS.org
3
+ //
4
+
5
+ import { describe, expect, it } from '@effect/vitest';
6
+ import * as LanguageModel from 'effect/ai/LanguageModel';
7
+ import * as Effect from 'effect/Effect';
8
+ import * as Layer from 'effect/Layer';
9
+ import * as Stream from 'effect/Stream';
10
+
11
+ import { AiModelResolver, AiService, AiUsage, Model } from '@dxos/ai';
12
+
13
+ import * as AiMetering from './AiMetering.ts';
14
+ import * as Trace from './Trace.ts';
15
+
16
+ const HAIKU = 'com.anthropic.model.claude-haiku-5-5.default';
17
+
18
+ const stub = LanguageModel.make({
19
+ generateText: () =>
20
+ Effect.succeed([
21
+ { type: 'text', text: 'ok' },
22
+ {
23
+ type: 'finish',
24
+ reason: 'stop',
25
+ usage: { inputTokens: { uncached: 1_000, total: 1_000 }, outputTokens: { total: 200 } },
26
+ },
27
+ ]),
28
+ streamText: () => Stream.empty,
29
+ });
30
+
31
+ const upstream = AiModelResolver.buildAiService.pipe(
32
+ Layer.provide(
33
+ AiModelResolver.resolver(
34
+ { name: 'stub' },
35
+ Effect.succeed(() => Layer.effect(LanguageModel.LanguageModel, stub)),
36
+ ),
37
+ ),
38
+ );
39
+
40
+ /** The metered service over the stub, with every trace message it writes collected into `messages`. */
41
+ const setup = () => {
42
+ const messages: Trace.Message[] = [];
43
+ const trace = Trace.testTraceService().pipe(
44
+ Layer.provide(Layer.succeed(Trace.TraceSink, { write: (message) => messages.push(message) })),
45
+ );
46
+ return { messages, layer: AiMetering.metered.pipe(Layer.provide(Layer.merge(upstream, trace))) };
47
+ };
48
+
49
+ const call = LanguageModel.generateText({ prompt: 'hi' }).pipe(Effect.provide(AiService.languageModel(HAIKU)));
50
+
51
+ describe('AiMetering', () => {
52
+ it.effect('writes a model-call event per call, attributed to the caller stage and thread', () =>
53
+ Effect.gen(function* () {
54
+ const { messages, layer } = setup();
55
+ yield* call.pipe(
56
+ AiUsage.withStage('extract-facts'),
57
+ Effect.provideService(Trace.CurrentThread, 'thread-1'),
58
+ Effect.provide(layer),
59
+ );
60
+
61
+ expect(messages).toHaveLength(1);
62
+ expect(messages[0].meta.thread).toEqual('thread-1');
63
+ const [event] = messages.flatMap(Trace.flatten);
64
+ expect(Trace.isOfType(Trace.ModelCall, event)).toBe(true);
65
+ expect(event.data).toMatchObject({
66
+ modelId: Model.claudeHaiku55.id.toString(),
67
+ model: 'claude-haiku-5-5',
68
+ stage: 'extract-facts',
69
+ inputTokens: 1_000,
70
+ outputTokens: 200,
71
+ });
72
+ }),
73
+ );
74
+
75
+ it.effect('totals calls per model and stage, priced from the catalog', () =>
76
+ Effect.gen(function* () {
77
+ const { messages, layer } = setup();
78
+ yield* Effect.all([call, call], { concurrency: 'unbounded' }).pipe(
79
+ AiUsage.withStage('topics'),
80
+ Effect.provide(layer),
81
+ );
82
+
83
+ const [total] = AiMetering.summarize(messages.flatMap(Trace.flatten));
84
+ expect(total).toMatchObject({ model: 'claude-haiku-5-5', stage: 'topics', calls: 2, inputTokens: 2_000 });
85
+ // 2,000 input at $0.10/M plus 400 output at $0.50/M.
86
+ expect(total.cost).toBeCloseTo(0.0004, 10);
87
+ }),
88
+ );
89
+ });
@@ -0,0 +1,93 @@
1
+ //
2
+ // Copyright 2026 DXOS.org
3
+ //
4
+
5
+ // @import-as-namespace
6
+
7
+ import * as Effect from 'effect/Effect';
8
+ import * as Fiber from 'effect/Fiber';
9
+ import * as Layer from 'effect/Layer';
10
+
11
+ import { AiService, AiUsage } from '@dxos/ai';
12
+
13
+ import * as Trace from './Trace.ts';
14
+
15
+ /**
16
+ * An `AiService` that writes a {@link Trace.ModelCall} event for every language-model call made
17
+ * through the `AiService` below it, so a run's token usage (and, with catalog prices, its cost) can
18
+ * be read back from its trace. Lives here rather than in `@dxos/ai`, which cannot depend on the trace.
19
+ */
20
+ export const metered: Layer.Layer<AiService.AiService, never, AiService.AiService | Trace.TraceService> = Layer.effect(
21
+ AiService.AiService,
22
+ Effect.gen(function* () {
23
+ const upstream = yield* AiService.AiService;
24
+ const writer = yield* Trace.TraceService;
25
+ return AiUsage.instrument(upstream, (call) => {
26
+ // The recorder runs synchronously on the model call's fiber, so the caller's thread is readable here.
27
+ const thread = Fiber.getCurrent()?.getRef(Trace.CurrentThread);
28
+ writer.write(
29
+ Trace.ModelCall,
30
+ {
31
+ modelId: call.modelId,
32
+ model: call.model,
33
+ provider: call.provider,
34
+ stage: call.stage,
35
+ spanName: call.spanName,
36
+ inputTokens: call.inputTokens,
37
+ outputTokens: call.outputTokens,
38
+ cacheReadTokens: call.cacheReadTokens,
39
+ cacheWriteTokens: call.cacheWriteTokens,
40
+ start: call.start,
41
+ end: call.end,
42
+ },
43
+ thread === undefined ? undefined : { thread },
44
+ );
45
+ });
46
+ }),
47
+ );
48
+
49
+ /** Token and dollar totals for one model (and stage), as {@link summarize} reports them. */
50
+ export type Total = AiUsage.Tokens & {
51
+ readonly model: string;
52
+ readonly stage?: string;
53
+ readonly calls: number;
54
+ /** USD at the catalog's list price; undefined when the catalog has no price for the model. */
55
+ readonly cost?: number;
56
+ };
57
+
58
+ /**
59
+ * Totals of the {@link Trace.ModelCall} events among `events`, one per model and stage, priced from
60
+ * the model catalog.
61
+ */
62
+ export const summarize = (events: Iterable<Trace.Event>): Total[] => {
63
+ const totals = new Map<string, Total & { readonly modelId?: string }>();
64
+ for (const event of events) {
65
+ if (!Trace.isOfType(Trace.ModelCall, event)) {
66
+ continue;
67
+ }
68
+ const call = event.data;
69
+ const key = `${call.modelId ?? call.model}\u0000${call.stage ?? ''}`;
70
+ const total = totals.get(key) ?? {
71
+ modelId: call.modelId,
72
+ model: call.model,
73
+ stage: call.stage,
74
+ calls: 0,
75
+ inputTokens: 0,
76
+ outputTokens: 0,
77
+ cacheReadTokens: 0,
78
+ cacheWriteTokens: 0,
79
+ };
80
+ totals.set(key, {
81
+ ...total,
82
+ calls: total.calls + 1,
83
+ inputTokens: total.inputTokens + call.inputTokens,
84
+ outputTokens: total.outputTokens + call.outputTokens,
85
+ cacheReadTokens: total.cacheReadTokens + call.cacheReadTokens,
86
+ cacheWriteTokens: total.cacheWriteTokens + call.cacheWriteTokens,
87
+ });
88
+ }
89
+ return [...totals.values()].map(({ modelId, ...total }) => {
90
+ const pricing = modelId === undefined ? undefined : AiUsage.pricingOf(modelId);
91
+ return pricing === undefined ? total : { ...total, cost: AiUsage.cost(total, pricing) };
92
+ });
93
+ };
@@ -0,0 +1,75 @@
1
+ //
2
+ // Copyright 2026 DXOS.org
3
+ //
4
+
5
+ import * as Schema from 'effect/Schema';
6
+ import { describe, test } from 'vitest';
7
+
8
+ import { DXN } from '@dxos/keys';
9
+
10
+ import * as Hook from './Hook.ts';
11
+ import * as Operation from './Operation.ts';
12
+
13
+ const operation = Operation.make({
14
+ meta: { key: DXN.make('com.example.operation.hook'), name: 'Hook' },
15
+ input: Schema.Struct({}),
16
+ output: Schema.Void,
17
+ });
18
+
19
+ const PLANNING_SKILL = 'com.example.skill.planning';
20
+ const PLANNING = 'com.example.plugin.planning';
21
+ const AUDIT = 'com.example.plugin.audit';
22
+
23
+ const [reminder] = Hook.forPlugin(PLANNING, [
24
+ { key: 'com.example.hook.reminder', event: 'end-request', skill: PLANNING_SKILL, operation },
25
+ ]);
26
+ const [audit] = Hook.forPlugin(AUDIT, [{ key: 'com.example.hook.audit', event: 'end-request', operation }]);
27
+ const catalog = [reminder, audit];
28
+
29
+ const resolve = (props: Partial<Parameters<typeof Hook.resolve>[0]>) => {
30
+ const { run, ...rest } = Hook.resolve({ catalog, event: 'end-request', skillKeys: new Set(), ...props });
31
+ return { run: run.map((hook) => hook.key), ...rest };
32
+ };
33
+
34
+ describe('Hook.resolve', () => {
35
+ test("a plugin is on by default only if every one of its hooks names a skill, and then where it's bound", ({
36
+ expect,
37
+ }) => {
38
+ expect(Hook.isOnByDefault(catalog, PLANNING)).toBe(true);
39
+ expect(Hook.isOnByDefault(catalog, AUDIT)).toBe(false);
40
+ expect(resolve({})).toEqual({ run: [], byDefault: [], inactive: [], missing: [] });
41
+ expect(resolve({ skillKeys: new Set([PLANNING_SKILL]) })).toEqual({
42
+ run: [reminder.key],
43
+ byDefault: [reminder.key],
44
+ inactive: [],
45
+ missing: [],
46
+ });
47
+ });
48
+
49
+ test('instructions override the space plugin by plugin', ({ expect }) => {
50
+ expect(
51
+ resolve({
52
+ space: { [PLANNING]: false, [AUDIT]: true },
53
+ instructions: { [PLANNING]: true },
54
+ skillKeys: new Set([PLANNING_SKILL]),
55
+ }),
56
+ ).toEqual({ run: [reminder.key, audit.key], byDefault: [], inactive: [], missing: [] });
57
+ expect(resolve({ space: { [AUDIT]: true }, instructions: { [AUDIT]: false } })).toEqual({
58
+ run: [],
59
+ byDefault: [],
60
+ inactive: [],
61
+ missing: [],
62
+ });
63
+ });
64
+
65
+ test('a hook a setting turns on is inactive while its skill is unbound, and a plugin the host lacks is missing', ({
66
+ expect,
67
+ }) => {
68
+ expect(resolve({ space: { [PLANNING]: true, 'com.example.plugin.elsewhere': true } })).toEqual({
69
+ run: [],
70
+ byDefault: [],
71
+ inactive: [reminder.key],
72
+ missing: ['com.example.plugin.elsewhere'],
73
+ });
74
+ });
75
+ });
package/src/Hook.ts ADDED
@@ -0,0 +1,154 @@
1
+ //
2
+ // Copyright 2026 DXOS.org
3
+ //
4
+
5
+ // @import-as-namespace
6
+
7
+ import * as Option from 'effect/Option';
8
+ import * as Schema from 'effect/Schema';
9
+
10
+ import { Annotation, Obj } from '@dxos/echo';
11
+
12
+ import type * as Operation from './Operation.ts';
13
+
14
+ /**
15
+ * A lifecycle hook an agent host can run, contributed by a plugin beside its skills rather than declared on a
16
+ * {@link Skill}, so a skill stays to the Agent Skills spec's fields. Static: a hook is code, never stored in a
17
+ * space. Whether it runs is up to its plugin's {@link SettingsAnnotation} entry (see {@link resolve}).
18
+ */
19
+ export type Definition = {
20
+ /** Stable id the trace names the hook by, e.g. `org.dxos.hook.planning.planReminder`. */
21
+ key: string;
22
+
23
+ /** Id of the plugin that contributes the hook; settings turn hooks on and off by plugin. */
24
+ plugin: string;
25
+
26
+ /**
27
+ * When the hook fires. `end-request` is after the model has driven a request to completion: the
28
+ * series of agent/tool turns a prompt starts.
29
+ */
30
+ event: 'end-request';
31
+
32
+ /** Key of a skill that must be bound to the conversation for the hook to fire; absent ⇒ every conversation. */
33
+ skill?: string;
34
+
35
+ /** Runs with the conversation in its environment; may return {@link Output}. */
36
+ operation: Operation.Definition.Any;
37
+
38
+ /** Passed as the operation's input. */
39
+ input?: Record<string, unknown>;
40
+
41
+ /**
42
+ * Run in the background: the request settles without waiting for the hook, and the agent process
43
+ * awaits it before it finishes. For work the user should not wait on, e.g. reviewing the turn that
44
+ * just ended.
45
+ */
46
+ async?: boolean;
47
+ };
48
+
49
+ /**
50
+ * What a hook returns. A `followUp` is queued to the agent as a synthetic prompt, so the request
51
+ * continues instead of ending — e.g. a reminder that the plan still has open tasks.
52
+ */
53
+ export const Output = Schema.Struct({
54
+ followUp: Schema.optional(Schema.String),
55
+ });
56
+
57
+ export type Output = Schema.Schema.Type<typeof Output>;
58
+
59
+ /** A hook as a plugin declares it; the plugin adds its id when it contributes the hook ({@link forPlugin}). */
60
+ export type Declaration = Omit<Definition, 'plugin'>;
61
+
62
+ /** `hooks` as `plugin` contributes them. */
63
+ export const forPlugin = (plugin: string, hooks: readonly Declaration[]): Definition[] =>
64
+ hooks.map((hook) => ({ ...hook, plugin }));
65
+
66
+ /** Plugin ids whose hooks are turned on (`true`) or off (`false`); a plugin not listed has its default. */
67
+ export type Settings = Readonly<Record<string, boolean>>;
68
+
69
+ /**
70
+ * Which plugins' hooks run, on a space's properties (for every agent in the space, wherever it runs) and on an
71
+ * agent's instructions (for runs with those instructions, overriding the space plugin by plugin).
72
+ */
73
+ export const SettingsAnnotation = Annotation.make({
74
+ id: 'org.dxos.annotation.hooks',
75
+ schema: Schema.Record(Schema.String, Schema.Boolean),
76
+ });
77
+
78
+ /** Turns `plugin`'s hooks on or off in `target`'s settings (a space's properties or an agent's instructions). */
79
+ export const setEnabled = (target: Obj.Unknown, plugin: string, enabled: boolean): void => {
80
+ Obj.update(target, (target) => {
81
+ const settings = Annotation.get(target, SettingsAnnotation).pipe(Option.getOrElse(() => ({})));
82
+ Annotation.set(target, SettingsAnnotation, { ...settings, [plugin]: enabled });
83
+ });
84
+ };
85
+
86
+ /**
87
+ * Whether `plugin`'s hooks run when no setting names it: only if every one of them is gated by a skill, so a
88
+ * host that has every plugin (EDGE) runs nothing a conversation did not opt into by binding the skill.
89
+ */
90
+ export const isOnByDefault = (catalog: readonly Definition[], plugin: string): boolean =>
91
+ catalog.every((hook) => hook.plugin !== plugin || hook.skill !== undefined);
92
+
93
+ /** The hooks one request runs, and what the trace records about the rest. */
94
+ export type Resolution = {
95
+ /** On, available on this host, and their skill condition holds. */
96
+ run: Definition[];
97
+ /** Keys of the hooks in `run` that are on by their plugin's default rather than a setting. */
98
+ byDefault: string[];
99
+ /** Keys of hooks a setting turns on whose skill is not bound. */
100
+ inactive: string[];
101
+ /** Plugins a setting turns on that contribute no hook on this host (e.g. not enabled here). */
102
+ missing: string[];
103
+ };
104
+
105
+ /**
106
+ * The hooks for `event` whose plugin `space` and `instructions` leave on, given the skills bound to the
107
+ * conversation. Hooks run in catalog order.
108
+ */
109
+ export const resolve = ({
110
+ catalog,
111
+ event,
112
+ space = {},
113
+ instructions = {},
114
+ skillKeys,
115
+ }: {
116
+ catalog: readonly Definition[];
117
+ event: Definition['event'];
118
+ space?: Settings;
119
+ instructions?: Settings;
120
+ skillKeys: ReadonlySet<string>;
121
+ }): Resolution => {
122
+ const settings: Settings = { ...space, ...instructions };
123
+ const resolution: Resolution = {
124
+ run: [],
125
+ byDefault: [],
126
+ inactive: [],
127
+ missing: Object.keys(settings)
128
+ .filter((plugin) => settings[plugin] && !catalog.some((hook) => hook.plugin === plugin))
129
+ .sort(),
130
+ };
131
+ for (const hook of catalog) {
132
+ const setting = settings[hook.plugin];
133
+ if (hook.event !== event || !(setting ?? isOnByDefault(catalog, hook.plugin))) {
134
+ continue;
135
+ }
136
+ if (hook.skill === undefined || skillKeys.has(hook.skill)) {
137
+ resolution.run.push(hook);
138
+ if (setting === undefined) {
139
+ resolution.byDefault.push(hook.key);
140
+ }
141
+ } else if (setting !== undefined) {
142
+ resolution.inactive.push(hook.key);
143
+ }
144
+ }
145
+ return resolution;
146
+ };
147
+
148
+ /** The follow-up a hook's output asks for; anything else, including no output, asks for none. */
149
+ export const followUp = (output: unknown): string | undefined =>
150
+ Schema.decodeUnknownOption(Output)(output).pipe(
151
+ Option.flatMap(({ followUp }) => Option.fromNullishOr(followUp)),
152
+ Option.filter((text) => text.length > 0),
153
+ Option.getOrUndefined,
154
+ );
@@ -135,3 +135,26 @@ describe('tryToolNameFromKey', () => {
135
135
  expect(() => Operation.toolNameFromKey('org.dxos.operation.9bad.go')).toThrow();
136
136
  });
137
137
  });
138
+
139
+ describe('Operation consent preview', () => {
140
+ const op = Operation.make({
141
+ input: Schema.Struct({ to: Schema.String, body: Schema.String }),
142
+ output: Schema.Void,
143
+ meta: { key: KEY, name: 'Send' },
144
+ });
145
+
146
+ test('previews the named string field of the input', ({ expect }) => {
147
+ const annotated = op.pipe(
148
+ Operation.annotate(Operation.ConsentPreviewAnnotation, { field: 'body', label: 'Reply' }),
149
+ );
150
+ expect(Operation.getConsentPreview(annotated, { to: 'dana', body: 'Hi Dana' })).toEqual({
151
+ label: 'Reply',
152
+ text: 'Hi Dana',
153
+ });
154
+ expect(Operation.getConsentPreview(annotated, { to: 'dana', body: ' ' })).toBeUndefined();
155
+ });
156
+
157
+ test('previews nothing for an operation that names no field', ({ expect }) => {
158
+ expect(Operation.getConsentPreview(op, { to: 'dana', body: 'Hi Dana' })).toBeUndefined();
159
+ });
160
+ });