durable-chat 0.0.0-stage → 1.0.1
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/LICENSE +21 -0
- package/LICENSES/mcp-sdk-MIT.txt +21 -0
- package/LICENSES/pi-MIT.txt +21 -0
- package/LICENSES/typebox-MIT.txt +23 -0
- package/LICENSES/yaml-ISC.txt +13 -0
- package/README.md +794 -2
- package/THIRD_PARTY_NOTICES.md +46 -0
- package/dist/agent-instructions.js +176 -0
- package/dist/auth.js +91 -0
- package/dist/chat.js +121 -0
- package/dist/cli.js +519 -0
- package/dist/codemode.js +23 -0
- package/dist/commands.js +227 -0
- package/dist/config-commands.js +142 -0
- package/dist/config.js +567 -0
- package/dist/context-usage.js +48 -0
- package/dist/existing-session.js +52 -0
- package/dist/faux.js +89 -0
- package/dist/forks.js +33 -0
- package/dist/format.js +144 -0
- package/dist/handoff.js +56 -0
- package/dist/harness.js +446 -0
- package/dist/images.js +64 -0
- package/dist/jobs.js +274 -0
- package/dist/mcp.js +231 -0
- package/dist/models.js +64 -0
- package/dist/reboot.js +70 -0
- package/dist/reminders.js +120 -0
- package/dist/rollback.js +72 -0
- package/dist/state.js +64 -0
- package/dist/tags.js +44 -0
- package/dist/tasks.js +466 -0
- package/dist/tool.js +205 -0
- package/dist/tui/app.js +1750 -0
- package/dist/tui/browser.js +19 -0
- package/dist/tui/composer.js +47 -0
- package/dist/tui/dialog.js +39 -0
- package/dist/tui/format.js +223 -0
- package/dist/tui/main.js +83 -0
- package/dist/tui/selection.js +161 -0
- package/dist/tui/state.js +98 -0
- package/dist/tui/transcript.js +151 -0
- package/dist/watch.js +134 -0
- package/dist/workspaces.js +106 -0
- package/package.json +57 -4
package/dist/harness.js
ADDED
|
@@ -0,0 +1,446 @@
|
|
|
1
|
+
import { closeSync, mkdirSync, openSync, readFileSync, unlinkSync, writeSync } from "node:fs";
|
|
2
|
+
import { dirname, resolve } from "node:path";
|
|
3
|
+
import { BACKGROUND_CONTEXT } from "@earendil-works/chord/context";
|
|
4
|
+
import { createModels, createProvider } from "@earendil-works/pi-ai/models";
|
|
5
|
+
import { fauxProvider } from "@earendil-works/pi-ai/providers/faux";
|
|
6
|
+
import { openaiCodexProvider } from "@earendil-works/pi-ai/providers/openai-codex";
|
|
7
|
+
import { openaiProvider } from "@earendil-works/pi-ai/providers/openai";
|
|
8
|
+
import { openAICompletionsApi } from "@earendil-works/pi-ai/api/openai-completions.lazy";
|
|
9
|
+
import { createRegistry, defineExtension, Harness } from "@earendil-works/pi-durable";
|
|
10
|
+
import { createRepositoryInstructions } from "./agent-instructions.js";
|
|
11
|
+
import { jobEnvironment } from "./workspaces.js";
|
|
12
|
+
import { CodingTools } from "@earendil-works/pi-durable/tools";
|
|
13
|
+
import { openNodeSqliteStorage } from "@earendil-works/pi-durable/storage/sqlite/node";
|
|
14
|
+
import { resolveConfig, parseThinkingLevel } from "./config.js";
|
|
15
|
+
import { PiAuthStore } from "./auth.js";
|
|
16
|
+
import { createFauxResponder } from "./faux.js";
|
|
17
|
+
import { applyStartupJobModel, applyThinkingLevel, MAIN_INSTRUCTIONS } from "./jobs.js";
|
|
18
|
+
import { connectMcp } from "./mcp.js";
|
|
19
|
+
import { createTaskExtension } from "./tool.js";
|
|
20
|
+
import { openCodemode } from "./codemode.js";
|
|
21
|
+
import { supportsImages as modelSupportsImages } from "./images.js";
|
|
22
|
+
import { ReminderTools } from "./reminders.js";
|
|
23
|
+
import { JobTask } from "./tasks.js";
|
|
24
|
+
import { JobHandoffTools } from "./handoff.js";
|
|
25
|
+
import { installRollbackSnapshot, rollbackSource } from "./rollback.js";
|
|
26
|
+
import { defaultModelId, modelChoices, selectModel } from "./models.js";
|
|
27
|
+
import { RebootArchive, rebootClosedStore } from "./reboot.js";
|
|
28
|
+
/** Register a built-in under its configured name, including the models used for request dispatch. */
|
|
29
|
+
function registerProvider(models, provider, name, config) {
|
|
30
|
+
models.setProvider(name === provider.id ? provider : {
|
|
31
|
+
...provider,
|
|
32
|
+
id: name,
|
|
33
|
+
getModels: () => provider.getModels().map((model) => ({ ...model, provider: name })),
|
|
34
|
+
getAllModels: () => (provider.getAllModels?.() ?? provider.getModels()).map((model) => ({ ...model, provider: name })),
|
|
35
|
+
});
|
|
36
|
+
// Pre-named-provider checkpoints can still poll the original provider. Explicit entries win.
|
|
37
|
+
if (name !== provider.id && !config.providers.some((entry) => entry.name === provider.id))
|
|
38
|
+
models.setProvider(provider);
|
|
39
|
+
}
|
|
40
|
+
/** Every configured entry is registered on one catalog, so `/model` can list across providers. */
|
|
41
|
+
export function setupProviders(config) {
|
|
42
|
+
const authenticated = config.providers.filter((entry) => entry.kind === "openai-codex" || entry.kind === "openai");
|
|
43
|
+
const models = createModels({
|
|
44
|
+
...(authenticated.length === 0 ? {} : {
|
|
45
|
+
credentials: new PiAuthStore(undefined, new Map(authenticated.map((entry) => [entry.name, entry.kind]))),
|
|
46
|
+
}),
|
|
47
|
+
});
|
|
48
|
+
// Each faux entry gets its own offline instance, so a switch to another entry still reaches
|
|
49
|
+
// a scripted responder and lists its configured model.
|
|
50
|
+
const responders = new Map();
|
|
51
|
+
for (const entry of config.providers) {
|
|
52
|
+
if (entry.kind === "openai-codex") {
|
|
53
|
+
const provider = openaiCodexProvider();
|
|
54
|
+
registerProvider(models, provider, entry.name, config);
|
|
55
|
+
if (models.getModel(entry.name, defaultModelId(entry)) === undefined) {
|
|
56
|
+
throw new Error(`The OpenAI Codex catalog does not list model "${entry.model}".`);
|
|
57
|
+
}
|
|
58
|
+
continue;
|
|
59
|
+
}
|
|
60
|
+
if (entry.kind === "faux") {
|
|
61
|
+
// A faux entry names its own model, so the listed model is the configured one.
|
|
62
|
+
const offline = fauxProvider({ provider: entry.name, tokensPerSecond: 60, ...(entry.model === undefined ? {} : { models: [{ id: entry.model, contextWindow: entry.contextWindow, maxTokens: entry.maxTokens }] }) });
|
|
63
|
+
models.setProvider(offline.provider);
|
|
64
|
+
responders.set(entry.name, createFauxResponder(offline));
|
|
65
|
+
continue;
|
|
66
|
+
}
|
|
67
|
+
if (entry.kind === "openai") {
|
|
68
|
+
const provider = openaiProvider();
|
|
69
|
+
registerProvider(models, provider, entry.name, config);
|
|
70
|
+
if (models.getModel(entry.name, defaultModelId(entry)) === undefined) {
|
|
71
|
+
throw new Error(`The OpenAI catalog does not list model "${entry.model}".`);
|
|
72
|
+
}
|
|
73
|
+
continue;
|
|
74
|
+
}
|
|
75
|
+
const apiKey = entry.apiKey ?? "local-no-auth";
|
|
76
|
+
const localModel = {
|
|
77
|
+
id: defaultModelId(entry),
|
|
78
|
+
name: defaultModelId(entry),
|
|
79
|
+
api: "openai-completions",
|
|
80
|
+
provider: entry.name,
|
|
81
|
+
baseUrl: entry.baseUrl,
|
|
82
|
+
reasoning: true,
|
|
83
|
+
input: ["text"],
|
|
84
|
+
cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },
|
|
85
|
+
contextWindow: entry.contextWindow,
|
|
86
|
+
maxTokens: entry.maxTokens,
|
|
87
|
+
compat: {
|
|
88
|
+
// llama.cpp and vLLM servers commonly reject the OpenAI `developer` role.
|
|
89
|
+
supportsDeveloperRole: false,
|
|
90
|
+
thinkingFormat: "chat-template",
|
|
91
|
+
chatTemplateKwargs: { enable_thinking: { $var: "thinking.enabled" } },
|
|
92
|
+
},
|
|
93
|
+
};
|
|
94
|
+
models.setProvider(createProvider({
|
|
95
|
+
id: entry.name,
|
|
96
|
+
name: `Local OpenAI-compatible (${entry.name})`,
|
|
97
|
+
baseUrl: entry.baseUrl,
|
|
98
|
+
auth: { apiKey: { name: "Local API key", resolve: async () => ({ auth: { apiKey } }) } },
|
|
99
|
+
models: [localModel],
|
|
100
|
+
api: openAICompletionsApi(),
|
|
101
|
+
}));
|
|
102
|
+
}
|
|
103
|
+
const active = config.active;
|
|
104
|
+
return {
|
|
105
|
+
models,
|
|
106
|
+
model: { provider: active.name, modelId: defaultModelId(active) },
|
|
107
|
+
label: `${active.name}/${defaultModelId(active)}${active.kind === "faux" ? " (offline)" : ""}`,
|
|
108
|
+
...(responders.get(active.name) === undefined ? {} : { faux: responders.get(active.name) }),
|
|
109
|
+
};
|
|
110
|
+
}
|
|
111
|
+
export class StoreInUseError extends Error {
|
|
112
|
+
storePath;
|
|
113
|
+
pid;
|
|
114
|
+
constructor(storePath, pid) {
|
|
115
|
+
super(`The store ${storePath} is already open by pid ${pid}. One process owns it.`);
|
|
116
|
+
this.name = "StoreInUseError";
|
|
117
|
+
this.storePath = storePath;
|
|
118
|
+
this.pid = pid;
|
|
119
|
+
}
|
|
120
|
+
}
|
|
121
|
+
/** One process owns a store; a stale lock from a dead pid is reclaimed. */
|
|
122
|
+
export function acquireStoreLock(storePath) {
|
|
123
|
+
const lockPath = `${storePath}.lock`;
|
|
124
|
+
mkdirSync(dirname(storePath), { recursive: true });
|
|
125
|
+
for (let attempt = 0; attempt < 2; attempt++) {
|
|
126
|
+
try {
|
|
127
|
+
const fd = openSync(lockPath, "wx");
|
|
128
|
+
writeSync(fd, JSON.stringify({ pid: process.pid, at: Date.now() }));
|
|
129
|
+
closeSync(fd);
|
|
130
|
+
return () => {
|
|
131
|
+
try {
|
|
132
|
+
unlinkSync(lockPath);
|
|
133
|
+
}
|
|
134
|
+
catch {
|
|
135
|
+
// Already gone.
|
|
136
|
+
}
|
|
137
|
+
};
|
|
138
|
+
}
|
|
139
|
+
catch (error) {
|
|
140
|
+
if (error.code !== "EEXIST")
|
|
141
|
+
throw error;
|
|
142
|
+
let pid;
|
|
143
|
+
try {
|
|
144
|
+
pid = JSON.parse(readFileSync(lockPath, "utf8")).pid;
|
|
145
|
+
}
|
|
146
|
+
catch {
|
|
147
|
+
pid = undefined;
|
|
148
|
+
}
|
|
149
|
+
if (pid !== undefined && isAlive(pid)) {
|
|
150
|
+
throw new StoreInUseError(storePath, pid);
|
|
151
|
+
}
|
|
152
|
+
try {
|
|
153
|
+
unlinkSync(lockPath);
|
|
154
|
+
}
|
|
155
|
+
catch {
|
|
156
|
+
// Another opener removed it.
|
|
157
|
+
}
|
|
158
|
+
}
|
|
159
|
+
}
|
|
160
|
+
throw new Error(`Could not lock the store ${storePath}.`);
|
|
161
|
+
}
|
|
162
|
+
function isAlive(pid) {
|
|
163
|
+
try {
|
|
164
|
+
process.kill(pid, 0);
|
|
165
|
+
return true;
|
|
166
|
+
}
|
|
167
|
+
catch (error) {
|
|
168
|
+
return error.code === "EPERM";
|
|
169
|
+
}
|
|
170
|
+
}
|
|
171
|
+
export async function openRuntime(options) {
|
|
172
|
+
const config = resolveConfig({
|
|
173
|
+
...(options.storePath === undefined ? {} : { store: options.storePath }),
|
|
174
|
+
...(options.provider === undefined ? {} : { provider: options.provider }),
|
|
175
|
+
...(options.model === undefined ? {} : { model: options.model }),
|
|
176
|
+
...(options.configPath === undefined ? {} : { configPath: options.configPath }),
|
|
177
|
+
});
|
|
178
|
+
return openConfiguredRuntime(config, {
|
|
179
|
+
cwd: process.cwd(), withMcp: options.withMcp ?? config.mcp.enabled, verbose: options.verbose === true,
|
|
180
|
+
modelLimits: { contextWindow: config.contextWindow, maxTokens: config.maxTokens },
|
|
181
|
+
}, acquireStoreLock(resolve(config.storePath)));
|
|
182
|
+
}
|
|
183
|
+
/** Reboots retain the startup configuration and transfer the still-held store lock to the new runtime. */
|
|
184
|
+
async function openConfiguredRuntime(config, options, releaseLock, releaseOnFailure = true, archivePath, restoredFrom) {
|
|
185
|
+
const storePath = resolve(config.storePath);
|
|
186
|
+
const { cwd, withMcp } = options;
|
|
187
|
+
const context = BACKGROUND_CONTEXT;
|
|
188
|
+
let mcp;
|
|
189
|
+
let codemode;
|
|
190
|
+
let harness;
|
|
191
|
+
let storage;
|
|
192
|
+
try {
|
|
193
|
+
const setup = setupProviders(config);
|
|
194
|
+
const mcpSetup = withMcp
|
|
195
|
+
? await connectMcp({
|
|
196
|
+
...(config.mcp.configPath === undefined ? {} : { configPath: config.mcp.configPath }),
|
|
197
|
+
servers: config.mcp.servers,
|
|
198
|
+
tools: config.mcp.tools,
|
|
199
|
+
verbose: options.verbose === true,
|
|
200
|
+
})
|
|
201
|
+
: { extensions: [], notes: [], close: async () => undefined };
|
|
202
|
+
mcp = mcpSetup;
|
|
203
|
+
codemode = config.codemode ? openCodemode() : undefined;
|
|
204
|
+
const repositoryInstructions = createRepositoryInstructions(cwd);
|
|
205
|
+
const jobExtensions = [
|
|
206
|
+
repositoryInstructions,
|
|
207
|
+
CodingTools,
|
|
208
|
+
JobHandoffTools,
|
|
209
|
+
...(codemode === undefined ? [] : [codemode.extension]),
|
|
210
|
+
...mcpSetup.extensions.filter((extension) => extension.name !== "durable-chat.tasks"),
|
|
211
|
+
];
|
|
212
|
+
const jobOptions = {
|
|
213
|
+
maxTurns: config.jobMaxTurns, thinkingLevel: config.thinkingLevel, autoContinue: config.autoContinue,
|
|
214
|
+
};
|
|
215
|
+
const tasksExtension = createTaskExtension({
|
|
216
|
+
model: setup.model,
|
|
217
|
+
jobExtensions,
|
|
218
|
+
cwd,
|
|
219
|
+
jobOptions,
|
|
220
|
+
});
|
|
221
|
+
const registry = createRegistry();
|
|
222
|
+
registry.install(CodingTools);
|
|
223
|
+
registry.install(repositoryInstructions);
|
|
224
|
+
registry.install(JobHandoffTools);
|
|
225
|
+
registry.install(defineExtension({ name: "durable-chat.jobs", tasks: [JobTask] }));
|
|
226
|
+
registry.install(tasksExtension);
|
|
227
|
+
registry.install(ReminderTools);
|
|
228
|
+
if (codemode !== undefined)
|
|
229
|
+
registry.install(codemode.extension);
|
|
230
|
+
for (const extension of mcpSetup.extensions)
|
|
231
|
+
registry.install(extension);
|
|
232
|
+
storage = await openNodeSqliteStorage(storePath);
|
|
233
|
+
harness = await Harness.open(storage, {
|
|
234
|
+
models: setup.models,
|
|
235
|
+
registry,
|
|
236
|
+
settings: {
|
|
237
|
+
retry: { maxRetries: config.retries },
|
|
238
|
+
stream: { maxRetries: config.retries, timeoutMs: config.streamTimeoutMs },
|
|
239
|
+
},
|
|
240
|
+
env: (target, callContext) => jobEnvironment(target, callContext, cwd),
|
|
241
|
+
onReport: (report) => {
|
|
242
|
+
const error = report.error instanceof Error ? report.error.message : String(report.error);
|
|
243
|
+
const task = "task" in report && report.task !== undefined ? ` #${report.task.id}` : "";
|
|
244
|
+
process.stderr.write(`[durable-chat] ${report.kind}${task}: ${error}\n`);
|
|
245
|
+
},
|
|
246
|
+
}, context);
|
|
247
|
+
setup.faux?.ensure();
|
|
248
|
+
const root = await harness.root(context, { agent: { model: setup.model } });
|
|
249
|
+
await applyStartupJobModel(harness, setup.model, context, repositoryInstructions);
|
|
250
|
+
await root.configure({
|
|
251
|
+
model: setup.model,
|
|
252
|
+
thinkingLevel: config.thinkingLevel,
|
|
253
|
+
maxTurns: config.maxTurns,
|
|
254
|
+
instructions: MAIN_INSTRUCTIONS,
|
|
255
|
+
extensions: [tasksExtension, repositoryInstructions, ReminderTools, ...(codemode === undefined ? [] : [codemode.extension])],
|
|
256
|
+
tools: null,
|
|
257
|
+
modelTools: null,
|
|
258
|
+
cwd,
|
|
259
|
+
}, context);
|
|
260
|
+
if (archivePath !== undefined) {
|
|
261
|
+
await harness.commit(async (tx) => {
|
|
262
|
+
const archive = await tx.doc(RebootArchive);
|
|
263
|
+
archive.path = archivePath;
|
|
264
|
+
if (restoredFrom !== undefined)
|
|
265
|
+
archive.restoredFrom = restoredFrom;
|
|
266
|
+
}, context);
|
|
267
|
+
}
|
|
268
|
+
const archiveInfo = await harness.snapshot(RebootArchive, context);
|
|
269
|
+
const previousStateArchive = archiveInfo?.path;
|
|
270
|
+
let closing;
|
|
271
|
+
const close = (release) => {
|
|
272
|
+
closing ??= (async () => {
|
|
273
|
+
try {
|
|
274
|
+
await harness?.close(context);
|
|
275
|
+
}
|
|
276
|
+
finally {
|
|
277
|
+
try {
|
|
278
|
+
await mcp?.close();
|
|
279
|
+
}
|
|
280
|
+
finally {
|
|
281
|
+
try {
|
|
282
|
+
await codemode?.close();
|
|
283
|
+
}
|
|
284
|
+
finally {
|
|
285
|
+
if (release)
|
|
286
|
+
releaseLock();
|
|
287
|
+
}
|
|
288
|
+
}
|
|
289
|
+
}
|
|
290
|
+
})();
|
|
291
|
+
return closing;
|
|
292
|
+
};
|
|
293
|
+
const replace = async (sourcePath) => {
|
|
294
|
+
if (closing !== undefined)
|
|
295
|
+
throw new Error("This runtime is already closing or closed.");
|
|
296
|
+
const source = sourcePath === undefined ? undefined : rollbackSource(sourcePath, [], storePath);
|
|
297
|
+
const releaseSource = source === undefined ? undefined : acquireStoreLock(source);
|
|
298
|
+
try {
|
|
299
|
+
await close(false);
|
|
300
|
+
return await rebootClosedStore(storePath, async (archive) => {
|
|
301
|
+
if (source !== undefined)
|
|
302
|
+
installRollbackSnapshot(source, storePath);
|
|
303
|
+
return openConfiguredRuntime(config, options, releaseLock, false, archive, source);
|
|
304
|
+
}, source === undefined ? "Reboot" : "Rollback");
|
|
305
|
+
}
|
|
306
|
+
catch (error) {
|
|
307
|
+
releaseLock();
|
|
308
|
+
throw error;
|
|
309
|
+
}
|
|
310
|
+
finally {
|
|
311
|
+
releaseSource?.();
|
|
312
|
+
}
|
|
313
|
+
};
|
|
314
|
+
let choices;
|
|
315
|
+
const listModels = async (signal) => {
|
|
316
|
+
if (closing !== undefined)
|
|
317
|
+
throw new Error("This runtime is already closing or closed.");
|
|
318
|
+
const result = await modelChoices(config, setup.models, setup.model, signal);
|
|
319
|
+
choices = result;
|
|
320
|
+
return result;
|
|
321
|
+
};
|
|
322
|
+
const switchTo = async (entry, modelId, selected) => {
|
|
323
|
+
if (closing !== undefined)
|
|
324
|
+
throw new Error("This runtime is already closing or closed.");
|
|
325
|
+
const target = { provider: entry.name, modelId };
|
|
326
|
+
if (target.provider === setup.model.provider && target.modelId === setup.model.modelId)
|
|
327
|
+
return { runtime: app };
|
|
328
|
+
// Shutdown preserves durable checkpoints; the replacement configures subsequent requests.
|
|
329
|
+
// The startup limits carry an environment override; a different entry brings its own.
|
|
330
|
+
const base = entry.name === config.provider ? options.modelLimits : { contextWindow: entry.contextWindow, maxTokens: entry.maxTokens };
|
|
331
|
+
const nextActive = { ...entry, model: modelId };
|
|
332
|
+
const nextConfig = {
|
|
333
|
+
...config,
|
|
334
|
+
// Keep the active entry inside the listed providers, so the picker reports the model in use.
|
|
335
|
+
providers: config.providers.map((candidate) => candidate === entry ? nextActive : candidate),
|
|
336
|
+
...(entry.model === undefined ? {} : { model: entry.model }),
|
|
337
|
+
...(entry.baseUrl === undefined ? {} : { baseUrl: entry.baseUrl }),
|
|
338
|
+
...(entry.apiKey === undefined ? {} : { apiKey: entry.apiKey }),
|
|
339
|
+
...(entry.apiKeyEnv === undefined ? {} : { apiKeyEnv: entry.apiKeyEnv }),
|
|
340
|
+
provider: entry.name, active: nextActive, model: modelId,
|
|
341
|
+
contextWindow: Math.min(base.contextWindow, selected.contextWindow),
|
|
342
|
+
maxTokens: Math.min(base.maxTokens, selected.maxTokens),
|
|
343
|
+
streamTimeoutMs: entry.streamTimeoutMs,
|
|
344
|
+
// A session thinking override survives a switch within the same provider.
|
|
345
|
+
thinkingLevel: entry.name === config.provider ? config.thinkingLevel : entry.thinkingLevel,
|
|
346
|
+
};
|
|
347
|
+
try {
|
|
348
|
+
await close(false);
|
|
349
|
+
}
|
|
350
|
+
catch (error) {
|
|
351
|
+
releaseLock();
|
|
352
|
+
throw error;
|
|
353
|
+
}
|
|
354
|
+
try {
|
|
355
|
+
return { runtime: await openConfiguredRuntime(nextConfig, options, releaseLock, false) };
|
|
356
|
+
}
|
|
357
|
+
catch (error) {
|
|
358
|
+
try {
|
|
359
|
+
const recovered = await openConfiguredRuntime(config, options, releaseLock, false);
|
|
360
|
+
return { runtime: recovered, error: `Model unchanged: ${error instanceof Error ? error.message : String(error)}` };
|
|
361
|
+
}
|
|
362
|
+
catch (recoveryError) {
|
|
363
|
+
releaseLock();
|
|
364
|
+
throw new AggregateError([error, recoveryError], `Model switch and recovery failed. State remains at ${storePath}; restart with ${setup.label}.`);
|
|
365
|
+
}
|
|
366
|
+
}
|
|
367
|
+
};
|
|
368
|
+
const app = {
|
|
369
|
+
harness,
|
|
370
|
+
root,
|
|
371
|
+
context,
|
|
372
|
+
config,
|
|
373
|
+
storePath,
|
|
374
|
+
model: setup.model,
|
|
375
|
+
modelLabel: setup.label,
|
|
376
|
+
get thinkingLevel() { return jobOptions.thinkingLevel; },
|
|
377
|
+
supportsImages: () => {
|
|
378
|
+
const model = setup.models.getModel(setup.model.provider, setup.model.modelId);
|
|
379
|
+
return model === undefined ? false : modelSupportsImages(model);
|
|
380
|
+
},
|
|
381
|
+
cwd,
|
|
382
|
+
mcpNotes: mcpSetup.notes,
|
|
383
|
+
mcpAttempted: withMcp,
|
|
384
|
+
mcpConnected: mcpSetup.extensions.some((extension) => extension.name === "durable-chat.mcp.substrate" && !extension.tools?.some((tool) => tool.name === "mcp_substrate_unavailable")),
|
|
385
|
+
tasksExtension,
|
|
386
|
+
jobExtensions,
|
|
387
|
+
...(codemode === undefined ? {} : { codemodeExtension: codemode.extension }),
|
|
388
|
+
...(setup.faux === undefined ? {} : { faux: setup.faux }),
|
|
389
|
+
...(previousStateArchive == null ? {} : { previousStateArchive }),
|
|
390
|
+
...(archiveInfo?.restoredFrom === undefined ? {} : { restoredFrom: archiveInfo.restoredFrom }),
|
|
391
|
+
listModels,
|
|
392
|
+
async switchModel(input) {
|
|
393
|
+
const selected = selectModel(input, (choices ?? await listModels()).items);
|
|
394
|
+
const entry = config.providers.find((candidate) => candidate.name === selected.provider) ?? config.active;
|
|
395
|
+
return switchTo(entry, selected.id, { contextWindow: selected.contextWindow, maxTokens: selected.maxTokens });
|
|
396
|
+
},
|
|
397
|
+
async switchProvider(name) {
|
|
398
|
+
const entry = config.providers.find((candidate) => candidate.name === name.trim());
|
|
399
|
+
if (entry === undefined) {
|
|
400
|
+
return { runtime: app, error: `No configured provider "${name.trim()}". Known: ${config.providers.map((candidate) => candidate.name).join(", ")}.` };
|
|
401
|
+
}
|
|
402
|
+
return switchTo(entry, defaultModelId(entry), { contextWindow: entry.contextWindow, maxTokens: entry.maxTokens });
|
|
403
|
+
},
|
|
404
|
+
reboot: () => replace(),
|
|
405
|
+
async setThinkingLevel(raw) {
|
|
406
|
+
if (closing !== undefined)
|
|
407
|
+
throw new Error("This runtime is already closing or closed.");
|
|
408
|
+
const level = parseThinkingLevel(raw);
|
|
409
|
+
// The effective config for this run; the config file still decides the next run.
|
|
410
|
+
config.thinkingLevel = level;
|
|
411
|
+
jobOptions.thinkingLevel = level;
|
|
412
|
+
await root.configure({ thinkingLevel: level }, context);
|
|
413
|
+
await applyThinkingLevel(harness, level, context);
|
|
414
|
+
return level;
|
|
415
|
+
},
|
|
416
|
+
rollback: (source) => replace(source),
|
|
417
|
+
close: () => close(true),
|
|
418
|
+
};
|
|
419
|
+
return app;
|
|
420
|
+
}
|
|
421
|
+
catch (error) {
|
|
422
|
+
try {
|
|
423
|
+
await harness?.close(context);
|
|
424
|
+
}
|
|
425
|
+
catch {
|
|
426
|
+
// Preserve the original startup error.
|
|
427
|
+
}
|
|
428
|
+
try {
|
|
429
|
+
await storage?.close(context);
|
|
430
|
+
}
|
|
431
|
+
catch { /* Reboot recovery checks journal closure before moving replacement files. */ }
|
|
432
|
+
try {
|
|
433
|
+
await mcp?.close();
|
|
434
|
+
}
|
|
435
|
+
catch { /* Preserve the original startup error. */ }
|
|
436
|
+
try {
|
|
437
|
+
await codemode?.close();
|
|
438
|
+
}
|
|
439
|
+
catch { /* Preserve the original startup error. */ }
|
|
440
|
+
finally {
|
|
441
|
+
if (releaseOnFailure)
|
|
442
|
+
releaseLock();
|
|
443
|
+
}
|
|
444
|
+
throw error;
|
|
445
|
+
}
|
|
446
|
+
}
|
package/dist/images.js
ADDED
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
import { readFileSync } from "node:fs";
|
|
2
|
+
import { basename, extname } from "node:path";
|
|
3
|
+
import { createNodePhotonImages } from "@earendil-works/pi-durable/images/node";
|
|
4
|
+
import { DEFAULT_IMAGE_LIMITS } from "@earendil-works/pi-durable/tools";
|
|
5
|
+
/** Providers only send image blocks when the model declares image input; otherwise they drop them. */
|
|
6
|
+
export function supportsImages(model) {
|
|
7
|
+
return model.input.includes("image");
|
|
8
|
+
}
|
|
9
|
+
export const MAX_ATTACHMENTS = 4;
|
|
10
|
+
/** Formats providers take inline; the image processor converts the others, such as BMP, to PNG. */
|
|
11
|
+
const INLINE_TYPES = new Set(["image/png", "image/jpeg", "image/gif", "image/webp"]);
|
|
12
|
+
const MIME_BY_EXTENSION = {
|
|
13
|
+
".png": "image/png", ".jpg": "image/jpeg", ".jpeg": "image/jpeg", ".gif": "image/gif", ".webp": "image/webp",
|
|
14
|
+
};
|
|
15
|
+
/** The extension decides when there is one; a clipboard image is bytes with no name, so read its signature. */
|
|
16
|
+
function mimeOf(source, bytes) {
|
|
17
|
+
const known = MIME_BY_EXTENSION[extname(source).toLowerCase()];
|
|
18
|
+
if (known !== undefined)
|
|
19
|
+
return known;
|
|
20
|
+
if (bytes.length >= 4 && bytes[0] === 0x89 && bytes[1] === 0x50 && bytes[2] === 0x4e && bytes[3] === 0x47)
|
|
21
|
+
return "image/png";
|
|
22
|
+
if (bytes.length >= 2 && bytes[0] === 0xff && bytes[1] === 0xd8)
|
|
23
|
+
return "image/jpeg";
|
|
24
|
+
if (bytes.length >= 3 && bytes[0] === 0x47 && bytes[1] === 0x49 && bytes[2] === 0x46)
|
|
25
|
+
return "image/gif";
|
|
26
|
+
if (bytes.length >= 12 && bytes[0] === 0x52 && bytes[1] === 0x49 && bytes[2] === 0x46 && bytes[3] === 0x46
|
|
27
|
+
&& bytes[8] === 0x57 && bytes[9] === 0x45 && bytes[10] === 0x42 && bytes[11] === 0x50)
|
|
28
|
+
return "image/webp";
|
|
29
|
+
return "application/octet-stream";
|
|
30
|
+
}
|
|
31
|
+
/** Photon prepares images on a worker thread, so a large photo does not stall the TUI's event loop. */
|
|
32
|
+
export function createImagePaster(clipboard, limits = DEFAULT_IMAGE_LIMITS) {
|
|
33
|
+
let processor;
|
|
34
|
+
const prepare = async (bytes, source) => {
|
|
35
|
+
const mimeType = mimeOf(source, bytes);
|
|
36
|
+
if (!INLINE_TYPES.has(mimeType))
|
|
37
|
+
throw new Error(`${source} is not an image format providers take inline.`);
|
|
38
|
+
processor ??= await createNodePhotonImages();
|
|
39
|
+
// A Buffer's pool buffer cannot be transferred to the Photon worker, so pass a plain Uint8Array.
|
|
40
|
+
const prepared = await processor.prepare(new Uint8Array(bytes), mimeType, limits);
|
|
41
|
+
if (prepared === undefined)
|
|
42
|
+
throw new Error(`${source} cannot be decoded or made to fit the image limits.`);
|
|
43
|
+
return { source, data: prepared.data, mimeType: prepared.mimeType };
|
|
44
|
+
};
|
|
45
|
+
return {
|
|
46
|
+
async paste() {
|
|
47
|
+
if (clipboard === undefined)
|
|
48
|
+
throw new Error("The clipboard is unavailable in this environment.");
|
|
49
|
+
const paths = await clipboard.getFilePaths?.();
|
|
50
|
+
if (paths !== undefined && paths !== null)
|
|
51
|
+
return Promise.all(paths.map((path) => prepare(readFileSync(path), path)));
|
|
52
|
+
const image = await clipboard.getImage();
|
|
53
|
+
if (image === undefined)
|
|
54
|
+
throw new Error("This terminal cannot read a clipboard image.");
|
|
55
|
+
if (image === null)
|
|
56
|
+
return [];
|
|
57
|
+
return [await prepare(image, "clipboard")];
|
|
58
|
+
},
|
|
59
|
+
fromPath: (path) => prepare(readFileSync(path), path),
|
|
60
|
+
};
|
|
61
|
+
}
|
|
62
|
+
export function attachmentLabel(attachments) {
|
|
63
|
+
return attachments.map((attachment) => basename(attachment.source)).join(", ");
|
|
64
|
+
}
|