@layernorm/overlay-agent-host 0.9.0 → 0.10.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 (77) hide show
  1. package/README.md +4 -4
  2. package/dist/cli.js +1 -1
  3. package/dist/cli.js.map +1 -1
  4. package/dist/host-capabilities.d.ts +1 -1
  5. package/dist/host-capabilities.d.ts.map +1 -1
  6. package/dist/host-capabilities.js +1 -1
  7. package/dist/host-capabilities.js.map +1 -1
  8. package/dist/local-tools-exec.d.ts.map +1 -1
  9. package/dist/local-tools-exec.js +3 -0
  10. package/dist/local-tools-exec.js.map +1 -1
  11. package/dist/private-threads-access.d.ts +62 -0
  12. package/dist/private-threads-access.d.ts.map +1 -0
  13. package/dist/private-threads-access.js +141 -0
  14. package/dist/private-threads-access.js.map +1 -0
  15. package/dist/private-threads-context.d.ts +44 -9
  16. package/dist/private-threads-context.d.ts.map +1 -1
  17. package/dist/private-threads-context.js +115 -31
  18. package/dist/private-threads-context.js.map +1 -1
  19. package/dist/private-threads-images.d.ts +15 -0
  20. package/dist/private-threads-images.d.ts.map +1 -0
  21. package/dist/private-threads-images.js +38 -0
  22. package/dist/private-threads-images.js.map +1 -0
  23. package/dist/private-threads-ipc.d.ts +16 -0
  24. package/dist/private-threads-ipc.d.ts.map +1 -1
  25. package/dist/private-threads-ipc.js +72 -12
  26. package/dist/private-threads-ipc.js.map +1 -1
  27. package/dist/private-threads-limits.d.ts +51 -0
  28. package/dist/private-threads-limits.d.ts.map +1 -0
  29. package/dist/private-threads-limits.js +51 -0
  30. package/dist/private-threads-limits.js.map +1 -0
  31. package/dist/private-threads-messages.d.ts +62 -0
  32. package/dist/private-threads-messages.d.ts.map +1 -0
  33. package/dist/private-threads-messages.js +156 -0
  34. package/dist/private-threads-messages.js.map +1 -0
  35. package/dist/private-threads-models.d.ts +7 -1
  36. package/dist/private-threads-models.d.ts.map +1 -1
  37. package/dist/private-threads-models.js +43 -0
  38. package/dist/private-threads-models.js.map +1 -1
  39. package/dist/private-threads-overlay-model.d.ts +1 -0
  40. package/dist/private-threads-overlay-model.d.ts.map +1 -1
  41. package/dist/private-threads-overlay-tools.d.ts +2 -0
  42. package/dist/private-threads-overlay-tools.d.ts.map +1 -1
  43. package/dist/private-threads-overlay-tools.js +2 -1
  44. package/dist/private-threads-overlay-tools.js.map +1 -1
  45. package/dist/private-threads-pieces.d.ts +14 -0
  46. package/dist/private-threads-pieces.d.ts.map +1 -0
  47. package/dist/private-threads-pieces.js +85 -0
  48. package/dist/private-threads-pieces.js.map +1 -0
  49. package/dist/private-threads-progress.d.ts +35 -0
  50. package/dist/private-threads-progress.d.ts.map +1 -0
  51. package/dist/private-threads-progress.js +77 -0
  52. package/dist/private-threads-progress.js.map +1 -0
  53. package/dist/private-threads-protocol.d.ts +228 -4
  54. package/dist/private-threads-protocol.d.ts.map +1 -1
  55. package/dist/private-threads-protocol.js +66 -6
  56. package/dist/private-threads-protocol.js.map +1 -1
  57. package/dist/private-threads-recall.d.ts +10 -0
  58. package/dist/private-threads-recall.d.ts.map +1 -0
  59. package/dist/private-threads-recall.js +40 -0
  60. package/dist/private-threads-recall.js.map +1 -0
  61. package/dist/private-threads-schema.d.ts +8 -0
  62. package/dist/private-threads-schema.d.ts.map +1 -0
  63. package/dist/private-threads-schema.js +186 -0
  64. package/dist/private-threads-schema.js.map +1 -0
  65. package/dist/private-threads-store.d.ts +112 -10
  66. package/dist/private-threads-store.d.ts.map +1 -1
  67. package/dist/private-threads-store.js +468 -62
  68. package/dist/private-threads-store.js.map +1 -1
  69. package/dist/private-threads-turn-model.d.ts +7 -0
  70. package/dist/private-threads-turn-model.d.ts.map +1 -0
  71. package/dist/private-threads-turn-model.js +31 -0
  72. package/dist/private-threads-turn-model.js.map +1 -0
  73. package/dist/private-threads.d.ts +42 -18
  74. package/dist/private-threads.d.ts.map +1 -1
  75. package/dist/private-threads.js +336 -211
  76. package/dist/private-threads.js.map +1 -1
  77. package/package.json +2 -2
@@ -1,27 +1,29 @@
1
+ import { randomUUID } from 'node:crypto';
1
2
  import { homedir, platform } from 'node:os';
2
3
  import { join } from 'node:path';
3
- import { createAnthropic } from '@ai-sdk/anthropic';
4
- import { createGoogleGenerativeAI } from '@ai-sdk/google';
5
- import { createOpenAI } from '@ai-sdk/openai';
6
- import { createOpenRouter } from '@openrouter/ai-sdk-provider';
7
- import { ToolLoopAgent, createAgentUIStream, isStepCount, readUIMessageStream, wrapLanguageModel, } from 'ai';
8
- import { retryWithoutToolImages } from '@layernorm/overlay-agent-bridge-protocol';
4
+ import { setImmediate, setTimeout as wait } from 'node:timers/promises';
5
+ import { convertToModelMessages, createUIMessageStream, streamText, toUIMessageStream, validateUIMessages, } from 'ai';
9
6
  import { LocalToolExecutor } from './local-tools.js';
10
7
  import { LocalTerminals, localTerminalsRoot } from './local-tools-terminal.js';
11
- import { listProviderModels } from './private-threads-models.js';
12
- import { createOverlayRelayModel } from './private-threads-overlay-model.js';
13
- import { contextWindowFor, createContextCompaction, instructionsWithSummary, messagesAfterSummary, summaryBoundary, } from './private-threads-context.js';
8
+ import { TurnAccess, modelTokenRefused, toolsTokenRefused } from './private-threads-access.js';
9
+ import { listProviderModels, modelContextWindow } from './private-threads-models.js';
10
+ import { SummaryBoundary, createContextCompaction, instructionsWithSummary, loadThreadContext, } from './private-threads-context.js';
11
+ import { SEARCH_WAIT_MS } from './private-threads-limits.js';
12
+ import { answerApprovals, closeOpenCalls, pendingApprovals } from './private-threads-messages.js';
13
+ import { ProgressCheck, stuckMessage } from './private-threads-progress.js';
14
+ import { RECALL_INSTRUCTIONS, recallTools } from './private-threads-recall.js';
14
15
  import { connectOverlayTools, withOverlayTools } from './private-threads-overlay-tools.js';
15
16
  import { LocalMcpServers } from './private-threads-local-mcp.js';
16
- import { IMAGE_NOT_KEPT, privateComputerTools, SCREENSHOT_NOT_KEPT } from './private-threads-tools.js';
17
+ import { privateComputerTools } from './private-threads-tools.js';
18
+ import { createModel, withImageRecovery } from './private-threads-turn-model.js';
19
+ import { partSize, withoutImages, withoutToolImages } from './private-threads-images.js';
17
20
  import { titleFrom, writeTitle } from './private-threads-title.js';
18
21
  import { privateRequestSchema, } from './private-threads-protocol.js';
19
- const MAX_STEPS = 60;
20
22
  const DEFAULT_TITLE = 'New thread';
21
23
  /**
22
- * Runs private threads: one ToolLoopAgent per turn, in this process, with this
23
- * computer's tools. The transcript is saved after every step, so quitting keeps
24
- * everything up to the last finished step.
24
+ * Runs private threads in this process with this computer's tools. A turn starts from what is saved here, never from
25
+ * the page, and reads only what its model is sent. The reply is saved after every step, so quitting keeps everything up
26
+ * to the last finished step.
25
27
  */
26
28
  export class PrivateThreadService {
27
29
  options;
@@ -30,10 +32,18 @@ export class PrivateThreadService {
30
32
  terminals = new Map();
31
33
  /** Titles being written. They run beside the reply, so neither waits for the other. */
32
34
  titles = new Map();
35
+ /** Earlier parts of replies that are still going, whose images are dropped when the reply ends. */
36
+ openReplies = new Map();
33
37
  localMcp;
38
+ /** Threads whose text is being indexed, one batch at a time. */
39
+ indexing = new Map();
40
+ /** Deletions that were cut off when the host last quit. */
41
+ resumedDeletes;
42
+ closing = false;
34
43
  constructor(options) {
35
44
  this.options = options;
36
45
  this.localMcp = options.localMcp ?? new LocalMcpServers({ log: options.log });
46
+ this.resumedDeletes = Promise.all(options.store.deleting().map(threadId => this.finishDelete(threadId)));
37
47
  }
38
48
  async handle(input) {
39
49
  const request = privateRequestSchema.parse(input);
@@ -42,62 +52,38 @@ export class PrivateThreadService {
42
52
  async dispatch(request) {
43
53
  const { store } = this.options;
44
54
  switch (request.method) {
45
- case 'list':
46
- return { threads: store.list(request.owner), running: [...this.runs.keys()] };
47
- case 'get': {
48
- const thread = store.get(request.owner, request.threadId);
49
- if (!thread)
50
- throw new Error('This private thread is not on this computer.');
51
- return { thread, messages: store.messages(thread.id), running: this.runs.has(thread.id) };
55
+ case 'list': {
56
+ const { userId, workspaceId } = request.owner;
57
+ const running = [...this.runs].filter(([, run]) => run.owner.userId === userId && run.owner.workspaceId === workspaceId);
58
+ return { ...store.list(request.owner, request.after), running: running.map(([threadId]) => threadId) };
52
59
  }
53
- case 'create': {
54
- if (store.get(request.owner, request.threadId))
55
- throw new Error('A thread with this id already exists.');
56
- const now = Date.now();
57
- const thread = store.create({
58
- ...request.owner, id: request.threadId, agentId: request.agentId, title: request.title,
59
- folder: request.folder, model: request.model, createdAt: now, updatedAt: now,
60
- });
61
- this.options.emit({ kind: 'threads', owner: request.owner });
62
- return { thread };
60
+ case 'get': {
61
+ const thread = this.owned(request);
62
+ const running = this.runs.has(thread.id);
63
+ // A reply that can still go on must be complete: the page adds to it, and its requests can be answered.
64
+ const whole = (message, latest) => request.whole === true || (latest && (running || pendingApprovals(message).length > 0));
65
+ return { thread, ...store.page(thread.id, request.page, whole), running };
63
66
  }
67
+ case 'pieces':
68
+ return store.pieces(this.owned(request).id, request.messageId, request.revision, request.from);
69
+ case 'part':
70
+ return store.partSlice(this.owned(request).id, request.messageId, request.revision, request.part, request.from);
71
+ case 'activity':
72
+ return store.activity(this.owned(request).id, request.before);
73
+ case 'search':
74
+ return await this.search(this.owned(request).id, request);
75
+ case 'edits':
76
+ return store.edits(this.owned(request).id, request.after);
77
+ case 'create':
78
+ return this.create(request);
64
79
  case 'send':
65
80
  return this.send(request);
66
- case 'stop': {
67
- const run = this.runs.get(request.threadId);
68
- if (!run || !store.get(request.owner, request.threadId))
69
- return { stopped: false };
70
- run.controller.abort();
71
- await run.done;
72
- return { stopped: true };
73
- }
74
- case 'update': {
75
- if (request.folder !== undefined && store.messages(request.threadId).length > 0) {
76
- throw new Error('The folder is fixed once the thread has a message.');
77
- }
78
- const thread = store.update(request.owner, request.threadId, {
79
- ...(request.title ? { title: request.title } : {}),
80
- ...(request.folder !== undefined ? { folder: request.folder } : {}),
81
- });
82
- if (!thread)
83
- throw new Error('This private thread is not on this computer.');
84
- this.options.emit({ kind: 'threads', owner: request.owner });
85
- return { thread };
86
- }
87
- case 'delete': {
88
- const run = this.runs.get(request.threadId);
89
- if (run) {
90
- run.controller.abort();
91
- await run.done;
92
- }
93
- await this.stopTitle(request.threadId);
94
- const deleted = store.delete(request.owner, request.threadId);
95
- if (deleted)
96
- await this.stopTerminals(request.threadId);
97
- if (deleted)
98
- this.options.emit({ kind: 'threads', owner: request.owner });
99
- return { deleted };
100
- }
81
+ case 'stop':
82
+ return await this.stop(request);
83
+ case 'update':
84
+ return this.update(request);
85
+ case 'delete':
86
+ return await this.delete(request);
101
87
  case 'models':
102
88
  return { models: await (this.options.listModels ?? listProviderModels)(request.provider, request.apiKey) };
103
89
  case 'mcpCheck':
@@ -106,34 +92,111 @@ export class PrivateThreadService {
106
92
  return { stopped: await this.localMcp.stop(request.serverId) };
107
93
  }
108
94
  }
109
- send(request) {
95
+ create(request) {
96
+ const { store } = this.options;
97
+ if (store.get(request.owner, request.threadId))
98
+ throw new Error('A thread with this id already exists.');
99
+ const now = Date.now();
100
+ const thread = store.create({
101
+ ...request.owner, id: request.threadId, agentId: request.agentId, title: request.title,
102
+ folder: request.folder, model: request.model, createdAt: now, updatedAt: now,
103
+ });
104
+ this.options.emit({ kind: 'threads', owner: request.owner });
105
+ return { thread };
106
+ }
107
+ async stop(request) {
108
+ const { store } = this.options;
109
+ const run = this.runs.get(request.threadId);
110
+ if (!run || !store.get(request.owner, request.threadId))
111
+ return { stopped: false };
112
+ run.controller.abort();
113
+ await run.done;
114
+ return { stopped: true };
115
+ }
116
+ update(request) {
110
117
  const { store } = this.options;
111
- const thread = store.get(request.owner, request.threadId);
118
+ this.owned(request);
119
+ if (request.folder !== undefined && store.hasMessages(request.threadId)) {
120
+ throw new Error('The folder is fixed once the thread has a message.');
121
+ }
122
+ const thread = store.update(request.owner, request.threadId, {
123
+ ...(request.title ? { title: request.title } : {}),
124
+ ...(request.folder !== undefined ? { folder: request.folder } : {}),
125
+ });
126
+ if (!thread)
127
+ throw new Error('This private thread is not on this computer.');
128
+ this.options.emit({ kind: 'threads', owner: request.owner });
129
+ return { thread };
130
+ }
131
+ async delete(request) {
132
+ const { store } = this.options;
133
+ if (!store.get(request.owner, request.threadId))
134
+ return { deleted: false };
135
+ const run = this.runs.get(request.threadId);
136
+ if (run) {
137
+ run.controller.abort();
138
+ await run.done;
139
+ }
140
+ await this.stopTitle(request.threadId);
141
+ const deleted = store.startDelete(request.owner, request.threadId);
142
+ if (deleted)
143
+ await Promise.all([this.finishDelete(request.threadId), this.stopTerminals(request.threadId)]);
144
+ this.openReplies.delete(request.threadId);
145
+ if (deleted)
146
+ this.options.emit({ kind: 'threads', owner: request.owner, deletedThreadId: request.threadId });
147
+ return { deleted };
148
+ }
149
+ owned(request) {
150
+ const thread = this.options.store.get(request.owner, request.threadId);
112
151
  if (!thread)
113
152
  throw new Error('This private thread is not on this computer.');
153
+ return thread;
154
+ }
155
+ send(request) {
156
+ const { store } = this.options;
157
+ const thread = this.owned(request);
114
158
  if (this.runs.has(thread.id))
115
159
  throw new Error('This thread is already running. Stop it first.');
116
- const messages = withoutToolImages(request.messages, { keepLast: true });
117
- store.saveMessages(thread.id, messages);
160
+ const said = this.saveInput(thread.id, request.input);
118
161
  const model = `${request.model.provider}/${request.model.modelId}`;
119
- const title = thread.title === DEFAULT_TITLE ? titleFrom(messages) : null;
162
+ const title = said && thread.title === DEFAULT_TITLE ? titleFrom([said]) : null;
120
163
  if (title || thread.model !== model) {
121
164
  store.update(request.owner, thread.id, { model, ...(title ? { title } : {}) });
122
165
  this.options.emit({ kind: 'threads', owner: request.owner });
123
166
  }
124
- if (title)
125
- this.startTitle(request, messages, title);
167
+ if (said && title)
168
+ this.startTitle(request, [said], title);
126
169
  const controller = new AbortController();
127
- const run = { turnId: request.turnId, controller, done: Promise.resolve() };
170
+ const run = { turnId: request.turnId, owner: request.owner, controller, done: Promise.resolve() };
128
171
  this.runs.set(thread.id, run);
129
- run.done = this.execute(request, messages, controller.signal).finally(() => {
130
- if (this.runs.get(thread.id) === run)
131
- this.runs.delete(thread.id);
132
- });
172
+ run.done = this.execute(request, controller.signal);
133
173
  return { turnId: request.turnId };
134
174
  }
135
- async execute(request, messages, signal) {
136
- const { emit } = this.options;
175
+ /** Saves what the page adds: a new message, which is returned, or answers checked against the latest saved reply. */
176
+ saveInput(threadId, input) {
177
+ const { store } = this.options;
178
+ const latest = store.latest(threadId);
179
+ if ('approvals' in input) {
180
+ store.saveMessage(threadId, answerApprovals(latest, input.approvals));
181
+ return null;
182
+ }
183
+ const message = { id: input.message.id, role: 'user', parts: [{ type: 'text', text: input.message.text }] };
184
+ const saved = store.message(threadId, message.id);
185
+ if (saved) {
186
+ // Sending the same unanswered message again tries it again. Nothing already saved can be replaced.
187
+ const same = saved.role === 'user' && saved.id === latest?.id && saved.parts.map(part => part.type === 'text' ? part.text : '').join('') === input.message.text;
188
+ if (!same)
189
+ throw new Error('This message was already sent.');
190
+ return saved;
191
+ }
192
+ // The new message passes by anything the last reply was still waiting for.
193
+ if (latest?.role === 'assistant')
194
+ store.saveMessage(threadId, withoutImages(closeOpenCalls(latest)));
195
+ store.saveMessage(threadId, message);
196
+ return message;
197
+ }
198
+ async execute(request, stopped) {
199
+ const { emit, store } = this.options;
137
200
  const { threadId, turnId } = request;
138
201
  emit({ kind: 'turn', threadId, turnId, state: 'running' });
139
202
  const executor = new LocalToolExecutor({
@@ -141,68 +204,190 @@ export class PrivateThreadService {
141
204
  grant: () => ({ mode: 'selected_roots', roots: request.roots }),
142
205
  });
143
206
  let failure;
207
+ // Losing access to Overlay ends the turn like Stop does, but says why.
208
+ const refused = new AbortController();
209
+ const signal = AbortSignal.any([stopped, refused.signal]);
210
+ const access = (kind, given) => new TurnAccess({
211
+ ...given, signal,
212
+ renew: renewSignal => this.options.renewAccess
213
+ ? this.options.renewAccess({ turnId, kind }, renewSignal)
214
+ : Promise.reject(new Error('This turn’s access can’t be renewed.')),
215
+ // A server that refuses the first connection leaves the turn without Overlay's tools, as before.
216
+ refusedToken: (headers, body) => kind === 'model' ? modelTokenRefused(headers, body) : overlay !== null && toolsTokenRefused(headers),
217
+ onRefused: (error) => {
218
+ failure = publicError(error);
219
+ refused.abort(error);
220
+ },
221
+ });
144
222
  let overlay = null;
223
+ const modelAccess = request.model.provider === 'overlay' ? access('model', request.model.relay) : null;
145
224
  let localMcp = null;
225
+ let contextWindow;
146
226
  try {
147
227
  ;
148
- [overlay, localMcp] = await Promise.all([
228
+ [overlay, localMcp, contextWindow] = await Promise.all([
149
229
  (this.options.connectOverlayTools ?? connectOverlayTools)(request.overlay, {
150
230
  signal,
231
+ fetch: request.overlay ? access('tools', request.overlay).fetch : fetch,
151
232
  onUnavailable: (reason) => this.options.log?.(`Overlay tools unavailable for this turn: ${publicError(reason)}`),
152
233
  }),
153
234
  request.localMcp?.length ? this.localMcp.open(request.localMcp, { signal, approvalMode: request.approvalMode }) : null,
235
+ (this.options.contextWindow ?? modelContextWindow)(request.model),
154
236
  ]);
155
- const model = withImageRecovery((this.options.createModel ?? createModel)(request.model));
156
- const instructions = instructionsFor(request, overlay, localMcp);
157
- const tools = withLocalMcpTools(withOverlayTools(privateComputerTools({
237
+ const computerTools = privateComputerTools({
158
238
  executor, approvalMode: request.approvalMode, abortSignal: signal,
159
239
  onTerminalStarted: (id) => this.rememberTerminal(threadId, id),
160
- }), overlay), localMcp);
161
- const saved = this.options.store.summary(threadId);
162
- const agent = new ToolLoopAgent({
163
- model,
164
- instructions: instructionsWithSummary(instructions, saved?.summary),
165
- tools,
166
- stopWhen: isStepCount(MAX_STEPS),
167
- prepareStep: createContextCompaction({
168
- model,
169
- contextWindow: this.options.contextWindow ?? contextWindowFor(request.model.provider, request.model.modelId),
170
- instructions,
171
- tools,
172
- previousSummary: saved?.summary,
173
- abortSignal: signal,
174
- onCompacted: (summary) => this.options.store.saveSummary(threadId, { summary, throughMessageId: summaryBoundary(messages) }),
175
- }),
176
240
  });
177
- const stream = await createAgentUIStream({
178
- agent,
179
- uiMessages: messagesAfterSummary(messages, saved),
180
- abortSignal: signal,
181
- originalMessages: messages,
182
- onError: (error) => { failure = publicError(error); return failure; },
241
+ await this.reply({
242
+ threadId, contextWindow, signal,
243
+ model: withImageRecovery((this.options.createModel ?? createModel)(request.model, modelAccess?.fetch)),
244
+ instructions: instructionsFor(request, overlay, localMcp),
245
+ tools: withLocalMcpTools(withOverlayTools({ ...computerTools, ...recallTools(store, threadId, () => this.indexText(threadId)) }, overlay), localMcp),
246
+ emit: chunk => emit({ kind: 'chunk', threadId, turnId, chunk }),
247
+ onError: (error) => failure ??= publicError(error),
183
248
  });
184
- const [forPage, forDisk] = toReadable(stream).tee();
185
- const saving = this.persist(threadId, messages, forDisk);
186
- const reader = forPage.getReader();
187
- for (;;) {
188
- const { done, value } = await reader.read();
189
- if (done)
190
- break;
191
- emit({ kind: 'chunk', threadId, turnId, chunk: value });
192
- }
193
- await saving;
194
249
  }
195
250
  catch (error) {
196
251
  if (!signal.aborted)
197
- failure = publicError(error);
252
+ failure ??= publicError(error);
198
253
  }
199
254
  finally {
200
255
  localMcp?.release();
201
256
  // An approval ends this turn and continues in the next one, which may type into a session started here.
202
- const waiting = !signal.aborted && !failure && waitsForApproval(this.options.store.messages(threadId));
257
+ const waiting = !signal.aborted && !failure && pendingApprovals(store.latest(threadId)).length > 0;
203
258
  await Promise.all([waiting ? undefined : this.stopTerminals(threadId), overlay?.close()]);
259
+ try {
260
+ if (!waiting)
261
+ this.closeReply(threadId);
262
+ // This turn's messages, so a later search doesn't wait. Anything left is indexed then.
263
+ if (store.keepsSearch(threadId))
264
+ store.indexNextText(threadId);
265
+ }
266
+ catch (error) {
267
+ failure ??= publicError(error);
268
+ }
204
269
  }
205
- emit({ kind: 'turn', threadId, turnId, state: signal.aborted ? 'stopped' : failure ? 'error' : 'finished', ...(failure ? { error: failure } : {}) });
270
+ // Before the page hears, so it can send again at once.
271
+ this.runs.delete(threadId);
272
+ emit({ kind: 'turn', threadId, turnId, state: stopped.aborted ? 'stopped' : failure ? 'error' : 'finished', ...(failure ? { error: failure } : {}) });
273
+ }
274
+ /**
275
+ * Runs the model and its tools until it has answered. A long reply is saved as several messages, each with its own
276
+ * run of the agent loop that continues from the same model messages. That bounds what one step saves, what the page
277
+ * copies on every update and what the loop keeps in memory, so a step costs the same however long the reply gets.
278
+ */
279
+ async reply(turn) {
280
+ const { store } = this.options;
281
+ const { threadId, signal, model, tools, onError } = turn;
282
+ const context = await loadThreadContext({ store, threadId, model, contextWindow: turn.contextWindow, abortSignal: signal });
283
+ const last = context.messages.at(-1);
284
+ let continuing = last?.role === 'assistant' ? last : undefined;
285
+ // A turn that was cut off may have left images behind.
286
+ const messages = withoutToolImages(context.messages, { keepLast: true });
287
+ messages.forEach((message, index) => { if (message !== context.messages[index])
288
+ store.saveMessage(threadId, message); });
289
+ const closed = context.messages.filter(message => message !== continuing && message.id !== context.openingId);
290
+ const boundary = new SummaryBoundary(closed.map(({ id, parts }) => ({ id, modelMessages: parts.some(part => part.type !== 'step-start') ? 1 : 0 })));
291
+ let summary = context.summary;
292
+ const compact = createContextCompaction({
293
+ model, tools, contextWindow: turn.contextWindow, instructions: turn.instructions, previousSummary: summary, abortSignal: signal,
294
+ onCompacted: (written, kept, steps) => {
295
+ summary = written;
296
+ store.saveSummary(threadId, { summary, throughMessageId: boundary.after(kept, steps) ?? store.summary(threadId)?.throughMessageId ?? null });
297
+ },
298
+ });
299
+ signal.throwIfAborted();
300
+ const progress = new ProgressCheck();
301
+ let stuck = null;
302
+ let carried = await convertToModelMessages(await validateUIMessages({ messages, tools: tools }), { tools });
303
+ for (;;) {
304
+ const original = continuing;
305
+ const messageId = original?.id ?? `msg_${randomUUID()}`;
306
+ const size = partSize(original?.parts ?? []);
307
+ let sent = [];
308
+ let next = null;
309
+ let partSteps = 0;
310
+ const { stream: chunks } = streamText({
311
+ model,
312
+ instructions: instructionsWithSummary(turn.instructions, summary),
313
+ messages: carried,
314
+ tools,
315
+ abortSignal: signal,
316
+ // Asked only when the model wants another step. A run may take any number of steps: it ends when the model is
317
+ // done, on Stop, on an error (such as too little budget) or with a question when it's stuck.
318
+ stopWhen: ({ steps }) => {
319
+ const step = steps.at(-1);
320
+ stuck = progress.add(step.content);
321
+ if (stuck !== null)
322
+ return true;
323
+ size.add(step.content);
324
+ if (!size.full())
325
+ return false;
326
+ partSteps = steps.length;
327
+ next = [...sent, ...step.response.messages];
328
+ return true;
329
+ },
330
+ prepareStep: async (step) => {
331
+ const compacted = await compact(step);
332
+ sent = compacted?.messages ?? step.messages;
333
+ return compacted;
334
+ },
335
+ // Errors reach the page through the stream. The default logs them whole, with the conversation that was sent.
336
+ onError: () => undefined,
337
+ });
338
+ const save = ({ responseMessage }) => {
339
+ if (responseMessage.parts.length > 0)
340
+ store.saveMessage(threadId, responseMessage);
341
+ };
342
+ const stream = createUIMessageStream({
343
+ originalMessages: original ? [original] : [],
344
+ generateId: () => messageId,
345
+ execute: ({ writer }) => writer.merge(toUIMessageStream({ stream: chunks, tools, onError })),
346
+ onError,
347
+ // Saved before the page sees the step end, so whatever it then reads includes it.
348
+ onStepEnd: save,
349
+ onEnd: save,
350
+ });
351
+ const reader = stream.getReader();
352
+ for (;;) {
353
+ const { done, value } = await reader.read();
354
+ if (done)
355
+ break;
356
+ turn.emit(value);
357
+ }
358
+ this.openReplies.set(threadId, [...this.openReplies.get(threadId) ?? [], messageId]);
359
+ if (stuck !== null && !signal.aborted)
360
+ return this.askToContinue(threadId, stuck, turn.emit);
361
+ if (!next || signal.aborted)
362
+ return;
363
+ boundary.close(messageId, partSteps);
364
+ carried = next;
365
+ continuing = undefined;
366
+ }
367
+ }
368
+ /** Ends a stuck turn with a question, saved and streamed like any reply. The person answers with an ordinary message. */
369
+ askToContinue(threadId, cycle, emit) {
370
+ const text = stuckMessage(cycle);
371
+ const messageId = `msg_${randomUUID()}`;
372
+ this.options.store.saveMessage(threadId, { id: messageId, role: 'assistant', parts: [{ type: 'text', text, state: 'done' }] });
373
+ emit({ type: 'start', messageId });
374
+ emit({ type: 'text-start', id: messageId });
375
+ emit({ type: 'text-delta', id: messageId, delta: text });
376
+ emit({ type: 'text-end', id: messageId });
377
+ emit({ type: 'finish' });
378
+ }
379
+ /** The turn is over: its calls can't finish, its images have been seen, and later turns must not send them again. */
380
+ closeReply(threadId) {
381
+ const { store } = this.options;
382
+ const latest = store.latest(threadId);
383
+ if (latest?.role === 'assistant')
384
+ store.saveMessage(threadId, withoutImages(closeOpenCalls(latest)));
385
+ for (const id of this.openReplies.get(threadId) ?? []) {
386
+ const part = store.message(threadId, id);
387
+ if (part)
388
+ store.saveMessage(threadId, withoutImages(part));
389
+ }
390
+ this.openReplies.delete(threadId);
206
391
  }
207
392
  /** Replaces the placeholder title with a written one, unless the person renamed the thread first. */
208
393
  startTitle(request, messages, placeholder) {
@@ -223,6 +408,35 @@ export class PrivateThreadService {
223
408
  this.titles.delete(threadId); });
224
409
  this.titles.set(threadId, { controller, done });
225
410
  }
411
+ /** One batch at a time, so other threads keep running. Quitting leaves the rest for the next start. */
412
+ async finishDelete(threadId) {
413
+ while (!this.closing && this.options.store.deleteNext(threadId))
414
+ await setImmediate();
415
+ }
416
+ /** Indexes everything not indexed yet. Batches let other threads run in between, and quitting or deleting stops them. */
417
+ indexText(threadId) {
418
+ const running = this.indexing.get(threadId);
419
+ if (running)
420
+ return running;
421
+ const run = async () => {
422
+ while (!this.closing && this.options.store.indexNextText(threadId))
423
+ await setImmediate();
424
+ };
425
+ const done = run().finally(() => { this.indexing.delete(threadId); });
426
+ this.indexing.set(threadId, done);
427
+ return done;
428
+ }
429
+ /** Waits briefly for indexing, which goes on afterwards, and says when it isn't finished. */
430
+ async search(threadId, request) {
431
+ const timer = new AbortController();
432
+ await Promise.race([this.indexText(threadId), wait(SEARCH_WAIT_MS, undefined, { signal: timer.signal }).catch(() => undefined)]);
433
+ timer.abort();
434
+ const { store } = this.options;
435
+ // The thread may have been deleted meanwhile, or a running reply saved again, which the first of these picks up.
436
+ this.owned({ owner: request.owner, threadId });
437
+ store.indexNextText(threadId);
438
+ return store.searchMessages(threadId, request.words, request.after);
439
+ }
226
440
  async stopTitle(threadId) {
227
441
  const title = this.titles.get(threadId);
228
442
  title?.controller.abort();
@@ -239,40 +453,10 @@ export class PrivateThreadService {
239
453
  if (ids)
240
454
  await new LocalTerminals(localTerminalsRoot(this.options.stateDirectory)).stopAll(ids).catch(() => undefined);
241
455
  }
242
- /** Saves the transcript at every finished step and once more at the end. */
243
- async persist(threadId, messages, stream) {
244
- const last = messages.at(-1);
245
- const continuing = last?.role === 'assistant' ? last : undefined;
246
- const base = continuing ? messages.slice(0, -1) : messages;
247
- let latest = continuing;
248
- let stepsSinceSave = 0;
249
- const save = () => { if (latest)
250
- this.options.store.saveMessages(threadId, [...base, latest]); };
251
- const [steps, snapshots] = stream.tee();
252
- const counting = (async () => {
253
- const reader = steps.getReader();
254
- for (;;) {
255
- const { done, value } = await reader.read();
256
- if (done)
257
- return;
258
- if (value.type === 'finish-step')
259
- stepsSinceSave++;
260
- }
261
- })();
262
- for await (const message of readUIMessageStream({ stream: snapshots, ...(continuing ? { message: continuing } : {}) })) {
263
- latest = message;
264
- if (stepsSinceSave > 0) {
265
- stepsSinceSave = 0;
266
- save();
267
- }
268
- }
269
- await counting;
270
- // The turn is over: its screenshots have been seen, and keeping them would resend every image on each turn.
271
- if (latest)
272
- this.options.store.saveMessages(threadId, withoutToolImages([...base, latest], { keepLast: false }));
273
- }
274
456
  /** Stops every run; their transcripts are already saved up to the last step. */
275
457
  async shutdown() {
458
+ this.closing = true;
459
+ await Promise.allSettled([this.resumedDeletes, ...this.indexing.values()]);
276
460
  for (const run of this.runs.values())
277
461
  run.controller.abort();
278
462
  await Promise.allSettled([...this.runs.values()].map(run => run.done));
@@ -281,28 +465,6 @@ export class PrivateThreadService {
281
465
  await this.localMcp.shutdown();
282
466
  }
283
467
  }
284
- export function createModel(model) {
285
- switch (model.provider) {
286
- case 'anthropic': return createAnthropic({ apiKey: model.apiKey })(model.modelId);
287
- case 'openai': return createOpenAI({ apiKey: model.apiKey })(model.modelId);
288
- case 'google': return createGoogleGenerativeAI({ apiKey: model.apiKey })(model.modelId);
289
- case 'openrouter': return createOpenRouter({ apiKey: model.apiKey })(model.modelId);
290
- case 'overlay': return createOverlayRelayModel(model.modelId, model.relay);
291
- }
292
- }
293
- /** A provider can refuse a request because of an image a tool returned. Send it once more without those images. */
294
- export function withImageRecovery(model) {
295
- if (typeof model === 'string')
296
- return model;
297
- return wrapLanguageModel({
298
- model: model,
299
- middleware: {
300
- specificationVersion: 'v4',
301
- wrapGenerate: ({ params, model: inner }) => retryWithoutToolImages(params, next => inner.doGenerate(next)),
302
- wrapStream: ({ params, model: inner }) => retryWithoutToolImages(params, next => inner.doStream(next)),
303
- },
304
- });
305
- }
306
468
  /** Local MCP tools are named `server__tool`, so they never take the name of a computer or Overlay tool. */
307
469
  function withLocalMcpTools(tools, localMcp) {
308
470
  if (!localMcp)
@@ -323,37 +485,13 @@ function instructionsFor(request, overlay, localMcp) {
323
485
  `You work on this ${os} computer with the computer tools, in these folders: ${request.roots.join(', ')}.`,
324
486
  `The person's home folder is ${homedir()}. Use absolute paths.`,
325
487
  `Today is ${new Date().toDateString()}.`,
488
+ RECALL_INSTRUCTIONS,
326
489
  'Work step by step, check your results, and finish with a short summary of what you did.',
327
490
  ].join('\n'),
328
491
  overlay && Object.keys(overlay.tools).length > 0 ? overlay.instructions : '',
329
492
  localMcp?.instructions ?? '',
330
493
  ].filter(Boolean).join('\n\n');
331
494
  }
332
- /**
333
- * Drops screenshots and viewed images from finished turns; the tool row keeps its size and the model is told to take a new one.
334
- * `keepLast` keeps the images of a turn that is continuing (an approval answered mid-turn).
335
- */
336
- export function withoutToolImages(messages, options) {
337
- return messages.map((message, index) => {
338
- if (message.role !== 'assistant' || (options.keepLast && index === messages.length - 1))
339
- return message;
340
- let changed = false;
341
- const parts = message.parts.map((part) => {
342
- const output = part.output;
343
- if ((part.type !== 'tool-computer_screenshot' && part.type !== 'tool-computer_view_image') || !output || typeof output !== 'object' || !('imageBase64' in output))
344
- return part;
345
- changed = true;
346
- const { imageBase64: _image, ...rest } = output;
347
- void _image;
348
- return { ...part, output: { ...rest, message: part.type === 'tool-computer_screenshot' ? SCREENSHOT_NOT_KEPT : IMAGE_NOT_KEPT } };
349
- });
350
- return changed ? { ...message, parts } : message;
351
- });
352
- }
353
- function waitsForApproval(messages) {
354
- const last = messages.at(-1);
355
- return last?.role === 'assistant' && last.parts.some(part => part.state === 'approval-requested');
356
- }
357
495
  /** Provider errors can echo request details; keep the message and drop anything that looks like a key. */
358
496
  function publicError(error) {
359
497
  const message = error instanceof Error ? error.message : String(error);
@@ -363,19 +501,6 @@ function publicError(error) {
363
501
  .replace(/ovlp_[A-Za-z0-9]+/g, '[redacted]')
364
502
  .slice(0, 1_000) || 'The model call failed.';
365
503
  }
366
- function toReadable(iterable) {
367
- const iterator = iterable[Symbol.asyncIterator]();
368
- return new ReadableStream({
369
- async pull(controller) {
370
- const { done, value } = await iterator.next();
371
- if (done)
372
- controller.close();
373
- else
374
- controller.enqueue(value);
375
- },
376
- async cancel() { await iterator.return?.(); },
377
- });
378
- }
379
504
  export function privateThreadsDatabasePath(stateDirectory) {
380
505
  return join(stateDirectory, 'private-threads.sqlite');
381
506
  }