@bastani/atomic 0.9.38-alpha.8 → 0.9.38
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/CHANGELOG.md +112 -0
- package/dist/builtin/intercom/CHANGELOG.md +10 -0
- package/dist/builtin/intercom/package.json +1 -1
- package/dist/builtin/mcp/package.json +1 -1
- package/dist/builtin/subagents/CHANGELOG.md +10 -0
- package/dist/builtin/subagents/package.json +1 -1
- package/dist/builtin/web-access/CHANGELOG.md +7 -0
- package/dist/builtin/web-access/package.json +1 -1
- package/dist/builtin/workflows/CHANGELOG.md +60 -0
- package/dist/builtin/workflows/package.json +1 -1
- package/dist/builtin/workflows/src/extension/index.bundle.mjs +5 -0
- package/dist/core/agent-session-prompt.d.ts.map +1 -1
- package/dist/core/agent-session-prompt.js +57 -15
- package/dist/core/agent-session-prompt.js.map +1 -1
- package/dist/core/queued-input-admission.d.ts +20 -0
- package/dist/core/queued-input-admission.d.ts.map +1 -0
- package/dist/core/queued-input-admission.js +55 -0
- package/dist/core/queued-input-admission.js.map +1 -0
- package/dist/core/storage/session/legacy-session-store.d.ts +6 -3
- package/dist/core/storage/session/legacy-session-store.d.ts.map +1 -1
- package/dist/core/storage/session/legacy-session-store.js +26 -12
- package/dist/core/storage/session/legacy-session-store.js.map +1 -1
- package/dist/core/storage/session/legacy-session-summary.d.ts +11 -0
- package/dist/core/storage/session/legacy-session-summary.d.ts.map +1 -0
- package/dist/core/storage/session/legacy-session-summary.js +103 -0
- package/dist/core/storage/session/legacy-session-summary.js.map +1 -0
- package/dist/extensions/mcp/client/transports/streamable-http.js +9 -8
- package/dist/extensions/mcp/client/transports/streamable-http.js.map +1 -1
- package/dist/main-session.d.ts.map +1 -1
- package/dist/main-session.js +4 -1
- package/dist/main-session.js.map +1 -1
- package/dist/modes/interactive/components/chat-session-host-actions.d.ts +4 -0
- package/dist/modes/interactive/components/chat-session-host-actions.d.ts.map +1 -1
- package/dist/modes/interactive/components/chat-session-host-actions.js +104 -30
- package/dist/modes/interactive/components/chat-session-host-actions.js.map +1 -1
- package/dist/modes/interactive/components/chat-session-host-events.d.ts.map +1 -1
- package/dist/modes/interactive/components/chat-session-host-events.js +1 -0
- package/dist/modes/interactive/components/chat-session-host-events.js.map +1 -1
- package/dist/modes/interactive/components/chat-session-host-state.d.ts +4 -0
- package/dist/modes/interactive/components/chat-session-host-state.d.ts.map +1 -1
- package/dist/modes/interactive/components/chat-session-host-state.js +4 -0
- package/dist/modes/interactive/components/chat-session-host-state.js.map +1 -1
- package/dist/modes/interactive/components/session-selector.js +4 -3
- package/dist/modes/interactive/components/session-selector.js.map +1 -1
- package/dist/modes/interactive/interactive-input-handling.js +8 -2
- package/dist/modes/interactive/interactive-input-handling.js.map +1 -1
- package/dist/modes/interactive/interactive-mode-base.d.ts +4 -0
- package/dist/modes/interactive/interactive-mode-base.d.ts.map +1 -1
- package/dist/modes/interactive/interactive-mode-base.js +4 -0
- package/dist/modes/interactive/interactive-mode-base.js.map +1 -1
- package/dist/modes/interactive/interactive-process-lifecycle.js +8 -2
- package/dist/modes/interactive/interactive-process-lifecycle.js.map +1 -1
- package/dist/modes/interactive/interactive-queueing.js +94 -73
- package/dist/modes/interactive/interactive-queueing.js.map +1 -1
- package/dist/modes/interactive/interactive-session-runtime.js +1 -0
- package/dist/modes/interactive/interactive-session-runtime.js.map +1 -1
- package/docs/docs.json +5 -2
- package/docs/llama-cpp.md +94 -1
- package/docs/sessions.md +1 -1
- package/docs/usage.md +2 -0
- package/npm-shrinkwrap.json +32 -32
- package/package.json +3 -3
- package/docs/nvidia-rtx-llama-cpp.md +0 -101
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"legacy-session-store.js","sourceRoot":"","sources":["../../../../src/core/storage/session/legacy-session-store.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,MAAM,SAAS,CAAC;AACrC,OAAO,EAAE,IAAI,EAAE,MAAM,kBAAkB,CAAC;AACxC,O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createSessionCwdMatcher } from \"../../../utils/canonical-path.ts\";\nimport type { SessionEntry } from \"../../session-manager-types.ts\";\nimport type { SqliteDatabase } from \"../database.js\";\nimport { openNodeSqliteDatabase } from \"../node-sqlite.js\";\nimport { SessionExistsError, SessionNotFoundError } from \"./errors.js\";\nimport { type JsonlSessionFile, JsonlSessionStore } from \"./jsonl-session-store.js\";\nimport { summarizeSession } from \"./session-summary.js\";\nimport type {\n\tSessionListQuery,\n\tSessionRecordHeader,\n\tSessionSnapshot,\n\tSessionStore,\n\tSessionSummary,\n\tSessionWriteOptions,\n\tStorageDescriptor,\n} from \"./types.js\";\n\nconst DELETED_TABLE = \"session_legacy_deleted\";\n\n/**\n * The default session store, plus the JSONL sessions saved before it existed.\n *\n * Sessions from before the SQLite default stay in `<agentDir>/sessions` and are\n * listed from there, so `/resume` and `--continue` show them without any upfront\n * work. A legacy session is converted into the database only when it is opened,\n * following pi's migrate-on-load pattern; afterwards it is read from the database\n * like any other session. The JSONL files are never modified. Deleting a session\n * records its ID so a legacy copy of it is not listed again.\n */\nexport class LegacySessionStore implements SessionStore {\n\tprivate readonly inner: SessionStore;\n\tprivate readonly legacyDirectory: string;\n\tprivate readonly databasePath: string;\n\tprivate legacy?: Promise<JsonlSessionStore | undefined>;\n\tprivate index?: Promise<ReadonlyMap<string, readonly JsonlSessionFile[]>>;\n\tprivate readonly summaries = new Map<string, { readonly stamp: string; readonly summary: SessionSummary | null }>();\n\tprivate deletions?: Promise<SqliteDatabase>;\n\n\tconstructor(inner: SessionStore, options: { readonly legacyDirectory: string; readonly databasePath: string }) {\n\t\tthis.inner = inner;\n\t\tthis.legacyDirectory = options.legacyDirectory;\n\t\tthis.databasePath = options.databasePath;\n\t}\n\n\tget descriptor(): StorageDescriptor {\n\t\treturn this.inner.descriptor;\n\t}\n\n\tcreate(header: SessionRecordHeader, entries: readonly SessionEntry[]): Promise<{ readonly lastSeq: number }> {\n\t\treturn this.inner.create(header, entries);\n\t}\n\n\tasync append(\n\t\tsessionId: string,\n\t\tentries: readonly SessionEntry[],\n\t\toptions: SessionWriteOptions,\n\t): Promise<{ readonly lastSeq: number }> {\n\t\tawait this.convert(sessionId);\n\t\treturn this.inner.append(sessionId, entries, options);\n\t}\n\n\tasync replace(\n\t\tsessionId: string,\n\t\theader: SessionRecordHeader,\n\t\tentries: readonly SessionEntry[],\n\t\toptions: SessionWriteOptions,\n\t): Promise<{ readonly lastSeq: number }> {\n\t\tawait this.convert(sessionId);\n\t\treturn this.inner.replace(sessionId, header, entries, options);\n\t}\n\n\tasync load(sessionId: string): Promise<SessionSnapshot> {\n\t\tawait this.convert(sessionId);\n\t\treturn this.inner.load(sessionId);\n\t}\n\n\tasync readHeader(sessionId: string): Promise<SessionRecordHeader | undefined> {\n\t\tconst header = await this.inner.readHeader(sessionId);\n\t\tif (header !== undefined) return header;\n\t\treturn (await this.findLegacy(sessionId))?.header;\n\t}\n\n\tasync delete(sessionId: string): Promise<void> {\n\t\tconst legacy = await this.findLegacy(sessionId);\n\t\tif (legacy !== undefined) await this.markDeleted(sessionId);\n\t\ttry {\n\t\t\tawait this.inner.delete(sessionId);\n\t\t} catch (error) {\n\t\t\tif (!(error instanceof SessionNotFoundError) || legacy === undefined) throw error;\n\t\t}\n\t}\n\n\tasync *list(query: SessionListQuery): AsyncIterable<SessionSummary> {\n\t\tconst listed = new Set<string>();\n\t\tfor await (const summary of this.inner.list(query)) {\n\t\t\tlisted.add(summary.id);\n\t\t\tyield summary;\n\t\t}\n\t\tfor await (const file of this.legacyFiles(query)) {\n\t\t\tif (listed.has(file.header.id) || (await this.inner.readHeader(file.header.id)) !== undefined) continue;\n\t\t\tconst summary = await this.summarize(file.header.id);\n\t\t\tif (summary === undefined) continue;\n\t\t\tlisted.add(summary.id);\n\t\t\tyield summary;\n\t\t}\n\t}\n\n\tasync findMostRecent(query: {\n\t\treadonly cwd: string;\n\t\treadonly includeInternal?: boolean;\n\t}): Promise<SessionSummary | undefined> {\n\t\tlet latest = await this.inner.findMostRecent(query);\n\t\tfor await (const file of this.legacyFiles(query)) {\n\t\t\tif ((await this.inner.readHeader(file.header.id)) !== undefined) continue;\n\t\t\tconst summary = await this.summarize(file.header.id);\n\t\t\tif (summary !== undefined && (!latest || Date.parse(summary.modifiedAt) > Date.parse(latest.modifiedAt))) {\n\t\t\t\tlatest = summary;\n\t\t\t}\n\t\t}\n\t\treturn latest;\n\t}\n\n\tasync close(): Promise<void> {\n\t\tconst legacy = this.legacy;\n\t\tconst deletions = this.deletions;\n\t\tthis.legacy = undefined;\n\t\tthis.deletions = undefined;\n\t\tthis.index = undefined;\n\t\tthis.summaries.clear();\n\t\tawait Promise.all([\n\t\t\tlegacy?.then((store) => store?.close()).catch(() => {}),\n\t\t\tdeletions?.then((database) => database.close()).catch(() => {}),\n\t\t]);\n\t\tawait this.inner.close();\n\t}\n\n\t/** Convert one legacy session into the database the first time it is needed. */\n\tprivate async convert(sessionId: string): Promise<void> {\n\t\tif ((await this.inner.readHeader(sessionId)) !== undefined) return;\n\t\tconst snapshot = await this.readLegacy(sessionId);\n\t\tif (snapshot === undefined) return;\n\t\ttry {\n\t\t\tawait this.inner.create(snapshot.header, snapshot.entries);\n\t\t} catch (error) {\n\t\t\tif (!(error instanceof SessionExistsError)) throw error;\n\t\t}\n\t\tif (await this.isDeleted(sessionId)) await this.inner.delete(sessionId).catch(() => {});\n\t}\n\n\t/** The first readable copy of a legacy session; a damaged duplicate does not hide a readable one. */\n\tprivate async readLegacy(sessionId: string): Promise<SessionSnapshot | undefined> {\n\t\tif (await this.isDeleted(sessionId)) return undefined;\n\t\tfor (const file of (await this.legacyIndex()).get(sessionId) ?? []) {\n\t\t\ttry {\n\t\t\t\tconst snapshot = await file.read();\n\t\t\t\tsummarizeSession(snapshot);\n\t\t\t\treturn snapshot;\n\t\t\t} catch {\n\t\t\t\t// Try the next copy.\n\t\t\t}\n\t\t}\n\t\treturn undefined;\n\t}\n\n\tprivate async findLegacy(sessionId: string): Promise<JsonlSessionFile | undefined> {\n\t\tconst file = (await this.legacyIndex()).get(sessionId)?.[0];\n\t\tif (file === undefined || (await this.isDeleted(sessionId))) return undefined;\n\t\treturn file;\n\t}\n\n\tprivate async *legacyFiles(query: {\n\t\treadonly cwd?: string;\n\t\treadonly includeInternal?: boolean;\n\t}): AsyncIterable<JsonlSessionFile> {\n\t\tconst matchesCwd = query.cwd === undefined ? undefined : createSessionCwdMatcher(query.cwd);\n\t\tfor (const [file] of (await this.legacyIndex()).values()) {\n\t\t\tif (file === undefined) continue;\n\t\t\tif (matchesCwd && !matchesCwd(file.header.cwd)) continue;\n\t\t\tif (!query.includeInternal && file.header.internal) continue;\n\t\t\tif (await this.isDeleted(file.header.id)) continue;\n\t\t\tyield file;\n\t\t}\n\t}\n\n\t/** Header-only index of the legacy directory, read once; nothing writes legacy sessions any more. */\n\tprivate legacyIndex(): Promise<ReadonlyMap<string, readonly JsonlSessionFile[]>> {\n\t\tthis.index ??= (async () => {\n\t\t\tconst files = new Map<string, JsonlSessionFile[]>();\n\t\t\tconst legacy = await this.legacyStore();\n\t\t\tif (legacy === undefined) return files;\n\t\t\ttry {\n\t\t\t\tfor await (const file of legacy.scanFiles()) {\n\t\t\t\t\tconst copies = files.get(file.header.id);\n\t\t\t\t\tif (copies) copies.push(file);\n\t\t\t\t\telse files.set(file.header.id, [file]);\n\t\t\t\t}\n\t\t\t} catch {\n\t\t\t\t// An unreadable legacy directory leaves only the sessions already in the database.\n\t\t\t}\n\t\t\treturn files;\n\t\t})();\n\t\treturn this.index;\n\t}\n\n\t/** Summaries are cached per store until a copy of the session changes on disk. */\n\tprivate async summarize(sessionId: string): Promise<SessionSummary | undefined> {\n\t\tconst stamp = await this.fileStamp(sessionId);\n\t\tconst cached = this.summaries.get(sessionId);\n\t\tif (cached !== undefined && cached.stamp === stamp) return cached.summary ?? undefined;\n\t\tconst snapshot = await this.readLegacy(sessionId);\n\t\tconst summary = snapshot === undefined ? null : summarizeSession(snapshot);\n\t\tthis.summaries.set(sessionId, { stamp, summary });\n\t\treturn summary ?? undefined;\n\t}\n\n\tprivate async fileStamp(sessionId: string): Promise<string> {\n\t\tconst stamps = await Promise.all(\n\t\t\t((await this.legacyIndex()).get(sessionId) ?? []).map(async (file) => {\n\t\t\t\tconst stats = await stat(file.location).catch(() => undefined);\n\t\t\t\treturn stats === undefined ? \"missing\" : `${stats.size}:${stats.mtimeMs}`;\n\t\t\t}),\n\t\t);\n\t\treturn stamps.join(\"|\");\n\t}\n\n\tprivate legacyStore(): Promise<JsonlSessionStore | undefined> {\n\t\tthis.legacy ??= existsSync(this.legacyDirectory)\n\t\t\t? JsonlSessionStore.open(this.legacyDirectory, { scanExisting: false }).catch(() => undefined)\n\t\t\t: Promise.resolve(undefined);\n\t\treturn this.legacy;\n\t}\n\n\tprivate deletionDatabase(): Promise<SqliteDatabase> {\n\t\tthis.deletions ??= openNodeSqliteDatabase(this.databasePath).then(async (database) => {\n\t\t\tawait database.exec(\n\t\t\t\t`CREATE TABLE IF NOT EXISTS ${DELETED_TABLE}(id TEXT PRIMARY KEY, deleted_at INTEGER NOT NULL)`,\n\t\t\t);\n\t\t\treturn database;\n\t\t});\n\t\treturn this.deletions;\n\t}\n\n\tprivate async isDeleted(sessionId: string): Promise<boolean> {\n\t\tconst database = await this.deletionDatabase();\n\t\treturn (await database.get(`SELECT id FROM ${DELETED_TABLE} WHERE id = ?`, sessionId)) !== undefined;\n\t}\n\n\tprivate async markDeleted(sessionId: string): Promise<void> {\n\t\tconst database = await this.deletionDatabase();\n\t\tawait database.run(`INSERT OR IGNORE INTO ${DELETED_TABLE} VALUES (?, ?)`, sessionId, Date.now());\n\t}\n}\n"]}
|
|
1
|
+
{"version":3,"file":"legacy-session-store.js","sourceRoot":"","sources":["../../../../src/core/storage/session/legacy-session-store.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,MAAM,SAAS,CAAC;AACrC,OAAO,EAAE,IAAI,EAAE,MAAM,kBAAkB,CAAC;AACxC,OAAO,EAAE,uBAAuB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AC,yBAAyB,aAAa,gBAAgB,EAAE,SAAS,EAAE,IAAI,CAAC,GAAG,EAAE,CAAC,CAAC;IACnG,CAAC;CACD","sourcesContent":["import { existsSync } from \"node:fs\";\nimport { stat } from \"node:fs/promises\";\nimport { createSessionCwdMatcher } from \"../../../utils/canonical-path.ts\";\nimport type { SessionEntry } from \"../../session-manager-types.ts\";\nimport type { SqliteDatabase } from \"../database.js\";\nimport { openNodeSqliteDatabase } from \"../node-sqlite.js\";\nimport { SessionExistsError, SessionNotFoundError } from \"./errors.js\";\nimport { type JsonlSessionFile, JsonlSessionStore } from \"./jsonl-session-store.js\";\nimport { summarizeLegacySession } from \"./legacy-session-summary.js\";\nimport { summarizeSession } from \"./session-summary.js\";\nimport type {\n\tSessionListQuery,\n\tSessionRecordHeader,\n\tSessionSnapshot,\n\tSessionStore,\n\tSessionSummary,\n\tSessionWriteOptions,\n\tStorageDescriptor,\n} from \"./types.js\";\n\nconst DELETED_TABLE = \"session_legacy_deleted\";\n\n/**\n * The default session store, plus the JSONL sessions saved before it existed.\n *\n * Sessions from before the SQLite default stay in `<agentDir>/sessions` and are\n * listed from there, so `/resume` and `--continue` show them without any upfront\n * work. A legacy session is converted into the database only when it is opened,\n * following pi's migrate-on-load pattern; afterwards it is read from the database\n * like any other session. The JSONL files are never modified. Deleting a session\n * records its ID so a legacy copy of it is not listed again. Listing reads a large legacy\n * session only from its two ends, so its cost does not grow with the size of the history.\n */\nexport class LegacySessionStore implements SessionStore {\n\tprivate readonly inner: SessionStore;\n\tprivate readonly legacyDirectory: string;\n\tprivate readonly databasePath: string;\n\tprivate legacy?: Promise<JsonlSessionStore | undefined>;\n\tprivate index?: Promise<ReadonlyMap<string, readonly JsonlSessionFile[]>>;\n\tprivate readonly summaries = new Map<string, { readonly stamp: string; readonly summary: SessionSummary | null }>();\n\tprivate deletions?: Promise<SqliteDatabase>;\n\n\tconstructor(inner: SessionStore, options: { readonly legacyDirectory: string; readonly databasePath: string }) {\n\t\tthis.inner = inner;\n\t\tthis.legacyDirectory = options.legacyDirectory;\n\t\tthis.databasePath = options.databasePath;\n\t}\n\n\tget descriptor(): StorageDescriptor {\n\t\treturn this.inner.descriptor;\n\t}\n\n\tcreate(header: SessionRecordHeader, entries: readonly SessionEntry[]): Promise<{ readonly lastSeq: number }> {\n\t\treturn this.inner.create(header, entries);\n\t}\n\n\tasync append(\n\t\tsessionId: string,\n\t\tentries: readonly SessionEntry[],\n\t\toptions: SessionWriteOptions,\n\t): Promise<{ readonly lastSeq: number }> {\n\t\tawait this.convert(sessionId);\n\t\treturn this.inner.append(sessionId, entries, options);\n\t}\n\n\tasync replace(\n\t\tsessionId: string,\n\t\theader: SessionRecordHeader,\n\t\tentries: readonly SessionEntry[],\n\t\toptions: SessionWriteOptions,\n\t): Promise<{ readonly lastSeq: number }> {\n\t\tawait this.convert(sessionId);\n\t\treturn this.inner.replace(sessionId, header, entries, options);\n\t}\n\n\tasync load(sessionId: string): Promise<SessionSnapshot> {\n\t\tawait this.convert(sessionId);\n\t\treturn this.inner.load(sessionId);\n\t}\n\n\tasync readHeader(sessionId: string): Promise<SessionRecordHeader | undefined> {\n\t\tconst header = await this.inner.readHeader(sessionId);\n\t\tif (header !== undefined) return header;\n\t\treturn (await this.findLegacy(sessionId))?.header;\n\t}\n\n\tasync delete(sessionId: string): Promise<void> {\n\t\tconst legacy = await this.findLegacy(sessionId);\n\t\tif (legacy !== undefined) await this.markDeleted(sessionId);\n\t\ttry {\n\t\t\tawait this.inner.delete(sessionId);\n\t\t} catch (error) {\n\t\t\tif (!(error instanceof SessionNotFoundError) || legacy === undefined) throw error;\n\t\t}\n\t}\n\n\tasync *list(query: SessionListQuery): AsyncIterable<SessionSummary> {\n\t\tconst listed = new Set<string>();\n\t\tfor await (const summary of this.inner.list(query)) {\n\t\t\tlisted.add(summary.id);\n\t\t\tyield summary;\n\t\t}\n\t\tfor await (const file of this.legacyFiles(query)) {\n\t\t\tif (listed.has(file.header.id) || (await this.inner.readHeader(file.header.id)) !== undefined) continue;\n\t\t\tconst summary = await this.summarize(file.header.id);\n\t\t\tif (summary === undefined) continue;\n\t\t\tlisted.add(summary.id);\n\t\t\tyield summary;\n\t\t}\n\t}\n\n\tasync findMostRecent(query: {\n\t\treadonly cwd: string;\n\t\treadonly includeInternal?: boolean;\n\t}): Promise<SessionSummary | undefined> {\n\t\tlet latest = await this.inner.findMostRecent(query);\n\t\tfor await (const file of this.legacyFiles(query)) {\n\t\t\tif ((await this.inner.readHeader(file.header.id)) !== undefined) continue;\n\t\t\tconst summary = await this.summarize(file.header.id);\n\t\t\tif (summary !== undefined && (!latest || Date.parse(summary.modifiedAt) > Date.parse(latest.modifiedAt))) {\n\t\t\t\tlatest = summary;\n\t\t\t}\n\t\t}\n\t\treturn latest;\n\t}\n\n\tasync close(): Promise<void> {\n\t\tconst legacy = this.legacy;\n\t\tconst deletions = this.deletions;\n\t\tthis.legacy = undefined;\n\t\tthis.deletions = undefined;\n\t\tthis.index = undefined;\n\t\tthis.summaries.clear();\n\t\tawait Promise.all([\n\t\t\tlegacy?.then((store) => store?.close()).catch(() => {}),\n\t\t\tdeletions?.then((database) => database.close()).catch(() => {}),\n\t\t]);\n\t\tawait this.inner.close();\n\t}\n\n\t/** Convert one legacy session into the database the first time it is needed. */\n\tprivate async convert(sessionId: string): Promise<void> {\n\t\tif ((await this.inner.readHeader(sessionId)) !== undefined) return;\n\t\tconst snapshot = await this.readLegacy(sessionId);\n\t\tif (snapshot === undefined) return;\n\t\ttry {\n\t\t\tawait this.inner.create(snapshot.header, snapshot.entries);\n\t\t} catch (error) {\n\t\t\tif (!(error instanceof SessionExistsError)) throw error;\n\t\t}\n\t\tif (await this.isDeleted(sessionId)) await this.inner.delete(sessionId).catch(() => {});\n\t}\n\n\t/** The first readable copy of a legacy session; a damaged duplicate does not hide a readable one. */\n\tprivate async readLegacy(sessionId: string): Promise<SessionSnapshot | undefined> {\n\t\tif (await this.isDeleted(sessionId)) return undefined;\n\t\tfor (const file of (await this.legacyIndex()).get(sessionId) ?? []) {\n\t\t\ttry {\n\t\t\t\tconst snapshot = await file.read();\n\t\t\t\tsummarizeSession(snapshot);\n\t\t\t\treturn snapshot;\n\t\t\t} catch {\n\t\t\t\t// Try the next copy.\n\t\t\t}\n\t\t}\n\t\treturn undefined;\n\t}\n\n\tprivate async findLegacy(sessionId: string): Promise<JsonlSessionFile | undefined> {\n\t\tconst file = (await this.legacyIndex()).get(sessionId)?.[0];\n\t\tif (file === undefined || (await this.isDeleted(sessionId))) return undefined;\n\t\treturn file;\n\t}\n\n\tprivate async *legacyFiles(query: {\n\t\treadonly cwd?: string;\n\t\treadonly includeInternal?: boolean;\n\t}): AsyncIterable<JsonlSessionFile> {\n\t\tconst matchesCwd = query.cwd === undefined ? undefined : createSessionCwdMatcher(query.cwd);\n\t\tfor (const [file] of (await this.legacyIndex()).values()) {\n\t\t\tif (file === undefined) continue;\n\t\t\tif (matchesCwd && !matchesCwd(file.header.cwd)) continue;\n\t\t\tif (!query.includeInternal && file.header.internal) continue;\n\t\t\tif (await this.isDeleted(file.header.id)) continue;\n\t\t\tyield file;\n\t\t}\n\t}\n\n\t/** Header-only index of the legacy directory, read once; nothing writes legacy sessions any more. */\n\tprivate legacyIndex(): Promise<ReadonlyMap<string, readonly JsonlSessionFile[]>> {\n\t\tthis.index ??= (async () => {\n\t\t\tconst files = new Map<string, JsonlSessionFile[]>();\n\t\t\tconst legacy = await this.legacyStore();\n\t\t\tif (legacy === undefined) return files;\n\t\t\ttry {\n\t\t\t\tfor await (const file of legacy.scanFiles()) {\n\t\t\t\t\tconst copies = files.get(file.header.id);\n\t\t\t\t\tif (copies) copies.push(file);\n\t\t\t\t\telse files.set(file.header.id, [file]);\n\t\t\t\t}\n\t\t\t} catch {\n\t\t\t\t// An unreadable legacy directory leaves only the sessions already in the database.\n\t\t\t}\n\t\t\treturn files;\n\t\t})();\n\t\treturn this.index;\n\t}\n\n\t/**\n\t * Listing rows are cached per store until a copy of the session changes on disk. A row is built\n\t * from bounded reads, not a full parse, so listing does not cost the size of the history.\n\t */\n\tprivate async summarize(sessionId: string): Promise<SessionSummary | undefined> {\n\t\tconst copies = await Promise.all(\n\t\t\t((await this.legacyIndex()).get(sessionId) ?? []).map(async (file) => ({\n\t\t\t\tfile,\n\t\t\t\tstats: await stat(file.location).catch(() => undefined),\n\t\t\t})),\n\t\t);\n\t\tconst stamp = copies\n\t\t\t.map(({ stats }) => (stats === undefined ? \"missing\" : `${stats.size}:${stats.mtimeMs}`))\n\t\t\t.join(\"|\");\n\t\tconst cached = this.summaries.get(sessionId);\n\t\tif (cached !== undefined && cached.stamp === stamp) return cached.summary ?? undefined;\n\t\tlet summary: SessionSummary | null = null;\n\t\tfor (const { file, stats } of copies) {\n\t\t\tif (stats === undefined) continue;\n\t\t\ttry {\n\t\t\t\tsummary = await summarizeLegacySession(file, stats.size, stats.mtimeMs);\n\t\t\t\tbreak;\n\t\t\t} catch {\n\t\t\t\t// Try the next copy.\n\t\t\t}\n\t\t}\n\t\tthis.summaries.set(sessionId, { stamp, summary });\n\t\treturn summary ?? undefined;\n\t}\n\n\tprivate legacyStore(): Promise<JsonlSessionStore | undefined> {\n\t\tthis.legacy ??= existsSync(this.legacyDirectory)\n\t\t\t? JsonlSessionStore.open(this.legacyDirectory, { scanExisting: false }).catch(() => undefined)\n\t\t\t: Promise.resolve(undefined);\n\t\treturn this.legacy;\n\t}\n\n\tprivate deletionDatabase(): Promise<SqliteDatabase> {\n\t\tthis.deletions ??= openNodeSqliteDatabase(this.databasePath).then(async (database) => {\n\t\t\tawait database.exec(\n\t\t\t\t`CREATE TABLE IF NOT EXISTS ${DELETED_TABLE}(id TEXT PRIMARY KEY, deleted_at INTEGER NOT NULL)`,\n\t\t\t);\n\t\t\treturn database;\n\t\t});\n\t\treturn this.deletions;\n\t}\n\n\tprivate async isDeleted(sessionId: string): Promise<boolean> {\n\t\tconst database = await this.deletionDatabase();\n\t\treturn (await database.get(`SELECT id FROM ${DELETED_TABLE} WHERE id = ?`, sessionId)) !== undefined;\n\t}\n\n\tprivate async markDeleted(sessionId: string): Promise<void> {\n\t\tconst database = await this.deletionDatabase();\n\t\tawait database.run(`INSERT OR IGNORE INTO ${DELETED_TABLE} VALUES (?, ?)`, sessionId, Date.now());\n\t}\n}\n"]}
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
import type { JsonlSessionFile } from "./jsonl-session-store.js";
|
|
2
|
+
import type { SessionSummary } from "./types.js";
|
|
3
|
+
/**
|
|
4
|
+
* Summarizes an unconverted legacy session without parsing all of it. A session larger than the
|
|
5
|
+
* window is described by its header, the lines up to its first user message, and the lines in its
|
|
6
|
+
* last window. Names, summaries and search text written in between are not seen, and the message
|
|
7
|
+
* count is a lower bound; opening the session converts it in full. A line in either end that
|
|
8
|
+
* cannot be parsed marks the copy as damaged, as it would for a full read.
|
|
9
|
+
*/
|
|
10
|
+
export declare function summarizeLegacySession(file: JsonlSessionFile, size: number, modifiedMs: number): Promise<SessionSummary>;
|
|
11
|
+
//# sourceMappingURL=legacy-session-summary.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"legacy-session-summary.d.ts","sourceRoot":"","sources":["../../../../src/core/storage/session/legacy-session-summary.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,0BAA0B,CAAC;AAOjE,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,YAAY,CAAC;AA4EjD;;;;;;GAMG;AACH,wBAAsB,sBAAsB,CAC3C,IAAI,EAAE,gBAAgB,EACtB,IAAI,EAAE,MAAM,EACZ,UAAU,EAAE,MAAM,GAChB,OAAO,CAAC,cAAc,CAAC,CAazB"}
|
|
@@ -0,0 +1,103 @@
|
|
|
1
|
+
import { open } from "node:fs/promises";
|
|
2
|
+
import { applySessionSummaryEntries, materializeSessionSummaryMetadata, summarizeSession, } from "./session-summary.js";
|
|
3
|
+
/** A session this size or smaller is read whole; a larger one is read from its two ends only. */
|
|
4
|
+
const SUMMARY_WINDOW_BYTES = 32 * 1024;
|
|
5
|
+
/** How far into a large session to look for its first user message before reading it whole. */
|
|
6
|
+
const HEAD_SCAN_LIMIT_BYTES = 256 * 1024;
|
|
7
|
+
const HEAD_CHUNK_BYTES = 16 * 1024;
|
|
8
|
+
const NEWLINE = 10;
|
|
9
|
+
function applyLine(scan, line) {
|
|
10
|
+
if (!line.trim())
|
|
11
|
+
return;
|
|
12
|
+
const { state, texts } = applySessionSummaryEntries(scan.state, [JSON.parse(line)]);
|
|
13
|
+
scan.state = state;
|
|
14
|
+
for (const { text } of texts)
|
|
15
|
+
scan.texts.push(text);
|
|
16
|
+
}
|
|
17
|
+
/** Reads entries up to the first user message; returns the offset after the last line consumed. */
|
|
18
|
+
async function scanHead(handle, scan) {
|
|
19
|
+
const chunk = Buffer.alloc(HEAD_CHUNK_BYTES);
|
|
20
|
+
let pending = Buffer.alloc(0);
|
|
21
|
+
let offset = 0;
|
|
22
|
+
let end = 0;
|
|
23
|
+
let header = true;
|
|
24
|
+
while (offset < HEAD_SCAN_LIMIT_BYTES) {
|
|
25
|
+
const { bytesRead } = await handle.read(chunk, 0, chunk.length, offset);
|
|
26
|
+
if (bytesRead === 0) {
|
|
27
|
+
if (pending.length > 0)
|
|
28
|
+
applyLine(scan, pending.toString("utf8"));
|
|
29
|
+
return { end: end + pending.length, complete: true };
|
|
30
|
+
}
|
|
31
|
+
offset += bytesRead;
|
|
32
|
+
pending = Buffer.concat([pending, chunk.subarray(0, bytesRead)]);
|
|
33
|
+
for (let newline = pending.indexOf(NEWLINE); newline !== -1; newline = pending.indexOf(NEWLINE)) {
|
|
34
|
+
const line = pending.subarray(0, newline).toString("utf8");
|
|
35
|
+
pending = pending.subarray(newline + 1);
|
|
36
|
+
end += newline + 1;
|
|
37
|
+
if (header)
|
|
38
|
+
header = false;
|
|
39
|
+
else
|
|
40
|
+
applyLine(scan, line);
|
|
41
|
+
if (scan.state.firstMessage)
|
|
42
|
+
return { end, complete: true };
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
return { end, complete: false };
|
|
46
|
+
}
|
|
47
|
+
/**
|
|
48
|
+
* Reads the last window of the file, from the first whole line in it, never re-reading the head.
|
|
49
|
+
* Returns false when the window skips part of the file and holds no complete message, so the
|
|
50
|
+
* latest message time is unknown and the caller must read the session whole.
|
|
51
|
+
*/
|
|
52
|
+
async function scanTail(handle, size, headEnd, scan) {
|
|
53
|
+
const start = Math.max(size - SUMMARY_WINDOW_BYTES, headEnd);
|
|
54
|
+
if (start >= size)
|
|
55
|
+
return true;
|
|
56
|
+
const skipsMiddle = start > headEnd;
|
|
57
|
+
const bytes = Buffer.alloc(size - start + 1);
|
|
58
|
+
let filled = 0;
|
|
59
|
+
while (filled < bytes.length) {
|
|
60
|
+
const { bytesRead } = await handle.read(bytes, filled, bytes.length - filled, start - 1 + filled);
|
|
61
|
+
if (bytesRead === 0)
|
|
62
|
+
break;
|
|
63
|
+
filled += bytesRead;
|
|
64
|
+
}
|
|
65
|
+
let from = 1;
|
|
66
|
+
if (bytes[0] !== NEWLINE) {
|
|
67
|
+
const newline = bytes.subarray(0, filled).indexOf(NEWLINE, 1);
|
|
68
|
+
if (newline === -1)
|
|
69
|
+
return !skipsMiddle;
|
|
70
|
+
from = newline + 1;
|
|
71
|
+
}
|
|
72
|
+
if (skipsMiddle)
|
|
73
|
+
scan.state = { ...scan.state, latestMessageTime: null };
|
|
74
|
+
for (const line of bytes.subarray(from, filled).toString("utf8").split("\n"))
|
|
75
|
+
applyLine(scan, line);
|
|
76
|
+
return !skipsMiddle || scan.state.latestMessageTime !== null;
|
|
77
|
+
}
|
|
78
|
+
/**
|
|
79
|
+
* Summarizes an unconverted legacy session without parsing all of it. A session larger than the
|
|
80
|
+
* window is described by its header, the lines up to its first user message, and the lines in its
|
|
81
|
+
* last window. Names, summaries and search text written in between are not seen, and the message
|
|
82
|
+
* count is a lower bound; opening the session converts it in full. A line in either end that
|
|
83
|
+
* cannot be parsed marks the copy as damaged, as it would for a full read.
|
|
84
|
+
*/
|
|
85
|
+
export async function summarizeLegacySession(file, size, modifiedMs) {
|
|
86
|
+
if (size <= SUMMARY_WINDOW_BYTES)
|
|
87
|
+
return summarizeSession(await file.read());
|
|
88
|
+
const scan = { state: applySessionSummaryEntries(undefined, []).state, texts: [] };
|
|
89
|
+
const handle = await open(file.location, "r");
|
|
90
|
+
try {
|
|
91
|
+
const head = await scanHead(handle, scan);
|
|
92
|
+
if (!head.complete)
|
|
93
|
+
return summarizeSession(await file.read());
|
|
94
|
+
if (!(await scanTail(handle, size, head.end, scan)))
|
|
95
|
+
return summarizeSession(await file.read());
|
|
96
|
+
}
|
|
97
|
+
finally {
|
|
98
|
+
await handle.close();
|
|
99
|
+
}
|
|
100
|
+
const state = { ...scan.state, latestMessageTime: scan.state.latestMessageTime ?? modifiedMs };
|
|
101
|
+
return { ...materializeSessionSummaryMetadata(file.header, state), searchText: scan.texts.join(" ") };
|
|
102
|
+
}
|
|
103
|
+
//# sourceMappingURL=legacy-session-summary.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"legacy-session-summary.js","sourceRoot":"","sources":["../../../../src/core/storage/session/legacy-session-summary.ts"],"names":[],"mappings":"AAAA,OAAO,EAAmB,IAAI,EAAE,MAAM,kBAAkB,CAAC;AAGzD,OAAO,EACN,0BAA0B,EAC1B,iCAAiC,EAEjC,gBAAgB,GAChB,MAAM,sBAAsB,CAAC;AAG9B,iGAAiG;AACjG,MAAM,oBAAoB,GAAG,EAAE,GAAG,IAAI,CAAC;AAEvC,+FAA+F;AAC/F,MAAM,qBAAqB,GAAG,GAAG,GAAG,IAAI,CAAC;AACzC,MAAM,gBAAgB,GAAG,EAAE,GAAG,IAAI,CAAC;AACnC,MAAM,OAAO,GAAG,EAAE,CAAC;AAOnB,SAAS,SAAS,CAAC,IAAU,EAAE,IAAY;IAC1C,IAAI,CAAC,IAAI,CAAC,IAAI,EAAE;QAAE,OAAO;IACzB,MAAM,EAAE,KAAK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AAG,MAAM,IAAI,CAAC,IAAI,CAAC,QAAQ,EAAE,GAAG,CAAC,CAAC;IAC9C,IAAI,CAAC;QACJ,MAAM,IAAI,GAAG,MAAM,QAAQ,CAAC,MAAM,EAAE,IAAI,CAAC,CAAC;QAC1C,IAAI,CAAC,IAAI,CAAC,QAAQ;YAAE,OAAO,gBAAgB,CAAC,MAAM,IAAI,CAAC,IAAI,EAAE,CAAC,CAAC;QAC/D,IAAI,CAAC,CAAC,MAAM,QAAQ,CAAC,MAAM,EAAE,IAAI,EAAE,IAAI,CAAC,GAAG,EAAE,IAAI,CAAC,CAAC;YAAE,OAAO,gBAAgB,CAAC,MAAM,IAAI,CAAC,IAAI,EAAE,CAAC,CAAC;IACjG,CAAC;YAAS,CAAC;QACV,MAAM,MAAM,CAAC,KAAK,EAAE,CAAC;IACtB,CAAC;IACD,MAAM,KAAK,GAAG,EAAE,GAAG,IAAI,CAAC,KAAK,EAAE,iBAAiB,EAAE,IAAI,CAAC,KAAK,CAAC,iBAAiB,IAAI,UAAU,EAAE,CAAC;IAC/F,OAAO,EAAE,GAAG,iCAAiC,CAAC,IAAI,CAAC,MAAM,EAAE,KAAK,CAAC,EAAE,UAAU,EAAE,IAAI,CAAC,KAAK,CAAC,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC;AACvG,CAAC","sourcesContent":["import { type FileHandle, open } from \"node:fs/promises\";\nimport type { SessionEntry } from \"../../session-manager-types.ts\";\nimport type { JsonlSessionFile } from \"./jsonl-session-store.js\";\nimport {\n\tapplySessionSummaryEntries,\n\tmaterializeSessionSummaryMetadata,\n\ttype SessionSummaryState,\n\tsummarizeSession,\n} from \"./session-summary.js\";\nimport type { SessionSummary } from \"./types.js\";\n\n/** A session this size or smaller is read whole; a larger one is read from its two ends only. */\nconst SUMMARY_WINDOW_BYTES = 32 * 1024;\n\n/** How far into a large session to look for its first user message before reading it whole. */\nconst HEAD_SCAN_LIMIT_BYTES = 256 * 1024;\nconst HEAD_CHUNK_BYTES = 16 * 1024;\nconst NEWLINE = 10;\n\ninterface Scan {\n\tstate: SessionSummaryState;\n\ttexts: string[];\n}\n\nfunction applyLine(scan: Scan, line: string): void {\n\tif (!line.trim()) return;\n\tconst { state, texts } = applySessionSummaryEntries(scan.state, [JSON.parse(line) as SessionEntry]);\n\tscan.state = state;\n\tfor (const { text } of texts) scan.texts.push(text);\n}\n\n/** Reads entries up to the first user message; returns the offset after the last line consumed. */\nasync function scanHead(handle: FileHandle, scan: Scan): Promise<{ end: number; complete: boolean }> {\n\tconst chunk = Buffer.alloc(HEAD_CHUNK_BYTES);\n\tlet pending = Buffer.alloc(0);\n\tlet offset = 0;\n\tlet end = 0;\n\tlet header = true;\n\twhile (offset < HEAD_SCAN_LIMIT_BYTES) {\n\t\tconst { bytesRead } = await handle.read(chunk, 0, chunk.length, offset);\n\t\tif (bytesRead === 0) {\n\t\t\tif (pending.length > 0) applyLine(scan, pending.toString(\"utf8\"));\n\t\t\treturn { end: end + pending.length, complete: true };\n\t\t}\n\t\toffset += bytesRead;\n\t\tpending = Buffer.concat([pending, chunk.subarray(0, bytesRead)]);\n\t\tfor (let newline = pending.indexOf(NEWLINE); newline !== -1; newline = pending.indexOf(NEWLINE)) {\n\t\t\tconst line = pending.subarray(0, newline).toString(\"utf8\");\n\t\t\tpending = pending.subarray(newline + 1);\n\t\t\tend += newline + 1;\n\t\t\tif (header) header = false;\n\t\t\telse applyLine(scan, line);\n\t\t\tif (scan.state.firstMessage) return { end, complete: true };\n\t\t}\n\t}\n\treturn { end, complete: false };\n}\n\n/**\n * Reads the last window of the file, from the first whole line in it, never re-reading the head.\n * Returns false when the window skips part of the file and holds no complete message, so the\n * latest message time is unknown and the caller must read the session whole.\n */\nasync function scanTail(handle: FileHandle, size: number, headEnd: number, scan: Scan): Promise<boolean> {\n\tconst start = Math.max(size - SUMMARY_WINDOW_BYTES, headEnd);\n\tif (start >= size) return true;\n\tconst skipsMiddle = start > headEnd;\n\tconst bytes = Buffer.alloc(size - start + 1);\n\tlet filled = 0;\n\twhile (filled < bytes.length) {\n\t\tconst { bytesRead } = await handle.read(bytes, filled, bytes.length - filled, start - 1 + filled);\n\t\tif (bytesRead === 0) break;\n\t\tfilled += bytesRead;\n\t}\n\tlet from = 1;\n\tif (bytes[0] !== NEWLINE) {\n\t\tconst newline = bytes.subarray(0, filled).indexOf(NEWLINE, 1);\n\t\tif (newline === -1) return !skipsMiddle;\n\t\tfrom = newline + 1;\n\t}\n\tif (skipsMiddle) scan.state = { ...scan.state, latestMessageTime: null };\n\tfor (const line of bytes.subarray(from, filled).toString(\"utf8\").split(\"\\n\")) applyLine(scan, line);\n\treturn !skipsMiddle || scan.state.latestMessageTime !== null;\n}\n\n/**\n * Summarizes an unconverted legacy session without parsing all of it. A session larger than the\n * window is described by its header, the lines up to its first user message, and the lines in its\n * last window. Names, summaries and search text written in between are not seen, and the message\n * count is a lower bound; opening the session converts it in full. A line in either end that\n * cannot be parsed marks the copy as damaged, as it would for a full read.\n */\nexport async function summarizeLegacySession(\n\tfile: JsonlSessionFile,\n\tsize: number,\n\tmodifiedMs: number,\n): Promise<SessionSummary> {\n\tif (size <= SUMMARY_WINDOW_BYTES) return summarizeSession(await file.read());\n\tconst scan: Scan = { state: applySessionSummaryEntries(undefined, []).state, texts: [] };\n\tconst handle = await open(file.location, \"r\");\n\ttry {\n\t\tconst head = await scanHead(handle, scan);\n\t\tif (!head.complete) return summarizeSession(await file.read());\n\t\tif (!(await scanTail(handle, size, head.end, scan))) return summarizeSession(await file.read());\n\t} finally {\n\t\tawait handle.close();\n\t}\n\tconst state = { ...scan.state, latestMessageTime: scan.state.latestMessageTime ?? modifiedMs };\n\treturn { ...materializeSessionSummaryMetadata(file.header, state), searchText: scan.texts.join(\" \") };\n}\n"]}
|
|
@@ -278,13 +278,14 @@ export class StreamableHttpTransport extends TransportEvents {
|
|
|
278
278
|
await consumeSseStream(stream, {
|
|
279
279
|
maxEventBytes: this.options.maxMessageBytes ?? DEFAULT_MAX_MESSAGE_BYTES,
|
|
280
280
|
onId: (id) => {
|
|
281
|
+
if (id !== cursor.lastEventId)
|
|
282
|
+
cursor.advanced = true;
|
|
281
283
|
cursor.lastEventId = id;
|
|
282
284
|
},
|
|
283
285
|
onRetry: (delayMs) => {
|
|
284
286
|
cursor.retryMs = delayMs;
|
|
285
287
|
},
|
|
286
288
|
onEvent: (event) => {
|
|
287
|
-
cursor.received = true;
|
|
288
289
|
// Events without data prime resumption; other event types are not JSON-RPC.
|
|
289
290
|
if (!event.data.trim() || (event.event !== undefined && event.event !== "message"))
|
|
290
291
|
return;
|
|
@@ -307,7 +308,7 @@ export class StreamableHttpTransport extends TransportEvents {
|
|
|
307
308
|
* server may close response streams at will. Otherwise only this request fails.
|
|
308
309
|
*/
|
|
309
310
|
async consumeResponseStream(body, requestId) {
|
|
310
|
-
const cursor = { lastEventId: undefined, retryMs: undefined,
|
|
311
|
+
const cursor = { lastEventId: undefined, retryMs: undefined, advanced: false };
|
|
311
312
|
let answered = false;
|
|
312
313
|
const onMessage = (message) => {
|
|
313
314
|
if (isJsonRpcResponse(message) && message.id === requestId)
|
|
@@ -331,9 +332,9 @@ export class StreamableHttpTransport extends TransportEvents {
|
|
|
331
332
|
break;
|
|
332
333
|
if (cursor.lastEventId === undefined || attempt >= this.maxRetries())
|
|
333
334
|
break;
|
|
334
|
-
if (cursor.
|
|
335
|
+
if (cursor.advanced)
|
|
335
336
|
attempt = 0;
|
|
336
|
-
cursor.
|
|
337
|
+
cursor.advanced = false;
|
|
337
338
|
if (!(await this.sleep(this.reconnectDelay(attempt++, cursor.retryMs))))
|
|
338
339
|
return;
|
|
339
340
|
try {
|
|
@@ -363,7 +364,7 @@ export class StreamableHttpTransport extends TransportEvents {
|
|
|
363
364
|
}
|
|
364
365
|
/** Keep the server-to-client stream open, reconnecting with backoff when it drops. */
|
|
365
366
|
async runGetStream() {
|
|
366
|
-
const cursor = { lastEventId: undefined, retryMs: undefined,
|
|
367
|
+
const cursor = { lastEventId: undefined, retryMs: undefined, advanced: false };
|
|
367
368
|
for (let attempt = 0; !this.closed;) {
|
|
368
369
|
try {
|
|
369
370
|
const stream = await this.openSseStream(cursor.lastEventId);
|
|
@@ -372,8 +373,8 @@ export class StreamableHttpTransport extends TransportEvents {
|
|
|
372
373
|
return;
|
|
373
374
|
const openedAt = Date.now();
|
|
374
375
|
await this.consumeSse(stream, cursor);
|
|
375
|
-
//
|
|
376
|
-
if (cursor.
|
|
376
|
+
// Resumable progress, or a stream that stayed up for a while, counts as healthy.
|
|
377
|
+
if (cursor.advanced || Date.now() - openedAt > this.maxDelay())
|
|
377
378
|
attempt = 0;
|
|
378
379
|
}
|
|
379
380
|
catch (error) {
|
|
@@ -384,7 +385,7 @@ export class StreamableHttpTransport extends TransportEvents {
|
|
|
384
385
|
return;
|
|
385
386
|
}
|
|
386
387
|
}
|
|
387
|
-
cursor.
|
|
388
|
+
cursor.advanced = false;
|
|
388
389
|
if (attempt >= this.maxRetries()) {
|
|
389
390
|
this.emitError(new Error("MCP server-to-client stream dropped and could not be reopened"));
|
|
390
391
|
return;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"streamable-http.js","sourceRoot":"","sources":["../../../../../src/extensions/mcp/client/transports/streamable-http.ts"],"names":[],"mappings":"AACA,OAAO,EACN,gBAAgB,EAChB,iBAAiB,EACjB,oBAAoB,EAGpB,aAAa,EACb,wBAAwB,EACxB,mBAAmB,EACnB,OAAO,GACP,MAAM,wBAAwB,CAAC;AAChC,OAAO,EACN,yBAAyB,EAGzB,eAAe,GACf,MAAM,gBAAgB,CAAC;AAExB,MAAM,oBAAoB,GAAG,CAAC,GAAG,IAAI,CAAC;AACtC,MAAM,wBAAwB,GAAG,GAAG,CAAC;AACrC,MAAM,kCAAkC,GAAG,KAAK,CAAC;AACjD,MAAM,8BAA8B,GAAG,MAAM,CAAC;AAC9C,MAAM,6BAA6B,GAAG,CAAC,CAAC;AAiBxC,MAAM,CAAC,KAAK,UAAU,gBAAgB,CAAC,MAAkC,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GAAG,EAAE;gBACpB,YAAY,CAAC,KAAK,CAAC,CAAC;gBACpB,OAAO,CAAC,KAAK,CAAC,CAAC;YAChB,CAAC,CAAC;YACF,MAAM,KAAK,GAAG,UAAU,CAAC,GAAG,EAAE;gBAC7B,MAAM,CAAC,mBAAmB,CAAC,OAAO,EAAE,OAAO,CAAC,CAAC;gBAC7C,OAAO,CAAC,IAAI,CAAC,CAAC;YACf,CAAC,EAAE,EAAE,CAAC,CAAC;YACP,0DAA0D;YAC1D,KAAK,CAAC,KAAK,EAAE,EAAE,CAAC;YAChB,MAAM,CAAC,gBAAgB,CAAC,OAAO,EAAE,OAAO,EAAE,EAAE,IAAI,EAAE,IAAI,EAAE,CAAC,CAAC;QAC3D,CAAC,CAAC,CAAC;IACJ,CAAC;CACD","sourcesContent":["import type { AuthProvider, McpFetch } from \"../auth-provider.js\";\nimport {\n\tisJsonRpcRequest,\n\tisJsonRpcResponse,\n\tJSON_RPC_ERROR_CODES,\n\ttype JsonRpcId,\n\ttype JsonRpcMessage,\n\tMcpAbortError,\n\tMcpConnectionClosedError,\n\tparseJsonRpcMessage,\n\ttoError,\n} from \"../protocol/jsonrpc.js\";\nimport {\n\tDEFAULT_MAX_MESSAGE_BYTES,\n\ttype McpTransport,\n\ttype McpTransportSendOptions,\n\tTransportEvents,\n} from \"./transport.js\";\n\nconst MAX_ERROR_BODY_BYTES = 8 * 1024;\nconst ERROR_MESSAGE_BODY_CHARS = 500;\nconst DEFAULT_RECONNECT_INITIAL_DELAY_MS = 1_000;\nconst DEFAULT_RECONNECT_MAX_DELAY_MS = 30_000;\nconst DEFAULT_RECONNECT_MAX_RETRIES = 5;\n\nexport interface SseEvent {\n\tevent?: string;\n\tdata: string;\n\tid?: string;\n}\n\nexport interface ConsumeSseOptions {\n\tmaxEventBytes?: number;\n\tonEvent(event: SseEvent): void;\n\t/** Called for every `id` field, including events without data (for example resumption priming events). */\n\tonId?(id: string): void;\n\t/** Called for every valid `retry` field, in milliseconds. */\n\tonRetry?(delayMs: number): void;\n}\n\nexport async function consumeSseStream(stream: ReadableStream<Uint8Array>, options: ConsumeSseOptions): Promise<void> {\n\tconst reader = stream.getReader();\n\tconst decoder = new TextDecoder();\n\tlet buffered = \"\";\n\tlet eventName: string | undefined;\n\tlet eventId: string | undefined;\n\tlet dataLines: string[] = [];\n\t// Bytes of the pending event's data, including the \"\\n\" joins, so events streamed as many\n\t// short `data:` lines without a terminating blank line cannot grow without bound.\n\tlet dataBytes = 0;\n\tconst maxEventBytes = options.maxEventBytes ?? DEFAULT_MAX_MESSAGE_BYTES;\n\n\tconst dispatch = () => {\n\t\tif (dataLines.length === 0) {\n\t\t\teventName = undefined;\n\t\t\teventId = undefined;\n\t\t\treturn;\n\t\t}\n\t\tconst data = dataLines.join(\"\\n\");\n\t\toptions.onEvent({ ...(eventName ? { event: eventName } : {}), data, ...(eventId ? { id: eventId } : {}) });\n\t\teventName = undefined;\n\t\teventId = undefined;\n\t\tdataLines = [];\n\t\tdataBytes = 0;\n\t};\n\n\tconst processLine = (rawLine: string) => {\n\t\tconst line = rawLine.endsWith(\"\\r\") ? rawLine.slice(0, -1) : rawLine;\n\t\tif (line === \"\") {\n\t\t\tdispatch();\n\t\t\treturn;\n\t\t}\n\t\tif (line.startsWith(\":\")) return;\n\t\tconst colon = line.indexOf(\":\");\n\t\tconst field = colon < 0 ? line : line.slice(0, colon);\n\t\tlet value = colon < 0 ? \"\" : line.slice(colon + 1);\n\t\tif (value.startsWith(\" \")) value = value.slice(1);\n\t\tif (field === \"data\") {\n\t\t\tdataBytes += Buffer.byteLength(value) + (dataLines.length > 0 ? 1 : 0);\n\t\t\tif (dataBytes > maxEventBytes) throw new Error(`MCP SSE event exceeds ${maxEventBytes} bytes`);\n\t\t\tdataLines.push(value);\n\t\t} else if (field === \"event\") eventName = value;\n\t\telse if (field === \"id\" && !value.includes(\"\\0\")) {\n\t\t\teventId = value;\n\t\t\toptions.onId?.(value);\n\t\t} else if (field === \"retry\" && /^\\d+$/.test(value)) options.onRetry?.(Number(value));\n\t};\n\n\ttry {\n\t\twhile (true) {\n\t\t\tconst { done, value } = await reader.read();\n\t\t\tif (done) break;\n\t\t\tbuffered += decoder.decode(value, { stream: true });\n\t\t\tlet newline = buffered.indexOf(\"\\n\");\n\t\t\twhile (newline >= 0) {\n\t\t\t\tprocessLine(buffered.slice(0, newline));\n\t\t\t\tbuffered = buffered.slice(newline + 1);\n\t\t\t\tnewline = buffered.indexOf(\"\\n\");\n\t\t\t}\n\t\t\tif (Buffer.byteLength(buffered) > maxEventBytes)\n\t\t\t\tthrow new Error(`MCP SSE event exceeds ${maxEventBytes} bytes`);\n\t\t}\n\t\tbuffered += decoder.decode();\n\t\tif (buffered) processLine(buffered);\n\t\tdispatch();\n\t} finally {\n\t\treader.releaseLock();\n\t}\n}\n\nexport interface StreamableHttpReconnectOptions {\n\t/** Delay before the first reconnection attempt, unless the server sent a `retry` field. Default: 1000. */\n\tinitialDelayMs?: number;\n\t/** Upper bound for the exponential backoff. Default: 30000. */\n\tmaxDelayMs?: number;\n\t/** Consecutive failed attempts before giving up on a stream. Default: 5. */\n\tmaxRetries?: number;\n}\n\nexport interface StreamableHttpTransportOptions {\n\turl: string | URL;\n\theaders?: Record<string, string>;\n\tfetch?: McpFetch;\n\t/** Open the server-to-client GET stream after initialization. Default: true. */\n\topenGetStream?: boolean;\n\tmaxMessageBytes?: number;\n\tauthProvider?: AuthProvider;\n\t/** Reconnection of dropped SSE streams (the GET stream, and response streams that carry event IDs). */\n\treconnect?: StreamableHttpReconnectOptions;\n}\n\nexport class McpHttpError extends Error {\n\treadonly status: number;\n\treadonly body: string;\n\n\tconstructor(status: number, message: string, body = \"\") {\n\t\tsuper(message);\n\t\tthis.name = \"McpHttpError\";\n\t\tthis.status = status;\n\t\tthis.body = body;\n\t}\n}\n\nexport class McpAuthRequiredError extends McpHttpError {\n\treadonly wwwAuthenticate: string | null;\n\n\tconstructor(response: Response, body = \"\") {\n\t\tsuper(401, \"MCP server requires authentication\", body);\n\t\tthis.name = \"McpAuthRequiredError\";\n\t\tthis.wwwAuthenticate = response.headers.get(\"www-authenticate\");\n\t}\n}\n\nexport class McpSessionExpiredError extends McpHttpError {\n\tconstructor(body = \"\") {\n\t\tsuper(404, \"MCP session expired\", body);\n\t\tthis.name = \"McpSessionExpiredError\";\n\t}\n}\n\nfunction contentType(response: Response): string | undefined {\n\treturn response.headers.get(\"content-type\")?.split(\";\", 1)[0]?.trim().toLowerCase();\n}\n\n/** 401, or 403 with an `insufficient_scope` bearer challenge (step-up authorization). */\nfunction needsAuthorization(response: Response): boolean {\n\tif (response.status === 401) return true;\n\tif (response.status !== 403) return false;\n\treturn /(?:^|[\\s,])error=\"?insufficient_scope\"?/i.test(response.headers.get(\"www-authenticate\") ?? \"\");\n}\n\n/** Statuses worth retrying when a stream fails to (re)open. */\nfunction isTransientStatus(status: number): boolean {\n\treturn status === 408 || status === 429 || status >= 500;\n}\n\nfunction discard(response: Response): Promise<void> {\n\treturn response.body?.cancel().catch(() => {}) ?? Promise.resolve();\n}\n\nfunction describeHttpFailure(status: number, body: string): string {\n\tconst text = body.trim();\n\tconst snippet = text.length > ERROR_MESSAGE_BODY_CHARS ? `${text.slice(0, ERROR_MESSAGE_BODY_CHARS - 3)}...` : text;\n\treturn `MCP HTTP request failed with status ${status}${snippet ? `: ${snippet}` : \"\"}`;\n}\n\ninterface StreamCursor {\n\tlastEventId: string | undefined;\n\tretryMs: number | undefined;\n\t/** Whether the stream delivered any event since it was (re)opened. */\n\treceived: boolean;\n}\n\nexport class StreamableHttpTransport extends TransportEvents implements McpTransport {\n\treadonly url: URL;\n\treadonly options: Readonly<StreamableHttpTransportOptions>;\n\tprivate fetch: McpFetch;\n\tprivate controller = new AbortController();\n\tprivate started = false;\n\tprivate closed = false;\n\tprivate sessionIdValue: string | undefined;\n\tprivate protocolVersion: string | undefined;\n\tprivate getStreamStarted = false;\n\t/** Access token of the latest request, which `close()` reuses instead of asking the auth provider. */\n\tprivate lastToken: string | undefined;\n\n\tconstructor(options: StreamableHttpTransportOptions) {\n\t\tsuper();\n\t\tthis.options = Object.freeze({ ...options, headers: options.headers ? { ...options.headers } : undefined });\n\t\tthis.url = new URL(options.url);\n\t\tconst fetch = options.fetch ?? globalThis.fetch;\n\t\t// Call fetch without a receiver. `this.fetch(...)` and `context.fetch(...)` would pass the transport or\n\t\t// the auth context as `this`, which Cloudflare Workers reject for the platform fetch (\"Illegal invocation\").\n\t\tthis.fetch = (input, init) => fetch(input, init);\n\t}\n\n\tget sessionId(): string | undefined {\n\t\treturn this.sessionIdValue;\n\t}\n\n\tasync start(): Promise<void> {\n\t\tif (this.started) throw new Error(\"MCP Streamable HTTP transport already started\");\n\t\tif (this.closed) throw new McpConnectionClosedError();\n\t\tthis.started = true;\n\t}\n\n\tsetProtocolVersion(version: string): void {\n\t\tthis.protocolVersion = version;\n\t}\n\n\tasync send(message: JsonRpcMessage, { signal }: McpTransportSendOptions = {}): Promise<void> {\n\t\tif (!this.started || this.closed) throw new McpConnectionClosedError();\n\t\tconst response = await this.authorizedFetch(\n\t\t\t\"POST\",\n\t\t\t{\n\t\t\t\theaders: { accept: \"application/json, text/event-stream\", \"content-type\": \"application/json\" },\n\t\t\t\tbody: JSON.stringify(message),\n\t\t\t},\n\t\t\tsignal,\n\t\t);\n\t\tawait this.checkResponse(response);\n\t\tthis.captureSession(response);\n\n\t\tif (!isJsonRpcRequest(message)) {\n\t\t\t// Notifications and responses are acknowledged with 202 and carry no reply; ignore any body.\n\t\t\tawait discard(response);\n\t\t\t// The server-to-client stream may only open once the session is initialized.\n\t\t\tif (\"method\" in message && message.method === \"notifications/initialized\") this.startGetStream();\n\t\t\treturn;\n\t\t}\n\t\tif (response.status === 202 || response.status === 204) {\n\t\t\tthrow new McpHttpError(response.status, `MCP server accepted request ${message.method} without a response`);\n\t\t}\n\t\tconst type = contentType(response);\n\t\tif (type === \"application/json\") {\n\t\t\tconst body: unknown = await response.json();\n\t\t\tfor (const item of Array.isArray(body) ? body : [body]) this.emitMessage(parseJsonRpcMessage(item));\n\t\t\treturn;\n\t\t}\n\t\tif (type === \"text/event-stream\" && response.body) {\n\t\t\tvoid this.consumeResponseStream(response.body, message.id);\n\t\t\treturn;\n\t\t}\n\t\tawait discard(response);\n\t\tthrow new McpHttpError(response.status, `Unsupported MCP response content type: ${type ?? \"missing\"}`);\n\t}\n\n\tasync close(): Promise<void> {\n\t\tif (this.closed) return;\n\t\tthis.closed = true;\n\t\tthis.controller.abort();\n\t\tif (this.started && this.sessionIdValue) {\n\t\t\t// Best effort: the session expires on the server anyway. The auth provider may refresh tokens\n\t\t\t// over the network, so it is not asked here and closing never waits for a refresh.\n\t\t\ttry {\n\t\t\t\tconst response = await this.fetch(this.url, {\n\t\t\t\t\tmethod: \"DELETE\",\n\t\t\t\t\theaders: this.buildHeaders({}, this.lastToken),\n\t\t\t\t\tsignal: AbortSignal.timeout(1_000),\n\t\t\t\t});\n\t\t\t\tawait discard(response);\n\t\t\t} catch {}\n\t\t}\n\t\tthis.emitClose();\n\t}\n\n\t/**\n\t * Fetch with auth headers. A 401 (or a 403 asking for more scope) is handed to the auth provider\n\t * once, and the request is retried with whatever credentials it left behind.\n\t */\n\tprivate async authorizedFetch(\n\t\tmethod: \"GET\" | \"POST\",\n\t\tinit: { headers: Record<string, string>; body?: string },\n\t\tsignal?: AbortSignal,\n\t): Promise<Response> {\n\t\tconst onUnauthorized = this.options.authProvider?.onUnauthorized?.bind(this.options.authProvider);\n\t\tfor (let attempt = 0; ; attempt++) {\n\t\t\tconst { headers, token } = await this.headers(init.headers);\n\t\t\tif (signal?.aborted) throw new McpAbortError();\n\t\t\tconst response = await this.fetch(this.url, {\n\t\t\t\tmethod,\n\t\t\t\theaders,\n\t\t\t\tbody: init.body,\n\t\t\t\tsignal: this.controller.signal,\n\t\t\t});\n\t\t\tif (attempt > 0 || !onUnauthorized || !needsAuthorization(response)) return response;\n\t\t\ttry {\n\t\t\t\tawait onUnauthorized({ response, serverUrl: this.url, fetch: this.fetch, token });\n\t\t\t} finally {\n\t\t\t\tawait discard(response);\n\t\t\t}\n\t\t}\n\t}\n\n\tprivate async headers(extra: Record<string, string> = {}): Promise<{ headers: Headers; token?: string }> {\n\t\tconst token = await this.options.authProvider?.token();\n\t\tthis.lastToken = token;\n\t\treturn { headers: this.buildHeaders(extra, token), ...(token ? { token } : {}) };\n\t}\n\n\tprivate buildHeaders(extra: Record<string, string>, token: string | undefined): Headers {\n\t\tconst headers = new Headers(this.options.headers);\n\t\tfor (const [name, value] of Object.entries(extra)) headers.set(name, value);\n\t\tif (this.sessionIdValue) headers.set(\"Mcp-Session-Id\", this.sessionIdValue);\n\t\tif (this.protocolVersion) headers.set(\"MCP-Protocol-Version\", this.protocolVersion);\n\t\tif (token) headers.set(\"Authorization\", `Bearer ${token}`);\n\t\treturn headers;\n\t}\n\n\tprivate captureSession(response: Response): void {\n\t\tconst sessionId = response.headers.get(\"mcp-session-id\");\n\t\tif (sessionId) this.sessionIdValue = sessionId;\n\t}\n\n\tprivate async checkResponse(response: Response): Promise<void> {\n\t\tif (response.ok) return;\n\t\tconst body = (await response.text().catch(() => \"\")).slice(0, MAX_ERROR_BODY_BYTES);\n\t\tif (response.status === 401) throw new McpAuthRequiredError(response, body);\n\t\tif (response.status === 404 && this.sessionIdValue) throw new McpSessionExpiredError(body);\n\t\tthrow new McpHttpError(response.status, describeHttpFailure(response.status, body), body);\n\t}\n\n\tprivate async consumeSse(\n\t\tstream: ReadableStream<Uint8Array>,\n\t\tcursor: StreamCursor,\n\t\tonMessage?: (message: JsonRpcMessage) => void,\n\t): Promise<void> {\n\t\tawait consumeSseStream(stream, {\n\t\t\tmaxEventBytes: this.options.maxMessageBytes ?? DEFAULT_MAX_MESSAGE_BYTES,\n\t\t\tonId: (id) => {\n\t\t\t\tcursor.lastEventId = id;\n\t\t\t},\n\t\t\tonRetry: (delayMs) => {\n\t\t\t\tcursor.retryMs = delayMs;\n\t\t\t},\n\t\t\tonEvent: (event) => {\n\t\t\t\tcursor.received = true;\n\t\t\t\t// Events without data prime resumption; other event types are not JSON-RPC.\n\t\t\t\tif (!event.data.trim() || (event.event !== undefined && event.event !== \"message\")) return;\n\t\t\t\tlet message: JsonRpcMessage;\n\t\t\t\ttry {\n\t\t\t\t\tmessage = parseJsonRpcMessage(JSON.parse(event.data));\n\t\t\t\t} catch (error) {\n\t\t\t\t\tthis.emitError(error);\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tonMessage?.(message);\n\t\t\t\tthis.emitMessage(message);\n\t\t\t},\n\t\t});\n\t}\n\n\t/**\n\t * Read the SSE stream answering one request. When the stream ends or breaks before the response\n\t * arrives and the server assigned event IDs, resume it with GET and `Last-Event-ID`, as the\n\t * server may close response streams at will. Otherwise only this request fails.\n\t */\n\tprivate async consumeResponseStream(body: ReadableStream<Uint8Array>, requestId: JsonRpcId): Promise<void> {\n\t\tconst cursor: StreamCursor = { lastEventId: undefined, retryMs: undefined, received: false };\n\t\tlet answered = false;\n\t\tconst onMessage = (message: JsonRpcMessage) => {\n\t\t\tif (isJsonRpcResponse(message) && message.id === requestId) answered = true;\n\t\t};\n\t\tlet stream: ReadableStream<Uint8Array> | undefined = body;\n\t\tlet failure: unknown;\n\t\tfor (let attempt = 0; ; ) {\n\t\t\tif (stream) {\n\t\t\t\ttry {\n\t\t\t\t\tawait this.consumeSse(stream, cursor, onMessage);\n\t\t\t\t\tfailure = undefined;\n\t\t\t\t} catch (error) {\n\t\t\t\t\tfailure = error;\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (answered || this.closed) return;\n\t\t\tif (failure !== undefined && !this.isRetryable(failure)) break;\n\t\t\tif (cursor.lastEventId === undefined || attempt >= this.maxRetries()) break;\n\t\t\tif (cursor.received) attempt = 0;\n\t\t\tcursor.received = false;\n\t\t\tif (!(await this.sleep(this.reconnectDelay(attempt++, cursor.retryMs)))) return;\n\t\t\ttry {\n\t\t\t\tstream = await this.openSseStream(cursor.lastEventId);\n\t\t\t} catch (error) {\n\t\t\t\tfailure = error;\n\t\t\t\tif (!this.isRetryable(error)) break;\n\t\t\t\tstream = undefined;\n\t\t\t}\n\t\t}\n\t\tif (this.closed) return;\n\t\tconst reason = failure === undefined ? \"stream ended without a response\" : toError(failure).message;\n\t\tthis.emitMessage({\n\t\t\tjsonrpc: \"2.0\",\n\t\t\tid: requestId,\n\t\t\terror: { code: JSON_RPC_ERROR_CODES.internalError, message: `MCP response stream failed: ${reason}` },\n\t\t});\n\t}\n\n\tprivate startGetStream(): void {\n\t\tif (this.options.openGetStream === false || this.getStreamStarted || this.closed) return;\n\t\tthis.getStreamStarted = true;\n\t\tvoid this.runGetStream();\n\t}\n\n\t/** Keep the server-to-client stream open, reconnecting with backoff when it drops. */\n\tprivate async runGetStream(): Promise<void> {\n\t\tconst cursor: StreamCursor = { lastEventId: undefined, retryMs: undefined, received: false };\n\t\tfor (let attempt = 0; !this.closed; ) {\n\t\t\ttry {\n\t\t\t\tconst stream = await this.openSseStream(cursor.lastEventId);\n\t\t\t\t// The server does not offer a GET stream.\n\t\t\t\tif (!stream) return;\n\t\t\t\tconst openedAt = Date.now();\n\t\t\t\tawait this.consumeSse(stream, cursor);\n\t\t\t\t// A stream that stayed up for a while counts as healthy, even if it was idle.\n\t\t\t\tif (cursor.received || Date.now() - openedAt > this.maxDelay()) attempt = 0;\n\t\t\t} catch (error) {\n\t\t\t\tif (this.closed) return;\n\t\t\t\tif (!this.isRetryable(error)) {\n\t\t\t\t\tthis.emitError(error);\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t}\n\t\t\tcursor.received = false;\n\t\t\tif (attempt >= this.maxRetries()) {\n\t\t\t\tthis.emitError(new Error(\"MCP server-to-client stream dropped and could not be reopened\"));\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tif (!(await this.sleep(this.reconnectDelay(attempt++, cursor.retryMs)))) return;\n\t\t}\n\t}\n\n\t/** Open a GET SSE stream. Resolves to undefined when the server answers 405 (no GET stream). */\n\tprivate async openSseStream(lastEventId: string | undefined): Promise<ReadableStream<Uint8Array> | undefined> {\n\t\tconst response = await this.authorizedFetch(\"GET\", {\n\t\t\theaders: {\n\t\t\t\taccept: \"text/event-stream\",\n\t\t\t\t...(lastEventId === undefined ? {} : { \"last-event-id\": lastEventId }),\n\t\t\t},\n\t\t});\n\t\tif (response.status === 405) {\n\t\t\tawait discard(response);\n\t\t\treturn undefined;\n\t\t}\n\t\tawait this.checkResponse(response);\n\t\tthis.captureSession(response);\n\t\tconst type = contentType(response);\n\t\tif (type !== \"text/event-stream\" || !response.body) {\n\t\t\tawait discard(response);\n\t\t\tthrow new McpHttpError(response.status, `Unsupported MCP GET response content type: ${type ?? \"missing\"}`);\n\t\t}\n\t\treturn response.body;\n\t}\n\n\t/**\n\t * Network failures and transient statuses are retried; auth, session, and protocol errors are not.\n\t * `fetch` reports network failures, including a connection dropped mid-body, as `TypeError`.\n\t */\n\tprivate isRetryable(error: unknown): boolean {\n\t\tif (error instanceof McpHttpError) return isTransientStatus(error.status);\n\t\tif (error instanceof TypeError) return true;\n\t\tconst code = (error as { code?: unknown } | undefined)?.code;\n\t\treturn typeof code === \"string\" && (code.startsWith(\"E\") || code.startsWith(\"UND_ERR\"));\n\t}\n\n\tprivate reconnectDelay(attempt: number, serverDelayMs: number | undefined): number {\n\t\tif (serverDelayMs !== undefined) return serverDelayMs;\n\t\tconst initial = this.options.reconnect?.initialDelayMs ?? DEFAULT_RECONNECT_INITIAL_DELAY_MS;\n\t\treturn Math.min(initial * 2 ** attempt, this.maxDelay());\n\t}\n\n\tprivate maxDelay(): number {\n\t\treturn this.options.reconnect?.maxDelayMs ?? DEFAULT_RECONNECT_MAX_DELAY_MS;\n\t}\n\n\tprivate maxRetries(): number {\n\t\treturn this.options.reconnect?.maxRetries ?? DEFAULT_RECONNECT_MAX_RETRIES;\n\t}\n\n\t/** Resolves false when the transport closed while waiting. */\n\tprivate sleep(ms: number): Promise<boolean> {\n\t\tconst signal = this.controller.signal;\n\t\tif (signal.aborted) return Promise.resolve(false);\n\t\treturn new Promise((resolve) => {\n\t\t\tconst onAbort = () => {\n\t\t\t\tclearTimeout(timer);\n\t\t\t\tresolve(false);\n\t\t\t};\n\t\t\tconst timer = setTimeout(() => {\n\t\t\t\tsignal.removeEventListener(\"abort\", onAbort);\n\t\t\t\tresolve(true);\n\t\t\t}, ms);\n\t\t\t// A reconnect wait alone does not keep the process alive.\n\t\t\ttimer.unref?.();\n\t\t\tsignal.addEventListener(\"abort\", onAbort, { once: true });\n\t\t});\n\t}\n}\n"]}
|
|
1
|
+
{"version":3,"file":"streamable-http.js","sourceRoot":"","sources":["../../../../../src/extensions/mcp/client/transports/streamable-http.ts"],"names":[],"mappings":"AACA,OAAO,EACN,gBAAgB,EAChB,iBAAiB,EACjB,oBAAoB,EAGpB,aAAa,EACb,wBAAwB,EACxB,mBAAmB,EACnB,OAAO,GACP,MAAM,wBAAwB,CAAC;AAChC,OAAO,EACN,yBAAyB,EAGzB,eAAe,GACf,MAAM,gBAAgB,CAAC;AAExB,MAAM,oBAAoB,GAAG,CAAC,GAAG,IAAI,CAAC;AACtC,MAAM,wBAAwB,GAAG,GAAG,CAAC;AACrC,MAAM,kCAAkC,GAAG,KAAK,CAAC;AACjD,MAAM,8BAA8B,GAAG,MAAM,CAAC;AAC9C,MAAM,6BAA6B,GAAG,CAAC,CAAC;AAiBxC,MAAM,CAAC,KAAK,UAAU,gBAAgB,CAAC,MAAkC,EAAE,OAA0B;IACpG,MAAM,MAAM,GAAG,MAAM,CAAC,SAAS,EAAE,CAAC;IAClC,MAAM,OAAO,GAAG,IAAI,WAAW,EAAE,CAAC;IAClC,IAAI,QAAQ,GAAG,EAAE,CAAC;IAClB,IAAI,SAA6B,CAAC;IAClC,IAAI,OAA2B,CAAC;IAChC,IAAI,SAAS,GAAa,EAAE,CAAC;IAC7B,0FAA0F;IAC1F,kFAAkF;IAClF,IAAI,SAAS,GAAG,CAAC,CAAC;IAClB,MAAM,aAAa,GAAG,OAAO,CAAC,aAAa,IAAI,y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K,CAAC,KAAK,EAAE,EAAE,CAAC;YAChB,MAAM,CAAC,gBAAgB,CAAC,OAAO,EAAE,OAAO,EAAE,EAAE,IAAI,EAAE,IAAI,EAAE,CAAC,CAAC;QAC3D,CAAC,CAAC,CAAC;IACJ,CAAC;CACD","sourcesContent":["import type { AuthProvider, McpFetch } from \"../auth-provider.js\";\nimport {\n\tisJsonRpcRequest,\n\tisJsonRpcResponse,\n\tJSON_RPC_ERROR_CODES,\n\ttype JsonRpcId,\n\ttype JsonRpcMessage,\n\tMcpAbortError,\n\tMcpConnectionClosedError,\n\tparseJsonRpcMessage,\n\ttoError,\n} from \"../protocol/jsonrpc.js\";\nimport {\n\tDEFAULT_MAX_MESSAGE_BYTES,\n\ttype McpTransport,\n\ttype McpTransportSendOptions,\n\tTransportEvents,\n} from \"./transport.js\";\n\nconst MAX_ERROR_BODY_BYTES = 8 * 1024;\nconst ERROR_MESSAGE_BODY_CHARS = 500;\nconst DEFAULT_RECONNECT_INITIAL_DELAY_MS = 1_000;\nconst DEFAULT_RECONNECT_MAX_DELAY_MS = 30_000;\nconst DEFAULT_RECONNECT_MAX_RETRIES = 5;\n\nexport interface SseEvent {\n\tevent?: string;\n\tdata: string;\n\tid?: string;\n}\n\nexport interface ConsumeSseOptions {\n\tmaxEventBytes?: number;\n\tonEvent(event: SseEvent): void;\n\t/** Called for every `id` field, including events without data (for example resumption priming events). */\n\tonId?(id: string): void;\n\t/** Called for every valid `retry` field, in milliseconds. */\n\tonRetry?(delayMs: number): void;\n}\n\nexport async function consumeSseStream(stream: ReadableStream<Uint8Array>, options: ConsumeSseOptions): Promise<void> {\n\tconst reader = stream.getReader();\n\tconst decoder = new TextDecoder();\n\tlet buffered = \"\";\n\tlet eventName: string | undefined;\n\tlet eventId: string | undefined;\n\tlet dataLines: string[] = [];\n\t// Bytes of the pending event's data, including the \"\\n\" joins, so events streamed as many\n\t// short `data:` lines without a terminating blank line cannot grow without bound.\n\tlet dataBytes = 0;\n\tconst maxEventBytes = options.maxEventBytes ?? DEFAULT_MAX_MESSAGE_BYTES;\n\n\tconst dispatch = () => {\n\t\tif (dataLines.length === 0) {\n\t\t\teventName = undefined;\n\t\t\teventId = undefined;\n\t\t\treturn;\n\t\t}\n\t\tconst data = dataLines.join(\"\\n\");\n\t\toptions.onEvent({ ...(eventName ? { event: eventName } : {}), data, ...(eventId ? { id: eventId } : {}) });\n\t\teventName = undefined;\n\t\teventId = undefined;\n\t\tdataLines = [];\n\t\tdataBytes = 0;\n\t};\n\n\tconst processLine = (rawLine: string) => {\n\t\tconst line = rawLine.endsWith(\"\\r\") ? rawLine.slice(0, -1) : rawLine;\n\t\tif (line === \"\") {\n\t\t\tdispatch();\n\t\t\treturn;\n\t\t}\n\t\tif (line.startsWith(\":\")) return;\n\t\tconst colon = line.indexOf(\":\");\n\t\tconst field = colon < 0 ? line : line.slice(0, colon);\n\t\tlet value = colon < 0 ? \"\" : line.slice(colon + 1);\n\t\tif (value.startsWith(\" \")) value = value.slice(1);\n\t\tif (field === \"data\") {\n\t\t\tdataBytes += Buffer.byteLength(value) + (dataLines.length > 0 ? 1 : 0);\n\t\t\tif (dataBytes > maxEventBytes) throw new Error(`MCP SSE event exceeds ${maxEventBytes} bytes`);\n\t\t\tdataLines.push(value);\n\t\t} else if (field === \"event\") eventName = value;\n\t\telse if (field === \"id\" && !value.includes(\"\\0\")) {\n\t\t\teventId = value;\n\t\t\toptions.onId?.(value);\n\t\t} else if (field === \"retry\" && /^\\d+$/.test(value)) options.onRetry?.(Number(value));\n\t};\n\n\ttry {\n\t\twhile (true) {\n\t\t\tconst { done, value } = await reader.read();\n\t\t\tif (done) break;\n\t\t\tbuffered += decoder.decode(value, { stream: true });\n\t\t\tlet newline = buffered.indexOf(\"\\n\");\n\t\t\twhile (newline >= 0) {\n\t\t\t\tprocessLine(buffered.slice(0, newline));\n\t\t\t\tbuffered = buffered.slice(newline + 1);\n\t\t\t\tnewline = buffered.indexOf(\"\\n\");\n\t\t\t}\n\t\t\tif (Buffer.byteLength(buffered) > maxEventBytes)\n\t\t\t\tthrow new Error(`MCP SSE event exceeds ${maxEventBytes} bytes`);\n\t\t}\n\t\tbuffered += decoder.decode();\n\t\tif (buffered) processLine(buffered);\n\t\tdispatch();\n\t} finally {\n\t\treader.releaseLock();\n\t}\n}\n\nexport interface StreamableHttpReconnectOptions {\n\t/** Delay before the first reconnection attempt, unless the server sent a `retry` field. Default: 1000. */\n\tinitialDelayMs?: number;\n\t/** Upper bound for the exponential backoff. Default: 30000. */\n\tmaxDelayMs?: number;\n\t/** Consecutive failed attempts before giving up on a stream. Default: 5. */\n\tmaxRetries?: number;\n}\n\nexport interface StreamableHttpTransportOptions {\n\turl: string | URL;\n\theaders?: Record<string, string>;\n\tfetch?: McpFetch;\n\t/** Open the server-to-client GET stream after initialization. Default: true. */\n\topenGetStream?: boolean;\n\tmaxMessageBytes?: number;\n\tauthProvider?: AuthProvider;\n\t/** Reconnection of dropped SSE streams (the GET stream, and response streams that carry event IDs). */\n\treconnect?: StreamableHttpReconnectOptions;\n}\n\nexport class McpHttpError extends Error {\n\treadonly status: number;\n\treadonly body: string;\n\n\tconstructor(status: number, message: string, body = \"\") {\n\t\tsuper(message);\n\t\tthis.name = \"McpHttpError\";\n\t\tthis.status = status;\n\t\tthis.body = body;\n\t}\n}\n\nexport class McpAuthRequiredError extends McpHttpError {\n\treadonly wwwAuthenticate: string | null;\n\n\tconstructor(response: Response, body = \"\") {\n\t\tsuper(401, \"MCP server requires authentication\", body);\n\t\tthis.name = \"McpAuthRequiredError\";\n\t\tthis.wwwAuthenticate = response.headers.get(\"www-authenticate\");\n\t}\n}\n\nexport class McpSessionExpiredError extends McpHttpError {\n\tconstructor(body = \"\") {\n\t\tsuper(404, \"MCP session expired\", body);\n\t\tthis.name = \"McpSessionExpiredError\";\n\t}\n}\n\nfunction contentType(response: Response): string | undefined {\n\treturn response.headers.get(\"content-type\")?.split(\";\", 1)[0]?.trim().toLowerCase();\n}\n\n/** 401, or 403 with an `insufficient_scope` bearer challenge (step-up authorization). */\nfunction needsAuthorization(response: Response): boolean {\n\tif (response.status === 401) return true;\n\tif (response.status !== 403) return false;\n\treturn /(?:^|[\\s,])error=\"?insufficient_scope\"?/i.test(response.headers.get(\"www-authenticate\") ?? \"\");\n}\n\n/** Statuses worth retrying when a stream fails to (re)open. */\nfunction isTransientStatus(status: number): boolean {\n\treturn status === 408 || status === 429 || status >= 500;\n}\n\nfunction discard(response: Response): Promise<void> {\n\treturn response.body?.cancel().catch(() => {}) ?? Promise.resolve();\n}\n\nfunction describeHttpFailure(status: number, body: string): string {\n\tconst text = body.trim();\n\tconst snippet = text.length > ERROR_MESSAGE_BODY_CHARS ? `${text.slice(0, ERROR_MESSAGE_BODY_CHARS - 3)}...` : text;\n\treturn `MCP HTTP request failed with status ${status}${snippet ? `: ${snippet}` : \"\"}`;\n}\n\ninterface StreamCursor {\n\tlastEventId: string | undefined;\n\tretryMs: number | undefined;\n\t/** Whether the stream delivered a new resumable event ID since it was (re)opened. */\n\tadvanced: boolean;\n}\n\nexport class StreamableHttpTransport extends TransportEvents implements McpTransport {\n\treadonly url: URL;\n\treadonly options: Readonly<StreamableHttpTransportOptions>;\n\tprivate fetch: McpFetch;\n\tprivate controller = new AbortController();\n\tprivate started = false;\n\tprivate closed = false;\n\tprivate sessionIdValue: string | undefined;\n\tprivate protocolVersion: string | undefined;\n\tprivate getStreamStarted = false;\n\t/** Access token of the latest request, which `close()` reuses instead of asking the auth provider. */\n\tprivate lastToken: string | undefined;\n\n\tconstructor(options: StreamableHttpTransportOptions) {\n\t\tsuper();\n\t\tthis.options = Object.freeze({ ...options, headers: options.headers ? { ...options.headers } : undefined });\n\t\tthis.url = new URL(options.url);\n\t\tconst fetch = options.fetch ?? globalThis.fetch;\n\t\t// Call fetch without a receiver. `this.fetch(...)` and `context.fetch(...)` would pass the transport or\n\t\t// the auth context as `this`, which Cloudflare Workers reject for the platform fetch (\"Illegal invocation\").\n\t\tthis.fetch = (input, init) => fetch(input, init);\n\t}\n\n\tget sessionId(): string | undefined {\n\t\treturn this.sessionIdValue;\n\t}\n\n\tasync start(): Promise<void> {\n\t\tif (this.started) throw new Error(\"MCP Streamable HTTP transport already started\");\n\t\tif (this.closed) throw new McpConnectionClosedError();\n\t\tthis.started = true;\n\t}\n\n\tsetProtocolVersion(version: string): void {\n\t\tthis.protocolVersion = version;\n\t}\n\n\tasync send(message: JsonRpcMessage, { signal }: McpTransportSendOptions = {}): Promise<void> {\n\t\tif (!this.started || this.closed) throw new McpConnectionClosedError();\n\t\tconst response = await this.authorizedFetch(\n\t\t\t\"POST\",\n\t\t\t{\n\t\t\t\theaders: { accept: \"application/json, text/event-stream\", \"content-type\": \"application/json\" },\n\t\t\t\tbody: JSON.stringify(message),\n\t\t\t},\n\t\t\tsignal,\n\t\t);\n\t\tawait this.checkResponse(response);\n\t\tthis.captureSession(response);\n\n\t\tif (!isJsonRpcRequest(message)) {\n\t\t\t// Notifications and responses are acknowledged with 202 and carry no reply; ignore any body.\n\t\t\tawait discard(response);\n\t\t\t// The server-to-client stream may only open once the session is initialized.\n\t\t\tif (\"method\" in message && message.method === \"notifications/initialized\") this.startGetStream();\n\t\t\treturn;\n\t\t}\n\t\tif (response.status === 202 || response.status === 204) {\n\t\t\tthrow new McpHttpError(response.status, `MCP server accepted request ${message.method} without a response`);\n\t\t}\n\t\tconst type = contentType(response);\n\t\tif (type === \"application/json\") {\n\t\t\tconst body: unknown = await response.json();\n\t\t\tfor (const item of Array.isArray(body) ? body : [body]) this.emitMessage(parseJsonRpcMessage(item));\n\t\t\treturn;\n\t\t}\n\t\tif (type === \"text/event-stream\" && response.body) {\n\t\t\tvoid this.consumeResponseStream(response.body, message.id);\n\t\t\treturn;\n\t\t}\n\t\tawait discard(response);\n\t\tthrow new McpHttpError(response.status, `Unsupported MCP response content type: ${type ?? \"missing\"}`);\n\t}\n\n\tasync close(): Promise<void> {\n\t\tif (this.closed) return;\n\t\tthis.closed = true;\n\t\tthis.controller.abort();\n\t\tif (this.started && this.sessionIdValue) {\n\t\t\t// Best effort: the session expires on the server anyway. The auth provider may refresh tokens\n\t\t\t// over the network, so it is not asked here and closing never waits for a refresh.\n\t\t\ttry {\n\t\t\t\tconst response = await this.fetch(this.url, {\n\t\t\t\t\tmethod: \"DELETE\",\n\t\t\t\t\theaders: this.buildHeaders({}, this.lastToken),\n\t\t\t\t\tsignal: AbortSignal.timeout(1_000),\n\t\t\t\t});\n\t\t\t\tawait discard(response);\n\t\t\t} catch {}\n\t\t}\n\t\tthis.emitClose();\n\t}\n\n\t/**\n\t * Fetch with auth headers. A 401 (or a 403 asking for more scope) is handed to the auth provider\n\t * once, and the request is retried with whatever credentials it left behind.\n\t */\n\tprivate async authorizedFetch(\n\t\tmethod: \"GET\" | \"POST\",\n\t\tinit: { headers: Record<string, string>; body?: string },\n\t\tsignal?: AbortSignal,\n\t): Promise<Response> {\n\t\tconst onUnauthorized = this.options.authProvider?.onUnauthorized?.bind(this.options.authProvider);\n\t\tfor (let attempt = 0; ; attempt++) {\n\t\t\tconst { headers, token } = await this.headers(init.headers);\n\t\t\tif (signal?.aborted) throw new McpAbortError();\n\t\t\tconst response = await this.fetch(this.url, {\n\t\t\t\tmethod,\n\t\t\t\theaders,\n\t\t\t\tbody: init.body,\n\t\t\t\tsignal: this.controller.signal,\n\t\t\t});\n\t\t\tif (attempt > 0 || !onUnauthorized || !needsAuthorization(response)) return response;\n\t\t\ttry {\n\t\t\t\tawait onUnauthorized({ response, serverUrl: this.url, fetch: this.fetch, token });\n\t\t\t} finally {\n\t\t\t\tawait discard(response);\n\t\t\t}\n\t\t}\n\t}\n\n\tprivate async headers(extra: Record<string, string> = {}): Promise<{ headers: Headers; token?: string }> {\n\t\tconst token = await this.options.authProvider?.token();\n\t\tthis.lastToken = token;\n\t\treturn { headers: this.buildHeaders(extra, token), ...(token ? { token } : {}) };\n\t}\n\n\tprivate buildHeaders(extra: Record<string, string>, token: string | undefined): Headers {\n\t\tconst headers = new Headers(this.options.headers);\n\t\tfor (const [name, value] of Object.entries(extra)) headers.set(name, value);\n\t\tif (this.sessionIdValue) headers.set(\"Mcp-Session-Id\", this.sessionIdValue);\n\t\tif (this.protocolVersion) headers.set(\"MCP-Protocol-Version\", this.protocolVersion);\n\t\tif (token) headers.set(\"Authorization\", `Bearer ${token}`);\n\t\treturn headers;\n\t}\n\n\tprivate captureSession(response: Response): void {\n\t\tconst sessionId = response.headers.get(\"mcp-session-id\");\n\t\tif (sessionId) this.sessionIdValue = sessionId;\n\t}\n\n\tprivate async checkResponse(response: Response): Promise<void> {\n\t\tif (response.ok) return;\n\t\tconst body = (await response.text().catch(() => \"\")).slice(0, MAX_ERROR_BODY_BYTES);\n\t\tif (response.status === 401) throw new McpAuthRequiredError(response, body);\n\t\tif (response.status === 404 && this.sessionIdValue) throw new McpSessionExpiredError(body);\n\t\tthrow new McpHttpError(response.status, describeHttpFailure(response.status, body), body);\n\t}\n\n\tprivate async consumeSse(\n\t\tstream: ReadableStream<Uint8Array>,\n\t\tcursor: StreamCursor,\n\t\tonMessage?: (message: JsonRpcMessage) => void,\n\t): Promise<void> {\n\t\tawait consumeSseStream(stream, {\n\t\t\tmaxEventBytes: this.options.maxMessageBytes ?? DEFAULT_MAX_MESSAGE_BYTES,\n\t\t\tonId: (id) => {\n\t\t\t\tif (id !== cursor.lastEventId) cursor.advanced = true;\n\t\t\t\tcursor.lastEventId = id;\n\t\t\t},\n\t\t\tonRetry: (delayMs) => {\n\t\t\t\tcursor.retryMs = delayMs;\n\t\t\t},\n\t\t\tonEvent: (event) => {\n\t\t\t\t// Events without data prime resumption; other event types are not JSON-RPC.\n\t\t\t\tif (!event.data.trim() || (event.event !== undefined && event.event !== \"message\")) return;\n\t\t\t\tlet message: JsonRpcMessage;\n\t\t\t\ttry {\n\t\t\t\t\tmessage = parseJsonRpcMessage(JSON.parse(event.data));\n\t\t\t\t} catch (error) {\n\t\t\t\t\tthis.emitError(error);\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tonMessage?.(message);\n\t\t\t\tthis.emitMessage(message);\n\t\t\t},\n\t\t});\n\t}\n\n\t/**\n\t * Read the SSE stream answering one request. When the stream ends or breaks before the response\n\t * arrives and the server assigned event IDs, resume it with GET and `Last-Event-ID`, as the\n\t * server may close response streams at will. Otherwise only this request fails.\n\t */\n\tprivate async consumeResponseStream(body: ReadableStream<Uint8Array>, requestId: JsonRpcId): Promise<void> {\n\t\tconst cursor: StreamCursor = { lastEventId: undefined, retryMs: undefined, advanced: false };\n\t\tlet answered = false;\n\t\tconst onMessage = (message: JsonRpcMessage) => {\n\t\t\tif (isJsonRpcResponse(message) && message.id === requestId) answered = true;\n\t\t};\n\t\tlet stream: ReadableStream<Uint8Array> | undefined = body;\n\t\tlet failure: unknown;\n\t\tfor (let attempt = 0; ; ) {\n\t\t\tif (stream) {\n\t\t\t\ttry {\n\t\t\t\t\tawait this.consumeSse(stream, cursor, onMessage);\n\t\t\t\t\tfailure = undefined;\n\t\t\t\t} catch (error) {\n\t\t\t\t\tfailure = error;\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (answered || this.closed) return;\n\t\t\tif (failure !== undefined && !this.isRetryable(failure)) break;\n\t\t\tif (cursor.lastEventId === undefined || attempt >= this.maxRetries()) break;\n\t\t\tif (cursor.advanced) attempt = 0;\n\t\t\tcursor.advanced = false;\n\t\t\tif (!(await this.sleep(this.reconnectDelay(attempt++, cursor.retryMs)))) return;\n\t\t\ttry {\n\t\t\t\tstream = await this.openSseStream(cursor.lastEventId);\n\t\t\t} catch (error) {\n\t\t\t\tfailure = error;\n\t\t\t\tif (!this.isRetryable(error)) break;\n\t\t\t\tstream = undefined;\n\t\t\t}\n\t\t}\n\t\tif (this.closed) return;\n\t\tconst reason = failure === undefined ? \"stream ended without a response\" : toError(failure).message;\n\t\tthis.emitMessage({\n\t\t\tjsonrpc: \"2.0\",\n\t\t\tid: requestId,\n\t\t\terror: { code: JSON_RPC_ERROR_CODES.internalError, message: `MCP response stream failed: ${reason}` },\n\t\t});\n\t}\n\n\tprivate startGetStream(): void {\n\t\tif (this.options.openGetStream === false || this.getStreamStarted || this.closed) return;\n\t\tthis.getStreamStarted = true;\n\t\tvoid this.runGetStream();\n\t}\n\n\t/** Keep the server-to-client stream open, reconnecting with backoff when it drops. */\n\tprivate async runGetStream(): Promise<void> {\n\t\tconst cursor: StreamCursor = { lastEventId: undefined, retryMs: undefined, advanced: false };\n\t\tfor (let attempt = 0; !this.closed; ) {\n\t\t\ttry {\n\t\t\t\tconst stream = await this.openSseStream(cursor.lastEventId);\n\t\t\t\t// The server does not offer a GET stream.\n\t\t\t\tif (!stream) return;\n\t\t\t\tconst openedAt = Date.now();\n\t\t\t\tawait this.consumeSse(stream, cursor);\n\t\t\t\t// Resumable progress, or a stream that stayed up for a while, counts as healthy.\n\t\t\t\tif (cursor.advanced || Date.now() - openedAt > this.maxDelay()) attempt = 0;\n\t\t\t} catch (error) {\n\t\t\t\tif (this.closed) return;\n\t\t\t\tif (!this.isRetryable(error)) {\n\t\t\t\t\tthis.emitError(error);\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t}\n\t\t\tcursor.advanced = false;\n\t\t\tif (attempt >= this.maxRetries()) {\n\t\t\t\tthis.emitError(new Error(\"MCP server-to-client stream dropped and could not be reopened\"));\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tif (!(await this.sleep(this.reconnectDelay(attempt++, cursor.retryMs)))) return;\n\t\t}\n\t}\n\n\t/** Open a GET SSE stream. Resolves to undefined when the server answers 405 (no GET stream). */\n\tprivate async openSseStream(lastEventId: string | undefined): Promise<ReadableStream<Uint8Array> | undefined> {\n\t\tconst response = await this.authorizedFetch(\"GET\", {\n\t\t\theaders: {\n\t\t\t\taccept: \"text/event-stream\",\n\t\t\t\t...(lastEventId === undefined ? {} : { \"last-event-id\": lastEventId }),\n\t\t\t},\n\t\t});\n\t\tif (response.status === 405) {\n\t\t\tawait discard(response);\n\t\t\treturn undefined;\n\t\t}\n\t\tawait this.checkResponse(response);\n\t\tthis.captureSession(response);\n\t\tconst type = contentType(response);\n\t\tif (type !== \"text/event-stream\" || !response.body) {\n\t\t\tawait discard(response);\n\t\t\tthrow new McpHttpError(response.status, `Unsupported MCP GET response content type: ${type ?? \"missing\"}`);\n\t\t}\n\t\treturn response.body;\n\t}\n\n\t/**\n\t * Network failures and transient statuses are retried; auth, session, and protocol errors are not.\n\t * `fetch` reports network failures, including a connection dropped mid-body, as `TypeError`.\n\t */\n\tprivate isRetryable(error: unknown): boolean {\n\t\tif (error instanceof McpHttpError) return isTransientStatus(error.status);\n\t\tif (error instanceof TypeError) return true;\n\t\tconst code = (error as { code?: unknown } | undefined)?.code;\n\t\treturn typeof code === \"string\" && (code.startsWith(\"E\") || code.startsWith(\"UND_ERR\"));\n\t}\n\n\tprivate reconnectDelay(attempt: number, serverDelayMs: number | undefined): number {\n\t\tif (serverDelayMs !== undefined) return serverDelayMs;\n\t\tconst initial = this.options.reconnect?.initialDelayMs ?? DEFAULT_RECONNECT_INITIAL_DELAY_MS;\n\t\treturn Math.min(initial * 2 ** attempt, this.maxDelay());\n\t}\n\n\tprivate maxDelay(): number {\n\t\treturn this.options.reconnect?.maxDelayMs ?? DEFAULT_RECONNECT_MAX_DELAY_MS;\n\t}\n\n\tprivate maxRetries(): number {\n\t\treturn this.options.reconnect?.maxRetries ?? DEFAULT_RECONNECT_MAX_RETRIES;\n\t}\n\n\t/** Resolves false when the transport closed while waiting. */\n\tprivate sleep(ms: number): Promise<boolean> {\n\t\tconst signal = this.controller.signal;\n\t\tif (signal.aborted) return Promise.resolve(false);\n\t\treturn new Promise((resolve) => {\n\t\t\tconst onAbort = () => {\n\t\t\t\tclearTimeout(timer);\n\t\t\t\tresolve(false);\n\t\t\t};\n\t\t\tconst timer = setTimeout(() => {\n\t\t\t\tsignal.removeEventListener(\"abort\", onAbort);\n\t\t\t\tresolve(true);\n\t\t\t}, ms);\n\t\t\t// A reconnect wait alone does not keep the process alive.\n\t\t\ttimer.unref?.();\n\t\t\tsignal.addEventListener(\"abort\", onAbort, { once: true });\n\t\t});\n\t}\n}\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"main-session.d.ts","sourceRoot":"","sources":["../src/main-session.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAAE,IAAI,EAAE,MAAM,eAAe,CAAC;AAI1C,OAAO,EAAiC,KAAK,eAAe,EAAE,MAAM,uBAAuB,CAAC;AAE5F,OAAO,EAAwB,cAAc,EAAE,MAAM,2BAA2B,CAAC;AAGjF,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,4BAA4B,CAAC;AAClE,OAAO,EAAE,KAAK,gBAAgB,EAAuB,MAAM,4BAA4B,CAAC;AACxF,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,iCAAiC,CAAC;
|
|
1
|
+
{"version":3,"file":"main-session.d.ts","sourceRoot":"","sources":["../src/main-session.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAAE,IAAI,EAAE,MAAM,eAAe,CAAC;AAI1C,OAAO,EAAiC,KAAK,eAAe,EAAE,MAAM,uBAAuB,CAAC;AAE5F,OAAO,EAAwB,cAAc,EAAE,MAAM,2BAA2B,CAAC;AAGjF,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,4BAA4B,CAAC;AAClE,OAAO,EAAE,KAAK,gBAAgB,EAAuB,MAAM,4BAA4B,CAAC;AACxF,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,iCAAiC,CAAC;AAsDpE,qBAAa,4BAA6B,SAAQ,KAAK;IACtD,QAAQ,CAAC,IAAI,6BAA6B;IAC1C,QAAQ,CAAC,gBAAgB,EAAE,SAAS,MAAM,EAAE,CAAC;IAE7C,YAAY,gBAAgB,EAAE,SAAS,MAAM,EAAE,EAM9C;CACD;AAED,wBAAgB,mBAAmB,CAAC,MAAM,EAAE,IAAI,GAAG,IAAI,CAUtD;AAED,wBAAgB,iBAAiB,CAAC,MAAM,EAAE,IAAI,GAAG,IAAI,CAcpD;AAED,wBAAgB,sBAAsB,CAAC,MAAM,EAAE,IAAI,GAAG,IAAI,CAqBzD;AA2BD,wBAAsB,2CAA2C,CAChE,cAAc,EAAE,cAAc,EAC9B,GAAG,GAAE,MAAM,CAAC,MAAM,EAAE,MAAM,GAAG,SAAS,CAAe,GACnD,OAAO,CAAC,cAAc,CAAC,CAIzB;AAWD,sFAAsF;AACtF,wBAAsB,qBAAqB,CAC1C,OAAO,EAAE,cAAc,EACvB,MAAM,EAAE,IAAI,EACZ,eAAe,EAAE,eAAe,EAChC,YAAY,CAAC,EAAE,YAAY,GAAG,gBAAgB,GAC5C,OAAO,CAAC,YAAY,GAAG,SAAS,CAAC,CA6BnC;AAED,wBAAsB,oBAAoB,CACzC,MAAM,EAAE,IAAI,EACZ,GAAG,EAAE,MAAM,EACX,UAAU,EAAE,MAAM,GAAG,SAAS,EAC9B,eAAe,EAAE,eAAe,EAChC,YAAY,CAAC,EAAE,YAAY,GAAG,gBAAgB,GAC5C,OAAO,CAAC,cAAc,CAAC,CA2BzB;AAmGD,wBAAsB,0BAA0B,CAC/C,KAAK,EAAE,eAAe,EACtB,eAAe,EAAE,eAAe,GAC9B,OAAO,CAAC,MAAM,GAAG,SAAS,CAAC,CA8B7B"}
|
package/dist/main-session.js
CHANGED
|
@@ -19,10 +19,13 @@ async function findLocalSessionByExactId(sessionId, cwd, store) {
|
|
|
19
19
|
return header &&
|
|
20
20
|
!classifiedWorkflowMetadata(header) &&
|
|
21
21
|
createSessionCwdMatcher(resolvePath(cwd))(resolvePath(header.cwd))
|
|
22
|
-
? { id: header.id }
|
|
22
|
+
? { id: header.id, cwd: header.cwd }
|
|
23
23
|
: undefined;
|
|
24
24
|
}
|
|
25
25
|
async function resolveSessionId(sessionArg, cwd, store) {
|
|
26
|
+
const exact = await findLocalSessionByExactId(sessionArg, cwd, store).catch(() => undefined);
|
|
27
|
+
if (exact)
|
|
28
|
+
return { type: "local", id: exact.id, cwd: exact.cwd };
|
|
26
29
|
const localSessions = await SessionManager.list(cwd, store, undefined, { includeInternal: true });
|
|
27
30
|
const resolution = await resolveSessionIdTargetAcrossScopes(sessionArg, localSessions, () => SessionManager.listAll(store, undefined, { includeInternal: true }));
|
|
28
31
|
if (resolution.kind === "exact" || resolution.kind === "unique_prefix") {
|