@layernorm/overlay-agent-host 0.8.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.
- package/Dockerfile +0 -1
- package/LICENSE +176 -0
- package/README.md +7 -7
- package/dist/cli.js +1 -1
- package/dist/cli.js.map +1 -1
- package/dist/host-capabilities.d.ts +1 -1
- package/dist/host-capabilities.d.ts.map +1 -1
- package/dist/host-capabilities.js +1 -1
- package/dist/host-capabilities.js.map +1 -1
- package/dist/keyed-lock.d.ts +2 -0
- package/dist/keyed-lock.d.ts.map +1 -0
- package/dist/keyed-lock.js +18 -0
- package/dist/keyed-lock.js.map +1 -0
- package/dist/local-tools-exec.d.ts +14 -1
- package/dist/local-tools-exec.d.ts.map +1 -1
- package/dist/local-tools-exec.js +71 -12
- package/dist/local-tools-exec.js.map +1 -1
- package/dist/local-tools-paths.d.ts +8 -0
- package/dist/local-tools-paths.d.ts.map +1 -1
- package/dist/local-tools-paths.js +6 -2
- package/dist/local-tools-paths.js.map +1 -1
- package/dist/local-tools-terminal.d.ts +12 -3
- package/dist/local-tools-terminal.d.ts.map +1 -1
- package/dist/local-tools-terminal.js +113 -8
- package/dist/local-tools-terminal.js.map +1 -1
- package/dist/local-tools.d.ts.map +1 -1
- package/dist/local-tools.js +10 -4
- package/dist/local-tools.js.map +1 -1
- package/dist/private-threads-access.d.ts +62 -0
- package/dist/private-threads-access.d.ts.map +1 -0
- package/dist/private-threads-access.js +141 -0
- package/dist/private-threads-access.js.map +1 -0
- package/dist/private-threads-context.d.ts +44 -9
- package/dist/private-threads-context.d.ts.map +1 -1
- package/dist/private-threads-context.js +115 -31
- package/dist/private-threads-context.js.map +1 -1
- package/dist/private-threads-images.d.ts +15 -0
- package/dist/private-threads-images.d.ts.map +1 -0
- package/dist/private-threads-images.js +38 -0
- package/dist/private-threads-images.js.map +1 -0
- package/dist/private-threads-ipc.d.ts +16 -0
- package/dist/private-threads-ipc.d.ts.map +1 -1
- package/dist/private-threads-ipc.js +72 -12
- package/dist/private-threads-ipc.js.map +1 -1
- package/dist/private-threads-limits.d.ts +51 -0
- package/dist/private-threads-limits.d.ts.map +1 -0
- package/dist/private-threads-limits.js +51 -0
- package/dist/private-threads-limits.js.map +1 -0
- package/dist/private-threads-messages.d.ts +62 -0
- package/dist/private-threads-messages.d.ts.map +1 -0
- package/dist/private-threads-messages.js +156 -0
- package/dist/private-threads-messages.js.map +1 -0
- package/dist/private-threads-models.d.ts +5 -7
- package/dist/private-threads-models.d.ts.map +1 -1
- package/dist/private-threads-models.js +40 -17
- package/dist/private-threads-models.js.map +1 -1
- package/dist/private-threads-overlay-model.d.ts +1 -0
- package/dist/private-threads-overlay-model.d.ts.map +1 -1
- package/dist/private-threads-overlay-tools.d.ts +2 -0
- package/dist/private-threads-overlay-tools.d.ts.map +1 -1
- package/dist/private-threads-overlay-tools.js +2 -1
- package/dist/private-threads-overlay-tools.js.map +1 -1
- package/dist/private-threads-pieces.d.ts +14 -0
- package/dist/private-threads-pieces.d.ts.map +1 -0
- package/dist/private-threads-pieces.js +85 -0
- package/dist/private-threads-pieces.js.map +1 -0
- package/dist/private-threads-progress.d.ts +35 -0
- package/dist/private-threads-progress.d.ts.map +1 -0
- package/dist/private-threads-progress.js +77 -0
- package/dist/private-threads-progress.js.map +1 -0
- package/dist/private-threads-protocol.d.ts +233 -38
- package/dist/private-threads-protocol.d.ts.map +1 -1
- package/dist/private-threads-protocol.js +73 -27
- package/dist/private-threads-protocol.js.map +1 -1
- package/dist/private-threads-recall.d.ts +10 -0
- package/dist/private-threads-recall.d.ts.map +1 -0
- package/dist/private-threads-recall.js +40 -0
- package/dist/private-threads-recall.js.map +1 -0
- package/dist/private-threads-schema.d.ts +8 -0
- package/dist/private-threads-schema.d.ts.map +1 -0
- package/dist/private-threads-schema.js +186 -0
- package/dist/private-threads-schema.js.map +1 -0
- package/dist/private-threads-store.d.ts +112 -10
- package/dist/private-threads-store.d.ts.map +1 -1
- package/dist/private-threads-store.js +468 -62
- package/dist/private-threads-store.js.map +1 -1
- package/dist/private-threads-title.d.ts +12 -0
- package/dist/private-threads-title.d.ts.map +1 -0
- package/dist/private-threads-title.js +47 -0
- package/dist/private-threads-title.js.map +1 -0
- package/dist/private-threads-tools.d.ts +3 -0
- package/dist/private-threads-tools.d.ts.map +1 -1
- package/dist/private-threads-tools.js +73 -8
- package/dist/private-threads-tools.js.map +1 -1
- package/dist/private-threads-turn-model.d.ts +7 -0
- package/dist/private-threads-turn-model.d.ts.map +1 -0
- package/dist/private-threads-turn-model.js +31 -0
- package/dist/private-threads-turn-model.js.map +1 -0
- package/dist/private-threads.d.ts +54 -21
- package/dist/private-threads.d.ts.map +1 -1
- package/dist/private-threads.js +378 -200
- package/dist/private-threads.js.map +1 -1
- package/package.json +3 -3
package/dist/private-threads.js
CHANGED
|
@@ -1,134 +1,202 @@
|
|
|
1
|
+
import { randomUUID } from 'node:crypto';
|
|
1
2
|
import { homedir, platform } from 'node:os';
|
|
2
3
|
import { join } from 'node:path';
|
|
3
|
-
import {
|
|
4
|
-
import {
|
|
5
|
-
import { createOpenAI } from '@ai-sdk/openai';
|
|
6
|
-
import { createOpenRouter } from '@openrouter/ai-sdk-provider';
|
|
7
|
-
import { ToolLoopAgent, createAgentUIStream, isStepCount, readUIMessageStream, } from 'ai';
|
|
4
|
+
import { setImmediate, setTimeout as wait } from 'node:timers/promises';
|
|
5
|
+
import { convertToModelMessages, createUIMessageStream, streamText, toUIMessageStream, validateUIMessages, } from 'ai';
|
|
8
6
|
import { LocalToolExecutor } from './local-tools.js';
|
|
9
|
-
import {
|
|
10
|
-
import {
|
|
11
|
-
import {
|
|
7
|
+
import { LocalTerminals, localTerminalsRoot } from './local-tools-terminal.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';
|
|
12
15
|
import { connectOverlayTools, withOverlayTools } from './private-threads-overlay-tools.js';
|
|
13
16
|
import { LocalMcpServers } from './private-threads-local-mcp.js';
|
|
14
|
-
import { privateComputerTools
|
|
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';
|
|
20
|
+
import { titleFrom, writeTitle } from './private-threads-title.js';
|
|
15
21
|
import { privateRequestSchema, } from './private-threads-protocol.js';
|
|
16
|
-
const MAX_STEPS = 60;
|
|
17
22
|
const DEFAULT_TITLE = 'New thread';
|
|
18
23
|
/**
|
|
19
|
-
* Runs private threads
|
|
20
|
-
*
|
|
21
|
-
*
|
|
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.
|
|
22
27
|
*/
|
|
23
28
|
export class PrivateThreadService {
|
|
24
29
|
options;
|
|
25
30
|
runs = new Map();
|
|
31
|
+
/** Terminal sessions each thread started, kept while it waits for an approval. */
|
|
32
|
+
terminals = new Map();
|
|
33
|
+
/** Titles being written. They run beside the reply, so neither waits for the other. */
|
|
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();
|
|
26
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;
|
|
27
43
|
constructor(options) {
|
|
28
44
|
this.options = options;
|
|
29
45
|
this.localMcp = options.localMcp ?? new LocalMcpServers({ log: options.log });
|
|
46
|
+
this.resumedDeletes = Promise.all(options.store.deleting().map(threadId => this.finishDelete(threadId)));
|
|
30
47
|
}
|
|
31
48
|
async handle(input) {
|
|
32
49
|
const request = privateRequestSchema.parse(input);
|
|
33
50
|
return await this.dispatch(request);
|
|
34
51
|
}
|
|
35
|
-
/** A signed-in plan is listed through the local proxy; a provider with the person's key. */
|
|
36
|
-
async listModels(request) {
|
|
37
|
-
if (request.provider === 'claude' || request.provider === 'chatgpt') {
|
|
38
|
-
return await (this.options.listPlanModels ?? listPlanModels)(request.provider, request.proxy);
|
|
39
|
-
}
|
|
40
|
-
return await (this.options.listModels ?? listProviderModels)(request.provider, request.apiKey);
|
|
41
|
-
}
|
|
42
52
|
async dispatch(request) {
|
|
43
53
|
const { store } = this.options;
|
|
44
54
|
switch (request.method) {
|
|
45
|
-
case 'list':
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
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 '
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
const
|
|
58
|
-
|
|
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
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
await
|
|
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
|
-
const deleted = store.delete(request.owner, request.threadId);
|
|
94
|
-
if (deleted)
|
|
95
|
-
this.options.emit({ kind: 'threads', owner: request.owner });
|
|
96
|
-
return { deleted };
|
|
97
|
-
}
|
|
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);
|
|
98
87
|
case 'models':
|
|
99
|
-
return { models: await this.listModels(request) };
|
|
88
|
+
return { models: await (this.options.listModels ?? listProviderModels)(request.provider, request.apiKey) };
|
|
100
89
|
case 'mcpCheck':
|
|
101
90
|
return await this.localMcp.check(request.server);
|
|
102
91
|
case 'mcpStop':
|
|
103
92
|
return { stopped: await this.localMcp.stop(request.serverId) };
|
|
104
93
|
}
|
|
105
94
|
}
|
|
106
|
-
|
|
95
|
+
create(request) {
|
|
107
96
|
const { store } = this.options;
|
|
108
|
-
|
|
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) {
|
|
117
|
+
const { store } = this.options;
|
|
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
|
+
});
|
|
109
126
|
if (!thread)
|
|
110
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);
|
|
151
|
+
if (!thread)
|
|
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);
|
|
111
158
|
if (this.runs.has(thread.id))
|
|
112
159
|
throw new Error('This thread is already running. Stop it first.');
|
|
113
|
-
const
|
|
114
|
-
store.saveMessages(thread.id, messages);
|
|
160
|
+
const said = this.saveInput(thread.id, request.input);
|
|
115
161
|
const model = `${request.model.provider}/${request.model.modelId}`;
|
|
116
|
-
const title = thread.title === DEFAULT_TITLE ? titleFrom(
|
|
162
|
+
const title = said && thread.title === DEFAULT_TITLE ? titleFrom([said]) : null;
|
|
117
163
|
if (title || thread.model !== model) {
|
|
118
164
|
store.update(request.owner, thread.id, { model, ...(title ? { title } : {}) });
|
|
119
165
|
this.options.emit({ kind: 'threads', owner: request.owner });
|
|
120
166
|
}
|
|
167
|
+
if (said && title)
|
|
168
|
+
this.startTitle(request, [said], title);
|
|
121
169
|
const controller = new AbortController();
|
|
122
|
-
const run = { turnId: request.turnId, controller, done: Promise.resolve() };
|
|
170
|
+
const run = { turnId: request.turnId, owner: request.owner, controller, done: Promise.resolve() };
|
|
123
171
|
this.runs.set(thread.id, run);
|
|
124
|
-
run.done = this.execute(request,
|
|
125
|
-
if (this.runs.get(thread.id) === run)
|
|
126
|
-
this.runs.delete(thread.id);
|
|
127
|
-
});
|
|
172
|
+
run.done = this.execute(request, controller.signal);
|
|
128
173
|
return { turnId: request.turnId };
|
|
129
174
|
}
|
|
130
|
-
|
|
131
|
-
|
|
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;
|
|
132
200
|
const { threadId, turnId } = request;
|
|
133
201
|
emit({ kind: 'turn', threadId, turnId, state: 'running' });
|
|
134
202
|
const executor = new LocalToolExecutor({
|
|
@@ -136,117 +204,267 @@ export class PrivateThreadService {
|
|
|
136
204
|
grant: () => ({ mode: 'selected_roots', roots: request.roots }),
|
|
137
205
|
});
|
|
138
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
|
+
});
|
|
139
222
|
let overlay = null;
|
|
223
|
+
const modelAccess = request.model.provider === 'overlay' ? access('model', request.model.relay) : null;
|
|
140
224
|
let localMcp = null;
|
|
225
|
+
let contextWindow;
|
|
141
226
|
try {
|
|
142
227
|
;
|
|
143
|
-
[overlay, localMcp] = await Promise.all([
|
|
228
|
+
[overlay, localMcp, contextWindow] = await Promise.all([
|
|
144
229
|
(this.options.connectOverlayTools ?? connectOverlayTools)(request.overlay, {
|
|
145
230
|
signal,
|
|
231
|
+
fetch: request.overlay ? access('tools', request.overlay).fetch : fetch,
|
|
146
232
|
onUnavailable: (reason) => this.options.log?.(`Overlay tools unavailable for this turn: ${publicError(reason)}`),
|
|
147
233
|
}),
|
|
148
234
|
request.localMcp?.length ? this.localMcp.open(request.localMcp, { signal, approvalMode: request.approvalMode }) : null,
|
|
235
|
+
(this.options.contextWindow ?? modelContextWindow)(request.model),
|
|
149
236
|
]);
|
|
150
|
-
const
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
const saved = this.options.store.summary(threadId);
|
|
154
|
-
const agent = new ToolLoopAgent({
|
|
155
|
-
model,
|
|
156
|
-
instructions: instructionsWithSummary(instructions, saved?.summary),
|
|
157
|
-
tools,
|
|
158
|
-
stopWhen: isStepCount(MAX_STEPS),
|
|
159
|
-
prepareStep: createContextCompaction({
|
|
160
|
-
model,
|
|
161
|
-
contextWindow: this.options.contextWindow ?? contextWindowFor(request.model.provider, request.model.modelId),
|
|
162
|
-
instructions,
|
|
163
|
-
tools,
|
|
164
|
-
previousSummary: saved?.summary,
|
|
165
|
-
abortSignal: signal,
|
|
166
|
-
onCompacted: (summary) => this.options.store.saveSummary(threadId, { summary, throughMessageId: summaryBoundary(messages) }),
|
|
167
|
-
}),
|
|
237
|
+
const computerTools = privateComputerTools({
|
|
238
|
+
executor, approvalMode: request.approvalMode, abortSignal: signal,
|
|
239
|
+
onTerminalStarted: (id) => this.rememberTerminal(threadId, id),
|
|
168
240
|
});
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
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),
|
|
175
248
|
});
|
|
176
|
-
const [forPage, forDisk] = toReadable(stream).tee();
|
|
177
|
-
const saving = this.persist(threadId, messages, forDisk);
|
|
178
|
-
const reader = forPage.getReader();
|
|
179
|
-
for (;;) {
|
|
180
|
-
const { done, value } = await reader.read();
|
|
181
|
-
if (done)
|
|
182
|
-
break;
|
|
183
|
-
emit({ kind: 'chunk', threadId, turnId, chunk: value });
|
|
184
|
-
}
|
|
185
|
-
await saving;
|
|
186
249
|
}
|
|
187
250
|
catch (error) {
|
|
188
251
|
if (!signal.aborted)
|
|
189
|
-
failure
|
|
252
|
+
failure ??= publicError(error);
|
|
190
253
|
}
|
|
191
254
|
finally {
|
|
192
255
|
localMcp?.release();
|
|
193
|
-
|
|
256
|
+
// An approval ends this turn and continues in the next one, which may type into a session started here.
|
|
257
|
+
const waiting = !signal.aborted && !failure && pendingApprovals(store.latest(threadId)).length > 0;
|
|
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
|
+
}
|
|
194
269
|
}
|
|
195
|
-
|
|
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 } : {}) });
|
|
196
273
|
}
|
|
197
|
-
/**
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
|
|
204
|
-
const
|
|
205
|
-
|
|
206
|
-
const
|
|
207
|
-
|
|
208
|
-
|
|
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();
|
|
209
352
|
for (;;) {
|
|
210
353
|
const { done, value } = await reader.read();
|
|
211
354
|
if (done)
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
stepsSinceSave++;
|
|
215
|
-
}
|
|
216
|
-
})();
|
|
217
|
-
for await (const message of readUIMessageStream({ stream: snapshots, ...(continuing ? { message: continuing } : {}) })) {
|
|
218
|
-
latest = message;
|
|
219
|
-
if (stepsSinceSave > 0) {
|
|
220
|
-
stepsSinceSave = 0;
|
|
221
|
-
save();
|
|
355
|
+
break;
|
|
356
|
+
turn.emit(value);
|
|
222
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;
|
|
223
366
|
}
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
|
|
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);
|
|
391
|
+
}
|
|
392
|
+
/** Replaces the placeholder title with a written one, unless the person renamed the thread first. */
|
|
393
|
+
startTitle(request, messages, placeholder) {
|
|
394
|
+
const { store, emit, log } = this.options;
|
|
395
|
+
const { owner, threadId } = request;
|
|
396
|
+
const controller = new AbortController();
|
|
397
|
+
const write = async () => {
|
|
398
|
+
const title = await writeTitle((this.options.createModel ?? createModel)(request.model), messages, controller.signal);
|
|
399
|
+
if (!title || controller.signal.aborted || store.get(owner, threadId)?.title !== placeholder)
|
|
400
|
+
return;
|
|
401
|
+
store.update(owner, threadId, { title });
|
|
402
|
+
emit({ kind: 'threads', owner });
|
|
403
|
+
};
|
|
404
|
+
const done = write()
|
|
405
|
+
.catch((error) => { if (!controller.signal.aborted)
|
|
406
|
+
log?.(`Title not written: ${publicError(error)}`); })
|
|
407
|
+
.finally(() => { if (this.titles.get(threadId)?.controller === controller)
|
|
408
|
+
this.titles.delete(threadId); });
|
|
409
|
+
this.titles.set(threadId, { controller, done });
|
|
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
|
+
}
|
|
440
|
+
async stopTitle(threadId) {
|
|
441
|
+
const title = this.titles.get(threadId);
|
|
442
|
+
title?.controller.abort();
|
|
443
|
+
await title?.done;
|
|
444
|
+
}
|
|
445
|
+
rememberTerminal(threadId, id) {
|
|
446
|
+
const ids = this.terminals.get(threadId) ?? new Set();
|
|
447
|
+
this.terminals.set(threadId, ids.add(id));
|
|
448
|
+
}
|
|
449
|
+
/** Stops the sessions one thread started. Sessions of other threads keep running. */
|
|
450
|
+
async stopTerminals(threadId) {
|
|
451
|
+
const ids = this.terminals.get(threadId);
|
|
452
|
+
this.terminals.delete(threadId);
|
|
453
|
+
if (ids)
|
|
454
|
+
await new LocalTerminals(localTerminalsRoot(this.options.stateDirectory)).stopAll(ids).catch(() => undefined);
|
|
228
455
|
}
|
|
229
456
|
/** Stops every run; their transcripts are already saved up to the last step. */
|
|
230
457
|
async shutdown() {
|
|
458
|
+
this.closing = true;
|
|
459
|
+
await Promise.allSettled([this.resumedDeletes, ...this.indexing.values()]);
|
|
231
460
|
for (const run of this.runs.values())
|
|
232
461
|
run.controller.abort();
|
|
233
462
|
await Promise.allSettled([...this.runs.values()].map(run => run.done));
|
|
463
|
+
await Promise.all([...this.titles.keys()].map(threadId => this.stopTitle(threadId)));
|
|
464
|
+
await Promise.all([...this.terminals.keys()].map(threadId => this.stopTerminals(threadId)));
|
|
234
465
|
await this.localMcp.shutdown();
|
|
235
466
|
}
|
|
236
467
|
}
|
|
237
|
-
export function createModel(model) {
|
|
238
|
-
switch (model.provider) {
|
|
239
|
-
case 'anthropic': return createAnthropic({ apiKey: model.apiKey })(model.modelId);
|
|
240
|
-
case 'openai': return createOpenAI({ apiKey: model.apiKey })(model.modelId);
|
|
241
|
-
case 'google': return createGoogleGenerativeAI({ apiKey: model.apiKey })(model.modelId);
|
|
242
|
-
case 'openrouter': return createOpenRouter({ apiKey: model.apiKey })(model.modelId);
|
|
243
|
-
// A signed-in plan, through Overlay Desktop's CLIProxyAPI on this computer: Claude speaks Anthropic's Messages API
|
|
244
|
-
// and ChatGPT (Codex) OpenAI's Responses API there.
|
|
245
|
-
case 'claude': return createAnthropic({ baseURL: `${model.proxy.url}/v1`, apiKey: model.proxy.key })(model.modelId);
|
|
246
|
-
case 'chatgpt': return createOpenAI({ baseURL: `${model.proxy.url}/v1`, apiKey: model.proxy.key }).responses(model.modelId);
|
|
247
|
-
case 'overlay': return createOverlayRelayModel(model.modelId, model.relay);
|
|
248
|
-
}
|
|
249
|
-
}
|
|
250
468
|
/** Local MCP tools are named `server__tool`, so they never take the name of a computer or Overlay tool. */
|
|
251
469
|
function withLocalMcpTools(tools, localMcp) {
|
|
252
470
|
if (!localMcp)
|
|
@@ -267,40 +485,13 @@ function instructionsFor(request, overlay, localMcp) {
|
|
|
267
485
|
`You work on this ${os} computer with the computer tools, in these folders: ${request.roots.join(', ')}.`,
|
|
268
486
|
`The person's home folder is ${homedir()}. Use absolute paths.`,
|
|
269
487
|
`Today is ${new Date().toDateString()}.`,
|
|
488
|
+
RECALL_INSTRUCTIONS,
|
|
270
489
|
'Work step by step, check your results, and finish with a short summary of what you did.',
|
|
271
490
|
].join('\n'),
|
|
272
491
|
overlay && Object.keys(overlay.tools).length > 0 ? overlay.instructions : '',
|
|
273
492
|
localMcp?.instructions ?? '',
|
|
274
493
|
].filter(Boolean).join('\n\n');
|
|
275
494
|
}
|
|
276
|
-
/**
|
|
277
|
-
* Drops screenshot images from finished turns; the tool row keeps its size and the model is told to take a new one.
|
|
278
|
-
* `keepLast` keeps the images of a turn that is continuing (an approval answered mid-turn).
|
|
279
|
-
*/
|
|
280
|
-
export function withoutScreenshotImages(messages, options) {
|
|
281
|
-
return messages.map((message, index) => {
|
|
282
|
-
if (message.role !== 'assistant' || (options.keepLast && index === messages.length - 1))
|
|
283
|
-
return message;
|
|
284
|
-
let changed = false;
|
|
285
|
-
const parts = message.parts.map((part) => {
|
|
286
|
-
const output = part.output;
|
|
287
|
-
if (part.type !== 'tool-computer_screenshot' || !output || typeof output !== 'object' || !('imageBase64' in output))
|
|
288
|
-
return part;
|
|
289
|
-
changed = true;
|
|
290
|
-
const { imageBase64: _image, ...rest } = output;
|
|
291
|
-
void _image;
|
|
292
|
-
return { ...part, output: { ...rest, message: SCREENSHOT_NOT_KEPT } };
|
|
293
|
-
});
|
|
294
|
-
return changed ? { ...message, parts } : message;
|
|
295
|
-
});
|
|
296
|
-
}
|
|
297
|
-
function titleFrom(messages) {
|
|
298
|
-
const text = messages.find(message => message.role === 'user')?.parts
|
|
299
|
-
.map(part => part.type === 'text' ? part.text : '').join(' ').replace(/\s+/g, ' ').trim();
|
|
300
|
-
if (!text)
|
|
301
|
-
return null;
|
|
302
|
-
return text.length > 60 ? `${text.slice(0, 57).trimEnd()}…` : text;
|
|
303
|
-
}
|
|
304
495
|
/** Provider errors can echo request details; keep the message and drop anything that looks like a key. */
|
|
305
496
|
function publicError(error) {
|
|
306
497
|
const message = error instanceof Error ? error.message : String(error);
|
|
@@ -310,19 +501,6 @@ function publicError(error) {
|
|
|
310
501
|
.replace(/ovlp_[A-Za-z0-9]+/g, '[redacted]')
|
|
311
502
|
.slice(0, 1_000) || 'The model call failed.';
|
|
312
503
|
}
|
|
313
|
-
function toReadable(iterable) {
|
|
314
|
-
const iterator = iterable[Symbol.asyncIterator]();
|
|
315
|
-
return new ReadableStream({
|
|
316
|
-
async pull(controller) {
|
|
317
|
-
const { done, value } = await iterator.next();
|
|
318
|
-
if (done)
|
|
319
|
-
controller.close();
|
|
320
|
-
else
|
|
321
|
-
controller.enqueue(value);
|
|
322
|
-
},
|
|
323
|
-
async cancel() { await iterator.return?.(); },
|
|
324
|
-
});
|
|
325
|
-
}
|
|
326
504
|
export function privateThreadsDatabasePath(stateDirectory) {
|
|
327
505
|
return join(stateDirectory, 'private-threads.sqlite');
|
|
328
506
|
}
|