@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
@@ -0,0 +1,114 @@
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, Feed, Obj, Ref } from '@dxos/echo';
9
+ import { IdentityDid } from '@dxos/keys';
10
+
11
+ import * as Trajectory from './Trajectory.ts';
12
+
13
+ const user: Trajectory.Sender = { role: 'user', identity: IdentityDid.random(), name: 'alice' };
14
+ const assistant: Trajectory.Sender = { role: 'assistant' };
15
+ const model = DXN.make('com.anthropic.model.claude-sonnet-5.default');
16
+ const anchor = Obj.ID.random();
17
+ const branch = Trajectory.ThreadId.make('3@a');
18
+
19
+ const payloads: Trajectory.Payload[] = [
20
+ { _tag: 'message', blocks: [{ _tag: 'text', text: 'hello' }] },
21
+ {
22
+ _tag: 'message',
23
+ blocks: [{ _tag: 'toolCall', toolCallId: 't1', name: 'search', input: '{}', providerExecuted: false }],
24
+ },
25
+ { _tag: 'turnBegin', model },
26
+ { _tag: 'turnEnd', finishReason: 'stop', usage: { inputTokens: 10, cacheReadTokens: 8 } },
27
+ { _tag: 'promptConsume', message: anchor },
28
+ { _tag: 'promptCancel', message: anchor },
29
+ { _tag: 'contextBind', skills: [], objects: [] },
30
+ { _tag: 'contextUnbind', skills: [], objects: [] },
31
+ { _tag: 'alarmSet', wakeAt: 1_000, message: 'check build' },
32
+ { _tag: 'alarmCancel', alarm: anchor },
33
+ { _tag: 'alarmFire', alarm: anchor },
34
+ { _tag: 'toolBackground', toolCallId: 't1', pid: 'p1' },
35
+ {
36
+ _tag: 'toolDeliver',
37
+ toolCallId: 't1',
38
+ result: { _tag: 'toolResult', toolCallId: 't1', name: 'search', providerExecuted: false },
39
+ },
40
+ { _tag: 'hookBegin', hook: 'lint', kind: 'agentic', thread: branch },
41
+ { _tag: 'hookEnd', begin: anchor, blocks: [{ _tag: 'text', text: 'ok' }] },
42
+ { _tag: 'compact', from: anchor, to: anchor, summary: [{ _tag: 'text', text: 'earlier work' }] },
43
+ { _tag: 'requestResolve', message: anchor, requestId: 'r1', resolution: { outcome: 'selected', optionId: 'allow' } },
44
+ { _tag: 'rewind', from: anchor },
45
+ { _tag: 'fork', from: { event: anchor } },
46
+ { _tag: 'threadOpen', mode: 'fork', from: { event: anchor }, purpose: 'turn' },
47
+ { _tag: 'threadMerge', mode: 'summary', summary: [{ _tag: 'text', text: 'subagent result' }] },
48
+ { _tag: 'threadClose', status: 'completed' },
49
+ { _tag: 'threadWait', on: branch },
50
+ { _tag: 'modelChange', model },
51
+ { _tag: 'custom', type: 'org.example.checkpoint', visible: false, data: { step: 3 } },
52
+ ];
53
+
54
+ describe('Trajectory', () => {
55
+ test('payload fixtures cover every tag', ({ expect }) => {
56
+ const tags = new Set(payloads.map((payload) => payload._tag));
57
+ expect(tags.size).to.eq(Trajectory.Payload.members.length);
58
+ });
59
+
60
+ test('every payload round-trips through the schema', ({ expect }) => {
61
+ for (const payload of payloads) {
62
+ const encoded = Schema.encodeSync(Trajectory.Payload)(payload);
63
+ expect(Schema.decodeUnknownSync(Trajectory.Payload)(encoded)).to.deep.eq(payload);
64
+ }
65
+ });
66
+
67
+ test('rejects an unknown tag', ({ expect }) => {
68
+ expect(() => Schema.decodeUnknownSync(Trajectory.Payload)({ _tag: 'nope' })).to.throw();
69
+ });
70
+
71
+ test('make() creates an event object for every payload', ({ expect }) => {
72
+ for (const payload of payloads) {
73
+ const event = Trajectory.make({ payload, sender: assistant });
74
+ expect(Obj.instanceOf(Trajectory.Event, event)).to.be.true;
75
+ expect(event.payload._tag).to.eq(payload._tag);
76
+ expect(Trajectory.threadOf(event)).to.be.undefined;
77
+ }
78
+ });
79
+
80
+ test("make() puts the event on its thread's branch and keeps the timestamp", ({ expect }) => {
81
+ const event = Trajectory.make({
82
+ payload: { _tag: 'message', blocks: [{ _tag: 'text', text: 'hi' }] },
83
+ sender: user,
84
+ thread: branch,
85
+ created: '2026-01-01T00:00:00.000Z',
86
+ });
87
+ expect(Trajectory.threadOf(event)).to.eq(branch);
88
+ expect(Feed.getBranch(event)).to.eq(branch);
89
+ expect(event.created).to.eq('2026-01-01T00:00:00.000Z');
90
+ });
91
+
92
+ test('sender identity must be a DID', ({ expect }) => {
93
+ expect(Schema.decodeUnknownSync(Trajectory.Sender)(user)).to.deep.eq(user);
94
+ expect(() => Schema.decodeUnknownSync(Trajectory.Sender)({ role: 'user', identity: 'alice' })).to.throw();
95
+ });
96
+
97
+ test('is() narrows by payload tag', ({ expect }) => {
98
+ const event = Trajectory.make({ payload: { _tag: 'alarmSet', wakeAt: 5 }, sender: assistant });
99
+ expect(Trajectory.is(event, 'alarmSet')).to.be.true;
100
+ expect(Trajectory.is(event, 'alarmFire')).to.be.false;
101
+ if (Trajectory.is(event, 'alarmSet')) {
102
+ expect(event.payload.wakeAt).to.eq(5);
103
+ }
104
+ });
105
+
106
+ test('threadOpen can fork from another conversation', ({ expect }) => {
107
+ const feed = Feed.make();
108
+ const event = Trajectory.make({
109
+ payload: { _tag: 'threadOpen', mode: 'fork', from: { feed: Ref.make(feed), event: anchor } },
110
+ sender: user,
111
+ });
112
+ expect(Trajectory.is(event, 'threadOpen') && event.payload.from?.feed?.target).to.eq(feed);
113
+ });
114
+ });
@@ -0,0 +1,440 @@
1
+ //
2
+ // Copyright 2026 DXOS.org
3
+ //
4
+
5
+ // @import-as-namespace
6
+
7
+ import * as Schema from 'effect/Schema';
8
+
9
+ import { Annotation, DXN, Feed, Obj, Ref, Type } from '@dxos/echo';
10
+ import { IdentityDid } from '@dxos/keys';
11
+ import { ContentBlock, Message as TypesMessage } from '@dxos/types';
12
+
13
+ import * as Skill from '../types/Skill.ts';
14
+
15
+ /**
16
+ * Id of an earlier event in the same log; events reference each other by id because they are never mutated.
17
+ */
18
+ export const EventId = Obj.ID;
19
+ export type EventId = Schema.Schema.Type<typeof EventId>;
20
+
21
+ /**
22
+ * A thread (or turn) is a branch of the conversation's feed: its opener is the branch's base, and every event written
23
+ * in it continues the branch. The main thread is the root branch, which has no id.
24
+ */
25
+ export const ThreadId = Feed.BranchId;
26
+ export type ThreadId = Schema.Schema.Type<typeof ThreadId>;
27
+
28
+ //
29
+ // Sender
30
+ //
31
+
32
+ /**
33
+ * `event` marks content from outside the conversation (alarm, webhook, email, background result), which the model
34
+ * sees as a synthetic user turn rather than as something a person typed.
35
+ */
36
+ export const Role = Schema.Literals(['user', 'assistant', 'tool', 'event']);
37
+ export type Role = Schema.Schema.Type<typeof Role>;
38
+
39
+ export const Sender = Schema.Struct({
40
+ role: Role,
41
+ /** Writer's identity, which tells participants apart in a multi-tenant chat. */
42
+ identity: Schema.optional(IdentityDid),
43
+ /** Object the sender stands for when it is not a person (agent session, service, hook). */
44
+ subject: Schema.optional(Ref.Ref(Obj.Unknown)),
45
+ name: Schema.optional(Schema.String),
46
+ });
47
+ export type Sender = Schema.Schema.Type<typeof Sender>;
48
+
49
+ //
50
+ // Content
51
+ //
52
+
53
+ /**
54
+ * Content seen by the model, attributed by the event's `sender`. A user message stays out of the prompt until a
55
+ * {@link PromptConsume} names it, so a prompt typed mid-turn never lands inside a prefix already sent.
56
+ */
57
+ export const Message = Schema.TaggedStruct('message', {
58
+ blocks: Schema.Array(ContentBlock.Any),
59
+ /** Files or objects attached alongside the blocks, as on `Message.Message`. */
60
+ attachments: Schema.optional(Schema.Array(TypesMessage.Attachment)),
61
+ /**
62
+ * `Message.Message`'s properties, carried so a message converts both ways; a channel backend's post receipt lives
63
+ * here (e.g. `discord.messageId`), which tells a mirror the message is already posted.
64
+ */
65
+ properties: Schema.optional(Schema.Record(Schema.String, Schema.Any)),
66
+ });
67
+ export type Message = Schema.Schema.Type<typeof Message>;
68
+
69
+ //
70
+ // Turn
71
+ //
72
+
73
+ export const Usage = Schema.Struct({
74
+ inputTokens: Schema.optional(Schema.Number),
75
+ outputTokens: Schema.optional(Schema.Number),
76
+ cacheReadTokens: Schema.optional(Schema.Number),
77
+ cacheWriteTokens: Schema.optional(Schema.Number),
78
+ });
79
+ export type Usage = Schema.Schema.Type<typeof Usage>;
80
+
81
+ /**
82
+ * What a thread or turn could see when it started: the parent thread up to and including `event`.
83
+ */
84
+ export const ThreadOrigin = Schema.Struct({
85
+ /** Feed of another conversation; absent for the current one. */
86
+ feed: Schema.optional(Ref.Ref(Feed.Feed)),
87
+ /** Parent thread; absent for the main thread. */
88
+ thread: Schema.optional(ThreadId),
89
+ /**
90
+ * Last event of the parent that was visible: the last event the writer had folded when it wrote the opener, so an
91
+ * event that syncs in afterwards stays out of what the thread saw.
92
+ */
93
+ event: EventId,
94
+ });
95
+ export type ThreadOrigin = Schema.Schema.Type<typeof ThreadOrigin>;
96
+
97
+ /**
98
+ * Start of one model request: the base of the turn's own branch, so every event the turn produces continues that
99
+ * branch, and `turnEnd` (the branch's last event) merges the turn into its parent.
100
+ */
101
+ export const TurnBegin = Schema.TaggedStruct('turnBegin', {
102
+ /** Model DXN, as `SessionConfig.model` stores it; absent when the writer does not choose the model. */
103
+ model: Schema.optional(DXN.Schema),
104
+ /** What the turn saw; absent when it started on an empty log. */
105
+ from: Schema.optional(ThreadOrigin),
106
+ });
107
+ export type TurnBegin = Schema.Schema.Type<typeof TurnBegin>;
108
+
109
+ /** Ends the turn whose branch it is written on. */
110
+ export const TurnEnd = Schema.TaggedStruct('turnEnd', {
111
+ finishReason: ContentBlock.FinishReason,
112
+ usage: Schema.optional(Usage),
113
+ error: Schema.optional(Schema.String),
114
+ });
115
+ export type TurnEnd = Schema.Schema.Type<typeof TurnEnd>;
116
+
117
+ //
118
+ // Prompt queue (pending = user messages with no consume or cancel).
119
+ //
120
+
121
+ /**
122
+ * The agent took a user message into its next turn; the message enters the prompt at this event's position.
123
+ */
124
+ export const PromptConsume = Schema.TaggedStruct('promptConsume', {
125
+ message: EventId,
126
+ });
127
+ export type PromptConsume = Schema.Schema.Type<typeof PromptConsume>;
128
+
129
+ export const PromptCancel = Schema.TaggedStruct('promptCancel', {
130
+ message: EventId,
131
+ });
132
+ export type PromptCancel = Schema.Schema.Type<typeof PromptCancel>;
133
+
134
+ //
135
+ // Context
136
+ //
137
+
138
+ const ContextDelta = {
139
+ skills: Schema.Array(Ref.Ref(Skill.Skill)),
140
+ objects: Schema.Array(Ref.Ref(Obj.Unknown)),
141
+ /**
142
+ * Connections whose MCP server the conversation turns on (`contextBind`) or off (`contextUnbind`); one never
143
+ * named follows the space default.
144
+ */
145
+ connections: Schema.optional(Schema.Array(Ref.Ref(Obj.Unknown))),
146
+ };
147
+
148
+ export const ContextBind = Schema.TaggedStruct('contextBind', ContextDelta);
149
+ export type ContextBind = Schema.Schema.Type<typeof ContextBind>;
150
+
151
+ export const ContextUnbind = Schema.TaggedStruct('contextUnbind', ContextDelta);
152
+ export type ContextUnbind = Schema.Schema.Type<typeof ContextUnbind>;
153
+
154
+ //
155
+ // Alarms
156
+ //
157
+
158
+ export const AlarmSet = Schema.TaggedStruct('alarmSet', {
159
+ /** Epoch milliseconds. */
160
+ wakeAt: Schema.Number,
161
+ message: Schema.optional(Schema.String),
162
+ });
163
+ export type AlarmSet = Schema.Schema.Type<typeof AlarmSet>;
164
+
165
+ export const AlarmCancel = Schema.TaggedStruct('alarmCancel', {
166
+ alarm: EventId,
167
+ });
168
+ export type AlarmCancel = Schema.Schema.Type<typeof AlarmCancel>;
169
+
170
+ export const AlarmFire = Schema.TaggedStruct('alarmFire', {
171
+ alarm: EventId,
172
+ });
173
+ export type AlarmFire = Schema.Schema.Type<typeof AlarmFire>;
174
+
175
+ //
176
+ // Background tools
177
+ //
178
+
179
+ /**
180
+ * A tool call that outlived its turn; its result arrives later as {@link ToolDeliver}.
181
+ */
182
+ export const ToolBackground = Schema.TaggedStruct('toolBackground', {
183
+ toolCallId: Schema.String,
184
+ /** Process running the call. */
185
+ pid: Schema.optional(Schema.String),
186
+ });
187
+ export type ToolBackground = Schema.Schema.Type<typeof ToolBackground>;
188
+
189
+ export const ToolDeliver = Schema.TaggedStruct('toolDeliver', {
190
+ toolCallId: Schema.String,
191
+ result: ContentBlock.ToolResult,
192
+ });
193
+ export type ToolDeliver = Schema.Schema.Type<typeof ToolDeliver>;
194
+
195
+ //
196
+ // Hooks
197
+ //
198
+
199
+ export const HookKind = Schema.Literals(['inline', 'background', 'agentic']);
200
+ export type HookKind = Schema.Schema.Type<typeof HookKind>;
201
+
202
+ export const HookBegin = Schema.TaggedStruct('hookBegin', {
203
+ hook: Schema.String,
204
+ kind: HookKind,
205
+ /** Thread an agentic hook runs in. */
206
+ thread: Schema.optional(ThreadId),
207
+ });
208
+ export type HookBegin = Schema.Schema.Type<typeof HookBegin>;
209
+
210
+ export const HookEnd = Schema.TaggedStruct('hookEnd', {
211
+ begin: EventId,
212
+ /** Output of an inline hook, which the model sees. */
213
+ blocks: Schema.optional(Schema.Array(ContentBlock.Any)),
214
+ error: Schema.optional(Schema.String),
215
+ });
216
+ export type HookEnd = Schema.Schema.Type<typeof HookEnd>;
217
+
218
+ //
219
+ // Compaction
220
+ //
221
+
222
+ /**
223
+ * Replaces the inclusive range `from`..`to` with `summary` in the prompt; the events themselves stay in the log.
224
+ */
225
+ export const Compact = Schema.TaggedStruct('compact', {
226
+ from: EventId,
227
+ to: EventId,
228
+ summary: Schema.Array(ContentBlock.Any),
229
+ /** Threads whose merged entries the range holds; a thread still running is never in it. */
230
+ closure: Schema.optional(Schema.Array(ThreadId)),
231
+ });
232
+ export type Compact = Schema.Schema.Type<typeof Compact>;
233
+
234
+ /**
235
+ * A person's answer to a `request` block an agent asked in an earlier message; the message itself never changes.
236
+ */
237
+ export const RequestResolve = Schema.TaggedStruct('requestResolve', {
238
+ message: EventId,
239
+ requestId: Schema.String,
240
+ resolution: Schema.Struct({
241
+ outcome: Schema.Literals(['selected', 'cancelled']),
242
+ optionId: Schema.optional(Schema.String),
243
+ }),
244
+ });
245
+ export type RequestResolve = Schema.Schema.Type<typeof RequestResolve>;
246
+
247
+ /**
248
+ * Discards the main thread from `from` on: its prompt entries and thread items go, the events stay in the log.
249
+ */
250
+ export const Rewind = Schema.TaggedStruct('rewind', {
251
+ /** First event discarded. */
252
+ from: EventId,
253
+ });
254
+ export type Rewind = Schema.Schema.Type<typeof Rewind>;
255
+
256
+ /**
257
+ * Continues another conversation: its prompt up to `from.event` precedes this feed's main thread.
258
+ */
259
+ export const Fork = Schema.TaggedStruct('fork', {
260
+ from: ThreadOrigin,
261
+ });
262
+ export type Fork = Schema.Schema.Type<typeof Fork>;
263
+
264
+ //
265
+ // Threads
266
+ //
267
+
268
+ /**
269
+ * `light` is a fork of main that also starts with a transcript of each thread still running beside it (its
270
+ * `siblings`), so a prompt sent while the agent works runs in parallel with that work.
271
+ */
272
+ export const ThreadMode = Schema.Literals(['fork', 'fresh', 'light']);
273
+ export type ThreadMode = Schema.Schema.Type<typeof ThreadMode>;
274
+
275
+ /**
276
+ * Opens a thread: the base of its own branch, whose id is the thread's; the event's `sender` owns the thread.
277
+ */
278
+ export const ThreadOpen = Schema.TaggedStruct('threadOpen', {
279
+ mode: ThreadMode,
280
+ /** Where a `fork` or `light` thread branches from; a `fresh` thread starts with no history. */
281
+ from: Schema.optional(ThreadOrigin),
282
+ purpose: Schema.optional(Schema.String),
283
+ /** `light` only: threads (or turns on main) still running when it opened, whose work it starts with. */
284
+ siblings: Schema.optional(Schema.Array(ThreadId)),
285
+ });
286
+ export type ThreadOpen = Schema.Schema.Type<typeof ThreadOpen>;
287
+
288
+ export const MergeMode = Schema.Literals(['raw', 'summary']);
289
+ export type MergeMode = Schema.Schema.Type<typeof MergeMode>;
290
+
291
+ /** Joins the thread whose branch it is written on to its parent. */
292
+ export const ThreadMerge = Schema.TaggedStruct('threadMerge', {
293
+ mode: MergeMode,
294
+ summary: Schema.optional(Schema.Array(ContentBlock.Any)),
295
+ });
296
+ export type ThreadMerge = Schema.Schema.Type<typeof ThreadMerge>;
297
+
298
+ /**
299
+ * A turn waits for another thread to end before it continues; written in the waiting turn's thread.
300
+ */
301
+ export const ThreadWait = Schema.TaggedStruct('threadWait', {
302
+ on: ThreadId,
303
+ });
304
+ export type ThreadWait = Schema.Schema.Type<typeof ThreadWait>;
305
+
306
+ export const ThreadStatus = Schema.Literals(['completed', 'failed', 'cancelled']);
307
+ export type ThreadStatus = Schema.Schema.Type<typeof ThreadStatus>;
308
+
309
+ /** Ends the thread whose branch it is written on without merging it. */
310
+ export const ThreadClose = Schema.TaggedStruct('threadClose', {
311
+ status: ThreadStatus,
312
+ });
313
+ export type ThreadClose = Schema.Schema.Type<typeof ThreadClose>;
314
+
315
+ //
316
+ // Config
317
+ //
318
+
319
+ export const ModelChange = Schema.TaggedStruct('modelChange', {
320
+ model: DXN.Schema,
321
+ });
322
+ export type ModelChange = Schema.Schema.Type<typeof ModelChange>;
323
+
324
+ //
325
+ // Escape hatch
326
+ //
327
+
328
+ /**
329
+ * Extension-defined event; `blocks` reach the model only when `visible` is set.
330
+ */
331
+ export const Custom = Schema.TaggedStruct('custom', {
332
+ /** Namespaced extension type (e.g. `org.example.checkpoint`). */
333
+ type: Schema.String,
334
+ visible: Schema.Boolean,
335
+ data: Schema.optional(Schema.Unknown),
336
+ blocks: Schema.optional(Schema.Array(ContentBlock.Any)),
337
+ });
338
+ export type Custom = Schema.Schema.Type<typeof Custom>;
339
+
340
+ export const Payload = Schema.Union([
341
+ Message,
342
+ TurnBegin,
343
+ TurnEnd,
344
+ PromptConsume,
345
+ PromptCancel,
346
+ ContextBind,
347
+ ContextUnbind,
348
+ AlarmSet,
349
+ AlarmCancel,
350
+ AlarmFire,
351
+ ToolBackground,
352
+ ToolDeliver,
353
+ HookBegin,
354
+ HookEnd,
355
+ Compact,
356
+ RequestResolve,
357
+ Rewind,
358
+ Fork,
359
+ ThreadOpen,
360
+ ThreadMerge,
361
+ ThreadWait,
362
+ ThreadClose,
363
+ ModelChange,
364
+ Custom,
365
+ ]);
366
+ export type Payload = Schema.Schema.Type<typeof Payload>;
367
+
368
+ export type PayloadTag = Payload['_tag'];
369
+
370
+ export type PayloadOf<T extends PayloadTag> = Extract<Payload, { _tag: T }>;
371
+
372
+ //
373
+ // Event
374
+ //
375
+
376
+ /**
377
+ * One immutable entry in an agent trajectory; every conversation state (history, queue, alarms, bindings, threads)
378
+ * is a reduction over the feed's events in feed order.
379
+ */
380
+ export class Event extends Type.makeObject<Event>(DXN.make('org.dxos.type.trajectory.event', '0.1.0'))(
381
+ Schema.Struct({
382
+ sender: Sender,
383
+ /** ISO timestamp; display only, ordering is by feed position. */
384
+ created: Schema.String.pipe(Annotation.GeneratorAnnotation.set('date.iso8601')),
385
+ payload: Payload,
386
+ }).pipe(Annotation.IconAnnotation.set({ icon: 'ph--path--regular', hue: 'indigo' })),
387
+ ) {}
388
+
389
+ /**
390
+ * An event narrowed to one payload kind.
391
+ */
392
+ export type EventOf<T extends PayloadTag> = Event & { readonly payload: PayloadOf<T> };
393
+
394
+ export type MakeProps<T extends Payload = Payload> = {
395
+ /** Set only when converting a record that already has an id, so references to it still resolve. */
396
+ id?: EventId;
397
+ payload: T;
398
+ sender: Sender;
399
+ /** The thread the event is written in: an append continues its branch. Absent for the main thread. */
400
+ thread?: ThreadId;
401
+ created?: string;
402
+ };
403
+
404
+ /**
405
+ * Creates an event (not yet appended to a feed).
406
+ */
407
+ export const make = <T extends Payload>({ id, payload, sender, thread, created }: MakeProps<T>): Event =>
408
+ Obj.make(Event, {
409
+ id,
410
+ sender,
411
+ created: created ?? new Date().toISOString(),
412
+ payload,
413
+ // Set at creation: putting it on afterwards opens a change on every event a turn writes.
414
+ ...(thread !== undefined ? { [Obj.Meta]: { keys: [Feed.branchKey(thread)] } } : {}),
415
+ });
416
+
417
+ /** Branches already read off events: a fold asks for an event's thread several times, and reading meta keys is not free. */
418
+ const threads = new WeakMap<Event, ThreadId>();
419
+
420
+ /**
421
+ * The thread an event belongs to: the branch it was written on, absent for the main thread. An opener (`turnBegin`,
422
+ * `threadOpen`) is the base of its branch, so its thread is the one it opens.
423
+ */
424
+ export const threadOf = (event: Event): ThreadId | undefined => {
425
+ const known = threads.get(event);
426
+ if (known !== undefined) {
427
+ return known;
428
+ }
429
+ const thread = Feed.getBranch(event);
430
+ // An event keeps its branch once it has one; an opener has none until its fork is written, so only a found one is kept.
431
+ if (thread !== undefined) {
432
+ threads.set(event, thread);
433
+ }
434
+ return thread;
435
+ };
436
+
437
+ /**
438
+ * Narrows an event by payload tag.
439
+ */
440
+ export const is = <T extends PayloadTag>(event: Event, tag: T): event is EventOf<T> => event.payload._tag === tag;
@@ -0,0 +1,113 @@
1
+ //
2
+ // Copyright 2026 DXOS.org
3
+ //
4
+
5
+ // @import-as-namespace
6
+
7
+ import { type ContentBlock } from '@dxos/types';
8
+
9
+ /**
10
+ * One thread as another thread's prompt shows it: text only, because another thread's tool calls may still be
11
+ * waiting for results, and a provider rejects a prompt holding a call without its result.
12
+ */
13
+ export type Thread = {
14
+ readonly id: string;
15
+ readonly purpose?: string;
16
+ readonly owner?: string;
17
+ readonly status: 'running' | 'done';
18
+ readonly entries: readonly {
19
+ readonly role: string;
20
+ readonly name?: string;
21
+ readonly blocks: readonly ContentBlock.Any[];
22
+ }[];
23
+ };
24
+
25
+ /** Entries a snapshot keeps from the end of a long thread; its first entry (the request) is always kept. */
26
+ export const TAIL_ENTRIES = 12;
27
+
28
+ /** Characters a tool call's arguments or result keep. */
29
+ export const TOOL_TEXT = 300;
30
+
31
+ /** Characters a single text block keeps. */
32
+ export const BLOCK_TEXT = 2_000;
33
+
34
+ const cut = (text: string, max: number): string => (text.length > max ? `${text.slice(0, max)}… (cut)` : text);
35
+
36
+ const renderBlock = (block: ContentBlock.Any): string | undefined => {
37
+ switch (block._tag) {
38
+ case 'text':
39
+ return block.text.trim().length > 0 ? cut(block.text.trim(), BLOCK_TEXT) : undefined;
40
+ case 'toolCall':
41
+ return `[calls ${block.name}(${cut(block.input, TOOL_TEXT)})]`;
42
+ case 'toolResult':
43
+ return `[${block.name} returned: ${cut(
44
+ typeof block.result === 'string'
45
+ ? block.result
46
+ : block.result === undefined
47
+ ? 'an error'
48
+ : JSON.stringify(block.result),
49
+ TOOL_TEXT,
50
+ )}]`;
51
+ case 'reasoning':
52
+ case 'stats':
53
+ case 'status':
54
+ case 'toolkit':
55
+ return undefined;
56
+ default:
57
+ return `[${block._tag}]`;
58
+ }
59
+ };
60
+
61
+ /**
62
+ * The lines of a thread's transcript; a long thread keeps its first entry and its last {@link TAIL_ENTRIES}.
63
+ */
64
+ export const lines = (entries: Thread['entries']): string[] => {
65
+ const kept =
66
+ entries.length > TAIL_ENTRIES + 1 ? [entries[0], undefined, ...entries.slice(-TAIL_ENTRIES)] : [...entries];
67
+ return kept.flatMap((entry) => {
68
+ if (entry === undefined) {
69
+ return [`(${entries.length - TAIL_ENTRIES - 1} earlier entries left out)`];
70
+ }
71
+ const text = entry.blocks.flatMap((block) => renderBlock(block) ?? []).join('\n');
72
+ return text.length > 0 ? [`${entry.name ?? entry.role}: ${text}`] : [];
73
+ });
74
+ };
75
+
76
+ /**
77
+ * One thread wrapped in its delimiters.
78
+ */
79
+ export const render = (thread: Thread): string => {
80
+ const attributes = [
81
+ `id="${thread.id}"`,
82
+ ...(thread.purpose ? [`title="${thread.purpose.replaceAll('"', "'")}"`] : []),
83
+ ...(thread.owner ? [`owner="${thread.owner}"`] : []),
84
+ `status="${thread.status}"`,
85
+ ].join(' ');
86
+ return [`<thread ${attributes}>`, ...lines(thread.entries), '</thread>'].join('\n');
87
+ };
88
+
89
+ /**
90
+ * What a light thread starts with: the work of every thread running beside it, then the separator that tells the
91
+ * model that work is not its own.
92
+ */
93
+ export const snapshot = (siblings: readonly Thread[], self: string): string =>
94
+ [
95
+ ...siblings.map(render),
96
+ '',
97
+ siblings.length === 1
98
+ ? 'The thread above is a separate request that is still running in parallel with this one.'
99
+ : 'The threads above are separate requests that are still running in parallel with this one.',
100
+ 'Their work is not yours: do not repeat, continue or answer it.',
101
+ `You are thread ${self}. Answer only the request that follows.`,
102
+ "If it depends on a result one of those threads has not produced yet, call `thread_wait` with that thread's id;",
103
+ 'it returns once the thread ends, with what the thread did.',
104
+ ].join('\n');
105
+
106
+ /**
107
+ * One line of the latest state of a running thread, appended after the history when a turn starts.
108
+ */
109
+ export const status = (thread: Thread): string => {
110
+ const last = thread.entries.at(-1);
111
+ const latest = last ? lines([last]).join(' ').replaceAll('\n', ' ') : 'nothing yet';
112
+ return `Thread ${thread.id}${thread.purpose ? ` ("${thread.purpose}")` : ''} is ${thread.status}; latest: ${cut(latest, TOOL_TEXT)}`;
113
+ };
@@ -0,0 +1,7 @@
1
+ //
2
+ // Copyright 2026 DXOS.org
3
+ //
4
+
5
+ export * as Reducer from './Reducer.ts';
6
+ export * as Trajectory from './Trajectory.ts';
7
+ export * as Transcript from './Transcript.ts';