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