zidane 6.6.3 → 6.6.5
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/dist/{acp-BQqhozmt.js → acp-Cv4Rm-WY.js} +3 -3
- package/dist/{acp-BQqhozmt.js.map → acp-Cv4Rm-WY.js.map} +1 -1
- package/dist/acp-cli.js +3 -3
- package/dist/acp.d.ts +1 -1
- package/dist/acp.js +1 -1
- package/dist/{agent-DTxH7RHW.js → agent-DpVdepFt.js} +2 -2
- package/dist/{agent-DTxH7RHW.js.map → agent-DpVdepFt.js.map} +1 -1
- package/dist/agent.d.ts +1 -1
- package/dist/agent.js +1 -1
- package/dist/{auth-7rv6ZfWk.js → auth-D2KIL4OS.js} +2 -2
- package/dist/{auth-7rv6ZfWk.js.map → auth-D2KIL4OS.js.map} +1 -1
- package/dist/chat/pure.d.ts +3 -3
- package/dist/chat.d.ts +4 -4
- package/dist/chat.js +3 -3
- package/dist/contexts/daytona.d.ts +2 -1
- package/dist/contexts/daytona.d.ts.map +1 -1
- package/dist/contexts/daytona.js +13 -2
- package/dist/contexts/daytona.js.map +1 -1
- package/dist/contexts/e2b.d.ts +1 -1
- package/dist/eval.d.ts +1 -1
- package/dist/eval.js +1 -1
- package/dist/extensions.d.ts +1 -1
- package/dist/extensions.js +1 -1
- package/dist/headless.d.ts +1 -1
- package/dist/headless.js +2 -2
- package/dist/{index-D0O-QO7Z.d.ts → index-CWCQwx4o.d.ts} +14 -2
- package/dist/index-CWCQwx4o.d.ts.map +1 -0
- package/dist/index.d.ts +1 -1
- package/dist/index.js +2 -2
- package/dist/mcp.d.ts +1 -1
- package/dist/output/stream-json.d.ts +1 -1
- package/dist/output/terminal.d.ts +1 -1
- package/dist/plugins.d.ts +1 -1
- package/dist/presets.d.ts +1 -1
- package/dist/presets.js +1 -1
- package/dist/providers/anthropic.d.ts +1 -1
- package/dist/providers/arcee.d.ts +1 -1
- package/dist/providers/baseten.d.ts +1 -1
- package/dist/providers/cerebras.d.ts +1 -1
- package/dist/providers/local.d.ts +1 -1
- package/dist/providers/openai-compat.d.ts +1 -1
- package/dist/providers/openai.d.ts +1 -1
- package/dist/providers/openrouter.d.ts +1 -1
- package/dist/providers/xai.d.ts +1 -1
- package/dist/providers.d.ts +1 -1
- package/dist/restate.d.ts +1 -1
- package/dist/restate.d.ts.map +1 -1
- package/dist/restate.js +76 -30
- package/dist/restate.js.map +1 -1
- package/dist/session/sqlite.d.ts +1 -1
- package/dist/{session-CyRLSsVa.js → session-BP6Ly2XF.js} +22 -3
- package/dist/session-BP6Ly2XF.js.map +1 -0
- package/dist/session.d.ts +2 -2
- package/dist/session.js +2 -2
- package/dist/skills.d.ts +1 -1
- package/dist/{tool-formatters-NrzD6Fkk.d.ts → tool-formatters-BubatDZA.d.ts} +2 -2
- package/dist/{tool-formatters-NrzD6Fkk.d.ts.map → tool-formatters-BubatDZA.d.ts.map} +1 -1
- package/dist/tools/fetch-url.d.ts +1 -1
- package/dist/tools/web-search.d.ts +1 -1
- package/dist/tools.d.ts +1 -1
- package/dist/tools.js +1 -1
- package/dist/{transcript-anchors-BjH-68k2.js → transcript-anchors-5qybec_s.js} +3 -3
- package/dist/{transcript-anchors-BjH-68k2.js.map → transcript-anchors-5qybec_s.js.map} +1 -1
- package/dist/{transcript-anchors-UhC58Tmj.d.ts → transcript-anchors-B4NSP1jM.d.ts} +2 -2
- package/dist/{transcript-anchors-UhC58Tmj.d.ts.map → transcript-anchors-B4NSP1jM.d.ts.map} +1 -1
- package/dist/tui.d.ts +3 -3
- package/dist/tui.js +4 -4
- package/dist/{turn-operations-Cuc9pwiB.d.ts → turn-operations-4rSHXmxe.d.ts} +3 -3
- package/dist/{turn-operations-Cuc9pwiB.d.ts.map → turn-operations-4rSHXmxe.d.ts.map} +1 -1
- package/dist/types.d.ts +1 -1
- package/package.json +1 -1
- package/dist/index-D0O-QO7Z.d.ts.map +0 -1
- package/dist/session-CyRLSsVa.js.map +0 -1
package/dist/session/sqlite.d.ts
CHANGED
|
@@ -351,6 +351,19 @@ const DANGEROUS_RECORD_KEYS = /* @__PURE__ */ new Set([
|
|
|
351
351
|
"constructor"
|
|
352
352
|
]);
|
|
353
353
|
const extensionSessionStorage = new AsyncLocalStorage();
|
|
354
|
+
const metaWriteRecorder = new AsyncLocalStorage();
|
|
355
|
+
/**
|
|
356
|
+
* Run `fn`, appending every `setMeta` call it makes on `session` to `writes`
|
|
357
|
+
* in order (including the ones made before `fn` throws). Scoped per call via
|
|
358
|
+
* `AsyncLocalStorage.run`, so concurrent tool bodies sharing one session only
|
|
359
|
+
* see their own writes. Only sessions built by {@link createSession} record.
|
|
360
|
+
*/
|
|
361
|
+
function recordSessionMetaWrites(session, writes, fn) {
|
|
362
|
+
return session ? metaWriteRecorder.run({
|
|
363
|
+
session,
|
|
364
|
+
writes
|
|
365
|
+
}, fn) : fn();
|
|
366
|
+
}
|
|
354
367
|
/**
|
|
355
368
|
* Run `fn` with `session` bound as the active extension session for the
|
|
356
369
|
* duration of the call (and every async continuation it spawns). Uses
|
|
@@ -488,7 +501,7 @@ async function createSession(options = {}) {
|
|
|
488
501
|
}
|
|
489
502
|
if (stats.cost !== void 0) run.cost = stats.cost;
|
|
490
503
|
}
|
|
491
|
-
|
|
504
|
+
const session = {
|
|
492
505
|
...store ? { store } : {},
|
|
493
506
|
get id() {
|
|
494
507
|
return data.id;
|
|
@@ -583,6 +596,11 @@ async function createSession(options = {}) {
|
|
|
583
596
|
setMeta(key, value) {
|
|
584
597
|
data.metadata[key] = value;
|
|
585
598
|
touch();
|
|
599
|
+
const recorder = metaWriteRecorder.getStore();
|
|
600
|
+
if (recorder?.session === session) recorder.writes.push({
|
|
601
|
+
key,
|
|
602
|
+
value
|
|
603
|
+
});
|
|
586
604
|
},
|
|
587
605
|
async save() {
|
|
588
606
|
if (!store) throw new Error("No SessionStore configured. Pass a store to createSession() to enable persistence.");
|
|
@@ -595,6 +613,7 @@ async function createSession(options = {}) {
|
|
|
595
613
|
return structuredClone(data);
|
|
596
614
|
}
|
|
597
615
|
};
|
|
616
|
+
return session;
|
|
598
617
|
}
|
|
599
618
|
/**
|
|
600
619
|
* Demote a persisted `'running'` status to `'idle'` (in place) and return the
|
|
@@ -719,6 +738,6 @@ function assertJsonBounded(value, maxBytes, label) {
|
|
|
719
738
|
if (Buffer.byteLength(json) > maxBytes) throw new Error(`${label} exceeds ${maxBytes} bytes.`);
|
|
720
739
|
}
|
|
721
740
|
//#endregion
|
|
722
|
-
export { getExtensionSessionState as a,
|
|
741
|
+
export { getExtensionSessionState as a, resumeChainRunIds as c, createRemoteStore as d, createMemoryStore as f, demoteStaleRunningStatus as i, setExtensionSessionState as l, currentExtensionSession as n, loadSession as o, createFileMapStore as p, deleteExtensionSessionState as r, recordSessionMetaWrites as s, createSession as t, withExtensionSession as u };
|
|
723
742
|
|
|
724
|
-
//# sourceMappingURL=session-
|
|
743
|
+
//# sourceMappingURL=session-BP6Ly2XF.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"session-BP6Ly2XF.js","names":[],"sources":["../src/session/file-map.ts","../src/session/memory.ts","../src/session/remote.ts","../src/session/index.ts"],"sourcesContent":["/**\n * File-map session store.\n *\n * Wraps a narrow 3-method adapter (`get` / `save` / `delete`) that exchanges a flat\n * map of filename → string content. Useful for embedding zidane sessions inside\n * host-provided session backends that only speak in file maps (not zidane's native\n * `SessionStore` shape).\n *\n * Serialization format:\n * - `turns.jsonl` — one `SessionTurn` per line.\n * - `meta.json` — session metadata (id, agentId, status, runs, metadata, timestamps).\n *\n * JSONL for turns keeps history inspectable with tools like `jq` and resilient to\n * partial corruption — parse up to the first bad line and you still have a valid\n * prefix. Metadata lives in its own file so large turn logs don't bloat the\n * metadata path.\n *\n * Scope: each `createFileMapStore` handles a **single session** — the adapter's\n * file map holds at most one zidane session at a time. This matches how host SDKs\n * scope their session stores per conversation.\n *\n * Divergences from the built-in memory / sqlite stores:\n * - `appendTurns` / `updateStatus` / `updateRun` auto-create a minimal `SessionData`\n * record on first write, instead of silently no-oping when the session hasn't been\n * explicitly `save()`-ed. This matches the host-SDK integration path where\n * `createSession(...)` → `agent.run(...)` directly without an explicit `save()` call.\n * - `updateRun` inserts the run if not found in the cached record (rather than\n * silently dropping). Run records therefore always reach the adapter.\n */\n\nimport type { SessionData, SessionRun, SessionStore } from '.'\nimport type { SessionTurn } from '../types'\n\n/**\n * Host-provided file-map adapter. Three methods exchanging `Record<string, string>`\n * payloads — the whole persistence surface the wrapper needs.\n */\nexport interface FileMapAdapter {\n /** Load the current file map. Returns an empty `files` record when nothing is persisted. */\n get: () => Promise<{ files: Record<string, string> }>\n /** Replace the persisted file map. Full-rewrite semantics. */\n save: (files: Record<string, string>) => Promise<void>\n /** Delete all persisted state. */\n delete: () => Promise<void>\n}\n\nexport interface FileMapStoreOptions {\n /** Filename for the JSONL turns log. Default: `turns.jsonl`. */\n turnsFile?: string\n /** Filename for the metadata JSON. Default: `meta.json`. */\n metaFile?: string\n}\n\ninterface MetaShape {\n id: string\n agentId?: string\n /** Optional — absent on files written before projectRoot persistence. */\n projectRoot?: string\n runs: SessionRun[]\n status: SessionData['status']\n metadata: Record<string, unknown>\n createdAt: number\n updatedAt: number\n}\n\nfunction toMeta(data: SessionData): MetaShape {\n return {\n id: data.id,\n agentId: data.agentId,\n projectRoot: data.projectRoot,\n runs: data.runs,\n status: data.status,\n metadata: data.metadata,\n createdAt: data.createdAt,\n updatedAt: data.updatedAt,\n }\n}\n\nfunction toData(meta: MetaShape, turns: SessionTurn[]): SessionData {\n return {\n id: meta.id,\n agentId: meta.agentId,\n ...(typeof meta.projectRoot === 'string' ? { projectRoot: meta.projectRoot } : {}),\n turns,\n runs: meta.runs,\n status: meta.status,\n metadata: meta.metadata,\n createdAt: meta.createdAt,\n updatedAt: meta.updatedAt,\n }\n}\n\nfunction parseTurnsJsonl(jsonl: string): SessionTurn[] {\n if (!jsonl)\n return []\n const turns: SessionTurn[] = []\n for (const line of jsonl.split('\\n')) {\n const trimmed = line.trim()\n if (!trimmed)\n continue\n try {\n turns.push(JSON.parse(trimmed) as SessionTurn)\n }\n catch {\n // Skip malformed lines — preserves the valid prefix on partial corruption.\n }\n }\n return turns\n}\n\nfunction serializeTurnsJsonl(turns: SessionTurn[]): string {\n if (turns.length === 0)\n return ''\n return `${turns.map(t => JSON.stringify(t)).join('\\n')}\\n`\n}\n\n/**\n * Create a single-session `SessionStore` backed by a file-map adapter.\n *\n * @example\n * ```ts\n * const session = await createSession({\n * store: createFileMapStore(hostSessionStore),\n * })\n * ```\n */\nexport function createFileMapStore(\n adapter: FileMapAdapter,\n options: FileMapStoreOptions = {},\n): SessionStore {\n const turnsFile = options.turnsFile ?? 'turns.jsonl'\n const metaFile = options.metaFile ?? 'meta.json'\n\n // Cached view of the persisted session. Populated lazily on first access so the\n // factory itself doesn't do I/O.\n let cached: SessionData | null = null\n let hydrated = false\n // In-flight hydrate memo: concurrent first calls share one adapter.get()\n // instead of racing two reads (the loser's view would clobber the winner's\n // subsequent writes — a lost-update race).\n let hydrating: Promise<void> | null = null\n // Turns salvaged from turns.jsonl when meta.json was present but corrupt.\n // We can't trust the (unparseable) meta for the session id, so we hold the\n // turns aside and re-attach them when the next write establishes an id —\n // the alternative (treating the session as missing) would let that write\n // overwrite an intact turns.jsonl with an empty one.\n let recoveredTurns: SessionTurn[] | null = null\n\n async function hydrate(): Promise<void> {\n if (hydrated)\n return\n if (!hydrating) {\n hydrating = (async () => {\n const { files } = await adapter.get()\n const metaRaw = files[metaFile]\n if (metaRaw) {\n let meta: MetaShape | null = null\n try {\n meta = JSON.parse(metaRaw) as MetaShape\n }\n catch {\n meta = null\n }\n if (meta) {\n cached = toData(meta, parseTurnsJsonl(files[turnsFile] ?? ''))\n }\n else {\n recoveredTurns = parseTurnsJsonl(files[turnsFile] ?? '')\n console.error(`[zidane/file-map] ${metaFile} exists but is not valid JSON — preserving ${recoveredTurns.length} turn(s) from ${turnsFile} for the next write instead of treating the session as missing`)\n }\n }\n hydrated = true\n })().finally(() => {\n hydrating = null\n })\n }\n return hydrating\n }\n\n async function persist(data: SessionData): Promise<void> {\n const meta = toMeta(data)\n await adapter.save({\n [metaFile]: JSON.stringify(meta, null, 2),\n [turnsFile]: serializeTurnsJsonl(data.turns),\n })\n }\n\n // Ensure `cached` exists for `sessionId`, creating a minimal record when first written.\n // Returns false when `cached` already holds a different sessionId (request ignored).\n async function ensureCachedFor(sessionId: string): Promise<boolean> {\n await hydrate()\n if (cached) {\n return cached.id === sessionId\n }\n const now = Date.now()\n cached = {\n id: sessionId,\n // Re-attach turns salvaged from a corrupt-meta hydrate so the next\n // persist() doesn't destroy an intact turns.jsonl.\n turns: recoveredTurns ?? [],\n runs: [],\n status: 'idle',\n metadata: {},\n createdAt: now,\n updatedAt: now,\n }\n recoveredTurns = null\n hydrated = true\n return true\n }\n\n return {\n async load(sessionId: string): Promise<SessionData | null> {\n await hydrate()\n if (!cached || cached.id !== sessionId)\n return null\n return structuredClone(cached)\n },\n\n async save(data: SessionData): Promise<void> {\n cached = structuredClone(data)\n hydrated = true\n await persist(cached)\n },\n\n async delete(sessionId: string): Promise<void> {\n await hydrate()\n if (cached && cached.id !== sessionId)\n return\n cached = null\n await adapter.delete()\n },\n\n async list(filter): Promise<string[]> {\n await hydrate()\n if (!cached)\n return []\n if (filter?.agentId && cached.agentId !== filter.agentId)\n return []\n // file-map stores exactly one session, so the projectRoot filter\n // either keeps it (match / axis off) or drops it entirely.\n if (filter && 'projectRoot' in filter) {\n const v = filter.projectRoot\n if (v === null && cached.projectRoot != null)\n return []\n if (typeof v === 'string' && cached.projectRoot !== v)\n return []\n }\n return [cached.id]\n },\n\n async appendTurns(sessionId: string, turns: SessionTurn[]): Promise<void> {\n const ok = await ensureCachedFor(sessionId)\n if (!ok)\n return\n cached!.turns.push(...structuredClone(turns))\n cached!.updatedAt = Date.now()\n await persist(cached!)\n },\n\n async getTurns(sessionId: string, from = 0, limit?: number): Promise<SessionTurn[]> {\n await hydrate()\n if (!cached || cached.id !== sessionId)\n return []\n const slice = cached.turns.slice(from, limit !== undefined ? from + limit : undefined)\n return structuredClone(slice) as SessionTurn[]\n },\n\n async updateRun(sessionId: string, run: SessionRun): Promise<void> {\n const ok = await ensureCachedFor(sessionId)\n if (!ok)\n return\n const idx = cached!.runs.findIndex(r => r.id === run.id)\n if (idx >= 0)\n cached!.runs[idx] = structuredClone(run)\n else\n cached!.runs.push(structuredClone(run))\n cached!.updatedAt = Date.now()\n await persist(cached!)\n },\n\n async updateStatus(sessionId: string, status: SessionData['status']): Promise<void> {\n const ok = await ensureCachedFor(sessionId)\n if (!ok)\n return\n cached!.status = status\n cached!.updatedAt = Date.now()\n await persist(cached!)\n },\n }\n}\n","/**\n * In-memory session store.\n * Useful for development and testing. Data is lost when the process exits.\n */\n\nimport type { SessionData, SessionRun, SessionStore } from '.'\nimport type { SessionTurn } from '../types'\n\nexport function createMemoryStore(): SessionStore {\n const sessions = new Map<string, SessionData>()\n\n // Auto-create a minimal record when turns arrive for an unknown id. Mirrors\n // the file-map store: `createSession({store})` + `agent.run()` appends\n // turns without an explicit `save()` first — a get-or-no-op `appendTurns`\n // would silently lose that history. Deliberately scoped to `appendTurns`\n // only: a late `updateRun`/`updateStatus` racing a `delete()` must stay a\n // no-op rather than resurrect a deleted session.\n function ensureSession(sessionId: string): SessionData {\n let data = sessions.get(sessionId)\n if (!data) {\n const now = Date.now()\n data = {\n id: sessionId,\n turns: [],\n runs: [],\n status: 'idle',\n metadata: {},\n createdAt: now,\n updatedAt: now,\n }\n sessions.set(sessionId, data)\n }\n return data\n }\n\n return {\n async load(sessionId: string) {\n const data = sessions.get(sessionId)\n return data ? structuredClone(data) : null\n },\n\n async save(session: SessionData) {\n sessions.set(session.id, structuredClone(session))\n },\n\n async delete(sessionId: string) {\n sessions.delete(sessionId)\n },\n\n async list(filter) {\n let ids = Array.from(sessions.keys())\n if (filter?.agentId) {\n ids = ids.filter(id => sessions.get(id)?.agentId === filter.agentId)\n }\n // `projectRoot` mirrors the SQLite store's tri-state contract:\n // string → only sessions tagged with that root\n // null → only UNTAGGED sessions (legacy / pre-v3 rows)\n // undefined → axis ignored (tagged + untagged both returned)\n if (filter && 'projectRoot' in filter) {\n const v = filter.projectRoot\n if (v === null)\n ids = ids.filter(id => sessions.get(id)?.projectRoot == null)\n else if (typeof v === 'string')\n ids = ids.filter(id => sessions.get(id)?.projectRoot === v)\n }\n if (filter?.limit) {\n ids = ids.slice(0, filter.limit)\n }\n return ids\n },\n\n async appendTurns(sessionId: string, turns: SessionTurn[]) {\n const data = ensureSession(sessionId)\n data.turns.push(...structuredClone(turns))\n data.updatedAt = Date.now()\n },\n\n async getTurns(sessionId: string, from = 0, limit?: number) {\n const data = sessions.get(sessionId)\n if (!data)\n return []\n const sliced = data.turns.slice(from, limit !== undefined ? from + limit : undefined)\n return structuredClone(sliced) as SessionTurn[]\n },\n\n async updateRun(sessionId: string, run: SessionRun) {\n const data = sessions.get(sessionId)\n if (!data)\n return\n // Upsert — see the matching comment in sqlite.ts's\n // `txnUpdateRun` for the failure mode. tl;dr: the agent's\n // `startRun()` only updates in-memory state; the store first\n // sees the run via `updateRun()` at finalize time, so an\n // update-only impl silently drops every new run.\n const idx = data.runs.findIndex(r => r.id === run.id)\n if (idx >= 0)\n data.runs[idx] = structuredClone(run)\n else\n data.runs.push(structuredClone(run))\n data.updatedAt = Date.now()\n },\n\n async updateStatus(sessionId: string, status: SessionData['status']) {\n const data = sessions.get(sessionId)\n if (!data)\n return\n data.status = status\n data.updatedAt = Date.now()\n },\n }\n}\n","/**\n * Remote session store via HTTP API.\n *\n * Expects a REST API with:\n * GET {url}/sessions/{id} -> SessionData | 404\n * PUT {url}/sessions/{id} -> save SessionData\n * DELETE {url}/sessions/{id} -> delete\n * GET {url}/sessions?agentId=&limit=&projectRoot= -> { ids: string[] }\n * `projectRoot=__null__` is the wire encoding for \"untagged only\".\n * POST {url}/sessions/{id}/turns -> append turns\n * GET {url}/sessions/{id}/turns?from=&limit= -> SessionTurn[]\n * PUT {url}/sessions/{id}/runs/{runId} -> update run\n * PATCH {url}/sessions/{id} -> { status }\n */\n\nimport type { SessionData, SessionRun, SessionStore } from '.'\nimport type { SessionTurn } from '../types'\n\nexport interface RemoteStoreOptions {\n /** Base URL of the session API */\n url: string\n /** Optional headers (e.g. for authentication) */\n headers?: Record<string, string>\n /** Per-request timeout in ms. Default 30s — bounds a hung backend. */\n timeoutMs?: number\n}\n\nconst TRAILING_SLASH = /\\/$/\nconst DEFAULT_TIMEOUT_MS = 30_000\n\nexport function createRemoteStore(options: RemoteStoreOptions): SessionStore {\n const baseUrl = options.url.replace(TRAILING_SLASH, '')\n const timeoutMs = options.timeoutMs ?? DEFAULT_TIMEOUT_MS\n const defaultHeaders: Record<string, string> = {\n 'Content-Type': 'application/json',\n ...options.headers,\n }\n\n async function request(path: string, init?: RequestInit): Promise<Response> {\n const url = `${baseUrl}${path}`\n // Bound every call so a hung backend can't wedge the caller forever.\n const res = await fetch(url, {\n ...init,\n headers: { ...defaultHeaders, ...init?.headers },\n signal: init?.signal ?? AbortSignal.timeout(timeoutMs),\n })\n return res\n }\n\n /**\n * Parse a JSON response body, rethrowing parse failures with URL/status\n * context so a malformed backend reply produces a diagnosable error\n * instead of an opaque `Unexpected token` from deep in `res.json()`.\n */\n async function parseJson<T>(res: Response, path: string): Promise<T> {\n try {\n return await res.json() as T\n }\n catch (cause) {\n throw new Error(\n `Remote session: malformed JSON from ${path} (${res.status} ${res.statusText})`,\n { cause },\n )\n }\n }\n\n return {\n async load(sessionId: string) {\n const res = await request(`/sessions/${encodeURIComponent(sessionId)}`)\n if (!res.ok) {\n if (res.status === 404)\n return null\n throw new Error(`Remote session load failed: ${res.status} ${res.statusText}`)\n }\n return await parseJson<SessionData>(res, `/sessions/${sessionId}`)\n },\n\n async save(session: SessionData) {\n const res = await request(`/sessions/${encodeURIComponent(session.id)}`, {\n method: 'PUT',\n body: JSON.stringify(session),\n })\n if (!res.ok) {\n throw new Error(`Remote session save failed: ${res.status} ${res.statusText}`)\n }\n },\n\n async delete(sessionId: string) {\n const res = await request(`/sessions/${encodeURIComponent(sessionId)}`, {\n method: 'DELETE',\n })\n if (!res.ok && res.status !== 404) {\n throw new Error(`Remote session delete failed: ${res.status} ${res.statusText}`)\n }\n },\n\n async list(filter) {\n const params = new URLSearchParams()\n if (filter?.agentId)\n params.set('agentId', filter.agentId)\n if (filter?.limit)\n params.set('limit', String(filter.limit))\n if (filter && 'projectRoot' in filter) {\n const v = filter.projectRoot\n if (v === null)\n params.set('projectRoot', '__null__')\n else if (typeof v === 'string')\n params.set('projectRoot', v)\n }\n\n const query = params.toString()\n const path = query ? `/sessions?${query}` : '/sessions'\n const res = await request(path)\n\n if (!res.ok) {\n throw new Error(`Remote session list failed: ${res.status} ${res.statusText}`)\n }\n\n const body = await parseJson<{ ids: string[] }>(res, path)\n if (!Array.isArray(body?.ids)) {\n throw new TypeError(`Remote session list: expected { ids: string[] } from ${path}, got ${typeof body?.ids}`)\n }\n return body.ids\n },\n\n async appendTurns(sessionId: string, turns: SessionTurn[]) {\n const res = await request(`/sessions/${encodeURIComponent(sessionId)}/turns`, {\n method: 'POST',\n body: JSON.stringify(turns),\n })\n if (!res.ok) {\n throw new Error(`Remote appendTurns failed: ${res.status} ${res.statusText}`)\n }\n },\n\n async getTurns(sessionId: string, from = 0, limit?: number) {\n const params = new URLSearchParams()\n if (from)\n params.set('from', String(from))\n if (limit !== undefined)\n params.set('limit', String(limit))\n\n const query = params.toString()\n const path = `/sessions/${encodeURIComponent(sessionId)}/turns${query ? `?${query}` : ''}`\n const res = await request(path)\n\n if (!res.ok) {\n throw new Error(`Remote getTurns failed: ${res.status} ${res.statusText}`)\n }\n\n const turns = await parseJson<SessionTurn[]>(res, path)\n if (!Array.isArray(turns)) {\n throw new TypeError(`Remote getTurns: expected SessionTurn[] from ${path}, got ${typeof turns}`)\n }\n return turns\n },\n\n async updateRun(sessionId: string, run: SessionRun) {\n const res = await request(\n `/sessions/${encodeURIComponent(sessionId)}/runs/${encodeURIComponent(run.id)}`,\n {\n method: 'PUT',\n body: JSON.stringify(run),\n },\n )\n if (!res.ok) {\n throw new Error(`Remote updateRun failed: ${res.status} ${res.statusText}`)\n }\n },\n\n async updateStatus(sessionId: string, status: SessionData['status']) {\n const res = await request(`/sessions/${encodeURIComponent(sessionId)}`, {\n method: 'PATCH',\n body: JSON.stringify({ status }),\n })\n if (!res.ok) {\n throw new Error(`Remote updateStatus failed: ${res.status} ${res.statusText}`)\n }\n },\n }\n}\n","/**\n * Session management for agents.\n *\n * A session tracks identity, turn history, and run metadata.\n * Plug in any storage backend by implementing the SessionStore interface,\n * or use one of the built-in stores: memory, sqlite, remote.\n */\n\nimport type { JsonValue, SessionMessage, SessionTurn, TurnUsage } from '../types'\nimport type { PairingDrop, ToWireMessagesOptions } from './messages'\nimport { AsyncLocalStorage } from 'node:async_hooks'\nimport { Buffer } from 'node:buffer'\nimport { dropInvalidToolPairings, toWireMessages } from './messages'\n\nexport type { SessionContentBlock, SessionMessage, SessionTurn } from '../types'\nexport { createFileMapStore } from './file-map'\n\nconst EXTENSION_SESSION_METADATA_KEY = 'extensions'\nconst EXTENSION_SESSION_ITEM_MAX_BYTES = 16_384\nconst EXTENSION_SESSION_TOTAL_MAX_BYTES = 65_536\nconst DANGEROUS_RECORD_KEYS = new Set(['__proto__', 'prototype', 'constructor'])\nconst extensionSessionStorage = new AsyncLocalStorage<Session>()\n\n/** One `setMeta` call, as recorded by {@link recordSessionMetaWrites}. */\nexport interface SessionMetaWrite {\n key: string\n value?: unknown\n}\n\nconst metaWriteRecorder = new AsyncLocalStorage<{ session: Session, writes: SessionMetaWrite[] }>()\n\n/**\n * Run `fn`, appending every `setMeta` call it makes on `session` to `writes`\n * in order (including the ones made before `fn` throws). Scoped per call via\n * `AsyncLocalStorage.run`, so concurrent tool bodies sharing one session only\n * see their own writes. Only sessions built by {@link createSession} record.\n */\nexport function recordSessionMetaWrites<T>(session: Session | undefined, writes: SessionMetaWrite[], fn: () => Promise<T>): Promise<T> {\n return session ? metaWriteRecorder.run({ session, writes }, fn) : fn()\n}\n\n/**\n * Run `fn` with `session` bound as the active extension session for the\n * duration of the call (and every async continuation it spawns). Uses\n * `AsyncLocalStorage.run` rather than `enterWith` so concurrent agents in the\n * same process (e.g. the GUI's multi-session host) never observe each other's\n * session through `currentExtensionSession()`.\n */\nexport function withExtensionSession<T>(session: Session | undefined, fn: () => T): T {\n if (!session)\n return fn()\n return extensionSessionStorage.run(session, fn)\n}\n\nexport function currentExtensionSession(): Session | undefined {\n return extensionSessionStorage.getStore()\n}\n\nexport function getExtensionSessionState<T = JsonValue>(\n session: Session | undefined,\n extensionName: string,\n key: string,\n): T | undefined {\n if (!session || !isSafeExtensionStateKey(extensionName) || !isSafeExtensionStateKey(key))\n return undefined\n const root = session.metadata[EXTENSION_SESSION_METADATA_KEY]\n if (!root || typeof root !== 'object' || Array.isArray(root))\n return undefined\n const byExtension = (root as Record<string, unknown>)[extensionName]\n if (!byExtension || typeof byExtension !== 'object' || Array.isArray(byExtension))\n return undefined\n const stored = (byExtension as Record<string, unknown>)[key]\n if (stored === undefined)\n return undefined\n // Hand back a copy so a caller mutating the result can't reach into the live\n // session metadata behind `setMeta`/`save`.\n return jsonClone(stored as JsonValue) as T\n}\n\nexport async function setExtensionSessionState(\n session: Session | undefined,\n extensionName: string,\n key: string,\n value: JsonValue,\n): Promise<void> {\n if (!session)\n return\n assertSafeExtensionStateKey(extensionName, 'extensionName')\n assertSafeExtensionStateKey(key, 'key')\n assertJsonBounded(value, EXTENSION_SESSION_ITEM_MAX_BYTES, `extension session state \"${extensionName}.${key}\"`)\n\n const root = cloneExtensionStateRoot(session.metadata[EXTENSION_SESSION_METADATA_KEY])\n const byExtension = clonePlainRecord(root[extensionName])\n // Deep-copy on write so later mutations to the caller's object don't bleed\n // into persisted state.\n byExtension[key] = jsonClone(value)\n root[extensionName] = byExtension\n assertJsonBounded(root as JsonValue, EXTENSION_SESSION_TOTAL_MAX_BYTES, 'extension session state')\n session.setMeta(EXTENSION_SESSION_METADATA_KEY, root)\n if (session.store)\n await session.save()\n}\n\nexport async function deleteExtensionSessionState(\n session: Session | undefined,\n extensionName: string,\n key: string,\n): Promise<void> {\n if (!session || !isSafeExtensionStateKey(extensionName) || !isSafeExtensionStateKey(key))\n return\n const root = cloneExtensionStateRoot(session.metadata[EXTENSION_SESSION_METADATA_KEY])\n const byExtension = clonePlainRecord(root[extensionName])\n if (!(key in byExtension))\n return\n delete byExtension[key]\n if (Object.keys(byExtension).length > 0)\n root[extensionName] = byExtension\n else\n delete root[extensionName]\n session.setMeta(EXTENSION_SESSION_METADATA_KEY, root)\n if (session.store)\n await session.save()\n}\n\n// ---------------------------------------------------------------------------\n// Types\n// ---------------------------------------------------------------------------\n\n/**\n * Transitive `resumedFromRunId` chain starting at `runId` (inclusive).\n *\n * A resumed run only persists the turns IT produced — the turns it was\n * seeded with still carry the original run's id. So reconstructing a\n * resumed child's full conversation means collecting turns from every run\n * in its resume lineage, not just the latest link. Cycle-guarded (a\n * malformed chain terminates instead of looping).\n */\nexport function resumeChainRunIds(runs: readonly SessionRun[], runId: string): Set<string> {\n const chain = new Set<string>()\n let id: string | undefined = runId\n while (id && !chain.has(id)) {\n chain.add(id)\n id = runs.find(r => r.id === id)?.resumedFromRunId\n }\n return chain\n}\n\nexport interface SessionRun {\n id: string\n startedAt: number\n endedAt?: number\n prompt: string\n status: 'running' | 'completed' | 'aborted' | 'error'\n turns?: number\n tokensIn?: number\n tokensOut?: number\n error?: string\n /** Per-turn usage breakdown */\n turnUsage?: TurnUsage[]\n /** Total usage across all turns */\n totalUsage?: TurnUsage\n /** Estimated cost in USD */\n cost?: number\n /**\n * The run that spawned this one, when the agent is a subagent sharing its\n * parent's session. Undefined on top-level `agent.run()`. Consumers can walk\n * `runs` by `parentRunId` to reconstruct the subagent tree.\n */\n parentRunId?: string\n /**\n * The prior run this one continues (see `AgentRunOptions.resumeRunId`).\n * Set when a stopped/failed subagent run was resumed — consumers can\n * chain runs by `resumedFromRunId` to render “child-4 (resumes child-2)”\n * style markers. Absent on normal runs.\n */\n resumedFromRunId?: string\n /**\n * Host-assigned display label (e.g. the spawn tool's `child-3`), persisted\n * so label → run resolution is a stored fact instead of a positional\n * guess. Positional `child-N` numbering can desynchronize from announced\n * labels (concurrent spawns `startRun` out of reservation order, a\n * pre-`startRun` throw advances the counter without a run, and reload\n * ordering ties break lexicographically) — resolving by stored label is\n * immune to all three. Absent on top-level runs and legacy sessions.\n */\n label?: string\n /**\n * Zero-based subagent depth. 0 = top-level run, 1 = direct child, …\n * Recorded here so hosts can query/filter by level without walking the tree.\n */\n depth?: number\n /**\n * How this run was initiated when not a plain user prompt. `command` marks\n * a sub-run driven from a `/` command's `ctx.runAgent`; `display` is the\n * short line the transcript shows instead of the full injected prompt\n * (which often embeds bulky material like a diff). Presentation-only —\n * the wire/model payload is unaffected. Absent on normal runs.\n */\n origin?: { kind: 'command', display?: string }\n}\n\nexport interface SessionData {\n id: string\n agentId?: string\n /**\n * Absolute path of the project this session belongs to — typically\n * the git root resolved from `cwd` at creation time, falling back to\n * `cwd` itself when not in a git repo. Set ONCE on creation and never\n * mutated thereafter (the session \"belongs\" to that project forever).\n *\n * Used by the TUI's sessions list to filter rows by current project,\n * so the user only sees conversations relevant to where they are\n * working — without needing one `.{prefix}/` directory per project.\n *\n * `undefined` on pre-tagging legacy sessions; the chat layer treats\n * those as \"untagged\" and hides them unless `Settings.showAllProjects`\n * is on.\n */\n projectRoot?: string\n turns: SessionTurn[]\n runs: SessionRun[]\n status: 'idle' | 'running' | 'completed' | 'error'\n metadata: Record<string, unknown>\n createdAt: number\n updatedAt: number\n}\n\n/**\n * Compact per-session summary returned by {@link SessionStore.listMeta}.\n * Raw facts only — presentation (title derivation, fallback strings)\n * stays in the chat layer (`listSessionMeta` / `deriveSessionTitle`).\n */\nexport interface SessionMetaRow {\n id: string\n /** Header metadata (may carry a stored `title`). */\n metadata: Record<string, unknown>\n /** Absent for untagged (legacy) sessions. */\n projectRoot?: string\n updatedAt: number\n turnCount: number\n /** Count of `role: 'user'` turns. */\n userMessageCount: number\n runCount: number\n /**\n * First `role: 'user'` turn — the title-derivation source. Stores may\n * omit it when `metadata.title` is already set (no derivation needed).\n */\n firstUserTurn?: SessionTurn\n}\n\n// ---------------------------------------------------------------------------\n// SessionStore interface (pluggable backend)\n// ---------------------------------------------------------------------------\n\nexport interface SessionStore {\n /** Optional: generate a session ID server-side (e.g. a database-issued UUID). */\n generateSessionId?: () => string | Promise<string>\n\n /**\n * Optional: generate a turn ID server-side for session-managed user turns.\n *\n * Provider-loop assistant and tool-result turns use AgentClock.randomUUID()\n * instead, so durable-execution adapters can keep those IDs replay-stable.\n */\n generateTurnId?: () => string | Promise<string>\n\n /** Load a session by ID. Returns null if not found. */\n load: (sessionId: string) => Promise<SessionData | null>\n\n /** Save a session (create or update, full document). */\n save: (session: SessionData) => Promise<void>\n\n /** Delete a session. */\n delete: (sessionId: string) => Promise<void>\n\n /**\n * List session IDs, optionally filtered. `projectRoot` restricts to\n * sessions whose `SessionData.projectRoot` matches exactly — untagged\n * (legacy) sessions are NOT returned under that filter; pass `null`\n * explicitly to ask for untagged ones, or omit the field to ignore\n * the axis entirely. `agentId` filters by recorded agent; the two\n * conditions AND together when both are set.\n */\n list: (filter?: { agentId?: string, limit?: number, projectRoot?: string | null }) => Promise<string[]>\n\n /**\n * Optional: list session summaries without materializing full sessions.\n *\n * The generic fallback (`listSessionMeta` in `zidane/chat`) is `list()`\n * + `load()` per id — O(every turn in the store) because each `load`\n * parses the full turn history just to count rows and derive a title.\n * Stores that can answer from an index (SQL aggregates, a denormalized\n * header) should implement this; the sqlite store turns a multi-hundred-\n * ms TUI boot cost into a single query.\n *\n * Same filter contract and ordering (most recently updated first) as\n * {@link list}.\n */\n listMeta?: (filter?: { agentId?: string, limit?: number, projectRoot?: string | null }) => Promise<SessionMetaRow[]>\n\n /** Append new turns to a session (incremental, avoids full re-save). */\n appendTurns: (sessionId: string, turns: SessionTurn[]) => Promise<void>\n\n /** Return a slice of turns for a session. */\n getTurns: (sessionId: string, from?: number, limit?: number) => Promise<SessionTurn[]>\n\n /**\n * Persist a run record (called after completeRun / abortRun / errorRun).\n *\n * **Upsert semantics required.** The agent's run lifecycle calls\n * `session.startRun()` to register a new run in IN-MEMORY state and\n * then `updateRun()` at finalize. The store doesn't see the run any\n * earlier — `appendTurns` is the only intermediate call, and it\n * persists turns but not runs. An update-only implementation would\n * silently drop every newly-created run record at finalize, leaving\n * the on-disk `runs[]` missing entries that the persisted turns\n * reference (which `eventsFromTurns` then mis-classifies via\n * `ancestryOf` → broken depth, broken `child-N` labels, broken\n * `userPrompts` history).\n *\n * Implementations MUST insert when the id doesn't exist and update\n * when it does. The bundled `sqlite` / `memory` / `file-map` stores\n * all follow this contract; remote stores using HTTP PUT get upsert\n * for free via REST semantics.\n */\n updateRun: (sessionId: string, run: SessionRun) => Promise<void>\n\n /** Update the top-level status of a session. */\n updateStatus: (sessionId: string, status: SessionData['status']) => Promise<void>\n\n /**\n * Optional: release backend resources (e.g. close the SQLite handle).\n * Hosts should call this on teardown when present; stores backed by\n * memory or remote HTTP have nothing to release and may omit it.\n */\n close?: () => void\n}\n\n// ---------------------------------------------------------------------------\n// Session (live instance wrapping a SessionData)\n// ---------------------------------------------------------------------------\n\nexport interface Session {\n /** Session ID */\n readonly id: string\n\n /** Agent ID (optional label) */\n readonly agentId?: string\n\n /**\n * Project this session was created under — see {@link SessionData.projectRoot}.\n * Set once on creation; surfaces here for read-only inspection.\n */\n readonly projectRoot?: string\n\n /**\n * Raw persisted turn history — kept pristine for fidelity (the model's\n * reasoning chain stays intact across reloads).\n *\n * **DO NOT pass this directly to a provider request.** Mid-pair\n * persistence (interrupted runs, partial-result writes, compaction\n * boundaries) leaves orphan `tool_use` / `tool_result` blocks here that\n * every provider 400s on (`tool_result must be preceded by a tool_call\n * with the same toolCallId`). The agent's own loop repairs these\n * just-in-time at wire-send time and never writes the repair back to\n * `turns`.\n *\n * For provider requests built outside `agent.run()`, use\n * {@link Session.toMessages} — it applies the same defensive pairing\n * repair and resolves to a guaranteed-safe `SessionMessage[]`.\n */\n readonly turns: SessionTurn[]\n\n /**\n * True when this session has no turns yet.\n *\n * Use this as a first-prompt signal when setting up a run — e.g. writing initial\n * configuration only on fresh sessions. Equivalent to `turns.length === 0`.\n */\n readonly isEmpty: boolean\n\n /** Top-level session status */\n readonly status: SessionData['status']\n\n /** All runs in this session */\n readonly runs: SessionRun[]\n\n /** Arbitrary metadata */\n readonly metadata: Record<string, unknown>\n\n /**\n * Start tracking a new run. `extras.parentRunId` + `extras.depth` are\n * populated by the spawn tool when a child agent shares its parent's\n * session; regular top-level `agent.run()` calls omit them.\n */\n startRun: (runId: string, prompt?: string, extras?: { parentRunId?: string, depth?: number, resumedFromRunId?: string, label?: string }) => void\n\n /** Mark a run as completed */\n completeRun: (runId: string, stats: { turns: number, tokensIn: number, tokensOut: number, turnUsage?: TurnUsage[], cost?: number }) => void\n\n /** Mark a run as aborted */\n /**\n * Optional `stats` lets the agent backfill the run's token totals when\n * the abort happened *after* the loop accumulated meaningful usage —\n * common when the user presses esc mid-streaming. Without it, the run\n * record reads `0 in / 0 out` on reload regardless of how much was\n * spent before the abort. Same shape as `completeRun`'s stats so the\n * persisted `totalUsage` aggregate stays consistent across paths.\n */\n abortRun: (runId: string, stats?: { turns: number, tokensIn: number, tokensOut: number, turnUsage?: TurnUsage[], cost?: number }) => void\n\n /** Mark a run as errored */\n /** Optional `stats` — same rationale as `abortRun.stats`. */\n errorRun: (runId: string, error: string, stats?: { turns: number, tokensIn: number, tokensOut: number, turnUsage?: TurnUsage[], cost?: number }) => void\n\n /** Append turns to in-memory history AND persist via store.appendTurns (if store present) */\n appendTurns: (turns: SessionTurn[]) => Promise<void>\n\n /** Replace all turns in-memory (does not persist — use save() for that) */\n setTurns: (turns: SessionTurn[]) => void\n\n /**\n * Replace all runs in-memory (does not persist — use save() for that).\n * Mirrors {@link setTurns} for the fork / restore case: callers that\n * bootstrap a session from an externally-derived snapshot (e.g.\n * `onForkTurn` copying parent runs into a child session) need this so\n * the cloned runs land in `data.runs` before the first `save()`.\n * Production agent runs continue to mutate runs via `startRun` /\n * `completeRun` / `updateRun`; this is the bulk-replace escape hatch.\n */\n setRuns: (runs: SessionRun[]) => void\n\n /** Update the session status in memory AND via store.updateStatus (if store present) */\n updateStatus: (status: SessionData['status']) => Promise<void>\n\n /** Persist an updated run record via store.updateRun (if store present) */\n updateRun: (run: SessionRun) => Promise<void>\n\n /** Generate a session-managed turn ID using store.generateTurnId if available, else crypto.randomUUID() */\n generateTurnId: () => string | Promise<string>\n\n /** Set metadata key */\n setMeta: (key: string, value: unknown) => void\n\n /** Persist the full session document to the store */\n save: () => Promise<void>\n\n /**\n * Project the session's persisted turns into wire-ready messages safe to\n * hand to any provider.\n *\n * The canonical answer to \"I need to send these turns to Anthropic /\n * OpenAI from outside `agent.run()`\" (sub-agent classifier, side-channel\n * summarizer, replay worker, …). Runs the same defensive pairing repair\n * the agent loop applies just-in-time at wire-send time\n * ({@link ensureToolResultPairing}), so orphan `tool_use` blocks and\n * dangling `tool_result`s never reach the provider as the 400\n * \"tool_result must be preceded by a tool_call with the same toolCallId\".\n *\n * Pass `provider` to also enforce the user-tail invariant\n * ({@link ensureEndsWithUserMessage}) — required for opus 4.7 / o-series\n * style models that reject assistant-prefill.\n *\n * Pure + idempotent. Resolves content refs only in the returned messages\n * and does NOT mutate `session.turns`. **Do not write the result back via\n * `setTurns` / `appendTurns`** — synthetic placeholders or resolved\n * payloads will contaminate persisted history.\n */\n toMessages: (options?: ToWireMessagesOptions) => Promise<SessionMessage[]>\n\n /** Serialize to SessionData */\n toJSON: () => SessionData\n\n /**\n * The backing store, when one was provided. Exposed so hosts can call\n * its optional `close()` on teardown (e.g. release the SQLite handle).\n */\n readonly store?: SessionStore\n}\n\n// ---------------------------------------------------------------------------\n// createSession\n// ---------------------------------------------------------------------------\n\nexport interface CreateSessionOptions {\n /** Session ID. If omitted and store provides generateSessionId, that is used. */\n id?: string\n /** Agent ID label */\n agentId?: string\n /**\n * Project tag — see {@link SessionData.projectRoot}. Stamped once on\n * creation; ignored when `_data` is set (restoring an existing\n * session preserves whatever was already persisted there). The TUI\n * resolves this from `findGitRoot(cwd) ?? cwd` so sessions started\n * from the same repo (no matter which subdir) share one tag.\n */\n projectRoot?: string\n /** Initial metadata */\n metadata?: Record<string, unknown>\n /** Storage backend (optional, enables save/load) */\n store?: SessionStore\n /**\n * Observability hook for the load-time pairing heal: fired once per block\n * or turn `dropInvalidToolPairings` deleted while restoring `_data`.\n * Deletions are permanent once the session is saved, so hosts that alert\n * on wire-time `pairing:repair` events should wire this to the same sink.\n * Only fires on the `_data` restore path; fresh sessions never heal.\n */\n onPairingDrop?: (drop: PairingDrop) => void\n /**\n * @internal: restore from existing data (bypasses id/agentId/metadata\n * options). The session ALIASES this object for its lifetime — every\n * mutation (appendTurns, run records, updatedAt) writes through to it,\n * and the load-time pairing heal may replace its `turns` array in place\n * before the session is returned. Callers must not retain independent\n * ownership expectations.\n */\n _data?: SessionData\n}\n\n/**\n * Create a new session.\n * Async so stores that generate IDs server-side (e.g. a database) can be supported.\n */\nexport async function createSession(options: CreateSessionOptions = {}): Promise<Session> {\n const store = options.store\n const now = Date.now()\n\n let sessionId = options.id\n if (!sessionId && store?.generateSessionId) {\n sessionId = await store.generateSessionId()\n }\n if (!sessionId) {\n sessionId = generateId()\n }\n\n // Load-time drop-only healing: restored sessions get structurally invalid\n // tool blocks (duplicate tool_call ids, orphan tool_results) deleted before\n // any consumer sees them. Pure deletions — never synthetic content — so\n // writing the result back to the store is safe (unlike `toMessages`\n // output). Without this, a transcript corrupted once (e.g. a retry that\n // re-appended an already-persisted turn) re-triggers wire-time pairing\n // repairs on every turn forever. `loadSession` persists the healed\n // transcript; direct `createSession({ _data })` callers get the in-memory\n // heal and persist on their next `save()`. The heal replaces `_data.turns`\n // IN PLACE: the session aliases `_data` for its whole lifetime (see the\n // option doc), so an on-the-side copy would make the corrupt path the only\n // one where a caller's retained reference diverges from the live session.\n // `loadSession` detects healing by comparing `session.turns` against its\n // pre-heal reference.\n if (options._data) {\n const restoreData = options._data\n const healed = dropInvalidToolPairings(restoreData.turns, {\n laneForRun: wireViewLaneResolver(restoreData.runs),\n ...(options.onPairingDrop ? { onDrop: options.onPairingDrop } : {}),\n })\n if (healed !== restoreData.turns)\n restoreData.turns = healed\n }\n\n const data: SessionData = options._data ?? {\n id: sessionId,\n agentId: options.agentId,\n // Stamp the project tag at creation only — restored sessions (the\n // `_data` branch above) keep whatever was already persisted, even\n // if `options.projectRoot` differs. A session's project identity\n // is sticky for its lifetime; loading the same session from a\n // different cwd doesn't re-home it.\n ...(options.projectRoot ? { projectRoot: options.projectRoot } : {}),\n turns: [],\n runs: [],\n status: 'idle',\n metadata: options.metadata ?? {},\n createdAt: now,\n updatedAt: now,\n }\n\n function touch() {\n data.updatedAt = Date.now()\n }\n\n function findRun(runId: string): SessionRun | undefined {\n return data.runs.find(r => r.id === runId)\n }\n\n /**\n * Apply per-run usage stats onto a SessionRun. Shared by `completeRun`,\n * `abortRun`, and `errorRun` so the on-disk shape stays consistent across\n * exit paths — historically only `completeRun` filled these in, and\n * aborted/errored runs rendered `0 in / 0 out` on reload regardless of\n * how much was actually consumed.\n */\n function applyRunStats(run: SessionRun, stats: { turns: number, tokensIn: number, tokensOut: number, turnUsage?: TurnUsage[], cost?: number }) {\n run.turns = stats.turns\n run.tokensIn = stats.tokensIn\n run.tokensOut = stats.tokensOut\n if (stats.turnUsage) {\n run.turnUsage = stats.turnUsage\n const total = stats.turnUsage.reduce((acc, t) => ({\n input: acc.input + t.input,\n output: acc.output + t.output,\n cacheCreation: (acc.cacheCreation ?? 0) + (t.cacheCreation ?? 0),\n cacheRead: (acc.cacheRead ?? 0) + (t.cacheRead ?? 0),\n thinking: (acc.thinking ?? 0) + (t.thinking ?? 0),\n }), { input: 0, output: 0, cacheCreation: 0, cacheRead: 0, thinking: 0 })\n run.totalUsage = {\n input: total.input,\n output: total.output,\n ...(total.cacheCreation ? { cacheCreation: total.cacheCreation } : {}),\n ...(total.cacheRead ? { cacheRead: total.cacheRead } : {}),\n ...(total.thinking ? { thinking: total.thinking } : {}),\n }\n }\n if (stats.cost !== undefined)\n run.cost = stats.cost\n }\n\n const session: Session = {\n ...(store ? { store } : {}),\n get id() { return data.id },\n get agentId() { return data.agentId },\n get projectRoot() { return data.projectRoot },\n get turns() { return data.turns },\n get isEmpty() { return data.turns.length === 0 },\n get status() { return data.status },\n get runs() { return data.runs },\n get metadata() { return data.metadata },\n\n startRun(runId: string, prompt?: string, extras?: { parentRunId?: string, depth?: number, resumedFromRunId?: string, label?: string }) {\n data.runs.push({\n id: runId,\n startedAt: Date.now(),\n prompt: prompt ?? '',\n status: 'running',\n ...(extras?.parentRunId ? { parentRunId: extras.parentRunId } : {}),\n ...(typeof extras?.depth === 'number' ? { depth: extras.depth } : {}),\n ...(extras?.resumedFromRunId ? { resumedFromRunId: extras.resumedFromRunId } : {}),\n ...(extras?.label ? { label: extras.label } : {}),\n })\n touch()\n },\n\n completeRun(runId: string, stats: { turns: number, tokensIn: number, tokensOut: number, turnUsage?: TurnUsage[], cost?: number }) {\n const run = findRun(runId)\n if (run) {\n run.status = 'completed'\n run.endedAt = Date.now()\n applyRunStats(run, stats)\n }\n touch()\n },\n\n abortRun(runId: string, stats?: { turns: number, tokensIn: number, tokensOut: number, turnUsage?: TurnUsage[], cost?: number }) {\n const run = findRun(runId)\n if (run) {\n run.status = 'aborted'\n run.endedAt = Date.now()\n // Backfill tokens when available so an aborted run's session\n // ledger reflects actual consumption rather than `0 in / 0 out`.\n if (stats)\n applyRunStats(run, stats)\n }\n touch()\n },\n\n errorRun(runId: string, error: string, stats?: { turns: number, tokensIn: number, tokensOut: number, turnUsage?: TurnUsage[], cost?: number }) {\n const run = findRun(runId)\n if (run) {\n run.status = 'error'\n run.endedAt = Date.now()\n run.error = error\n if (stats)\n applyRunStats(run, stats)\n }\n touch()\n },\n\n async appendTurns(turns: SessionTurn[]) {\n data.turns.push(...turns)\n touch()\n if (store) {\n await store.appendTurns(data.id, turns)\n }\n },\n\n setTurns(turns: SessionTurn[]) {\n data.turns = turns\n touch()\n },\n\n setRuns(runs: SessionRun[]) {\n data.runs = runs\n touch()\n },\n\n async updateStatus(status: SessionData['status']) {\n data.status = status\n touch()\n if (store) {\n await store.updateStatus(data.id, status)\n }\n },\n\n async updateRun(run: SessionRun) {\n if (store) {\n await store.updateRun(data.id, run)\n }\n },\n\n generateTurnId() {\n if (store?.generateTurnId) {\n return store.generateTurnId()\n }\n return crypto.randomUUID()\n },\n\n setMeta(key: string, value: unknown) {\n data.metadata[key] = value\n touch()\n const recorder = metaWriteRecorder.getStore()\n if (recorder?.session === session)\n recorder.writes.push({ key, value })\n },\n\n async save() {\n if (!store) {\n throw new Error('No SessionStore configured. Pass a store to createSession() to enable persistence.')\n }\n await store.save(data)\n },\n\n toMessages(options?: ToWireMessagesOptions) {\n return toWireMessages(data.turns, options)\n },\n\n toJSON() {\n return structuredClone(data)\n },\n }\n\n return session\n}\n\n/**\n * Demote a persisted `'running'` status to `'idle'` (in place) and return the\n * data. A persisted `'running'` is necessarily stale: the run that set it lived\n * in another process (crash, kill -9, power loss) and cannot still be executing\n * in a freshly-loaded session. Call this on the result of a raw `store.load()`\n * so consumers don't render a ghost in-progress state or refuse a new run.\n * `loadSession` applies it automatically; direct `store.load()` callers (e.g.\n * the TUI) should run loaded data through this.\n *\n * Run RECORDS get the same treatment: the agent persists each record at\n * run start with `status: 'running'` (crash durability — see the\n * `SessionStore.updateRun` contract), so a freshly-loaded session may\n * carry `'running'` runs that died with their process. They demote to\n * `'aborted'` so replay renders a truthful \"aborted\" state instead of a\n * perpetually-in-flight run.\n */\nexport function demoteStaleRunningStatus(data: SessionData): SessionData {\n if (data.status === 'running')\n data.status = 'idle'\n for (const run of data.runs) {\n if (run.status === 'running') {\n run.status = 'aborted'\n run.endedAt ??= run.startedAt\n }\n }\n return data\n}\n\nexport interface LoadSessionOptions {\n /** Forwarded to `createSession` — see {@link CreateSessionOptions.onPairingDrop}. */\n onPairingDrop?: (drop: PairingDrop) => void\n}\n\n/**\n * Load an existing session from a store.\n */\nexport async function loadSession(store: SessionStore, sessionId: string, options: LoadSessionOptions = {}): Promise<Session | null> {\n const loaded = await store.load(sessionId)\n if (!loaded)\n return null\n\n demoteStaleRunningStatus(loaded)\n\n // createSession heals structurally invalid tool pairings on the `_data`\n // branch (drop-only — see dropInvalidToolPairings). When it changed the\n // transcript, persist the healed version so the corruption never re-heals\n // (and never re-fires wire-time repairs) on subsequent loads.\n //\n // Best-effort: the in-memory heal is what correctness needs — persistence\n // is an optimization that retries on the next save(). A save failure\n // (read-only store, transient IO) must not make a loadable session throw\n // at load time. Note save() is a bulk overwrite of the loaded snapshot;\n // like every other save() caller (compact, fork), this assumes no other\n // process is appending to the session concurrently.\n const originalTurns = loaded.turns\n const originalTurnCount = originalTurns.length\n const session = await createSession({\n store,\n _data: loaded,\n ...(options.onPairingDrop ? { onPairingDrop: options.onPairingDrop } : {}),\n })\n if (session.turns !== originalTurns) {\n try {\n // Shrink the concurrent-writer window: another process may have\n // appended turns between our load() and now — a bulk save() would\n // silently discard them. Re-count before overwriting; on mismatch,\n // keep the heal in-memory and let a future clean load persist it.\n const current = await store.getTurns(sessionId)\n if (current.length === originalTurnCount)\n await session.save()\n }\n catch {\n // Healed in memory; persistence retries on the next save().\n }\n }\n return session\n}\n\n// ---------------------------------------------------------------------------\n// Re-export stores\n// ---------------------------------------------------------------------------\n\nexport type { FileMapAdapter, FileMapStoreOptions } from './file-map'\nexport { createMemoryStore } from './memory'\nexport { autoDetectAndConvert, dropInvalidToolPairings, fromAnthropic, fromOpenAI, toAnthropic, toOpenAI, toWireMessages } from './messages'\nexport type { PairingDrop, PairingDropKind } from './messages'\nexport type { ToWireMessagesOptions } from './messages'\nexport { createRemoteStore } from './remote'\nexport type { RemoteStoreOptions } from './remote'\n\n// NOTE: `createSqliteStore` is intentionally NOT re-exported here. It lives behind\n// the dedicated `zidane/session/sqlite` subpath so that non-Bun consumers don't\n// transitively evaluate `bun:sqlite` when they import from `zidane/session`.\n\n// ---------------------------------------------------------------------------\n// Helpers\n// ---------------------------------------------------------------------------\n\n/**\n * Build a `laneForRun` resolver (see `dropInvalidToolPairings`) from a\n * session's run records, mapping each runId to the wire view its turns reach:\n *\n * - depth-0 runs (and turns with no runId — legacy sessions) all share the\n * MAIN view: the top-level conversation spans every prompt's run, so\n * duplicate tool_call ids across those runs DO collide in one request.\n * - depth>0 runs get their resume-chain ROOT as lane: a resumed subagent\n * replays its ancestors' turns in its own view, but parallel subagents\n * never see each other's.\n * - runIds with no run record (the historical dropped-subagent-run bug) are\n * isolated in their own lane — conservative: same-runId corruption still\n * heals, and an untracked child's counter-style ids can't collide with the\n * main lane's.\n */\nfunction wireViewLaneResolver(runs: readonly SessionRun[]): (runId: string | undefined) => string {\n const MAIN_LANE = '\\0main'\n const byId = new Map(runs.map(r => [r.id, r]))\n const cache = new Map<string, string>()\n return (runId) => {\n if (runId === undefined)\n return MAIN_LANE\n const cached = cache.get(runId)\n if (cached !== undefined)\n return cached\n // Walk the resume chain to its root (cycle-guarded); the root decides.\n let lane = runId\n let cur: string | undefined = runId\n const seen = new Set<string>()\n while (cur !== undefined && !seen.has(cur)) {\n seen.add(cur)\n const rec = byId.get(cur)\n if (!rec)\n break // unknown run: isolate at the deepest known link\n lane = cur\n if ((rec.depth ?? 0) === 0) {\n lane = MAIN_LANE\n break\n }\n cur = rec.resumedFromRunId\n }\n cache.set(runId, lane)\n return lane\n }\n}\n\nfunction generateId(): string {\n return `ses_${Date.now().toString(36)}_${Math.random().toString(36).slice(2, 8)}`\n}\n\nfunction isSafeExtensionStateKey(key: string): boolean {\n return typeof key === 'string' && key.length > 0 && !DANGEROUS_RECORD_KEYS.has(key)\n}\n\nfunction jsonClone<T extends JsonValue>(value: T): T {\n return JSON.parse(JSON.stringify(value)) as T\n}\n\nfunction assertSafeExtensionStateKey(key: string, label: string): void {\n if (!isSafeExtensionStateKey(key))\n throw new Error(`Invalid extension session state ${label}.`)\n}\n\nfunction cloneExtensionStateRoot(value: unknown): Record<string, Record<string, JsonValue>> {\n return clonePlainRecord(value) as Record<string, Record<string, JsonValue>>\n}\n\nfunction clonePlainRecord(value: unknown): Record<string, JsonValue> {\n if (!value || typeof value !== 'object' || Array.isArray(value))\n return {}\n const out: Record<string, JsonValue> = {}\n for (const [key, child] of Object.entries(value as Record<string, unknown>)) {\n if (!isSafeExtensionStateKey(key))\n continue\n if (isJsonValue(child))\n out[key] = child\n }\n return out\n}\n\nfunction isJsonValue(value: unknown, depth = 0): value is JsonValue {\n if (value === null)\n return true\n if (typeof value === 'string' || typeof value === 'boolean')\n return true\n if (typeof value === 'number')\n return Number.isFinite(value)\n if (typeof value !== 'object')\n return false\n if (depth >= 8)\n return false\n if (Array.isArray(value))\n return value.every(item => isJsonValue(item, depth + 1))\n return Object.entries(value).every(([key, child]) =>\n isSafeExtensionStateKey(key) && isJsonValue(child, depth + 1),\n )\n}\n\nfunction assertJsonBounded(value: JsonValue, maxBytes: number, label: string): void {\n const json = JSON.stringify(value)\n if (json === undefined)\n throw new Error(`${label} must be JSON serializable.`)\n if (Buffer.byteLength(json) > maxBytes)\n throw new Error(`${label} exceeds ${maxBytes} bytes.`)\n}\n"],"mappings":";;;;AAiEA,SAAS,OAAO,MAA8B;CAC5C,OAAO;EACL,IAAI,KAAK;EACT,SAAS,KAAK;EACd,aAAa,KAAK;EAClB,MAAM,KAAK;EACX,QAAQ,KAAK;EACb,UAAU,KAAK;EACf,WAAW,KAAK;EAChB,WAAW,KAAK;CAClB;AACF;AAEA,SAAS,OAAO,MAAiB,OAAmC;CAClE,OAAO;EACL,IAAI,KAAK;EACT,SAAS,KAAK;EACd,GAAI,OAAO,KAAK,gBAAgB,WAAW,EAAE,aAAa,KAAK,YAAY,IAAI,CAAC;EAChF;EACA,MAAM,KAAK;EACX,QAAQ,KAAK;EACb,UAAU,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OAAO,QAAQ,KAAK,CAAC,CAAC,OAAO,CAAC,KAAK,WACxC,wBAAwB,GAAG,KAAK,YAAY,OAAO,QAAQ,CAAC,CAC9D;AACF;AAEA,SAAS,kBAAkB,OAAkB,UAAkB,OAAqB;CAClF,MAAM,OAAO,KAAK,UAAU,KAAK;CACjC,IAAI,SAAS,KAAA,GACX,MAAM,IAAI,MAAM,GAAG,MAAM,4BAA4B;CACvD,IAAI,OAAO,WAAW,IAAI,IAAI,UAC5B,MAAM,IAAI,MAAM,GAAG,MAAM,WAAW,SAAS,QAAQ;AACzD"}
|
package/dist/session.d.ts
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import { $g as
|
|
2
|
-
export { CreateSessionOptions, type FileMapAdapter, type FileMapStoreOptions, LoadSessionOptions, type PairingDrop, type PairingDropKind, type RemoteStoreOptions, Session, type SessionContentBlock, SessionData, type SessionMessage, SessionMetaRow, SessionRun, SessionStore, type SessionTurn, type ToWireMessagesOptions, autoDetectAndConvert, createFileMapStore, createMemoryStore, createRemoteStore, createSession, currentExtensionSession, deleteExtensionSessionState, demoteStaleRunningStatus, dropInvalidToolPairings, fromAnthropic, fromOpenAI, getExtensionSessionState, loadSession, resumeChainRunIds, setExtensionSessionState, toAnthropic, toOpenAI, toWireMessages, withExtensionSession };
|
|
1
|
+
import { $g as autoDetectAndConvert, Ag as loadSession, Bg as createFileMapStore, Cg as SessionRun, Dg as deleteExtensionSessionState, Eg as currentExtensionSession, Fg as RemoteStoreOptions, Ig as createRemoteStore, Lg as createMemoryStore, Mg as resumeChainRunIds, Ng as setExtensionSessionState, Og as demoteStaleRunningStatus, Pg as withExtensionSession, Rg as FileMapAdapter, Sg as SessionMetaWrite, Tg as createSession, Ug as PairingDrop, Wg as PairingDropKind, Zg as ToWireMessagesOptions, _g as CreateSessionOptions, a_ as fromAnthropic, bg as SessionData, bh as SessionTurn, d_ as toOpenAI, f_ as toWireMessages, gh as SessionContentBlock, jg as recordSessionMetaWrites, kg as getExtensionSessionState, o_ as fromOpenAI, t_ as dropInvalidToolPairings, u_ as toAnthropic, vg as LoadSessionOptions, wg as SessionStore, xg as SessionMetaRow, yg as Session, yh as SessionMessage, zg as FileMapStoreOptions } from "./index-CWCQwx4o.js";
|
|
2
|
+
export { CreateSessionOptions, type FileMapAdapter, type FileMapStoreOptions, LoadSessionOptions, type PairingDrop, type PairingDropKind, type RemoteStoreOptions, Session, type SessionContentBlock, SessionData, type SessionMessage, SessionMetaRow, SessionMetaWrite, SessionRun, SessionStore, type SessionTurn, type ToWireMessagesOptions, autoDetectAndConvert, createFileMapStore, createMemoryStore, createRemoteStore, createSession, currentExtensionSession, deleteExtensionSessionState, demoteStaleRunningStatus, dropInvalidToolPairings, fromAnthropic, fromOpenAI, getExtensionSessionState, loadSession, recordSessionMetaWrites, resumeChainRunIds, setExtensionSessionState, toAnthropic, toOpenAI, toWireMessages, withExtensionSession };
|
package/dist/session.js
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
import { _ as toOpenAI, d as fromOpenAI, g as toAnthropic, i as autoDetectAndConvert, o as dropInvalidToolPairings, u as fromAnthropic, v as toWireMessages } from "./messages-CZMUuKzo.js";
|
|
2
|
-
import { a as getExtensionSessionState, c as
|
|
3
|
-
export { autoDetectAndConvert, createFileMapStore, createMemoryStore, createRemoteStore, createSession, currentExtensionSession, deleteExtensionSessionState, demoteStaleRunningStatus, dropInvalidToolPairings, fromAnthropic, fromOpenAI, getExtensionSessionState, loadSession, resumeChainRunIds, setExtensionSessionState, toAnthropic, toOpenAI, toWireMessages, withExtensionSession };
|
|
2
|
+
import { a as getExtensionSessionState, c as resumeChainRunIds, d as createRemoteStore, f as createMemoryStore, i as demoteStaleRunningStatus, l as setExtensionSessionState, n as currentExtensionSession, o as loadSession, p as createFileMapStore, r as deleteExtensionSessionState, s as recordSessionMetaWrites, t as createSession, u as withExtensionSession } from "./session-BP6Ly2XF.js";
|
|
3
|
+
export { autoDetectAndConvert, createFileMapStore, createMemoryStore, createRemoteStore, createSession, currentExtensionSession, deleteExtensionSessionState, demoteStaleRunningStatus, dropInvalidToolPairings, fromAnthropic, fromOpenAI, getExtensionSessionState, loadSession, recordSessionMetaWrites, resumeChainRunIds, setExtensionSessionState, toAnthropic, toOpenAI, toWireMessages, withExtensionSession };
|
package/dist/skills.d.ts
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import { $c as createSkillActivationState, Ac as SkillInstallError, Bc as discoverSkills, Cc as resolveSkills, Dc as SKILL_PROVENANCE_FILE, Ec as stripShellInterpolations, Fc as installSkillFromSpec, Gc as buildCatalog, Hc as inferSource, Ic as listSkillCandidates, Jc as ActivationVia, Kc as IMPLICITLY_ALLOWED_SKILL_TOOLS, Lc as parseSkillInstallSpec, Mc as SkillInstallOptions, Nc as SkillInstallResult, Oc as SkillCandidateDetail, Pc as SkillInstallSpec, Qc as SkillActivationStateOptions, Rc as readSkillProvenance, Sc as validateSkillName, Tc as interpolateShellCommands, Uc as parseFrontmatter, Vc as getDefaultScanPaths, Wc as parseSkillFile, Xc as DeactivationReason, Yc as ActiveSkill, Zc as SkillActivationState, _c as matchesAllowedTool, bc as validateResourcePathReal, dc as defineSkill, dg as ShellInterpolationApproval, fc as writeSkillToDisk, fg as SkillConfig, gc as isToolAllowedByUnion, gg as SkillsConfig, hc as SkillValidationResult, hg as SkillSource, jc as SkillInstallErrorCode, kc as SkillInstallCandidate, mc as SkillValidationIssue, mg as SkillResource, pc as writeSkillsToDisk, pg as SkillDiagnostic, qc as installAllowedToolsGate, vc as parseAllowedToolPattern, wc as InterpolateShellCommandsOptions, xc as validateSkillForWrite, yc as validateResourcePath, zc as SourcedScanPath } from "./index-
|
|
1
|
+
import { $c as createSkillActivationState, Ac as SkillInstallError, Bc as discoverSkills, Cc as resolveSkills, Dc as SKILL_PROVENANCE_FILE, Ec as stripShellInterpolations, Fc as installSkillFromSpec, Gc as buildCatalog, Hc as inferSource, Ic as listSkillCandidates, Jc as ActivationVia, Kc as IMPLICITLY_ALLOWED_SKILL_TOOLS, Lc as parseSkillInstallSpec, Mc as SkillInstallOptions, Nc as SkillInstallResult, Oc as SkillCandidateDetail, Pc as SkillInstallSpec, Qc as SkillActivationStateOptions, Rc as readSkillProvenance, Sc as validateSkillName, Tc as interpolateShellCommands, Uc as parseFrontmatter, Vc as getDefaultScanPaths, Wc as parseSkillFile, Xc as DeactivationReason, Yc as ActiveSkill, Zc as SkillActivationState, _c as matchesAllowedTool, bc as validateResourcePathReal, dc as defineSkill, dg as ShellInterpolationApproval, fc as writeSkillToDisk, fg as SkillConfig, gc as isToolAllowedByUnion, gg as SkillsConfig, hc as SkillValidationResult, hg as SkillSource, jc as SkillInstallErrorCode, kc as SkillInstallCandidate, mc as SkillValidationIssue, mg as SkillResource, pc as writeSkillsToDisk, pg as SkillDiagnostic, qc as installAllowedToolsGate, vc as parseAllowedToolPattern, wc as InterpolateShellCommandsOptions, xc as validateSkillForWrite, yc as validateResourcePath, zc as SourcedScanPath } from "./index-CWCQwx4o.js";
|
|
2
2
|
export { type ActivationVia, type ActiveSkill, type DeactivationReason, IMPLICITLY_ALLOWED_SKILL_TOOLS, type InterpolateShellCommandsOptions, SKILL_PROVENANCE_FILE, type ShellInterpolationApproval, type SkillActivationState, type SkillActivationStateOptions, type SkillCandidateDetail, type SkillConfig, type SkillDiagnostic, type SkillInstallCandidate, SkillInstallError, type SkillInstallErrorCode, type SkillInstallOptions, type SkillInstallResult, type SkillInstallSpec, type SkillResource, type SkillSource, type SkillValidationIssue, type SkillValidationResult, type SkillsConfig, type SourcedScanPath, buildCatalog, createSkillActivationState, defineSkill, discoverSkills, getDefaultScanPaths, inferSource, installAllowedToolsGate, installSkillFromSpec, interpolateShellCommands, isToolAllowedByUnion, listSkillCandidates, matchesAllowedTool, parseAllowedToolPattern, parseFrontmatter, parseSkillFile, parseSkillInstallSpec, readSkillProvenance, resolveSkills, stripShellInterpolations, validateResourcePath, validateResourcePathReal, validateSkillForWrite, validateSkillName, writeSkillToDisk, writeSkillsToDisk };
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { Ed as StreamEvent, Rd as ProviderAuth, Td as Settings, Ud as ModelInfo, bh as SessionTurn, wd as SessionMeta, zd as ProviderKey } from "./index-
|
|
1
|
+
import { Ed as StreamEvent, Rd as ProviderAuth, Td as Settings, Ud as ModelInfo, bh as SessionTurn, wd as SessionMeta, zd as ProviderKey } from "./index-CWCQwx4o.js";
|
|
2
2
|
import { ReactNode } from "react";
|
|
3
3
|
|
|
4
4
|
//#region src/chat/turn-selection.d.ts
|
|
@@ -574,4 +574,4 @@ declare function displayNameFor(name: string, input?: Record<string, unknown>):
|
|
|
574
574
|
declare function formatToolCall(name: string, input: Record<string, unknown>): ToolFormatLine | null;
|
|
575
575
|
//#endregion
|
|
576
576
|
export { retagUserPromptEvents as $, highlightSegments as A, ApprovalDecision as B, SearchTurnResult as C, buildSessionSearchIndex as D, SessionSearchIndex as E, searchSessionIndex as F, useSafeModeActions as G, RequestApproval as H, searchSessionIndexAsync as I, EDIT_TOOL_NAMES as J, useSafeModeQueue as K, searchSessionTurns as L, searchSessionHistory as M, searchSessionHistoryIndex as N, buildSessionSearchIndexAsync as O, searchSessionHistoryIndexAsync as P, isVisible as Q, searchTurns as R, SearchSessionResult as S, SessionSearchExcerpt as T, SafeModeActions as U, ApprovalRequest as V, SafeModeProvider as W, isTurnHighlighted as X, isEditErrorResult as Y, isUserBashEvent as Z, splitMarkdownCodeBlocks as _, formatToolCall as a, IndexedSearchTurn as b, splitPromptSegments as c, filterModelCatalog as d, selectableTurnIds as et, indexOfEntry as f, normalizeMarkdownCodeFences as g, chunkMarkdownForRender as h, displayNameFor as i, searchHighlightRanges as j, filterSessionSearchCatalog as k, CatalogEntry as l, MarkdownSegment as m, ToolDisplayMeta as n, turnSelectionOwnership as nt, PromptSegment as o, MARKDOWN_RENDER_CHUNK_TARGET_BYTES as p, BASH_CALL_ID_PREFIX as q, ToolFormatLine as r, PromptSegmentRef as s, TOOL_DISPLAY as t, selectionAfterTurnRemoval as tt, buildModelCatalog as u, HighlightRange as v, SessionHistoryMatch as w, SearchExcerpt as x, HighlightSegment as y, searchableTurnText as z };
|
|
577
|
-
//# sourceMappingURL=tool-formatters-
|
|
577
|
+
//# sourceMappingURL=tool-formatters-BubatDZA.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"tool-formatters-
|
|
1
|
+
{"version":3,"file":"tool-formatters-BubatDZA.d.ts","names":[],"sources":["../src/chat/turn-selection.ts","../src/chat/safe-mode-context.tsx","../src/chat/history-search.ts","../src/chat/markdown-segments.ts","../src/chat/model-catalog.ts","../src/chat/prompt-segments.ts","../src/chat/tool-formatters.ts"],"mappings":";;;;;cAea,eAAA,EAAiB,WAAW;AAAzC;;;;AAAyC;AAAzC,iBAOgB,yBAAA,CACd,MAAA,qBACA,SAAA,UACA,KAAA;;;;;;;;AAAwB;AA2B1B;;;;AAA8C;AA0B9C;;;;iBA1BgB,iBAAA,CAAkB,IAAY;AA6B9C;;;;;;;;AAAA,cAHa,mBAAA;AAyDb;AAAA,iBAtDgB,eAAA,CAAgB,KAAA,EAAO,IAAI,CAAC,WAAA;;;AAyDrB;AAiEvB;;;;;;;;;AAAgE;AA2DhE;;;;;;;;AAA2E;AAkE3E;;;;;iBAjMgB,qBAAA,CACd,MAAA,WAAiB,WAAA,IACjB,aAAA,WAAwB,WAAA,cACd,WAAA;;;;;;;AAiM4B;AA8BxC;;;;;;iBA9JgB,SAAA,CAAU,KAAA,EAAO,WAAA,EAAa,QAAA,EAAU,QAAQ;;;;;;;;;;AAiKrB;;;;ACzU3C;;;;AAK6B;AAQ7B;;;;;;;;AAE4B;iBDoNZ,sBAAA,CAAuB,MAAA,WAAiB,WAAA,KAAgB,GAAG;;;;;;;;;;;;iBAkE3D,iBAAA,CACd,KAAA,EAAO,IAAA,CAAK,WAAA,aACZ,cAAA,iBACA,SAAA,EAAW,WAAA;;;;;;ACjRoB;AAIjC;;;;;;;;;;;;;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ptions, Dr as SkillsRunScriptToolOptions, Er as createSkillsUseTool, Fr as readFile, Fs as SubagentDef, Gh as ToolDef, Hr as edit, Hs as formatModelLine, Ir as multiEdit, Is as SubagentOverride, Jh as ReadStateEntry, Kh as ToolMap, Lr as listFiles, Ls as SubagentRegistry, Mr as CreateShellToolOptions, Ms as SpawnTool, Nr as createShellTool, Ns as SpawnToolOptions, Or as createSkillsRunScriptTool, Os as ChildAgent, Pr as shell, Ps as SpawnToolState, Qh as hydrateReadStateFromSession, Rr as InteractionToolOptions, Rs as createSpawnTool, Sr as LazyToolEntry, Tr as SkillsUseToolOptions, Us as matchModelEntries, Vr as glob, Vs as createModelSearchTool, Wh as ToolContext, Xh as getReadState, Yh as ReadStateMap, Zh as hashContent, _r as waitTask, br as TailTruncateOptions, eg as readStateKey, gr as WAIT_TASK_TIMED_OUT_PREFIX, hr as writeFile, jr as shellKill, js as SpawnTaskOutcome, kr as SkillsReadToolOptions, ks as ExtensionSubagentDef, qh as HydrateReadStateOptions, tg as resolveReadStateMap, vr as ValidationResult, wr as createToolSearchTool, xr as tailTruncate, yr as validateToolArgs, zr as createInteractionTool, zs as isSpawnTool } from "./index-
|
|
1
|
+
import { $h as hydrateReadStateFromSessionAsync, Ar as createSkillsReadTool, As as SpawnTaskInput, Br as grep, Bs as SpawnModelEntry, Cr as ToolSearchToolOptions, Dr as SkillsRunScriptToolOptions, Er as createSkillsUseTool, Fr as readFile, Fs as SubagentDef, Gh as ToolDef, Hr as edit, Hs as formatModelLine, Ir as multiEdit, Is as SubagentOverride, Jh as ReadStateEntry, Kh as ToolMap, Lr as listFiles, Ls as SubagentRegistry, Mr as CreateShellToolOptions, Ms as SpawnTool, Nr as createShellTool, Ns as SpawnToolOptions, Or as createSkillsRunScriptTool, Os as ChildAgent, Pr as shell, Ps as SpawnToolState, Qh as hydrateReadStateFromSession, Rr as InteractionToolOptions, Rs as createSpawnTool, Sr as LazyToolEntry, Tr as SkillsUseToolOptions, Us as matchModelEntries, Vr as glob, Vs as createModelSearchTool, Wh as ToolContext, Xh as getReadState, Yh as ReadStateMap, Zh as hashContent, _r as waitTask, br as TailTruncateOptions, eg as readStateKey, gr as WAIT_TASK_TIMED_OUT_PREFIX, hr as writeFile, jr as shellKill, js as SpawnTaskOutcome, kr as SkillsReadToolOptions, ks as ExtensionSubagentDef, qh as HydrateReadStateOptions, tg as resolveReadStateMap, vr as ValidationResult, wr as createToolSearchTool, xr as tailTruncate, yr as validateToolArgs, zr as createInteractionTool, zs as isSpawnTool } from "./index-CWCQwx4o.js";
|
|
2
2
|
export { type ChildAgent, type CreateShellToolOptions, type ExtensionSubagentDef, type HydrateReadStateOptions, type InteractionToolOptions, type LazyToolEntry, type ReadStateEntry, type ReadStateMap, type SkillsReadToolOptions, type SkillsRunScriptToolOptions, type SkillsUseToolOptions, type SpawnModelEntry, type SpawnTaskInput, type SpawnTaskOutcome, type SpawnTool, type SpawnToolOptions, type SpawnToolState, type SubagentDef, type SubagentOverride, type SubagentRegistry, type TailTruncateOptions, type ToolContext, type ToolDef, type ToolMap, type ToolSearchToolOptions, type ValidationResult, WAIT_TASK_TIMED_OUT_PREFIX, createInteractionTool, createModelSearchTool, createShellTool, createSkillsReadTool, createSkillsRunScriptTool, createSkillsUseTool, createSpawnTool, createToolSearchTool, edit, formatModelLine, getReadState, glob, grep, hashContent, hydrateReadStateFromSession, hydrateReadStateFromSessionAsync, isSpawnTool, listFiles, matchModelEntries, multiEdit, readFile, readStateKey, resolveReadStateMap, shell, shellKill, tailTruncate, validateToolArgs, waitTask, writeFile };
|
package/dist/tools.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import { At as createSkillsReadTool, Bn as hydrateReadStateFromSession, Bt as matchModelEntries, Ct as waitTask, Et as isSpawnTool, Ft as readFile, Gt as edit, Hn as readStateKey, Ht as createInteractionTool, Kt as validateToolArgs, Lt as multiEdit, Mt as createShellTool, Nt as shell, Ot as createSkillsUseTool, Pt as tailTruncate, Rn as getReadState, Rt as createModelSearchTool, St as WAIT_TASK_TIMED_OUT_PREFIX, Tt as createSpawnTool, Un as resolveReadStateMap, Ut as grep, Vn as hydrateReadStateFromSessionAsync, Vt as listFiles, Wt as glob, jt as shellKill, kt as createSkillsRunScriptTool, wt as createToolSearchTool, xt as writeFile, zn as hashContent, zt as formatModelLine } from "./agent-
|
|
1
|
+
import { At as createSkillsReadTool, Bn as hydrateReadStateFromSession, Bt as matchModelEntries, Ct as waitTask, Et as isSpawnTool, Ft as readFile, Gt as edit, Hn as readStateKey, Ht as createInteractionTool, Kt as validateToolArgs, Lt as multiEdit, Mt as createShellTool, Nt as shell, Ot as createSkillsUseTool, Pt as tailTruncate, Rn as getReadState, Rt as createModelSearchTool, St as WAIT_TASK_TIMED_OUT_PREFIX, Tt as createSpawnTool, Un as resolveReadStateMap, Ut as grep, Vn as hydrateReadStateFromSessionAsync, Vt as listFiles, Wt as glob, jt as shellKill, kt as createSkillsRunScriptTool, wt as createToolSearchTool, xt as writeFile, zn as hashContent, zt as formatModelLine } from "./agent-DpVdepFt.js";
|
|
2
2
|
export { WAIT_TASK_TIMED_OUT_PREFIX, createInteractionTool, createModelSearchTool, createShellTool, createSkillsReadTool, createSkillsRunScriptTool, createSkillsUseTool, createSpawnTool, createToolSearchTool, edit, formatModelLine, getReadState, glob, grep, hashContent, hydrateReadStateFromSession, hydrateReadStateFromSessionAsync, isSpawnTool, listFiles, matchModelEntries, multiEdit, readFile, readStateKey, resolveReadStateMap, shell, shellKill, tailTruncate, validateToolArgs, waitTask, writeFile };
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { n as __require } from "./rolldown-runtime-BhDjJH2R.js";
|
|
2
2
|
import { l as toolResultToText } from "./types-BIarq1qE.js";
|
|
3
|
-
import { Ct as waitTask, Ft as readFile$1, Gt as edit, Lt as multiEdit, Nt as shell, Tt as createSpawnTool, Ut as grep, Vt as listFiles, Wt as glob, Y as EMPTY_EXTENSION_REGISTRY, _t as composePresets, an as readKeybindingsRaw, b as migrateSessionArtifactDirs, jt as shellKill, nn as mergeKeybindings, on as resolveExtensionKeybindings, st as buildExtensionPreset, vt as definePreset, xt as writeFile$1 } from "./agent-
|
|
3
|
+
import { Ct as waitTask, Ft as readFile$1, Gt as edit, Lt as multiEdit, Nt as shell, Tt as createSpawnTool, Ut as grep, Vt as listFiles, Wt as glob, Y as EMPTY_EXTENSION_REGISTRY, _t as composePresets, an as readKeybindingsRaw, b as migrateSessionArtifactDirs, jt as shellKill, nn as mergeKeybindings, on as resolveExtensionKeybindings, st as buildExtensionPreset, vt as definePreset, xt as writeFile$1 } from "./agent-DpVdepFt.js";
|
|
4
4
|
import { a as formatDuration, c as previewLine, i as fmtTokens, l as shortId } from "./format-BF745pLL.js";
|
|
5
5
|
import { u as errorMessage } from "./errors-DKiMrOKq.js";
|
|
6
6
|
import { R as projectUserPaths, x as discoverSkills, z as findGitRoot$1 } from "./skills-BMGH_KK1.js";
|
|
@@ -12,7 +12,7 @@ import { r as formatTokenUsage } from "./stats-DAKBEKjc.js";
|
|
|
12
12
|
import { i as findActiveTriggers, n as collectReferences, o as mergeSuggestions, t as applyInsert } from "./completion-core-BRo86R_L.js";
|
|
13
13
|
import { r as fetchUrl } from "./fetch-url-ma-5_p0p.js";
|
|
14
14
|
import { webSearch } from "./tools/web-search.js";
|
|
15
|
-
import { T as restoreModelOptions, b as modelSupportsReasoning, d as BUILTIN_PROVIDERS, i as readCredentials, m as credKeyOf, n as applyApiKeyEnv, r as credentialsPath, t as detectAuth, x as modelsForDescriptor } from "./auth-
|
|
15
|
+
import { T as restoreModelOptions, b as modelSupportsReasoning, d as BUILTIN_PROVIDERS, i as readCredentials, m as credKeyOf, n as applyApiKeyEnv, r as credentialsPath, t as detectAuth, x as modelsForDescriptor } from "./auth-D2KIL4OS.js";
|
|
16
16
|
import { at as extractEditPayload, bt as chatReferenceTokensFromText, m as ownerOf, mt as parseEditOutcomesFromResult, u as capTranscriptEvents, w as chunkMarkdownForRender } from "./turn-operations-mMxDRgLY.js";
|
|
17
17
|
import { basename, dirname, isAbsolute, join, posix, relative, resolve, sep } from "node:path";
|
|
18
18
|
import { Buffer } from "node:buffer";
|
|
@@ -11176,4 +11176,4 @@ function computeTurnAnchors(items) {
|
|
|
11176
11176
|
//#endregion
|
|
11177
11177
|
export { buildToolToggle as $, singleAgentRegistry as $n, CATPPUCCIN_MACCHIATO as $t, writeProjects as A, bootProfileEnabled as An, DEFAULT_SESSION_TITLE as Ar, hintsLength as At, formatPathForCwd as B, performSelfUpdate as Bn, saveState as Br, SETTINGS_TOGGLES as Bt, addToSafelist as C, upsertMcpServer as Cn, SUBAGENT_GUIDANCE as Cr, makeRequestInteraction as Ct, projectsFilePath as D, discoverProjectMcps as Dn, envSection as Dr, useInteractionsQueue as Dt, matchesSafelistEntry as E, defaultMcpsConfigPaths as En, buildPlanSystem as Er, useInteractionsActions as Et, formatUsagePercent as F, compareSemver as Fn, lastContextSizeFromTurns as Fr, useEnabledToggleSet as Ft, runOAuthLogin as G, BUILD_AGENT as Gn, toolCallPreview as Gr, DEFAULT_THEME as Gt, normalizeRedirectPaste as H, chatAutoCompactBehavior as Hn, stripSpawnTokensLine as Hr, clampFps as Ht, mostConstrainedWindow as I, detectLibc as In, listSessionMeta as Ir, DEFAULT_SETTINGS as It, loadMcpToolsCache as J, DEFAULT_BUDGET_EXCLUDE_TOOLS as Jn, usageByModel as Jr, VAPORWAVE_THEME as Jt, supportsOAuth as K, BUILTIN_AGENTS as Kn, toolResultText as Kr, resolveChipColor as Kt, providerUsageSupported as L, detectPackageManager as Ln, loadState as Lr, SETTINGS_CATEGORIES as Lt, clearProviderUsageCache as M, buildUpdateHint as Mn, createStateStore as Mr, buildHints as Mt, fetchAllProviderUsage as N, useUpdateCheck as Nn, deriveSessionTitle as Nr, shortChord as Nt, readProjects as O, parseMcpsFile as On, chatReferenceTokensForPrompt as Or, EMPTY_HINTS as Ot, fetchProviderUsage as P, checkForUpdate as Pn, eventsFromTurns as Pr, listProjectFiles as Pt, subscribeMcpToolsCache as Q, resolveAgentId as Qn, CATPPUCCIN_LATTE as Qt, usageChecksOptedOut as R, parseSemver as Rn, marginTopFor as Rr, SETTINGS_CHOICES as Rt, IMPLICITLY_SAFE_TOOLS as S, removeMcpServer as Sn, PLAN_MODE_DOCTRINE_NO_PROMPTS as Sr, isModelInteraction as St, isOnSafelist as T, dedupMcpServersByName as Tn, buildBuildSystem as Tr, serializeInteractionResponse as Tt, redirectUriFromAuthUrl as U, discoverAgentsMd as Un, sumRunCosts as Ur, useSettings as Ut, fetchOAuthRedirect as V, resolvePlatformPackage as Vn, serverToolResultSummary as Vr, SettingsProvider as Vt, oauthUsesManualCodePaste as W, renderAgentsMdBlock as Wn, titleFromTurns as Wr, BUILTIN_THEMES as Wt, refreshMcpToolsCatalog as X, PLAN_AGENT as Xn, GRUVBOX_LIGHT as Xt, mcpToolsCachePath as Y, DEFAULT_PERSIST_EXCLUDE_TOOLS as Yn, GRUVBOX_DARK as Yt, saveMcpToolsCache as Z, accentColor as Zn, CATPPUCCIN_FRAPPE as Zt, resolveSessionExportTarget as _, useCompletion as _n, DOING_TASKS_DOCTRINE as _r, PRESENT_PLAN_TOOL as _t, useSurfaces as a, ConfigProvider as an, createTodoTools as ar, createFileMcpCredentialStore as at, useSafeModeActions as b, importFromClaudeCode as bn, INTERACTION_GUIDANCE_NO_PROMPTS as br, createInteractionTools as bt, discoverSystemMd as c, resolveStoragePaths as cn, isTodoTool as cr, McpAuthProvider as ct, userSystemMdPath as d, chainsEqual as dn, selectActiveTodos as dr, getMcpAuthStatus as dt, CATPPUCCIN_MOCHA as en, TODOREAD_TOOL as er, useMcpToolToggleMap as et, useStreamBuffer as f, filterChainFallbacks as fn, setTodosForRun as fr, reduceMcpAuth as ft, renderSession as g, toggleChainEntry as gn, COMMUNICATION_DOCTRINE as gr, InteractionsProvider as gt, discoverProjectSkills as h, sanitizeModelChain as hn, ACTIONS_WITH_CARE_DOCTRINE as hr, HOST_INTERACTION_ID_PREFIX as ht, useSelectStyle as i, useDiscoveryOptional as in, TODO_WRITE_COUNTS_METADATA_KEY as ir, parentServerName as it, USAGE_CACHE_TTL_MS as j, bootTick as jn, compactSummaryEvent as jr, truncateTrailing as jt, suggestSafelistEntries as k, tryOpenBrowser as kn, createChatTurnsReadTool as kr, clipHintsToWidth as kt, renderSystemMdSeed as l, buildRunModel as ln, pickActiveRunId as lr, useMcpAuthDispatch as lt, defaultSkillScanPaths as m, restoreChainFallbacks as mn, useActiveTodos as mr, AUTOMATIC_INTERACTION_INSTRUCTION as mt, ThemeProvider as n, DiscoveryProvider as nn, TODOWRITE_TOOL as nr, buildVisibleMcpRows as nt, useSyntaxStyles as o, useConfig as on, getArchivedTodosForRun as or, mcpCredentialsPath as ot, buildSkillsConfig as p, providerKeySetChanged as pn, todoProgressLabel as pr, ASK_USER_TOOL as pt, clearMcpToolsCache as q, DEFAULT_AGENT_ID as qn, updateToolEventOutcomes as qr, resolveTheme as qt, useColors as r, useDiscovery as rn, TODO_STATUS_GLYPHS as rr, indexOfServerRow as rt, useTheme as s, resolveConfig as sn, getTodosForRun as sr, patchMcpCredential as st, computeTurnAnchors as t, createDiscoverySlot as tn, TODOS_METADATA_KEY as tr, useMcpToolToggleSet as tt, userScopeOverridesLoad as u, chainPositionOf as un, pruneTodosByRun as ur, useMcpAuthState as ut, writeSessionExport as v, countClaudeSessionFiles as vn, IDENTITY_PREFIX as vr, buildResumedToolResultsTurn as vt, getSafelist as w, buildMcpServers as wn, TOKEN_DISCIPLINE_DOCTRINE as wr, pendingInteractionsFromTurns as wt, useSafeModeQueue as x, mcpsWritePath as xn, PLAN_MODE_DOCTRINE as xr, isInteractionTool as xt, SafeModeProvider as y, hasClaudeCodeSetup as yn, INTERACTION_GUIDANCE as yr, createAutomaticInteractionResponse as yt, usageSourceFor as z, performInPlaceSelfUpdate as zn, noticeTurnContent as zr, SETTINGS_INPUTS as zt };
|
|
11178
11178
|
|
|
11179
|
-
//# sourceMappingURL=transcript-anchors-
|
|
11179
|
+
//# sourceMappingURL=transcript-anchors-5qybec_s.js.map
|