@cydm/pie 2.7.20 → 2.8.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.
Files changed (40) hide show
  1. package/README.md +18 -0
  2. package/dist/builtin/extensions/ask-user/README.md +117 -0
  3. package/dist/builtin/extensions/ask-user/index.js +4 -3
  4. package/dist/builtin/extensions/cron/index.js +299 -39
  5. package/dist/builtin/extensions/im-forward/README.md +297 -0
  6. package/dist/builtin/extensions/im-forward/index.js +315 -27
  7. package/dist/builtin/extensions/mcp-adapter/README.md +27 -0
  8. package/dist/builtin/extensions/memory/index.js +515 -0
  9. package/dist/builtin/extensions/memory/package.json +19 -0
  10. package/dist/builtin/extensions/pie-ipc/README.md +21 -0
  11. package/dist/builtin/extensions/plan-mode/METHOD.md +70 -0
  12. package/dist/builtin/extensions/plan-mode/index.js +150 -82
  13. package/dist/builtin/extensions/subagent/README.md +315 -0
  14. package/dist/builtin/extensions/subagent/index.js +8 -5
  15. package/dist/builtin/extensions/todo/index.js +4 -3
  16. package/dist/builtin/skills/chrome-devtools-axi/chrome-devtools-axi-bridge.js +1 -1
  17. package/dist/builtin/skills/chrome-devtools-axi/chrome-devtools-axi-runtime.js +1 -1
  18. package/dist/builtin/skills/chrome-devtools-axi/{chunk-U75F4DPF.js → chunk-BNSAEVRT.js} +201 -77
  19. package/dist/builtin/skills/chrome-devtools-axi/{cli-4ITIR57L.js → cli-AO2ZTPRM.js} +57 -202
  20. package/dist/builtin/skills/computer-use-axi/computer-use-axi-broker.js +6 -1
  21. package/dist/builtin/skills/computer-use-axi/computer-use-axi-runtime.js +6 -1
  22. package/dist/chunks/auth-storage-3EGM3VTK.js +13 -0
  23. package/dist/chunks/{chunk-X7UO6BA6.js → chunk-3BC5KGDQ.js} +451 -162
  24. package/dist/chunks/chunk-3NHP7HK5.js +298 -0
  25. package/dist/chunks/chunk-6DNYGVZP.js +278 -0
  26. package/dist/chunks/{chunk-TGCI5M6R.js → chunk-GDIYSMTS.js} +22 -142
  27. package/dist/chunks/{chunk-2H2DD22Z.js → chunk-GH4VW2OT.js} +1 -1
  28. package/dist/chunks/chunk-ILUHTKF3.js +149 -0
  29. package/dist/chunks/{chunk-UDCGB3LZ.js → chunk-PK72LVWQ.js} +11841 -16501
  30. package/dist/chunks/chunk-RSL7E4R7.js +9634 -0
  31. package/dist/chunks/chunk-YRR6C43W.js +1740 -0
  32. package/dist/chunks/config-74AUVDLT.js +46 -0
  33. package/dist/chunks/model-registry-LI5THXV4.js +17 -0
  34. package/dist/chunks/src-66XSMIAM.js +134 -0
  35. package/dist/chunks/src-BPSQMSSC.js +431 -0
  36. package/dist/chunks/src-OPPYTPWG.js +285 -0
  37. package/dist/chunks/{src-GX4UBAYF.js → src-YG5M2H44.js} +2 -2
  38. package/dist/chunks/{test-stream-AKIZNFCM.js → test-stream-JBWXKOQA.js} +1 -1
  39. package/dist/cli.js +986 -2292
  40. package/package.json +3 -3
@@ -0,0 +1,298 @@
1
+ import { createRequire as __createRequire } from "node:module"; const require = __createRequire(import.meta.url);
2
+
3
+ // src/commands/memory-distill.ts
4
+ import * as fs from "node:fs";
5
+ import { createRequire } from "node:module";
6
+ import * as path from "node:path";
7
+ import { spawn } from "node:child_process";
8
+ var require2 = createRequire(import.meta.url);
9
+ function distillWorkerLogPath(memoryRoot) {
10
+ return path.join(memoryRoot, "distill-worker.log");
11
+ }
12
+ function distillLockPath(memoryRoot) {
13
+ return path.join(memoryRoot, "distill.lock");
14
+ }
15
+ function readDistillWorkerLog(memoryRoot, limit = 20) {
16
+ try {
17
+ const raw = fs.readFileSync(distillWorkerLogPath(memoryRoot), "utf8");
18
+ const lines = raw.split("\n").filter((line) => line.trim().length > 0);
19
+ return lines.slice(-limit);
20
+ } catch {
21
+ return [];
22
+ }
23
+ }
24
+ function spawnDistillWorker(memoryRoot, date) {
25
+ return spawnDistillCli(memoryRoot, ["--date", date]);
26
+ }
27
+ function spawnDistillAutoWorker(memoryRoot) {
28
+ return spawnDistillCli(memoryRoot, ["--auto"]);
29
+ }
30
+ function spawnDistillCli(memoryRoot, modeArgs) {
31
+ const logPath = distillWorkerLogPath(memoryRoot);
32
+ const entry = process.argv[1] ? path.resolve(process.argv[1]) : null;
33
+ if (!entry) return false;
34
+ try {
35
+ fs.mkdirSync(memoryRoot, { recursive: true });
36
+ } catch {
37
+ return false;
38
+ }
39
+ const args = [entry, "memory", "distill", ...modeArgs, "--worker", "--memory-root", memoryRoot];
40
+ let out;
41
+ try {
42
+ out = fs.openSync(logPath, "a");
43
+ const child = spawn(process.execPath, args, {
44
+ detached: true,
45
+ stdio: ["ignore", out, out],
46
+ env: { ...process.env, PIE_MEMORY_WORKER: "1" }
47
+ });
48
+ child.on("error", (error) => {
49
+ try {
50
+ fs.appendFileSync(logPath, `[${(/* @__PURE__ */ new Date()).toISOString()}] spawn failed: ${String(error)}
51
+ `);
52
+ } catch {
53
+ }
54
+ });
55
+ child.unref();
56
+ try {
57
+ fs.appendFileSync(logPath, `[${(/* @__PURE__ */ new Date()).toISOString()}] spawned worker (${modeArgs.join(" ")}) (pid ${child.pid})
58
+ `);
59
+ } catch {
60
+ }
61
+ return true;
62
+ } catch {
63
+ return false;
64
+ } finally {
65
+ if (out !== void 0) {
66
+ try {
67
+ fs.closeSync(out);
68
+ } catch {
69
+ }
70
+ }
71
+ }
72
+ }
73
+ var advisoryLockBackend = /* @__PURE__ */ (() => {
74
+ let impl;
75
+ return () => {
76
+ if (impl) return impl;
77
+ const koffi = require2("koffi");
78
+ const { createMemoryLockBackend } = require2("@pie/shared-headless-capabilities");
79
+ impl = createMemoryLockBackend(koffi);
80
+ return impl;
81
+ };
82
+ })();
83
+ function acquireAdvisoryLock(lockPath) {
84
+ const backend = advisoryLockBackend();
85
+ fs.mkdirSync(path.dirname(lockPath), { recursive: true });
86
+ let handle;
87
+ try {
88
+ handle = backend.open(lockPath);
89
+ } catch (error) {
90
+ throw error instanceof Error ? error : new Error(String(error));
91
+ }
92
+ try {
93
+ const result = backend.lock(handle);
94
+ if (result !== "acquired") {
95
+ backend.unlock(handle);
96
+ return null;
97
+ }
98
+ } catch (error) {
99
+ backend.unlock(handle);
100
+ throw error;
101
+ }
102
+ let released = false;
103
+ return {
104
+ release() {
105
+ if (released) return;
106
+ released = true;
107
+ backend.unlock(handle);
108
+ }
109
+ };
110
+ }
111
+ function acquireDistillLock(memoryRoot) {
112
+ const lock = acquireAdvisoryLock(distillLockPath(memoryRoot));
113
+ return lock ? () => lock.release() : null;
114
+ }
115
+ async function withModelTimeout(promise, timeoutMs, label) {
116
+ let timer;
117
+ try {
118
+ return await new Promise((resolve2, reject) => {
119
+ timer = setTimeout(() => reject(new Error(`${label} timed out after ${timeoutMs}ms`)), timeoutMs);
120
+ Promise.resolve(promise).then(
121
+ (value) => {
122
+ clearTimeout(timer);
123
+ resolve2(value);
124
+ },
125
+ (error) => {
126
+ clearTimeout(timer);
127
+ reject(error);
128
+ }
129
+ );
130
+ });
131
+ } finally {
132
+ if (timer !== void 0) {
133
+ const t = timer;
134
+ queueMicrotask(() => clearTimeout(t));
135
+ }
136
+ }
137
+ }
138
+ function normalizeCwdPath(value) {
139
+ if (value.length > 1 && value.endsWith(path.sep)) return value.slice(0, -1);
140
+ return value;
141
+ }
142
+ function pathContains(parent, child) {
143
+ if (parent === child) return true;
144
+ const parentWithSep = parent.endsWith(path.sep) ? parent : parent + path.sep;
145
+ return child.startsWith(parentWithSep);
146
+ }
147
+ async function readExcludeCwds() {
148
+ try {
149
+ const { getSettingsPath } = await import("./config-74AUVDLT.js");
150
+ const raw = JSON.parse(fs.readFileSync(getSettingsPath(), "utf8"));
151
+ const list = raw?.extensions?.memory?.excludeCwds;
152
+ if (!Array.isArray(list)) return [];
153
+ return list.filter((entry) => typeof entry === "string" && path.isAbsolute(entry)).map(normalizeCwdPath);
154
+ } catch {
155
+ return [];
156
+ }
157
+ }
158
+ async function runDistillWorkerMain(memoryRoot, date, noExit = false) {
159
+ const log = (message) => {
160
+ try {
161
+ fs.appendFileSync(distillWorkerLogPath(memoryRoot), `[${(/* @__PURE__ */ new Date()).toISOString()}] ${message}
162
+ `);
163
+ } catch {
164
+ }
165
+ };
166
+ const release = acquireDistillLock(memoryRoot);
167
+ if (!release) {
168
+ return { ok: false, error: "another distillation worker holds the lock", busy: true };
169
+ }
170
+ let result;
171
+ let ledger;
172
+ try {
173
+ const { ModelRegistry } = await import("./model-registry-LI5THXV4.js");
174
+ const { AuthStorage } = await import("./auth-storage-3EGM3VTK.js");
175
+ const { getSessionsDir } = await import("./config-74AUVDLT.js");
176
+ const { FileSessionStore } = await import("./src-OPPYTPWG.js");
177
+ const { MemoryStore, runDistillation } = await import("./src-BPSQMSSC.js");
178
+ const store = new MemoryStore(memoryRoot);
179
+ ledger = store;
180
+ const registry = new ModelRegistry(AuthStorage.create());
181
+ const excludeCwds = await readExcludeCwds();
182
+ const cwdFilter = excludeCwds.length > 0 ? (cwd) => {
183
+ if (!cwd) return true;
184
+ const normalized = normalizeCwdPath(cwd);
185
+ return !excludeCwds.some((excluded) => pathContains(excluded, normalized));
186
+ } : void 0;
187
+ const modelCall = (modelClass) => async (prompt, options) => {
188
+ const resolved = registry.resolveModelClass(modelClass);
189
+ if (!resolved.model || !resolved.apiKey) {
190
+ throw new Error(`no complete model/key pair for class ${modelClass}${resolved.fallbackReason ? `: ${resolved.fallbackReason}` : ""}`);
191
+ }
192
+ const { completeSimple } = await import("./src-66XSMIAM.js");
193
+ const message = await withModelTimeout(
194
+ completeSimple(
195
+ resolved.model,
196
+ {
197
+ systemPrompt: options?.system ?? "You are a precise extraction engine.",
198
+ messages: [{ role: "user", content: [{ type: "text", text: prompt }], timestamp: Date.now() }]
199
+ },
200
+ { apiKey: resolved.apiKey, maxTokens: Math.min(resolved.model.maxTokens ?? 4096, 4096) }
201
+ ),
202
+ 12e4,
203
+ `memory ${modelClass} model call`
204
+ );
205
+ if (message.stopReason && message.stopReason !== "stop") {
206
+ throw new Error(`memory model call ended with stopReason=${message.stopReason}`);
207
+ }
208
+ return message.content.filter((block) => block.type === "text").map((block) => block.text).join("\n");
209
+ };
210
+ const distilled = await runDistillation(
211
+ {
212
+ sessionStore: new FileSessionStore(getSessionsDir()),
213
+ memoryStore: store,
214
+ lightCall: modelCall("light"),
215
+ balancedCall: modelCall("balanced"),
216
+ callTimeoutMs: 12e4,
217
+ cwdFilter,
218
+ log
219
+ },
220
+ date
221
+ );
222
+ log(`done ${date}: status=${distilled.status} sessions=${distilled.sessions} ops=${distilled.patchOps}${distilled.error ? ` error=${distilled.error}` : ""}`);
223
+ if (distilled.status === "failed") {
224
+ ledger?.recordFailure(date, distilled.error ?? "unknown failure");
225
+ } else {
226
+ ledger?.clearFailures(date);
227
+ }
228
+ result = { ok: distilled.status === "applied" || distilled.status === "skipped-ran" || distilled.status === "skipped-empty", status: distilled.status, error: distilled.error };
229
+ } catch (error) {
230
+ const message = error instanceof Error ? error.message : String(error);
231
+ log(`failed ${date}: ${message}`);
232
+ try {
233
+ ledger?.recordFailure(date, message);
234
+ } catch {
235
+ }
236
+ result = { ok: false, error: message };
237
+ } finally {
238
+ release();
239
+ }
240
+ if (!noExit) {
241
+ const exitCode = result.ok ? 0 : 1;
242
+ setTimeout(() => process.exit(exitCode), 50).unref?.();
243
+ }
244
+ return result;
245
+ }
246
+ async function runDistillAuto(memoryRoot, days = 7) {
247
+ const log = (message) => {
248
+ try {
249
+ fs.appendFileSync(distillWorkerLogPath(memoryRoot), `[${(/* @__PURE__ */ new Date()).toISOString()}] ${message}
250
+ `);
251
+ } catch {
252
+ }
253
+ };
254
+ const { MemoryStore, todayKey } = await import("./src-BPSQMSSC.js");
255
+ const store = new MemoryStore(memoryRoot);
256
+ const today = todayKey(Date.now());
257
+ const dates = [];
258
+ for (let offset = days; offset >= 1; offset -= 1) {
259
+ const probe = /* @__PURE__ */ new Date();
260
+ probe.setDate(probe.getDate() - offset);
261
+ const date = todayKey(probe.getTime());
262
+ if (date === today) continue;
263
+ if (!store.hasRun(date)) dates.push(date);
264
+ }
265
+ if (dates.length === 0) {
266
+ log("auto: no missing checkpoints in the window");
267
+ return { ok: true, lines: ["memory --auto: no missing checkpoints in the last " + days + " days."] };
268
+ }
269
+ log(`auto: ${dates.length} missing date(s): ${dates.join(", ")}`);
270
+ const lines = [];
271
+ let ok = true;
272
+ let deferred = false;
273
+ for (const date of dates) {
274
+ const result = await runDistillWorkerMain(memoryRoot, date, true);
275
+ if (!result.ok && result.busy) {
276
+ lines.push(`${date}: busy \u2014 another distillation worker is running; next schedule retries`);
277
+ deferred = true;
278
+ break;
279
+ }
280
+ lines.push(`${date}: ${result.status ?? "failed"}${result.error ? ` \u2014 ${result.error}` : ""}`);
281
+ if (!result.ok) {
282
+ ok = false;
283
+ lines.push(`stopping: journal order requires oldest-first; fix and re-run --auto for ${dates.slice(dates.indexOf(date) + 1).join(", ") || "the remaining dates"}`);
284
+ break;
285
+ }
286
+ }
287
+ setTimeout(() => process.exit(ok || deferred ? 0 : 1), 50).unref?.();
288
+ return { ok: ok || deferred, lines };
289
+ }
290
+
291
+ export {
292
+ distillWorkerLogPath,
293
+ readDistillWorkerLog,
294
+ spawnDistillWorker,
295
+ spawnDistillAutoWorker,
296
+ runDistillWorkerMain,
297
+ runDistillAuto
298
+ };
@@ -0,0 +1,278 @@
1
+ import { createRequire as __createRequire } from "node:module"; const require = __createRequire(import.meta.url);
2
+ import {
3
+ getConfigDir
4
+ } from "./chunk-ILUHTKF3.js";
5
+
6
+ // src/core/auth-storage.ts
7
+ import * as fs from "fs";
8
+ import * as path from "path";
9
+ var AUTH_LOCK_WRITE_GRACE_MS = 1e3;
10
+ var DEFAULT_AUTH_LOCK_WAIT_MS = 2e3;
11
+ var OAUTH_EXPIRY_SKEW_MS = 3e4;
12
+ function syncSleepMs(ms) {
13
+ if (ms <= 0) return;
14
+ const cell = new Int32Array(new SharedArrayBuffer(4));
15
+ Atomics.wait(cell, 0, 0, ms);
16
+ }
17
+ function processIsAlive(pid) {
18
+ if (!Number.isSafeInteger(pid) || pid <= 0) return false;
19
+ try {
20
+ process.kill(pid, 0);
21
+ return true;
22
+ } catch (error) {
23
+ return error.code === "EPERM";
24
+ }
25
+ }
26
+ var InMemoryAuthStorageBackend = class {
27
+ snapshot = { oauth: {} };
28
+ read() {
29
+ return { oauth: { ...this.snapshot.oauth } };
30
+ }
31
+ write(snapshot) {
32
+ this.snapshot = { oauth: { ...snapshot.oauth } };
33
+ }
34
+ };
35
+ var AUTH_FILE_VERSION = 1;
36
+ var FileAuthStorageBackend = class {
37
+ constructor(authPath = path.join(getConfigDir(), "auth.json"), lockWaitMs = DEFAULT_AUTH_LOCK_WAIT_MS) {
38
+ this.authPath = authPath;
39
+ this.lockWaitMs = lockWaitMs;
40
+ }
41
+ authPath;
42
+ lockWaitMs;
43
+ errors = [];
44
+ read() {
45
+ try {
46
+ if (!fs.existsSync(this.authPath)) return { oauth: {} };
47
+ const raw = JSON.parse(fs.readFileSync(this.authPath, "utf8"));
48
+ if (!raw || typeof raw !== "object" || Array.isArray(raw)) return { oauth: {} };
49
+ const oauth = raw.oauth;
50
+ if (!oauth || typeof oauth !== "object" || Array.isArray(oauth)) return { oauth: {} };
51
+ return { oauth: { ...oauth } };
52
+ } catch (error) {
53
+ this.errors.push(error instanceof Error ? error : new Error(String(error)));
54
+ return { oauth: {} };
55
+ }
56
+ }
57
+ /** A lock whose owner is gone (or that never got populated) may be reclaimed. */
58
+ lockIsStale(lockPath) {
59
+ const stat = fs.lstatSync(lockPath);
60
+ if (stat.isSymbolicLink() || !stat.isFile()) return true;
61
+ let owner;
62
+ try {
63
+ owner = JSON.parse(fs.readFileSync(lockPath, "utf8"));
64
+ } catch {
65
+ }
66
+ const age = Date.now() - stat.mtimeMs;
67
+ const validOwner = owner?.version === 1 && Number.isSafeInteger(owner.pid) && typeof owner.token === "string" && typeof owner.createdAt === "number";
68
+ if (validOwner && processIsAlive(Number(owner.pid))) return false;
69
+ return validOwner || age > AUTH_LOCK_WRITE_GRACE_MS;
70
+ }
71
+ /** Atomically claim a stale lock via hard-link identity comparison before removing it. */
72
+ reclaimStaleLock(lockPath) {
73
+ if (!this.lockIsStale(lockPath)) return false;
74
+ const claimPath = `${lockPath}.reclaim-${process.pid}-${Math.random().toString(36).slice(2)}`;
75
+ try {
76
+ fs.linkSync(lockPath, claimPath);
77
+ const claimed = fs.lstatSync(claimPath);
78
+ const current = fs.lstatSync(lockPath);
79
+ if (claimed.isSymbolicLink() || !claimed.isFile() || current.isSymbolicLink() || !current.isFile()) return false;
80
+ if (claimed.dev !== current.dev || claimed.ino !== current.ino) return false;
81
+ fs.unlinkSync(lockPath);
82
+ return true;
83
+ } catch (error) {
84
+ const code = error.code;
85
+ if (code === "ENOENT" || code === "EEXIST") return false;
86
+ throw error;
87
+ } finally {
88
+ try {
89
+ fs.unlinkSync(claimPath);
90
+ } catch {
91
+ }
92
+ }
93
+ }
94
+ /** Acquire the fixed-path cross-process lock; the release fn is token-checked. */
95
+ acquireLock(directory, lockPath) {
96
+ fs.mkdirSync(directory, { recursive: true, mode: 448 });
97
+ const deadline = Date.now() + this.lockWaitMs;
98
+ while (true) {
99
+ const token = `${Math.random().toString(36).slice(2)}${Date.now().toString(36)}`;
100
+ try {
101
+ const fd = fs.openSync(lockPath, "wx", 384);
102
+ try {
103
+ fs.writeFileSync(fd, `${JSON.stringify({ version: 1, pid: process.pid, token, createdAt: Date.now() })}
104
+ `);
105
+ } finally {
106
+ fs.closeSync(fd);
107
+ }
108
+ return () => {
109
+ try {
110
+ const owner = JSON.parse(fs.readFileSync(lockPath, "utf8"));
111
+ if (owner?.token === token) fs.unlinkSync(lockPath);
112
+ } catch {
113
+ }
114
+ };
115
+ } catch (error) {
116
+ if (error.code !== "EEXIST") throw error;
117
+ try {
118
+ if (this.reclaimStaleLock(lockPath)) continue;
119
+ } catch (reclaimError) {
120
+ if (reclaimError.code === "ENOENT") continue;
121
+ throw reclaimError;
122
+ }
123
+ if (Date.now() >= deadline) throw new Error(`timed out waiting for auth storage lock: ${lockPath}`);
124
+ syncSleepMs(25);
125
+ }
126
+ }
127
+ }
128
+ /**
129
+ * Merge-on-write under a fixed-path cross-process lock: re-read the file,
130
+ * apply explicit removals (logout), merge our snapshot's oauth entries
131
+ * over whatever is on disk (preserving unrelated edits), then write back
132
+ * atomically with 0600 permissions.
133
+ */
134
+ write(snapshot) {
135
+ const directory = path.dirname(this.authPath);
136
+ const lockPath = `${this.authPath}.lock`;
137
+ let release;
138
+ try {
139
+ release = this.acquireLock(directory, lockPath);
140
+ try {
141
+ const onDisk = this.read();
142
+ const mergedOauth = { ...onDisk.oauth };
143
+ for (const removed of snapshot.removedOauth ?? []) {
144
+ delete mergedOauth[removed];
145
+ }
146
+ Object.assign(mergedOauth, snapshot.oauth);
147
+ const merged = {
148
+ version: AUTH_FILE_VERSION,
149
+ oauth: mergedOauth
150
+ };
151
+ const temporary = `${this.authPath}.${process.pid}.tmp`;
152
+ try {
153
+ fs.writeFileSync(temporary, `${JSON.stringify(merged, null, 2)}
154
+ `, { flag: "wx", mode: 384 });
155
+ fs.renameSync(temporary, this.authPath);
156
+ } finally {
157
+ if (fs.existsSync(temporary)) fs.unlinkSync(temporary);
158
+ }
159
+ } finally {
160
+ release();
161
+ }
162
+ } catch (error) {
163
+ this.errors.push(error instanceof Error ? error : new Error(String(error)));
164
+ }
165
+ }
166
+ drainErrors() {
167
+ return this.errors.splice(0);
168
+ }
169
+ };
170
+ var AuthStorage = class _AuthStorage {
171
+ providerApiKeys = /* @__PURE__ */ new Map();
172
+ runtimeApiKeys = /* @__PURE__ */ new Map();
173
+ providerEnvVars = /* @__PURE__ */ new Map();
174
+ legacyApiKey;
175
+ oauthCredentials = /* @__PURE__ */ new Map();
176
+ removedOauthProviders = /* @__PURE__ */ new Set();
177
+ backend;
178
+ constructor(backend) {
179
+ this.backend = backend;
180
+ if (backend) {
181
+ for (const [provider, credentials] of Object.entries(backend.read().oauth)) {
182
+ this.oauthCredentials.set(provider, credentials);
183
+ }
184
+ }
185
+ }
186
+ /** Runtime-only storage (no persistence). */
187
+ static create() {
188
+ return new _AuthStorage();
189
+ }
190
+ /** Storage bound to a persistence backend (OAuth credentials survive restarts). */
191
+ static fromStorage(backend) {
192
+ return new _AuthStorage(backend);
193
+ }
194
+ /** In-memory backend, for tests and embedders that manage their own persistence. */
195
+ static inMemory() {
196
+ return new _AuthStorage(new InMemoryAuthStorageBackend());
197
+ }
198
+ /** Drain buffered backend I/O errors (file backend only). */
199
+ drainErrors() {
200
+ const backend = this.backend;
201
+ if (backend && typeof backend.drainErrors === "function") {
202
+ return backend.drainErrors();
203
+ }
204
+ return [];
205
+ }
206
+ setLegacyApiKey(apiKey) {
207
+ this.legacyApiKey = apiKey;
208
+ }
209
+ setProviderApiKey(provider, apiKey) {
210
+ if (!apiKey) {
211
+ this.providerApiKeys.delete(provider);
212
+ return;
213
+ }
214
+ this.providerApiKeys.set(provider, apiKey);
215
+ }
216
+ setRuntimeApiKey(provider, apiKey) {
217
+ if (!apiKey) {
218
+ this.runtimeApiKeys.delete(provider);
219
+ return;
220
+ }
221
+ this.runtimeApiKeys.set(provider, apiKey);
222
+ }
223
+ setProviderEnvVar(provider, envVar) {
224
+ if (!envVar) {
225
+ this.providerEnvVars.delete(provider);
226
+ return;
227
+ }
228
+ this.providerEnvVars.set(provider, envVar);
229
+ }
230
+ getProviderEnvVar(provider) {
231
+ return this.providerEnvVars.get(provider);
232
+ }
233
+ setOAuthCredentials(provider, credentials) {
234
+ if (!credentials) {
235
+ this.oauthCredentials.delete(provider);
236
+ this.removedOauthProviders.add(provider);
237
+ this.runtimeApiKeys.delete(provider);
238
+ } else {
239
+ this.oauthCredentials.set(provider, credentials);
240
+ this.removedOauthProviders.delete(provider);
241
+ }
242
+ this.persistOAuth();
243
+ }
244
+ getOAuthCredentials(provider) {
245
+ return this.oauthCredentials.get(provider);
246
+ }
247
+ /** Providers with persisted OAuth credentials (for restore/refresh passes). */
248
+ getOAuthProviderNames() {
249
+ return [...this.oauthCredentials.keys()];
250
+ }
251
+ persistOAuth() {
252
+ if (!this.backend) return;
253
+ this.backend.write({
254
+ oauth: Object.fromEntries(this.oauthCredentials),
255
+ removedOauth: [...this.removedOauthProviders]
256
+ });
257
+ }
258
+ getApiKey(provider, explicitEnvVar) {
259
+ const envVar = explicitEnvVar || this.getProviderEnvVar(provider);
260
+ const envApiKey = envVar && typeof process !== "undefined" ? process.env?.[envVar] : void 0;
261
+ return this.runtimeApiKeys.get(provider) || this.providerApiKeys.get(provider) || envApiKey || this.usableOAuthAccessToken(provider) || this.legacyApiKey;
262
+ }
263
+ /** Persisted OAuth access token, when it exists and has not expired. */
264
+ usableOAuthAccessToken(provider) {
265
+ const credentials = this.oauthCredentials.get(provider);
266
+ if (!credentials?.access) return void 0;
267
+ if (credentials.expires !== void 0 && credentials.expires <= Date.now() + OAUTH_EXPIRY_SKEW_MS) {
268
+ return void 0;
269
+ }
270
+ return credentials.access;
271
+ }
272
+ };
273
+
274
+ export {
275
+ InMemoryAuthStorageBackend,
276
+ FileAuthStorageBackend,
277
+ AuthStorage
278
+ };