@earendil-works/pi-agent-core 0.83.0 → 0.84.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +9 -3
- package/dist/agent.d.ts +3 -1
- package/dist/agent.d.ts.map +1 -1
- package/dist/agent.js +6 -0
- package/dist/agent.js.map +1 -1
- package/dist/harness/agent-harness.d.ts +452 -85
- package/dist/harness/agent-harness.d.ts.map +1 -1
- package/dist/harness/agent-harness.js +204 -917
- package/dist/harness/agent-harness.js.map +1 -1
- package/dist/harness/compaction/branch-summarization.d.ts +13 -6
- package/dist/harness/compaction/branch-summarization.d.ts.map +1 -1
- package/dist/harness/compaction/branch-summarization.js +11 -15
- package/dist/harness/compaction/branch-summarization.js.map +1 -1
- package/dist/harness/compaction/compaction.d.ts +14 -17
- package/dist/harness/compaction/compaction.d.ts.map +1 -1
- package/dist/harness/compaction/compaction.js +23 -36
- package/dist/harness/compaction/compaction.js.map +1 -1
- package/dist/harness/env/nodejs.d.ts +1 -0
- package/dist/harness/env/nodejs.d.ts.map +1 -1
- package/dist/harness/env/nodejs.js +23 -7
- package/dist/harness/env/nodejs.js.map +1 -1
- package/dist/harness/messages.d.ts +3 -3
- package/dist/harness/messages.d.ts.map +1 -1
- package/dist/harness/messages.js +3 -3
- package/dist/harness/messages.js.map +1 -1
- package/dist/harness/prompt-templates.d.ts.map +1 -1
- package/dist/harness/prompt-templates.js +4 -9
- package/dist/harness/prompt-templates.js.map +1 -1
- package/dist/harness/reducer.d.ts +100 -0
- package/dist/harness/reducer.d.ts.map +1 -0
- package/dist/harness/reducer.js +415 -0
- package/dist/harness/reducer.js.map +1 -0
- package/dist/harness/result.d.ts +40 -0
- package/dist/harness/result.d.ts.map +1 -0
- package/dist/harness/result.js +41 -0
- package/dist/harness/result.js.map +1 -0
- package/dist/harness/session/context.d.ts +22 -0
- package/dist/harness/session/context.d.ts.map +1 -0
- package/dist/harness/session/context.js +67 -0
- package/dist/harness/session/context.js.map +1 -0
- package/dist/harness/session/index.d.ts +7 -0
- package/dist/harness/session/index.d.ts.map +1 -0
- package/dist/harness/session/index.js +6 -0
- package/dist/harness/session/index.js.map +1 -0
- package/dist/harness/session/jsonl/codec.d.ts +8 -0
- package/dist/harness/session/jsonl/codec.d.ts.map +1 -0
- package/dist/harness/session/jsonl/codec.js +190 -0
- package/dist/harness/session/jsonl/codec.js.map +1 -0
- package/dist/harness/session/jsonl/errors.d.ts +5 -0
- package/dist/harness/session/jsonl/errors.d.ts.map +1 -0
- package/dist/harness/session/jsonl/errors.js +11 -0
- package/dist/harness/session/jsonl/errors.js.map +1 -0
- package/dist/harness/session/jsonl/repo.d.ts +23 -0
- package/dist/harness/session/jsonl/repo.d.ts.map +1 -0
- package/dist/harness/session/jsonl/repo.js +132 -0
- package/dist/harness/session/jsonl/repo.js.map +1 -0
- package/dist/harness/session/jsonl/storage.d.ts +43 -0
- package/dist/harness/session/jsonl/storage.d.ts.map +1 -0
- package/dist/harness/session/jsonl/storage.js +208 -0
- package/dist/harness/session/jsonl/storage.js.map +1 -0
- package/dist/harness/session/jsonl/types.d.ts +38 -0
- package/dist/harness/session/jsonl/types.d.ts.map +1 -0
- package/dist/harness/session/jsonl/types.js +2 -0
- package/dist/harness/session/jsonl/types.js.map +1 -0
- package/dist/harness/session/jsonl.d.ts +3 -0
- package/dist/harness/session/jsonl.d.ts.map +1 -0
- package/dist/harness/session/jsonl.js +2 -0
- package/dist/harness/session/jsonl.js.map +1 -0
- package/dist/harness/session/memory.d.ts +44 -0
- package/dist/harness/session/memory.d.ts.map +1 -0
- package/dist/harness/session/memory.js +141 -0
- package/dist/harness/session/memory.js.map +1 -0
- package/dist/harness/session/search.d.ts +19 -0
- package/dist/harness/session/search.d.ts.map +1 -0
- package/dist/harness/session/search.js +42 -0
- package/dist/harness/session/search.js.map +1 -0
- package/dist/harness/session/session.d.ts +43 -42
- package/dist/harness/session/session.d.ts.map +1 -1
- package/dist/harness/session/session.js +187 -228
- package/dist/harness/session/session.js.map +1 -1
- package/dist/harness/session/state.d.ts +65 -0
- package/dist/harness/session/state.d.ts.map +1 -0
- package/dist/harness/session/state.js +319 -0
- package/dist/harness/session/state.js.map +1 -0
- package/dist/harness/session/testing/conformance.d.ts +4 -0
- package/dist/harness/session/testing/conformance.d.ts.map +1 -0
- package/dist/harness/session/testing/conformance.js +743 -0
- package/dist/harness/session/testing/conformance.js.map +1 -0
- package/dist/harness/session/testing/index.d.ts +3 -0
- package/dist/harness/session/testing/index.d.ts.map +1 -0
- package/dist/harness/session/testing/index.js +2 -0
- package/dist/harness/session/testing/index.js.map +1 -0
- package/dist/harness/session/testing/types.d.ts +14 -0
- package/dist/harness/session/testing/types.d.ts.map +1 -0
- package/dist/harness/session/testing/types.js +2 -0
- package/dist/harness/session/testing/types.js.map +1 -0
- package/dist/harness/session/types.d.ts +333 -0
- package/dist/harness/session/types.d.ts.map +1 -0
- package/dist/harness/session/types.js +10 -0
- package/dist/harness/session/types.js.map +1 -0
- package/dist/harness/skills.d.ts.map +1 -1
- package/dist/harness/skills.js +21 -19
- package/dist/harness/skills.js.map +1 -1
- package/dist/harness/telemetry.d.ts +1221 -0
- package/dist/harness/telemetry.d.ts.map +1 -0
- package/dist/harness/telemetry.js +508 -0
- package/dist/harness/telemetry.js.map +1 -0
- package/dist/harness/types.d.ts +6 -459
- package/dist/harness/types.d.ts.map +1 -1
- package/dist/harness/types.js +0 -19
- package/dist/harness/types.js.map +1 -1
- package/dist/index.d.ts +10 -9
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +7 -8
- package/dist/index.js.map +1 -1
- package/dist/proxy.d.ts +1 -1
- package/dist/proxy.d.ts.map +1 -1
- package/dist/proxy.js +1 -0
- package/dist/proxy.js.map +1 -1
- package/package.json +9 -2
- package/dist/harness/session/jsonl-repo.d.ts +0 -26
- package/dist/harness/session/jsonl-repo.d.ts.map +0 -1
- package/dist/harness/session/jsonl-repo.js +0 -103
- package/dist/harness/session/jsonl-repo.js.map +0 -1
- package/dist/harness/session/jsonl-storage.d.ts +0 -42
- package/dist/harness/session/jsonl-storage.d.ts.map +0 -1
- package/dist/harness/session/jsonl-storage.js +0 -293
- package/dist/harness/session/jsonl-storage.js.map +0 -1
- package/dist/harness/session/memory-repo.d.ts +0 -18
- package/dist/harness/session/memory-repo.d.ts.map +0 -1
- package/dist/harness/session/memory-repo.js +0 -42
- package/dist/harness/session/memory-repo.js.map +0 -1
- package/dist/harness/session/memory-storage.d.ts +0 -33
- package/dist/harness/session/memory-storage.d.ts.map +0 -1
- package/dist/harness/session/memory-storage.js +0 -168
- package/dist/harness/session/memory-storage.js.map +0 -1
- package/dist/harness/session/repo-utils.d.ts +0 -11
- package/dist/harness/session/repo-utils.d.ts.map +0 -1
- package/dist/harness/session/repo-utils.js +0 -39
- package/dist/harness/session/repo-utils.js.map +0 -1
package/dist/proxy.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"proxy.js","sourceRoot":"","sources":["../src/proxy.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAEH,2CAA2C;AAC3C,OAAO,EAIN,WAAW,EAEX,kBAAkB,GAIlB,MAAM,uBAAuB,CAAC;AAE/B,uDAAuD;AACvD,MAAM,uBAAwB,SAAQ,WAAoD;IACzF,cAAc;QACb,KAAK,CACJ,CAAC,KAAK,EAAE,EAAE,CAAC,KAAK,CAAC,IAAI,KAAK,MAAM,IAAI,KAAK,CAAC,IAAI,KAAK,OAAO,EAC1D,CAAC,KAAK,EAAE,EAAE,CAAC;YACV,IAAI,KAAK,CAAC,IAAI,KAAK,MAAM;gBAAE,OAAO,KAAK,CAAC,OAAO,CAAC;YAChD,IAAI,KAAK,CAAC,IAAI,KAAK,OAAO;gBAAE,OAAO,KAAK,CAAC,KAAK,CAAC;YAC/C,MAAM,IAAI,KAAK,CAAC,uBAAuB,CAAC,CAAC;QAAA,CACzC,CACD,CAAC;IAAA,CACF;CACD;AAmDD;;;;;;;;;;;;;;;;;;GAkBG;AACH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AE,MAAM,EAAE,UAAU,CAAC,MAAM,EAAE,KAAK,EAAE,OAAO,EAAE,CAAC;QAErE,SAAS,CAAC;YACT,MAAM,gBAAgB,GAAU,UAAU,CAAC;YAC3C,OAAO,CAAC,IAAI,CAAC,+BAAgC,UAAkB,CAAC,IAAI,EAAE,CAAC,CAAC;YACxE,OAAO,SAAS,CAAC;QAClB,CAAC;IACF,CAAC;AAAA,CACD","sourcesContent":["/**\n * Proxy stream function for apps that route LLM calls through a server.\n * The server manages auth and proxies requests to LLM providers.\n */\n\n// Internal import for JSON parsing utility\nimport {\n\ttype AssistantMessage,\n\ttype AssistantMessageEvent,\n\ttype Context,\n\tEventStream,\n\ttype Model,\n\tparseStreamingJson,\n\ttype SimpleStreamOptions,\n\ttype StopReason,\n\ttype ToolCall,\n} from \"@earendil-works/pi-ai\";\n\n// Create stream class matching ProxyMessageEventStream\nclass ProxyMessageEventStream extends EventStream<AssistantMessageEvent, AssistantMessage> {\n\tconstructor() {\n\t\tsuper(\n\t\t\t(event) => event.type === \"done\" || event.type === \"error\",\n\t\t\t(event) => {\n\t\t\t\tif (event.type === \"done\") return event.message;\n\t\t\t\tif (event.type === \"error\") return event.error;\n\t\t\t\tthrow new Error(\"Unexpected event type\");\n\t\t\t},\n\t\t);\n\t}\n}\n\n/**\n * Proxy event types - server sends these with partial field stripped to reduce bandwidth.\n */\nexport type ProxyAssistantMessageEvent =\n\t| { type: \"start\" }\n\t| { type: \"text_start\"; contentIndex: number }\n\t| { type: \"text_delta\"; contentIndex: number; delta: string }\n\t| { type: \"text_end\"; contentIndex: number; contentSignature?: string }\n\t| { type: \"thinking_start\"; contentIndex: number }\n\t| { type: \"thinking_delta\"; contentIndex: number; delta: string }\n\t| { type: \"thinking_end\"; contentIndex: number; contentSignature?: string }\n\t| { type: \"toolcall_start\"; contentIndex: number; id: string; toolName: string }\n\t| { type: \"toolcall_delta\"; contentIndex: number; delta: string }\n\t| { type: \"toolcall_end\"; contentIndex: number }\n\t| {\n\t\t\ttype: \"done\";\n\t\t\treason: Extract<StopReason, \"stop\" | \"length\" | \"toolUse\">;\n\t\t\tusage: AssistantMessage[\"usage\"];\n\t }\n\t| {\n\t\t\ttype: \"error\";\n\t\t\treason: Extract<StopReason, \"aborted\" | \"error\">;\n\t\t\terrorMessage?: string;\n\t\t\tusage: AssistantMessage[\"usage\"];\n\t };\n\ntype ProxySerializableStreamOptions = Pick<\n\tSimpleStreamOptions,\n\t| \"temperature\"\n\t| \"maxTokens\"\n\t| \"reasoning\"\n\t| \"cacheRetention\"\n\t| \"sessionId\"\n\t| \"headers\"\n\t| \"metadata\"\n\t| \"transport\"\n\t| \"thinkingBudgets\"\n\t| \"maxRetryDelayMs\"\n>;\n\nexport interface ProxyStreamOptions extends ProxySerializableStreamOptions {\n\t/** Local abort signal for the proxy request */\n\tsignal?: AbortSignal;\n\t/** Auth token for the proxy server */\n\tauthToken: string;\n\t/** Proxy server URL (e.g., \"https://genai.example.com\") */\n\tproxyUrl: string;\n}\n\n/**\n * Stream function that proxies through a server instead of calling LLM providers directly.\n * The server strips the partial field from delta events to reduce bandwidth.\n * We reconstruct the partial message client-side.\n *\n * Use this as the `streamFn` option when creating an Agent that needs to go through a proxy.\n *\n * @example\n * ```typescript\n * const agent = new Agent({\n * streamFn: (model, context, options) =>\n * streamProxy(model, context, {\n * ...options,\n * authToken: await getAuthToken(),\n * proxyUrl: \"https://genai.example.com\",\n * }),\n * });\n * ```\n */\nfunction buildProxyRequestOptions(options: ProxyStreamOptions): ProxySerializableStreamOptions {\n\treturn {\n\t\ttemperature: options.temperature,\n\t\tmaxTokens: options.maxTokens,\n\t\treasoning: options.reasoning,\n\t\tcacheRetention: options.cacheRetention,\n\t\tsessionId: options.sessionId,\n\t\theaders: options.headers,\n\t\tmetadata: options.metadata,\n\t\ttransport: options.transport,\n\t\tthinkingBudgets: options.thinkingBudgets,\n\t\tmaxRetryDelayMs: options.maxRetryDelayMs,\n\t};\n}\n\nexport function streamProxy(model: Model<any>, context: Context, options: ProxyStreamOptions): ProxyMessageEventStream {\n\tconst stream = new ProxyMessageEventStream();\n\n\t(async () => {\n\t\t// Initialize the partial message that we'll build up from events\n\t\tconst partial: AssistantMessage = {\n\t\t\trole: \"assistant\",\n\t\t\tstopReason: \"pending\",\n\t\t\tcontent: [],\n\t\t\tapi: model.api,\n\t\t\tprovider: model.provider,\n\t\t\tmodel: model.id,\n\t\t\tusage: {\n\t\t\t\tinput: 0,\n\t\t\t\toutput: 0,\n\t\t\t\tcacheRead: 0,\n\t\t\t\tcacheWrite: 0,\n\t\t\t\ttotalTokens: 0,\n\t\t\t\tcost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 },\n\t\t\t},\n\t\t\ttimestamp: Date.now(),\n\t\t};\n\n\t\tlet reader: ReadableStreamDefaultReader<Uint8Array> | undefined;\n\n\t\tconst abortHandler = () => {\n\t\t\tif (reader) {\n\t\t\t\treader.cancel(\"Request aborted by user\").catch(() => {});\n\t\t\t}\n\t\t};\n\n\t\tif (options.signal) {\n\t\t\toptions.signal.addEventListener(\"abort\", abortHandler);\n\t\t}\n\n\t\ttry {\n\t\t\tconst response = await fetch(`${options.proxyUrl}/api/stream`, {\n\t\t\t\tmethod: \"POST\",\n\t\t\t\theaders: {\n\t\t\t\t\tAuthorization: `Bearer ${options.authToken}`,\n\t\t\t\t\t\"Content-Type\": \"application/json\",\n\t\t\t\t},\n\t\t\t\tbody: JSON.stringify({\n\t\t\t\t\tmodel,\n\t\t\t\t\tcontext,\n\t\t\t\t\toptions: buildProxyRequestOptions(options),\n\t\t\t\t}),\n\t\t\t\tsignal: options.signal,\n\t\t\t});\n\n\t\t\tif (!response.ok) {\n\t\t\t\tlet errorMessage = `Proxy error: ${response.status} ${response.statusText}`;\n\t\t\t\ttry {\n\t\t\t\t\tconst errorData = (await response.json()) as { error?: string };\n\t\t\t\t\tif (errorData.error) {\n\t\t\t\t\t\terrorMessage = `Proxy error: ${errorData.error}`;\n\t\t\t\t\t}\n\t\t\t\t} catch {\n\t\t\t\t\t// Couldn't parse error response\n\t\t\t\t}\n\t\t\t\tthrow new Error(errorMessage);\n\t\t\t}\n\n\t\t\treader = response.body!.getReader();\n\t\t\tconst decoder = new TextDecoder();\n\t\t\tlet buffer = \"\";\n\n\t\t\twhile (true) {\n\t\t\t\tconst { done, value } = await reader.read();\n\t\t\t\tif (done) break;\n\n\t\t\t\tif (options.signal?.aborted) {\n\t\t\t\t\tthrow new Error(\"Request aborted by user\");\n\t\t\t\t}\n\n\t\t\t\tbuffer += decoder.decode(value, { stream: true });\n\t\t\t\tconst lines = buffer.split(\"\\n\");\n\t\t\t\tbuffer = lines.pop() || \"\";\n\n\t\t\t\tfor (const line of lines) {\n\t\t\t\t\tif (line.startsWith(\"data: \")) {\n\t\t\t\t\t\tconst data = line.slice(6).trim();\n\t\t\t\t\t\tif (data) {\n\t\t\t\t\t\t\tconst proxyEvent = JSON.parse(data) as ProxyAssistantMessageEvent;\n\t\t\t\t\t\t\tconst event = processProxyEvent(proxyEvent, partial);\n\t\t\t\t\t\t\tif (event) {\n\t\t\t\t\t\t\t\tstream.push(event);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (options.signal?.aborted) {\n\t\t\t\tthrow new Error(\"Request aborted by user\");\n\t\t\t}\n\n\t\t\tstream.end();\n\t\t} catch (error) {\n\t\t\tconst errorMessage = error instanceof Error ? error.message : String(error);\n\t\t\tconst reason = options.signal?.aborted ? \"aborted\" : \"error\";\n\t\t\tpartial.stopReason = reason;\n\t\t\tpartial.errorMessage = errorMessage;\n\t\t\tstream.push({\n\t\t\t\ttype: \"error\",\n\t\t\t\treason,\n\t\t\t\terror: partial,\n\t\t\t});\n\t\t\tstream.end();\n\t\t} finally {\n\t\t\tif (options.signal) {\n\t\t\t\toptions.signal.removeEventListener(\"abort\", abortHandler);\n\t\t\t}\n\t\t}\n\t})();\n\n\treturn stream;\n}\n\n/**\n * Process a proxy event and update the partial message.\n */\nfunction processProxyEvent(\n\tproxyEvent: ProxyAssistantMessageEvent,\n\tpartial: AssistantMessage,\n): AssistantMessageEvent | undefined {\n\tswitch (proxyEvent.type) {\n\t\tcase \"start\":\n\t\t\treturn { type: \"start\", partial };\n\n\t\tcase \"text_start\":\n\t\t\tpartial.content[proxyEvent.contentIndex] = { type: \"text\", text: \"\" };\n\t\t\treturn { type: \"text_start\", contentIndex: proxyEvent.contentIndex, partial };\n\n\t\tcase \"text_delta\": {\n\t\t\tconst content = partial.content[proxyEvent.contentIndex];\n\t\t\tif (content?.type === \"text\") {\n\t\t\t\tcontent.text += proxyEvent.delta;\n\t\t\t\treturn {\n\t\t\t\t\ttype: \"text_delta\",\n\t\t\t\t\tcontentIndex: proxyEvent.contentIndex,\n\t\t\t\t\tdelta: proxyEvent.delta,\n\t\t\t\t\tpartial,\n\t\t\t\t};\n\t\t\t}\n\t\t\tthrow new Error(\"Received text_delta for non-text content\");\n\t\t}\n\n\t\tcase \"text_end\": {\n\t\t\tconst content = partial.content[proxyEvent.contentIndex];\n\t\t\tif (content?.type === \"text\") {\n\t\t\t\tcontent.textSignature = proxyEvent.contentSignature;\n\t\t\t\treturn {\n\t\t\t\t\ttype: \"text_end\",\n\t\t\t\t\tcontentIndex: proxyEvent.contentIndex,\n\t\t\t\t\tcontent: content.text,\n\t\t\t\t\tpartial,\n\t\t\t\t};\n\t\t\t}\n\t\t\tthrow new Error(\"Received text_end for non-text content\");\n\t\t}\n\n\t\tcase \"thinking_start\":\n\t\t\tpartial.content[proxyEvent.contentIndex] = { type: \"thinking\", thinking: \"\" };\n\t\t\treturn { type: \"thinking_start\", contentIndex: proxyEvent.contentIndex, partial };\n\n\t\tcase \"thinking_delta\": {\n\t\t\tconst content = partial.content[proxyEvent.contentIndex];\n\t\t\tif (content?.type === \"thinking\") {\n\t\t\t\tcontent.thinking += proxyEvent.delta;\n\t\t\t\treturn {\n\t\t\t\t\ttype: \"thinking_delta\",\n\t\t\t\t\tcontentIndex: proxyEvent.contentIndex,\n\t\t\t\t\tdelta: proxyEvent.delta,\n\t\t\t\t\tpartial,\n\t\t\t\t};\n\t\t\t}\n\t\t\tthrow new Error(\"Received thinking_delta for non-thinking content\");\n\t\t}\n\n\t\tcase \"thinking_end\": {\n\t\t\tconst content = partial.content[proxyEvent.contentIndex];\n\t\t\tif (content?.type === \"thinking\") {\n\t\t\t\tcontent.thinkingSignature = proxyEvent.contentSignature;\n\t\t\t\treturn {\n\t\t\t\t\ttype: \"thinking_end\",\n\t\t\t\t\tcontentIndex: proxyEvent.contentIndex,\n\t\t\t\t\tcontent: content.thinking,\n\t\t\t\t\tpartial,\n\t\t\t\t};\n\t\t\t}\n\t\t\tthrow new Error(\"Received thinking_end for non-thinking content\");\n\t\t}\n\n\t\tcase \"toolcall_start\":\n\t\t\tpartial.content[proxyEvent.contentIndex] = {\n\t\t\t\ttype: \"toolCall\",\n\t\t\t\tid: proxyEvent.id,\n\t\t\t\tname: proxyEvent.toolName,\n\t\t\t\targuments: {},\n\t\t\t\tpartialJson: \"\",\n\t\t\t} satisfies ToolCall & { partialJson: string } as ToolCall;\n\t\t\treturn { type: \"toolcall_start\", contentIndex: proxyEvent.contentIndex, partial };\n\n\t\tcase \"toolcall_delta\": {\n\t\t\tconst content = partial.content[proxyEvent.contentIndex];\n\t\t\tif (content?.type === \"toolCall\") {\n\t\t\t\t(content as any).partialJson += proxyEvent.delta;\n\t\t\t\tcontent.arguments = parseStreamingJson((content as any).partialJson) || {};\n\t\t\t\tpartial.content[proxyEvent.contentIndex] = { ...content }; // Trigger reactivity\n\t\t\t\treturn {\n\t\t\t\t\ttype: \"toolcall_delta\",\n\t\t\t\t\tcontentIndex: proxyEvent.contentIndex,\n\t\t\t\t\tdelta: proxyEvent.delta,\n\t\t\t\t\tpartial,\n\t\t\t\t};\n\t\t\t}\n\t\t\tthrow new Error(\"Received toolcall_delta for non-toolCall content\");\n\t\t}\n\n\t\tcase \"toolcall_end\": {\n\t\t\tconst content = partial.content[proxyEvent.contentIndex];\n\t\t\tif (content?.type === \"toolCall\") {\n\t\t\t\tdelete (content as any).partialJson;\n\t\t\t\treturn {\n\t\t\t\t\ttype: \"toolcall_end\",\n\t\t\t\t\tcontentIndex: proxyEvent.contentIndex,\n\t\t\t\t\ttoolCall: content,\n\t\t\t\t\tpartial,\n\t\t\t\t};\n\t\t\t}\n\t\t\treturn undefined;\n\t\t}\n\n\t\tcase \"done\":\n\t\t\tpartial.stopReason = proxyEvent.reason;\n\t\t\tpartial.usage = proxyEvent.usage;\n\t\t\treturn { type: \"done\", reason: proxyEvent.reason, message: partial };\n\n\t\tcase \"error\":\n\t\t\tpartial.stopReason = proxyEvent.reason;\n\t\t\tpartial.errorMessage = proxyEvent.errorMessage;\n\t\t\tpartial.usage = proxyEvent.usage;\n\t\t\treturn { type: \"error\", reason: proxyEvent.reason, error: partial };\n\n\t\tdefault: {\n\t\t\tconst _exhaustiveCheck: never = proxyEvent;\n\t\t\tconsole.warn(`Unhandled proxy event type: ${(proxyEvent as any).type}`);\n\t\t\treturn undefined;\n\t\t}\n\t}\n}\n"]}
|
|
1
|
+
{"version":3,"file":"proxy.js","sourceRoot":"","sources":["../src/proxy.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAEH,2CAA2C;AAC3C,OAAO,EAIN,WAAW,EAEX,kBAAkB,GAIlB,MAAM,uBAAuB,CAAC;AAE/B,uDAAuD;AACvD,MAAM,uBAAwB,SAAQ,WAAoD;IACzF,cAAc;QACb,KAAK,CACJ,CAAC,KAAK,EAAE,EAAE,CAAC,KAAK,CAAC,IAAI,KAAK,MAAM,IAAI,KAAK,CAAC,IAAI,KAAK,OAAO,EAC1D,CAAC,KAAK,EAAE,EAAE,CAAC;YACV,IAAI,KAAK,CAAC,IAAI,KAAK,MAAM;gBAAE,OAAO,KAAK,CAAC,OAAO,CAAC;YAChD,IAAI,KAAK,CAAC,IAAI,KAAK,OAAO;gBAAE,OAAO,KAAK,CAAC,KAAK,CAA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,CAAC,MAAM,CAAC;YACvC,OAAO,CAAC,YAAY,GAAG,UAAU,CAAC,YAAY,CAAC;YAC/C,OAAO,CAAC,KAAK,GAAG,UAAU,CAAC,KAAK,CAAC;YACjC,OAAO,EAAE,IAAI,EAAE,OAAO,EAAE,MAAM,EAAE,UAAU,CAAC,MAAM,EAAE,KAAK,EAAE,OAAO,EAAE,CAAC;QAErE,SAAS,CAAC;YACT,MAAM,gBAAgB,GAAU,UAAU,CAAC;YAC3C,OAAO,CAAC,IAAI,CAAC,+BAAgC,UAAkB,CAAC,IAAI,EAAE,CAAC,CAAC;YACxE,OAAO,SAAS,CAAC;QAClB,CAAC;IACF,CAAC;AAAA,CACD","sourcesContent":["/**\n * Proxy stream function for apps that route LLM calls through a server.\n * The server manages auth and proxies requests to LLM providers.\n */\n\n// Internal import for JSON parsing utility\nimport {\n\ttype AssistantMessage,\n\ttype AssistantMessageEvent,\n\ttype Context,\n\tEventStream,\n\ttype Model,\n\tparseStreamingJson,\n\ttype SimpleStreamOptions,\n\ttype StopReason,\n\ttype ToolCall,\n} from \"@earendil-works/pi-ai\";\n\n// Create stream class matching ProxyMessageEventStream\nclass ProxyMessageEventStream extends EventStream<AssistantMessageEvent, AssistantMessage> {\n\tconstructor() {\n\t\tsuper(\n\t\t\t(event) => event.type === \"done\" || event.type === \"error\",\n\t\t\t(event) => {\n\t\t\t\tif (event.type === \"done\") return event.message;\n\t\t\t\tif (event.type === \"error\") return event.error;\n\t\t\t\tthrow new Error(\"Unexpected event type\");\n\t\t\t},\n\t\t);\n\t}\n}\n\n/**\n * Proxy event types - server sends these with partial field stripped to reduce bandwidth.\n */\nexport type ProxyAssistantMessageEvent =\n\t| { type: \"start\" }\n\t| { type: \"text_start\"; contentIndex: number }\n\t| { type: \"text_delta\"; contentIndex: number; delta: string }\n\t| { type: \"text_end\"; contentIndex: number; contentSignature?: string }\n\t| { type: \"thinking_start\"; contentIndex: number }\n\t| { type: \"thinking_delta\"; contentIndex: number; delta: string }\n\t| { type: \"thinking_end\"; contentIndex: number; contentSignature?: string }\n\t| { type: \"toolcall_start\"; contentIndex: number; id: string; toolName: string }\n\t| { type: \"toolcall_delta\"; contentIndex: number; delta: string }\n\t| { type: \"toolcall_end\"; contentIndex: number }\n\t| {\n\t\t\ttype: \"done\";\n\t\t\treason: Extract<StopReason, \"stop\" | \"length\" | \"toolUse\">;\n\t\t\tusage: AssistantMessage[\"usage\"];\n\t }\n\t| {\n\t\t\ttype: \"error\";\n\t\t\treason: Extract<StopReason, \"aborted\" | \"error\">;\n\t\t\terrorMessage?: string;\n\t\t\tusage: AssistantMessage[\"usage\"];\n\t };\n\ntype ProxySerializableStreamOptions = Pick<\n\tSimpleStreamOptions,\n\t| \"temperature\"\n\t| \"samplingParams\"\n\t| \"maxTokens\"\n\t| \"reasoning\"\n\t| \"cacheRetention\"\n\t| \"sessionId\"\n\t| \"headers\"\n\t| \"metadata\"\n\t| \"transport\"\n\t| \"thinkingBudgets\"\n\t| \"maxRetryDelayMs\"\n>;\n\nexport interface ProxyStreamOptions extends ProxySerializableStreamOptions {\n\t/** Local abort signal for the proxy request */\n\tsignal?: AbortSignal;\n\t/** Auth token for the proxy server */\n\tauthToken: string;\n\t/** Proxy server URL (e.g., \"https://genai.example.com\") */\n\tproxyUrl: string;\n}\n\n/**\n * Stream function that proxies through a server instead of calling LLM providers directly.\n * The server strips the partial field from delta events to reduce bandwidth.\n * We reconstruct the partial message client-side.\n *\n * Use this as the `streamFn` option when creating an Agent that needs to go through a proxy.\n *\n * @example\n * ```typescript\n * const agent = new Agent({\n * streamFn: (model, context, options) =>\n * streamProxy(model, context, {\n * ...options,\n * authToken: await getAuthToken(),\n * proxyUrl: \"https://genai.example.com\",\n * }),\n * });\n * ```\n */\nfunction buildProxyRequestOptions(options: ProxyStreamOptions): ProxySerializableStreamOptions {\n\treturn {\n\t\ttemperature: options.temperature,\n\t\tsamplingParams: options.samplingParams,\n\t\tmaxTokens: options.maxTokens,\n\t\treasoning: options.reasoning,\n\t\tcacheRetention: options.cacheRetention,\n\t\tsessionId: options.sessionId,\n\t\theaders: options.headers,\n\t\tmetadata: options.metadata,\n\t\ttransport: options.transport,\n\t\tthinkingBudgets: options.thinkingBudgets,\n\t\tmaxRetryDelayMs: options.maxRetryDelayMs,\n\t};\n}\n\nexport function streamProxy(model: Model<any>, context: Context, options: ProxyStreamOptions): ProxyMessageEventStream {\n\tconst stream = new ProxyMessageEventStream();\n\n\t(async () => {\n\t\t// Initialize the partial message that we'll build up from events\n\t\tconst partial: AssistantMessage = {\n\t\t\trole: \"assistant\",\n\t\t\tstopReason: \"pending\",\n\t\t\tcontent: [],\n\t\t\tapi: model.api,\n\t\t\tprovider: model.provider,\n\t\t\tmodel: model.id,\n\t\t\tusage: {\n\t\t\t\tinput: 0,\n\t\t\t\toutput: 0,\n\t\t\t\tcacheRead: 0,\n\t\t\t\tcacheWrite: 0,\n\t\t\t\ttotalTokens: 0,\n\t\t\t\tcost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 },\n\t\t\t},\n\t\t\ttimestamp: Date.now(),\n\t\t};\n\n\t\tlet reader: ReadableStreamDefaultReader<Uint8Array> | undefined;\n\n\t\tconst abortHandler = () => {\n\t\t\tif (reader) {\n\t\t\t\treader.cancel(\"Request aborted by user\").catch(() => {});\n\t\t\t}\n\t\t};\n\n\t\tif (options.signal) {\n\t\t\toptions.signal.addEventListener(\"abort\", abortHandler);\n\t\t}\n\n\t\ttry {\n\t\t\tconst response = await fetch(`${options.proxyUrl}/api/stream`, {\n\t\t\t\tmethod: \"POST\",\n\t\t\t\theaders: {\n\t\t\t\t\tAuthorization: `Bearer ${options.authToken}`,\n\t\t\t\t\t\"Content-Type\": \"application/json\",\n\t\t\t\t},\n\t\t\t\tbody: JSON.stringify({\n\t\t\t\t\tmodel,\n\t\t\t\t\tcontext,\n\t\t\t\t\toptions: buildProxyRequestOptions(options),\n\t\t\t\t}),\n\t\t\t\tsignal: options.signal,\n\t\t\t});\n\n\t\t\tif (!response.ok) {\n\t\t\t\tlet errorMessage = `Proxy error: ${response.status} ${response.statusText}`;\n\t\t\t\ttry {\n\t\t\t\t\tconst errorData = (await response.json()) as { error?: string };\n\t\t\t\t\tif (errorData.error) {\n\t\t\t\t\t\terrorMessage = `Proxy error: ${errorData.error}`;\n\t\t\t\t\t}\n\t\t\t\t} catch {\n\t\t\t\t\t// Couldn't parse error response\n\t\t\t\t}\n\t\t\t\tthrow new Error(errorMessage);\n\t\t\t}\n\n\t\t\treader = response.body!.getReader();\n\t\t\tconst decoder = new TextDecoder();\n\t\t\tlet buffer = \"\";\n\n\t\t\twhile (true) {\n\t\t\t\tconst { done, value } = await reader.read();\n\t\t\t\tif (done) break;\n\n\t\t\t\tif (options.signal?.aborted) {\n\t\t\t\t\tthrow new Error(\"Request aborted by user\");\n\t\t\t\t}\n\n\t\t\t\tbuffer += decoder.decode(value, { stream: true });\n\t\t\t\tconst lines = buffer.split(\"\\n\");\n\t\t\t\tbuffer = lines.pop() || \"\";\n\n\t\t\t\tfor (const line of lines) {\n\t\t\t\t\tif (line.startsWith(\"data: \")) {\n\t\t\t\t\t\tconst data = line.slice(6).trim();\n\t\t\t\t\t\tif (data) {\n\t\t\t\t\t\t\tconst proxyEvent = JSON.parse(data) as ProxyAssistantMessageEvent;\n\t\t\t\t\t\t\tconst event = processProxyEvent(proxyEvent, partial);\n\t\t\t\t\t\t\tif (event) {\n\t\t\t\t\t\t\t\tstream.push(event);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (options.signal?.aborted) {\n\t\t\t\tthrow new Error(\"Request aborted by user\");\n\t\t\t}\n\n\t\t\tstream.end();\n\t\t} catch (error) {\n\t\t\tconst errorMessage = error instanceof Error ? error.message : String(error);\n\t\t\tconst reason = options.signal?.aborted ? \"aborted\" : \"error\";\n\t\t\tpartial.stopReason = reason;\n\t\t\tpartial.errorMessage = errorMessage;\n\t\t\tstream.push({\n\t\t\t\ttype: \"error\",\n\t\t\t\treason,\n\t\t\t\terror: partial,\n\t\t\t});\n\t\t\tstream.end();\n\t\t} finally {\n\t\t\tif (options.signal) {\n\t\t\t\toptions.signal.removeEventListener(\"abort\", abortHandler);\n\t\t\t}\n\t\t}\n\t})();\n\n\treturn stream;\n}\n\n/**\n * Process a proxy event and update the partial message.\n */\nfunction processProxyEvent(\n\tproxyEvent: ProxyAssistantMessageEvent,\n\tpartial: AssistantMessage,\n): AssistantMessageEvent | undefined {\n\tswitch (proxyEvent.type) {\n\t\tcase \"start\":\n\t\t\treturn { type: \"start\", partial };\n\n\t\tcase \"text_start\":\n\t\t\tpartial.content[proxyEvent.contentIndex] = { type: \"text\", text: \"\" };\n\t\t\treturn { type: \"text_start\", contentIndex: proxyEvent.contentIndex, partial };\n\n\t\tcase \"text_delta\": {\n\t\t\tconst content = partial.content[proxyEvent.contentIndex];\n\t\t\tif (content?.type === \"text\") {\n\t\t\t\tcontent.text += proxyEvent.delta;\n\t\t\t\treturn {\n\t\t\t\t\ttype: \"text_delta\",\n\t\t\t\t\tcontentIndex: proxyEvent.contentIndex,\n\t\t\t\t\tdelta: proxyEvent.delta,\n\t\t\t\t\tpartial,\n\t\t\t\t};\n\t\t\t}\n\t\t\tthrow new Error(\"Received text_delta for non-text content\");\n\t\t}\n\n\t\tcase \"text_end\": {\n\t\t\tconst content = partial.content[proxyEvent.contentIndex];\n\t\t\tif (content?.type === \"text\") {\n\t\t\t\tcontent.textSignature = proxyEvent.contentSignature;\n\t\t\t\treturn {\n\t\t\t\t\ttype: \"text_end\",\n\t\t\t\t\tcontentIndex: proxyEvent.contentIndex,\n\t\t\t\t\tcontent: content.text,\n\t\t\t\t\tpartial,\n\t\t\t\t};\n\t\t\t}\n\t\t\tthrow new Error(\"Received text_end for non-text content\");\n\t\t}\n\n\t\tcase \"thinking_start\":\n\t\t\tpartial.content[proxyEvent.contentIndex] = { type: \"thinking\", thinking: \"\" };\n\t\t\treturn { type: \"thinking_start\", contentIndex: proxyEvent.contentIndex, partial };\n\n\t\tcase \"thinking_delta\": {\n\t\t\tconst content = partial.content[proxyEvent.contentIndex];\n\t\t\tif (content?.type === \"thinking\") {\n\t\t\t\tcontent.thinking += proxyEvent.delta;\n\t\t\t\treturn {\n\t\t\t\t\ttype: \"thinking_delta\",\n\t\t\t\t\tcontentIndex: proxyEvent.contentIndex,\n\t\t\t\t\tdelta: proxyEvent.delta,\n\t\t\t\t\tpartial,\n\t\t\t\t};\n\t\t\t}\n\t\t\tthrow new Error(\"Received thinking_delta for non-thinking content\");\n\t\t}\n\n\t\tcase \"thinking_end\": {\n\t\t\tconst content = partial.content[proxyEvent.contentIndex];\n\t\t\tif (content?.type === \"thinking\") {\n\t\t\t\tcontent.thinkingSignature = proxyEvent.contentSignature;\n\t\t\t\treturn {\n\t\t\t\t\ttype: \"thinking_end\",\n\t\t\t\t\tcontentIndex: proxyEvent.contentIndex,\n\t\t\t\t\tcontent: content.thinking,\n\t\t\t\t\tpartial,\n\t\t\t\t};\n\t\t\t}\n\t\t\tthrow new Error(\"Received thinking_end for non-thinking content\");\n\t\t}\n\n\t\tcase \"toolcall_start\":\n\t\t\tpartial.content[proxyEvent.contentIndex] = {\n\t\t\t\ttype: \"toolCall\",\n\t\t\t\tid: proxyEvent.id,\n\t\t\t\tname: proxyEvent.toolName,\n\t\t\t\targuments: {},\n\t\t\t\tpartialJson: \"\",\n\t\t\t} satisfies ToolCall & { partialJson: string } as ToolCall;\n\t\t\treturn { type: \"toolcall_start\", contentIndex: proxyEvent.contentIndex, partial };\n\n\t\tcase \"toolcall_delta\": {\n\t\t\tconst content = partial.content[proxyEvent.contentIndex];\n\t\t\tif (content?.type === \"toolCall\") {\n\t\t\t\t(content as any).partialJson += proxyEvent.delta;\n\t\t\t\tcontent.arguments = parseStreamingJson((content as any).partialJson) || {};\n\t\t\t\tpartial.content[proxyEvent.contentIndex] = { ...content }; // Trigger reactivity\n\t\t\t\treturn {\n\t\t\t\t\ttype: \"toolcall_delta\",\n\t\t\t\t\tcontentIndex: proxyEvent.contentIndex,\n\t\t\t\t\tdelta: proxyEvent.delta,\n\t\t\t\t\tpartial,\n\t\t\t\t};\n\t\t\t}\n\t\t\tthrow new Error(\"Received toolcall_delta for non-toolCall content\");\n\t\t}\n\n\t\tcase \"toolcall_end\": {\n\t\t\tconst content = partial.content[proxyEvent.contentIndex];\n\t\t\tif (content?.type === \"toolCall\") {\n\t\t\t\tdelete (content as any).partialJson;\n\t\t\t\treturn {\n\t\t\t\t\ttype: \"toolcall_end\",\n\t\t\t\t\tcontentIndex: proxyEvent.contentIndex,\n\t\t\t\t\ttoolCall: content,\n\t\t\t\t\tpartial,\n\t\t\t\t};\n\t\t\t}\n\t\t\treturn undefined;\n\t\t}\n\n\t\tcase \"done\":\n\t\t\tpartial.stopReason = proxyEvent.reason;\n\t\t\tpartial.usage = proxyEvent.usage;\n\t\t\treturn { type: \"done\", reason: proxyEvent.reason, message: partial };\n\n\t\tcase \"error\":\n\t\t\tpartial.stopReason = proxyEvent.reason;\n\t\t\tpartial.errorMessage = proxyEvent.errorMessage;\n\t\t\tpartial.usage = proxyEvent.usage;\n\t\t\treturn { type: \"error\", reason: proxyEvent.reason, error: partial };\n\n\t\tdefault: {\n\t\t\tconst _exhaustiveCheck: never = proxyEvent;\n\t\t\tconsole.warn(`Unhandled proxy event type: ${(proxyEvent as any).type}`);\n\t\t\treturn undefined;\n\t\t}\n\t}\n}\n"]}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@earendil-works/pi-agent-core",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.84.0",
|
|
4
4
|
"description": "General-purpose agent with transport abstraction, state management, and attachment support",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "./dist/index.js",
|
|
@@ -14,6 +14,10 @@
|
|
|
14
14
|
"types": "./dist/node.d.ts",
|
|
15
15
|
"import": "./dist/node.js"
|
|
16
16
|
},
|
|
17
|
+
"./session/testing": {
|
|
18
|
+
"types": "./dist/harness/session/testing/index.d.ts",
|
|
19
|
+
"import": "./dist/harness/session/testing/index.js"
|
|
20
|
+
},
|
|
17
21
|
"./package.json": "./package.json"
|
|
18
22
|
},
|
|
19
23
|
"files": [
|
|
@@ -22,6 +26,8 @@
|
|
|
22
26
|
],
|
|
23
27
|
"scripts": {
|
|
24
28
|
"clean": "shx rm -rf dist",
|
|
29
|
+
"generate-telemetry-docs": "node scripts/generate-telemetry-docs.ts",
|
|
30
|
+
"check:telemetry-docs": "node scripts/generate-telemetry-docs.ts --check",
|
|
25
31
|
"build": "tsgo -p tsconfig.build.json",
|
|
26
32
|
"test": "vitest --run",
|
|
27
33
|
"test:harness": "vitest --run --config vitest.harness.config.ts",
|
|
@@ -29,7 +35,8 @@
|
|
|
29
35
|
"prepublishOnly": "npm run build"
|
|
30
36
|
},
|
|
31
37
|
"dependencies": {
|
|
32
|
-
"@earendil-works/pi-ai": "^0.
|
|
38
|
+
"@earendil-works/pi-ai": "^0.84.0",
|
|
39
|
+
"@earendil-works/pi-telemetry": "^0.84.0",
|
|
33
40
|
"diff": "8.0.4",
|
|
34
41
|
"ignore": "7.0.5",
|
|
35
42
|
"typebox": "1.3.7",
|
|
@@ -1,26 +0,0 @@
|
|
|
1
|
-
import type { FileSystem, JsonlSessionCreateOptions, JsonlSessionListOptions, JsonlSessionMetadata, JsonlSessionRepoApi, Session } from "../types.ts";
|
|
2
|
-
type JsonlSessionRepoFileSystem = Pick<FileSystem, "cwd" | "absolutePath" | "joinPath" | "readTextFile" | "readTextLines" | "writeFile" | "appendFile" | "listDir" | "exists" | "createDir" | "remove">;
|
|
3
|
-
export declare class JsonlSessionRepo implements JsonlSessionRepoApi {
|
|
4
|
-
private readonly fs;
|
|
5
|
-
private readonly sessionsRootInput;
|
|
6
|
-
private sessionsRoot;
|
|
7
|
-
constructor(options: {
|
|
8
|
-
fs: JsonlSessionRepoFileSystem;
|
|
9
|
-
sessionsRoot: string;
|
|
10
|
-
});
|
|
11
|
-
private getSessionsRoot;
|
|
12
|
-
private getSessionDir;
|
|
13
|
-
private createSessionFilePath;
|
|
14
|
-
create(options: JsonlSessionCreateOptions): Promise<Session<JsonlSessionMetadata>>;
|
|
15
|
-
open(metadata: JsonlSessionMetadata): Promise<Session<JsonlSessionMetadata>>;
|
|
16
|
-
list(options?: JsonlSessionListOptions): Promise<JsonlSessionMetadata[]>;
|
|
17
|
-
delete(metadata: JsonlSessionMetadata): Promise<void>;
|
|
18
|
-
fork(sourceMetadata: JsonlSessionMetadata, options: JsonlSessionCreateOptions & {
|
|
19
|
-
entryId?: string;
|
|
20
|
-
position?: "before" | "at";
|
|
21
|
-
id?: string;
|
|
22
|
-
}): Promise<Session<JsonlSessionMetadata>>;
|
|
23
|
-
private listSessionDirs;
|
|
24
|
-
}
|
|
25
|
-
export {};
|
|
26
|
-
//# sourceMappingURL=jsonl-repo.d.ts.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"jsonl-repo.d.ts","sourceRoot":"","sources":["../../../src/harness/session/jsonl-repo.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EACX,UAAU,EACV,yBAAyB,EACzB,uBAAuB,EACvB,oBAAoB,EACpB,mBAAmB,EACnB,OAAO,EACP,MAAM,aAAa,CAAC;AAWrB,KAAK,0BAA0B,GAAG,IAAI,CACrC,UAAU,EACR,KAAK,GACL,cAAc,GACd,UAAU,GACV,cAAc,GACd,eAAe,GACf,WAAW,GACX,YAAY,GACZ,SAAS,GACT,QAAQ,GACR,WAAW,GACX,QAAQ,CACV,CAAC;AAMF,qBAAa,gBAAiB,YAAW,mBAAmB;IAC3D,OAAO,CAAC,QAAQ,CAAC,EAAE,CAA6B;IAChD,OAAO,CAAC,QAAQ,CAAC,iBAAiB,CAAS;IAC3C,OAAO,CAAC,YAAY,CAAqB;IAEzC,YAAY,OAAO,EAAE;QAAE,EAAE,EAAE,0BAA0B,CAAC;QAAC,YAAY,EAAE,MAAM,CAAA;KAAE,EAG5E;YAEa,eAAe;YAUf,aAAa;YAOb,qBAAqB;IAU7B,MAAM,CAAC,OAAO,EAAE,yBAAyB,GAAG,OAAO,CAAC,OAAO,CAAC,oBAAoB,CAAC,CAAC,CAgBvF;IAEK,IAAI,CAAC,QAAQ,EAAE,oBAAoB,GAAG,OAAO,CAAC,OAAO,CAAC,oBAAoB,CAAC,CAAC,CAQjF;IAEK,IAAI,CAAC,OAAO,GAAE,uBAA4B,GAAG,OAAO,CAAC,oBAAoB,EAAE,CAAC,CAsBjF;IAEK,MAAM,CAAC,QAAQ,EAAE,oBAAoB,GAAG,OAAO,CAAC,IAAI,CAAC,CAK1D;IAEK,IAAI,CACT,cAAc,EAAE,oBAAoB,EACpC,OAAO,EAAE,yBAAyB,GAAG;QAAE,OAAO,CAAC,EAAE,MAAM,CAAC;QAAC,QAAQ,CAAC,EAAE,QAAQ,GAAG,IAAI,CAAC;QAAC,EAAE,CAAC,EAAE,MAAM,CAAA;KAAE,GAChG,OAAO,CAAC,OAAO,CAAC,oBAAoB,CAAC,CAAC,CAwBxC;YAEa,eAAe;CAgB7B","sourcesContent":["import type {\n\tFileSystem,\n\tJsonlSessionCreateOptions,\n\tJsonlSessionListOptions,\n\tJsonlSessionMetadata,\n\tJsonlSessionRepoApi,\n\tSession,\n} from \"../types.ts\";\nimport { SessionError, toError } from \"../types.ts\";\nimport { JsonlSessionStorage, loadJsonlSessionMetadata } from \"./jsonl-storage.ts\";\nimport {\n\tcreateSessionId,\n\tcreateTimestamp,\n\tgetEntriesToFork,\n\tgetFileSystemResultOrThrow,\n\ttoSession,\n} from \"./repo-utils.ts\";\n\ntype JsonlSessionRepoFileSystem = Pick<\n\tFileSystem,\n\t| \"cwd\"\n\t| \"absolutePath\"\n\t| \"joinPath\"\n\t| \"readTextFile\"\n\t| \"readTextLines\"\n\t| \"writeFile\"\n\t| \"appendFile\"\n\t| \"listDir\"\n\t| \"exists\"\n\t| \"createDir\"\n\t| \"remove\"\n>;\n\nfunction encodeCwd(cwd: string): string {\n\treturn `--${cwd.replace(/^[/\\\\]/, \"\").replace(/[/\\\\:]/g, \"-\")}--`;\n}\n\nexport class JsonlSessionRepo implements JsonlSessionRepoApi {\n\tprivate readonly fs: JsonlSessionRepoFileSystem;\n\tprivate readonly sessionsRootInput: string;\n\tprivate sessionsRoot: string | undefined;\n\n\tconstructor(options: { fs: JsonlSessionRepoFileSystem; sessionsRoot: string }) {\n\t\tthis.fs = options.fs;\n\t\tthis.sessionsRootInput = options.sessionsRoot;\n\t}\n\n\tprivate async getSessionsRoot(): Promise<string> {\n\t\tif (!this.sessionsRoot) {\n\t\t\tthis.sessionsRoot = getFileSystemResultOrThrow(\n\t\t\t\tawait this.fs.absolutePath(this.sessionsRootInput),\n\t\t\t\t`Failed to resolve sessions root ${this.sessionsRootInput}`,\n\t\t\t);\n\t\t}\n\t\treturn this.sessionsRoot;\n\t}\n\n\tprivate async getSessionDir(cwd: string): Promise<string> {\n\t\treturn getFileSystemResultOrThrow(\n\t\t\tawait this.fs.joinPath([await this.getSessionsRoot(), encodeCwd(cwd)]),\n\t\t\t`Failed to resolve session directory for ${cwd}`,\n\t\t);\n\t}\n\n\tprivate async createSessionFilePath(cwd: string, sessionId: string, timestamp: string): Promise<string> {\n\t\treturn getFileSystemResultOrThrow(\n\t\t\tawait this.fs.joinPath([\n\t\t\t\tawait this.getSessionDir(cwd),\n\t\t\t\t`${timestamp.replace(/[:.]/g, \"-\")}_${sessionId}.jsonl`,\n\t\t\t]),\n\t\t\t`Failed to resolve session file path for ${sessionId}`,\n\t\t);\n\t}\n\n\tasync create(options: JsonlSessionCreateOptions): Promise<Session<JsonlSessionMetadata>> {\n\t\tconst id = options.id ?? createSessionId();\n\t\tconst createdAt = createTimestamp();\n\t\tconst sessionDir = await this.getSessionDir(options.cwd);\n\t\tgetFileSystemResultOrThrow(\n\t\t\tawait this.fs.createDir(sessionDir, { recursive: true }),\n\t\t\t`Failed to create session directory ${sessionDir}`,\n\t\t);\n\t\tconst filePath = await this.createSessionFilePath(options.cwd, id, createdAt);\n\t\tconst storage = await JsonlSessionStorage.create(this.fs, filePath, {\n\t\t\tcwd: options.cwd,\n\t\t\tsessionId: id,\n\t\t\tparentSessionPath: options.parentSessionPath,\n\t\t\tmetadata: options.metadata,\n\t\t});\n\t\treturn toSession(storage);\n\t}\n\n\tasync open(metadata: JsonlSessionMetadata): Promise<Session<JsonlSessionMetadata>> {\n\t\tif (\n\t\t\t!getFileSystemResultOrThrow(await this.fs.exists(metadata.path), `Failed to check session ${metadata.path}`)\n\t\t) {\n\t\t\tthrow new SessionError(\"not_found\", `Session not found: ${metadata.path}`);\n\t\t}\n\t\tconst storage = await JsonlSessionStorage.open(this.fs, metadata.path);\n\t\treturn toSession(storage);\n\t}\n\n\tasync list(options: JsonlSessionListOptions = {}): Promise<JsonlSessionMetadata[]> {\n\t\tconst dirs = options.cwd ? [await this.getSessionDir(options.cwd)] : await this.listSessionDirs();\n\t\tconst sessions: JsonlSessionMetadata[] = [];\n\t\tfor (const dir of dirs) {\n\t\t\tif (!getFileSystemResultOrThrow(await this.fs.exists(dir), `Failed to check session directory ${dir}`)) {\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tconst files = getFileSystemResultOrThrow(\n\t\t\t\tawait this.fs.listDir(dir),\n\t\t\t\t`Failed to list sessions in ${dir}`,\n\t\t\t).filter((file) => file.kind !== \"directory\" && file.name.endsWith(\".jsonl\"));\n\t\t\tfor (const file of files) {\n\t\t\t\ttry {\n\t\t\t\t\tsessions.push(await loadJsonlSessionMetadata(this.fs, file.path));\n\t\t\t\t} catch (error) {\n\t\t\t\t\tconst cause = toError(error);\n\t\t\t\t\tif (!(cause instanceof SessionError) || cause.code !== \"invalid_session\") throw cause;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tsessions.sort((a, b) => new Date(b.createdAt).getTime() - new Date(a.createdAt).getTime());\n\t\treturn sessions;\n\t}\n\n\tasync delete(metadata: JsonlSessionMetadata): Promise<void> {\n\t\tgetFileSystemResultOrThrow(\n\t\t\tawait this.fs.remove(metadata.path, { force: true }),\n\t\t\t`Failed to delete session ${metadata.path}`,\n\t\t);\n\t}\n\n\tasync fork(\n\t\tsourceMetadata: JsonlSessionMetadata,\n\t\toptions: JsonlSessionCreateOptions & { entryId?: string; position?: \"before\" | \"at\"; id?: string },\n\t): Promise<Session<JsonlSessionMetadata>> {\n\t\tconst source = await this.open(sourceMetadata);\n\t\tconst forkedEntries = await getEntriesToFork(source.getStorage(), options);\n\t\tconst id = options.id ?? createSessionId();\n\t\tconst createdAt = createTimestamp();\n\t\tconst sessionDir = await this.getSessionDir(options.cwd);\n\t\tgetFileSystemResultOrThrow(\n\t\t\tawait this.fs.createDir(sessionDir, { recursive: true }),\n\t\t\t`Failed to create session directory ${sessionDir}`,\n\t\t);\n\t\tconst storage = await JsonlSessionStorage.create(\n\t\t\tthis.fs,\n\t\t\tawait this.createSessionFilePath(options.cwd, id, createdAt),\n\t\t\t{\n\t\t\t\tcwd: options.cwd,\n\t\t\t\tsessionId: id,\n\t\t\t\tparentSessionPath: options.parentSessionPath ?? sourceMetadata.path,\n\t\t\t\tmetadata: options.metadata ?? sourceMetadata.metadata,\n\t\t\t},\n\t\t);\n\t\tfor (const entry of forkedEntries) {\n\t\t\tawait storage.appendEntry(entry);\n\t\t}\n\t\treturn toSession(storage);\n\t}\n\n\tprivate async listSessionDirs(): Promise<string[]> {\n\t\tconst sessionsRoot = await this.getSessionsRoot();\n\t\tif (\n\t\t\t!getFileSystemResultOrThrow(\n\t\t\t\tawait this.fs.exists(sessionsRoot),\n\t\t\t\t`Failed to check sessions root ${sessionsRoot}`,\n\t\t\t)\n\t\t) {\n\t\t\treturn [];\n\t\t}\n\t\tconst entries = getFileSystemResultOrThrow(\n\t\t\tawait this.fs.listDir(sessionsRoot),\n\t\t\t`Failed to list sessions root ${sessionsRoot}`,\n\t\t);\n\t\treturn entries.filter((entry) => entry.kind === \"directory\").map((entry) => entry.path);\n\t}\n}\n"]}
|
|
@@ -1,103 +0,0 @@
|
|
|
1
|
-
import { SessionError, toError } from "../types.js";
|
|
2
|
-
import { JsonlSessionStorage, loadJsonlSessionMetadata } from "./jsonl-storage.js";
|
|
3
|
-
import { createSessionId, createTimestamp, getEntriesToFork, getFileSystemResultOrThrow, toSession, } from "./repo-utils.js";
|
|
4
|
-
function encodeCwd(cwd) {
|
|
5
|
-
return `--${cwd.replace(/^[/\\]/, "").replace(/[/\\:]/g, "-")}--`;
|
|
6
|
-
}
|
|
7
|
-
export class JsonlSessionRepo {
|
|
8
|
-
fs;
|
|
9
|
-
sessionsRootInput;
|
|
10
|
-
sessionsRoot;
|
|
11
|
-
constructor(options) {
|
|
12
|
-
this.fs = options.fs;
|
|
13
|
-
this.sessionsRootInput = options.sessionsRoot;
|
|
14
|
-
}
|
|
15
|
-
async getSessionsRoot() {
|
|
16
|
-
if (!this.sessionsRoot) {
|
|
17
|
-
this.sessionsRoot = getFileSystemResultOrThrow(await this.fs.absolutePath(this.sessionsRootInput), `Failed to resolve sessions root ${this.sessionsRootInput}`);
|
|
18
|
-
}
|
|
19
|
-
return this.sessionsRoot;
|
|
20
|
-
}
|
|
21
|
-
async getSessionDir(cwd) {
|
|
22
|
-
return getFileSystemResultOrThrow(await this.fs.joinPath([await this.getSessionsRoot(), encodeCwd(cwd)]), `Failed to resolve session directory for ${cwd}`);
|
|
23
|
-
}
|
|
24
|
-
async createSessionFilePath(cwd, sessionId, timestamp) {
|
|
25
|
-
return getFileSystemResultOrThrow(await this.fs.joinPath([
|
|
26
|
-
await this.getSessionDir(cwd),
|
|
27
|
-
`${timestamp.replace(/[:.]/g, "-")}_${sessionId}.jsonl`,
|
|
28
|
-
]), `Failed to resolve session file path for ${sessionId}`);
|
|
29
|
-
}
|
|
30
|
-
async create(options) {
|
|
31
|
-
const id = options.id ?? createSessionId();
|
|
32
|
-
const createdAt = createTimestamp();
|
|
33
|
-
const sessionDir = await this.getSessionDir(options.cwd);
|
|
34
|
-
getFileSystemResultOrThrow(await this.fs.createDir(sessionDir, { recursive: true }), `Failed to create session directory ${sessionDir}`);
|
|
35
|
-
const filePath = await this.createSessionFilePath(options.cwd, id, createdAt);
|
|
36
|
-
const storage = await JsonlSessionStorage.create(this.fs, filePath, {
|
|
37
|
-
cwd: options.cwd,
|
|
38
|
-
sessionId: id,
|
|
39
|
-
parentSessionPath: options.parentSessionPath,
|
|
40
|
-
metadata: options.metadata,
|
|
41
|
-
});
|
|
42
|
-
return toSession(storage);
|
|
43
|
-
}
|
|
44
|
-
async open(metadata) {
|
|
45
|
-
if (!getFileSystemResultOrThrow(await this.fs.exists(metadata.path), `Failed to check session ${metadata.path}`)) {
|
|
46
|
-
throw new SessionError("not_found", `Session not found: ${metadata.path}`);
|
|
47
|
-
}
|
|
48
|
-
const storage = await JsonlSessionStorage.open(this.fs, metadata.path);
|
|
49
|
-
return toSession(storage);
|
|
50
|
-
}
|
|
51
|
-
async list(options = {}) {
|
|
52
|
-
const dirs = options.cwd ? [await this.getSessionDir(options.cwd)] : await this.listSessionDirs();
|
|
53
|
-
const sessions = [];
|
|
54
|
-
for (const dir of dirs) {
|
|
55
|
-
if (!getFileSystemResultOrThrow(await this.fs.exists(dir), `Failed to check session directory ${dir}`)) {
|
|
56
|
-
continue;
|
|
57
|
-
}
|
|
58
|
-
const files = getFileSystemResultOrThrow(await this.fs.listDir(dir), `Failed to list sessions in ${dir}`).filter((file) => file.kind !== "directory" && file.name.endsWith(".jsonl"));
|
|
59
|
-
for (const file of files) {
|
|
60
|
-
try {
|
|
61
|
-
sessions.push(await loadJsonlSessionMetadata(this.fs, file.path));
|
|
62
|
-
}
|
|
63
|
-
catch (error) {
|
|
64
|
-
const cause = toError(error);
|
|
65
|
-
if (!(cause instanceof SessionError) || cause.code !== "invalid_session")
|
|
66
|
-
throw cause;
|
|
67
|
-
}
|
|
68
|
-
}
|
|
69
|
-
}
|
|
70
|
-
sessions.sort((a, b) => new Date(b.createdAt).getTime() - new Date(a.createdAt).getTime());
|
|
71
|
-
return sessions;
|
|
72
|
-
}
|
|
73
|
-
async delete(metadata) {
|
|
74
|
-
getFileSystemResultOrThrow(await this.fs.remove(metadata.path, { force: true }), `Failed to delete session ${metadata.path}`);
|
|
75
|
-
}
|
|
76
|
-
async fork(sourceMetadata, options) {
|
|
77
|
-
const source = await this.open(sourceMetadata);
|
|
78
|
-
const forkedEntries = await getEntriesToFork(source.getStorage(), options);
|
|
79
|
-
const id = options.id ?? createSessionId();
|
|
80
|
-
const createdAt = createTimestamp();
|
|
81
|
-
const sessionDir = await this.getSessionDir(options.cwd);
|
|
82
|
-
getFileSystemResultOrThrow(await this.fs.createDir(sessionDir, { recursive: true }), `Failed to create session directory ${sessionDir}`);
|
|
83
|
-
const storage = await JsonlSessionStorage.create(this.fs, await this.createSessionFilePath(options.cwd, id, createdAt), {
|
|
84
|
-
cwd: options.cwd,
|
|
85
|
-
sessionId: id,
|
|
86
|
-
parentSessionPath: options.parentSessionPath ?? sourceMetadata.path,
|
|
87
|
-
metadata: options.metadata ?? sourceMetadata.metadata,
|
|
88
|
-
});
|
|
89
|
-
for (const entry of forkedEntries) {
|
|
90
|
-
await storage.appendEntry(entry);
|
|
91
|
-
}
|
|
92
|
-
return toSession(storage);
|
|
93
|
-
}
|
|
94
|
-
async listSessionDirs() {
|
|
95
|
-
const sessionsRoot = await this.getSessionsRoot();
|
|
96
|
-
if (!getFileSystemResultOrThrow(await this.fs.exists(sessionsRoot), `Failed to check sessions root ${sessionsRoot}`)) {
|
|
97
|
-
return [];
|
|
98
|
-
}
|
|
99
|
-
const entries = getFileSystemResultOrThrow(await this.fs.listDir(sessionsRoot), `Failed to list sessions root ${sessionsRoot}`);
|
|
100
|
-
return entries.filter((entry) => entry.kind === "directory").map((entry) => entry.path);
|
|
101
|
-
}
|
|
102
|
-
}
|
|
103
|
-
//# sourceMappingURL=jsonl-repo.js.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"jsonl-repo.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I,CAAC,CAAC;IAAA,CACxF;CACD","sourcesContent":["import type {\n\tFileSystem,\n\tJsonlSessionCreateOptions,\n\tJsonlSessionListOptions,\n\tJsonlSessionMetadata,\n\tJsonlSessionRepoApi,\n\tSession,\n} from \"../types.ts\";\nimport { SessionError, toError } from \"../types.ts\";\nimport { JsonlSessionStorage, loadJsonlSessionMetadata } from \"./jsonl-storage.ts\";\nimport {\n\tcreateSessionId,\n\tcreateTimestamp,\n\tgetEntriesToFork,\n\tgetFileSystemResultOrThrow,\n\ttoSession,\n} from \"./repo-utils.ts\";\n\ntype JsonlSessionRepoFileSystem = Pick<\n\tFileSystem,\n\t| \"cwd\"\n\t| \"absolutePath\"\n\t| \"joinPath\"\n\t| \"readTextFile\"\n\t| \"readTextLines\"\n\t| \"writeFile\"\n\t| \"appendFile\"\n\t| \"listDir\"\n\t| \"exists\"\n\t| \"createDir\"\n\t| \"remove\"\n>;\n\nfunction encodeCwd(cwd: string): string {\n\treturn `--${cwd.replace(/^[/\\\\]/, \"\").replace(/[/\\\\:]/g, \"-\")}--`;\n}\n\nexport class JsonlSessionRepo implements JsonlSessionRepoApi {\n\tprivate readonly fs: JsonlSessionRepoFileSystem;\n\tprivate readonly sessionsRootInput: string;\n\tprivate sessionsRoot: string | undefined;\n\n\tconstructor(options: { fs: JsonlSessionRepoFileSystem; sessionsRoot: string }) {\n\t\tthis.fs = options.fs;\n\t\tthis.sessionsRootInput = options.sessionsRoot;\n\t}\n\n\tprivate async getSessionsRoot(): Promise<string> {\n\t\tif (!this.sessionsRoot) {\n\t\t\tthis.sessionsRoot = getFileSystemResultOrThrow(\n\t\t\t\tawait this.fs.absolutePath(this.sessionsRootInput),\n\t\t\t\t`Failed to resolve sessions root ${this.sessionsRootInput}`,\n\t\t\t);\n\t\t}\n\t\treturn this.sessionsRoot;\n\t}\n\n\tprivate async getSessionDir(cwd: string): Promise<string> {\n\t\treturn getFileSystemResultOrThrow(\n\t\t\tawait this.fs.joinPath([await this.getSessionsRoot(), encodeCwd(cwd)]),\n\t\t\t`Failed to resolve session directory for ${cwd}`,\n\t\t);\n\t}\n\n\tprivate async createSessionFilePath(cwd: string, sessionId: string, timestamp: string): Promise<string> {\n\t\treturn getFileSystemResultOrThrow(\n\t\t\tawait this.fs.joinPath([\n\t\t\t\tawait this.getSessionDir(cwd),\n\t\t\t\t`${timestamp.replace(/[:.]/g, \"-\")}_${sessionId}.jsonl`,\n\t\t\t]),\n\t\t\t`Failed to resolve session file path for ${sessionId}`,\n\t\t);\n\t}\n\n\tasync create(options: JsonlSessionCreateOptions): Promise<Session<JsonlSessionMetadata>> {\n\t\tconst id = options.id ?? createSessionId();\n\t\tconst createdAt = createTimestamp();\n\t\tconst sessionDir = await this.getSessionDir(options.cwd);\n\t\tgetFileSystemResultOrThrow(\n\t\t\tawait this.fs.createDir(sessionDir, { recursive: true }),\n\t\t\t`Failed to create session directory ${sessionDir}`,\n\t\t);\n\t\tconst filePath = await this.createSessionFilePath(options.cwd, id, createdAt);\n\t\tconst storage = await JsonlSessionStorage.create(this.fs, filePath, {\n\t\t\tcwd: options.cwd,\n\t\t\tsessionId: id,\n\t\t\tparentSessionPath: options.parentSessionPath,\n\t\t\tmetadata: options.metadata,\n\t\t});\n\t\treturn toSession(storage);\n\t}\n\n\tasync open(metadata: JsonlSessionMetadata): Promise<Session<JsonlSessionMetadata>> {\n\t\tif (\n\t\t\t!getFileSystemResultOrThrow(await this.fs.exists(metadata.path), `Failed to check session ${metadata.path}`)\n\t\t) {\n\t\t\tthrow new SessionError(\"not_found\", `Session not found: ${metadata.path}`);\n\t\t}\n\t\tconst storage = await JsonlSessionStorage.open(this.fs, metadata.path);\n\t\treturn toSession(storage);\n\t}\n\n\tasync list(options: JsonlSessionListOptions = {}): Promise<JsonlSessionMetadata[]> {\n\t\tconst dirs = options.cwd ? [await this.getSessionDir(options.cwd)] : await this.listSessionDirs();\n\t\tconst sessions: JsonlSessionMetadata[] = [];\n\t\tfor (const dir of dirs) {\n\t\t\tif (!getFileSystemResultOrThrow(await this.fs.exists(dir), `Failed to check session directory ${dir}`)) {\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tconst files = getFileSystemResultOrThrow(\n\t\t\t\tawait this.fs.listDir(dir),\n\t\t\t\t`Failed to list sessions in ${dir}`,\n\t\t\t).filter((file) => file.kind !== \"directory\" && file.name.endsWith(\".jsonl\"));\n\t\t\tfor (const file of files) {\n\t\t\t\ttry {\n\t\t\t\t\tsessions.push(await loadJsonlSessionMetadata(this.fs, file.path));\n\t\t\t\t} catch (error) {\n\t\t\t\t\tconst cause = toError(error);\n\t\t\t\t\tif (!(cause instanceof SessionError) || cause.code !== \"invalid_session\") throw cause;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tsessions.sort((a, b) => new Date(b.createdAt).getTime() - new Date(a.createdAt).getTime());\n\t\treturn sessions;\n\t}\n\n\tasync delete(metadata: JsonlSessionMetadata): Promise<void> {\n\t\tgetFileSystemResultOrThrow(\n\t\t\tawait this.fs.remove(metadata.path, { force: true }),\n\t\t\t`Failed to delete session ${metadata.path}`,\n\t\t);\n\t}\n\n\tasync fork(\n\t\tsourceMetadata: JsonlSessionMetadata,\n\t\toptions: JsonlSessionCreateOptions & { entryId?: string; position?: \"before\" | \"at\"; id?: string },\n\t): Promise<Session<JsonlSessionMetadata>> {\n\t\tconst source = await this.open(sourceMetadata);\n\t\tconst forkedEntries = await getEntriesToFork(source.getStorage(), options);\n\t\tconst id = options.id ?? createSessionId();\n\t\tconst createdAt = createTimestamp();\n\t\tconst sessionDir = await this.getSessionDir(options.cwd);\n\t\tgetFileSystemResultOrThrow(\n\t\t\tawait this.fs.createDir(sessionDir, { recursive: true }),\n\t\t\t`Failed to create session directory ${sessionDir}`,\n\t\t);\n\t\tconst storage = await JsonlSessionStorage.create(\n\t\t\tthis.fs,\n\t\t\tawait this.createSessionFilePath(options.cwd, id, createdAt),\n\t\t\t{\n\t\t\t\tcwd: options.cwd,\n\t\t\t\tsessionId: id,\n\t\t\t\tparentSessionPath: options.parentSessionPath ?? sourceMetadata.path,\n\t\t\t\tmetadata: options.metadata ?? sourceMetadata.metadata,\n\t\t\t},\n\t\t);\n\t\tfor (const entry of forkedEntries) {\n\t\t\tawait storage.appendEntry(entry);\n\t\t}\n\t\treturn toSession(storage);\n\t}\n\n\tprivate async listSessionDirs(): Promise<string[]> {\n\t\tconst sessionsRoot = await this.getSessionsRoot();\n\t\tif (\n\t\t\t!getFileSystemResultOrThrow(\n\t\t\t\tawait this.fs.exists(sessionsRoot),\n\t\t\t\t`Failed to check sessions root ${sessionsRoot}`,\n\t\t\t)\n\t\t) {\n\t\t\treturn [];\n\t\t}\n\t\tconst entries = getFileSystemResultOrThrow(\n\t\t\tawait this.fs.listDir(sessionsRoot),\n\t\t\t`Failed to list sessions root ${sessionsRoot}`,\n\t\t);\n\t\treturn entries.filter((entry) => entry.kind === \"directory\").map((entry) => entry.path);\n\t}\n}\n"]}
|
|
@@ -1,42 +0,0 @@
|
|
|
1
|
-
import type { FileSystem, JsonlSessionMetadata, SessionEntryCursorOptions, SessionStorage, SessionTreeEntry } from "../types.ts";
|
|
2
|
-
type JsonlSessionStorageFileSystem = Pick<FileSystem, "readTextFile" | "readTextLines" | "writeFile" | "appendFile">;
|
|
3
|
-
export declare function loadJsonlSessionMetadata(fs: JsonlSessionStorageFileSystem, filePath: string): Promise<JsonlSessionMetadata>;
|
|
4
|
-
export declare class JsonlSessionStorage implements SessionStorage<JsonlSessionMetadata> {
|
|
5
|
-
private readonly fs;
|
|
6
|
-
private readonly filePath;
|
|
7
|
-
private readonly metadata;
|
|
8
|
-
private entries;
|
|
9
|
-
private byId;
|
|
10
|
-
private labelsById;
|
|
11
|
-
private currentLeafId;
|
|
12
|
-
private constructor();
|
|
13
|
-
static open(fs: JsonlSessionStorageFileSystem, filePath: string): Promise<JsonlSessionStorage>;
|
|
14
|
-
static create(fs: JsonlSessionStorageFileSystem, filePath: string, options: {
|
|
15
|
-
cwd: string;
|
|
16
|
-
sessionId: string;
|
|
17
|
-
parentSessionPath?: string;
|
|
18
|
-
metadata?: Record<string, unknown>;
|
|
19
|
-
}): Promise<JsonlSessionStorage>;
|
|
20
|
-
getMetadata(): Promise<JsonlSessionMetadata>;
|
|
21
|
-
getLeafId(): Promise<string | null>;
|
|
22
|
-
setLeafId(leafId: string | null): Promise<void>;
|
|
23
|
-
createEntryId(): Promise<string>;
|
|
24
|
-
appendEntry(entry: SessionTreeEntry): Promise<void>;
|
|
25
|
-
getEntry(id: string): Promise<SessionTreeEntry | undefined>;
|
|
26
|
-
findEntries<TType extends SessionTreeEntry["type"]>(type: TType): Promise<Array<Extract<SessionTreeEntry, {
|
|
27
|
-
type: TType;
|
|
28
|
-
}>>>;
|
|
29
|
-
getLabel(id: string): Promise<string | undefined>;
|
|
30
|
-
getSessionName(): Promise<string | undefined>;
|
|
31
|
-
getSessionStats(): Promise<{
|
|
32
|
-
messageCount: number;
|
|
33
|
-
cachedTokens: number;
|
|
34
|
-
uncachedTokens: number;
|
|
35
|
-
totalTokens: number;
|
|
36
|
-
costTotal: number;
|
|
37
|
-
}>;
|
|
38
|
-
getPathToRootOrCompaction(leafId: string | null): Promise<SessionTreeEntry[]>;
|
|
39
|
-
getEntries(options?: SessionEntryCursorOptions): Promise<SessionTreeEntry[]>;
|
|
40
|
-
}
|
|
41
|
-
export {};
|
|
42
|
-
//# sourceMappingURL=jsonl-storage.d.ts.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"jsonl-storage.d.ts","sourceRoot":"","sources":["../../../src/harness/session/jsonl-storage.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EACX,UAAU,EACV,oBAAoB,EAEpB,yBAAyB,EACzB,cAAc,EACd,gBAAgB,EAChB,MAAM,aAAa,CAAC;AAIrB,KAAK,6BAA6B,GAAG,IAAI,CAAC,UAAU,EAAE,cAAc,GAAG,eAAe,GAAG,WAAW,GAAG,YAAY,CAAC,CAAC;AAwIrH,wBAAsB,wBAAwB,CAC7C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CAEhE;IAEK,WAAW,CAAC,KAAK,SAAS,gBAAgB,CAAC,MAAM,CAAC,EACvD,IAAI,EAAE,KAAK,GACT,OAAO,CAAC,KAAK,CAAC,OAAO,CAAC,gBAAgB,EAAE;QAAE,IAAI,EAAE,KAAK,CAAA;KAAE,CAAC,CAAC,CAAC,CAE5D;IAEK,QAAQ,CAAC,EAAE,EAAE,MAAM,GAAG,OAAO,CAAC,MAAM,GAAG,SAAS,CAAC,CAEtD;IAEK,cAAc,IAAI,OAAO,CAAC,MAAM,GAAG,SAAS,CAAC,CAGlD;IAEK,eAAe;;;;;;OAwCpB;IAEK,yBAAyB,CAAC,MAAM,EAAE,MAAM,GAAG,IAAI,GAAG,OAAO,CAAC,gBAAgB,EAAE,CAAC,CAmBlF;IAEK,UAAU,CAAC,OAAO,CAAC,EAAE,yBAAyB,GAAG,OAAO,CAAC,gBAAgB,EAAE,CAAC,CAIjF;CACD","sourcesContent":["import { uuidv7 } from \"@earendil-works/pi-ai\";\nimport type {\n\tFileSystem,\n\tJsonlSessionMetadata,\n\tLeafEntry,\n\tSessionEntryCursorOptions,\n\tSessionStorage,\n\tSessionTreeEntry,\n} from \"../types.ts\";\nimport { SessionError, toError } from \"../types.ts\";\nimport { getFileSystemResultOrThrow } from \"./repo-utils.ts\";\n\ntype JsonlSessionStorageFileSystem = Pick<FileSystem, \"readTextFile\" | \"readTextLines\" | \"writeFile\" | \"appendFile\">;\n\ninterface SessionHeader {\n\ttype: \"session\";\n\tversion: 3;\n\tid: string;\n\ttimestamp: string;\n\tcwd: string;\n\tparentSession?: string;\n\tmetadata?: Record<string, unknown>;\n}\n\nfunction updateLabelCache(labelsById: Map<string, string>, entry: SessionTreeEntry): void {\n\tif (entry.type !== \"label\") return;\n\tconst label = entry.label?.trim();\n\tif (label) {\n\t\tlabelsById.set(entry.targetId, label);\n\t} else {\n\t\tlabelsById.delete(entry.targetId);\n\t}\n}\n\nfunction buildLabelsById(entries: SessionTreeEntry[]): Map<string, string> {\n\tconst labelsById = new Map<string, string>();\n\tfor (const entry of entries) {\n\t\tupdateLabelCache(labelsById, entry);\n\t}\n\treturn labelsById;\n}\n\nfunction generateEntryId(byId: { has(id: string): boolean }): string {\n\tfor (let i = 0; i < 100; i++) {\n\t\t// The uuidv7 prefix is timestamp-derived and nearly constant between calls,\n\t\t// so short ids must come from the random tail.\n\t\tconst id = uuidv7().slice(-8);\n\t\tif (!byId.has(id)) return id;\n\t}\n\treturn uuidv7();\n}\n\nfunction invalidSession(filePath: string, message: string, cause?: Error): SessionError {\n\treturn new SessionError(\"invalid_session\", `Invalid JSONL session file ${filePath}: ${message}`, cause);\n}\n\nfunction invalidEntry(filePath: string, lineNumber: number, message: string, cause?: Error): SessionError {\n\treturn new SessionError(\n\t\t\"invalid_entry\",\n\t\t`Invalid JSONL session file ${filePath}: line ${lineNumber} ${message}`,\n\t\tcause,\n\t);\n}\n\nfunction parseHeaderLine(line: string, filePath: string): SessionHeader {\n\tlet parsed: unknown;\n\ttry {\n\t\tparsed = JSON.parse(line);\n\t} catch (error) {\n\t\tthrow invalidSession(filePath, \"first line is not a valid session header\", toError(error));\n\t}\n\tif (typeof parsed !== \"object\" || parsed === null) {\n\t\tthrow invalidSession(filePath, \"first line is not a valid session header\");\n\t}\n\tconst header = parsed as Partial<SessionHeader>;\n\tif (header.type !== \"session\") throw invalidSession(filePath, \"first line is not a valid session header\");\n\tif (header.version !== 3) throw invalidSession(filePath, \"unsupported session version\");\n\tif (typeof header.id !== \"string\" || !header.id) throw invalidSession(filePath, \"session header is missing id\");\n\tif (typeof header.timestamp !== \"string\" || !header.timestamp) {\n\t\tthrow invalidSession(filePath, \"session header is missing timestamp\");\n\t}\n\tif (typeof header.cwd !== \"string\" || !header.cwd) throw invalidSession(filePath, \"session header is missing cwd\");\n\tif (header.parentSession !== undefined && typeof header.parentSession !== \"string\") {\n\t\tthrow invalidSession(filePath, \"session header parentSession must be a string\");\n\t}\n\tif (\n\t\theader.metadata !== undefined &&\n\t\t(typeof header.metadata !== \"object\" || header.metadata === null || Array.isArray(header.metadata))\n\t) {\n\t\tthrow invalidSession(filePath, \"session header metadata must be an object\");\n\t}\n\treturn {\n\t\ttype: \"session\",\n\t\tversion: 3,\n\t\tid: header.id,\n\t\ttimestamp: header.timestamp,\n\t\tcwd: header.cwd,\n\t\tparentSession: header.parentSession,\n\t\tmetadata: header.metadata,\n\t};\n}\n\nfunction parseEntryLine(line: string, filePath: string, lineNumber: number): SessionTreeEntry {\n\tlet parsed: unknown;\n\ttry {\n\t\tparsed = JSON.parse(line);\n\t} catch (error) {\n\t\tthrow invalidEntry(filePath, lineNumber, \"is not valid JSON\", toError(error));\n\t}\n\tif (typeof parsed !== \"object\" || parsed === null) {\n\t\tthrow invalidEntry(filePath, lineNumber, \"is not a valid session entry\");\n\t}\n\tconst entry = parsed as {\n\t\ttype?: unknown;\n\t\tid?: unknown;\n\t\tparentId?: unknown;\n\t\ttimestamp?: unknown;\n\t\ttargetId?: unknown;\n\t};\n\tif (typeof entry.type !== \"string\") throw invalidEntry(filePath, lineNumber, \"is missing entry type\");\n\tif (typeof entry.id !== \"string\" || !entry.id) throw invalidEntry(filePath, lineNumber, \"is missing entry id\");\n\tif (entry.parentId !== null && typeof entry.parentId !== \"string\") {\n\t\tthrow invalidEntry(filePath, lineNumber, \"has invalid parentId\");\n\t}\n\tif (typeof entry.timestamp !== \"string\" || !entry.timestamp) {\n\t\tthrow invalidEntry(filePath, lineNumber, \"is missing timestamp\");\n\t}\n\tif (entry.type === \"leaf\" && entry.targetId !== null && typeof entry.targetId !== \"string\") {\n\t\tthrow invalidEntry(filePath, lineNumber, \"has invalid targetId\");\n\t}\n\treturn entry as SessionTreeEntry;\n}\n\nfunction leafIdAfterEntry(entry: SessionTreeEntry): string | null {\n\treturn entry.type === \"leaf\" ? entry.targetId : entry.id;\n}\n\nfunction headerToSessionMetadata(header: SessionHeader, path: string): JsonlSessionMetadata {\n\treturn {\n\t\tid: header.id,\n\t\tcreatedAt: header.timestamp,\n\t\tcwd: header.cwd,\n\t\tpath,\n\t\tparentSessionPath: header.parentSession,\n\t\tmetadata: header.metadata,\n\t};\n}\n\nexport async function loadJsonlSessionMetadata(\n\tfs: JsonlSessionStorageFileSystem,\n\tfilePath: string,\n): Promise<JsonlSessionMetadata> {\n\tconst lines = getFileSystemResultOrThrow(\n\t\tawait fs.readTextLines(filePath, { maxLines: 1 }),\n\t\t`Failed to read session header ${filePath}`,\n\t);\n\tconst line = lines[0];\n\tif (line?.trim()) return headerToSessionMetadata(parseHeaderLine(line, filePath), filePath);\n\tthrow invalidSession(filePath, \"missing session header\");\n}\n\nasync function loadJsonlStorage(\n\tfs: JsonlSessionStorageFileSystem,\n\tfilePath: string,\n): Promise<{\n\theader: SessionHeader;\n\tentries: SessionTreeEntry[];\n\tleafId: string | null;\n}> {\n\tconst content = getFileSystemResultOrThrow(await fs.readTextFile(filePath), `Failed to read session ${filePath}`);\n\tconst lines = content.split(\"\\n\").filter((line) => line.trim());\n\tif (lines.length === 0) {\n\t\tthrow invalidSession(filePath, \"missing session header\");\n\t}\n\n\tconst header = parseHeaderLine(lines[0]!, filePath);\n\tconst entries: SessionTreeEntry[] = [];\n\tlet leafId: string | null = null;\n\tfor (let i = 1; i < lines.length; i++) {\n\t\tconst entry = parseEntryLine(lines[i]!, filePath, i + 1);\n\t\tentries.push(entry);\n\t\tleafId = leafIdAfterEntry(entry);\n\t}\n\treturn { header, entries, leafId };\n}\n\nexport class JsonlSessionStorage implements SessionStorage<JsonlSessionMetadata> {\n\tprivate readonly fs: JsonlSessionStorageFileSystem;\n\tprivate readonly filePath: string;\n\tprivate readonly metadata: JsonlSessionMetadata;\n\tprivate entries: SessionTreeEntry[];\n\tprivate byId: Map<string, SessionTreeEntry>;\n\tprivate labelsById: Map<string, string>;\n\tprivate currentLeafId: string | null;\n\n\tprivate constructor(\n\t\tfs: JsonlSessionStorageFileSystem,\n\t\tfilePath: string,\n\t\theader: SessionHeader,\n\t\tentries: SessionTreeEntry[],\n\t\tleafId: string | null,\n\t) {\n\t\tthis.fs = fs;\n\t\tthis.filePath = filePath;\n\t\tthis.metadata = headerToSessionMetadata(header, this.filePath);\n\t\tthis.entries = entries;\n\t\tthis.byId = new Map(entries.map((entry) => [entry.id, entry]));\n\t\tthis.labelsById = buildLabelsById(entries);\n\t\tthis.currentLeafId = leafId;\n\t}\n\n\tstatic async open(fs: JsonlSessionStorageFileSystem, filePath: string): Promise<JsonlSessionStorage> {\n\t\tconst loaded = await loadJsonlStorage(fs, filePath);\n\t\treturn new JsonlSessionStorage(fs, filePath, loaded.header, loaded.entries, loaded.leafId);\n\t}\n\n\tstatic async create(\n\t\tfs: JsonlSessionStorageFileSystem,\n\t\tfilePath: string,\n\t\toptions: {\n\t\t\tcwd: string;\n\t\t\tsessionId: string;\n\t\t\tparentSessionPath?: string;\n\t\t\tmetadata?: Record<string, unknown>;\n\t\t},\n\t): Promise<JsonlSessionStorage> {\n\t\tconst header: SessionHeader = {\n\t\t\ttype: \"session\",\n\t\t\tversion: 3,\n\t\t\tid: options.sessionId,\n\t\t\ttimestamp: new Date().toISOString(),\n\t\t\tcwd: options.cwd,\n\t\t\tparentSession: options.parentSessionPath,\n\t\t\tmetadata: options.metadata,\n\t\t};\n\t\tgetFileSystemResultOrThrow(\n\t\t\tawait fs.writeFile(filePath, `${JSON.stringify(header)}\\n`),\n\t\t\t`Failed to create session ${filePath}`,\n\t\t);\n\t\treturn new JsonlSessionStorage(fs, filePath, header, [], null);\n\t}\n\n\tasync getMetadata(): Promise<JsonlSessionMetadata> {\n\t\treturn this.metadata;\n\t}\n\n\tasync getLeafId(): Promise<string | null> {\n\t\tif (this.currentLeafId !== null && !this.byId.has(this.currentLeafId)) {\n\t\t\tthrow new SessionError(\"invalid_session\", `Entry ${this.currentLeafId} not found`);\n\t\t}\n\t\treturn this.currentLeafId;\n\t}\n\n\tasync setLeafId(leafId: string | null): Promise<void> {\n\t\tif (leafId !== null && !this.byId.has(leafId)) {\n\t\t\tthrow new SessionError(\"not_found\", `Entry ${leafId} not found`);\n\t\t}\n\t\tconst entry: LeafEntry = {\n\t\t\ttype: \"leaf\",\n\t\t\tid: generateEntryId(this.byId),\n\t\t\tparentId: this.currentLeafId,\n\t\t\ttimestamp: new Date().toISOString(),\n\t\t\ttargetId: leafId,\n\t\t};\n\t\tgetFileSystemResultOrThrow(\n\t\t\tawait this.fs.appendFile(this.filePath, `${JSON.stringify(entry)}\\n`),\n\t\t\t`Failed to append session leaf ${entry.id}`,\n\t\t);\n\t\tthis.entries.push(entry);\n\t\tthis.byId.set(entry.id, entry);\n\t\tthis.currentLeafId = leafId;\n\t}\n\n\tasync createEntryId(): Promise<string> {\n\t\treturn generateEntryId(this.byId);\n\t}\n\n\tasync appendEntry(entry: SessionTreeEntry): Promise<void> {\n\t\tgetFileSystemResultOrThrow(\n\t\t\tawait this.fs.appendFile(this.filePath, `${JSON.stringify(entry)}\\n`),\n\t\t\t`Failed to append session entry ${entry.id}`,\n\t\t);\n\t\tthis.entries.push(entry);\n\t\tthis.byId.set(entry.id, entry);\n\t\tupdateLabelCache(this.labelsById, entry);\n\t\tthis.currentLeafId = leafIdAfterEntry(entry);\n\t}\n\n\tasync getEntry(id: string): Promise<SessionTreeEntry | undefined> {\n\t\treturn this.byId.get(id);\n\t}\n\n\tasync findEntries<TType extends SessionTreeEntry[\"type\"]>(\n\t\ttype: TType,\n\t): Promise<Array<Extract<SessionTreeEntry, { type: TType }>>> {\n\t\treturn this.entries.filter((entry): entry is Extract<SessionTreeEntry, { type: TType }> => entry.type === type);\n\t}\n\n\tasync getLabel(id: string): Promise<string | undefined> {\n\t\treturn this.labelsById.get(id);\n\t}\n\n\tasync getSessionName(): Promise<string | undefined> {\n\t\tconst entries = await this.findEntries(\"session_info\");\n\t\treturn entries[entries.length - 1]?.name?.trim() || undefined;\n\t}\n\n\tasync getSessionStats() {\n\t\tlet messageCount = 0;\n\t\tlet cachedTokens = 0;\n\t\tlet uncachedTokens = 0;\n\t\tlet totalTokens = 0;\n\t\tlet costTotal = 0;\n\t\tfor (const entry of this.entries) {\n\t\t\tif (entry.type === \"message\") {\n\t\t\t\tmessageCount += 1;\n\t\t\t}\n\t\t\tconst usage =\n\t\t\t\tentry.type === \"message\"\n\t\t\t\t\t? entry.message.role === \"assistant\"\n\t\t\t\t\t\t? entry.message.usage\n\t\t\t\t\t\t: undefined\n\t\t\t\t\t: entry.type === \"compaction\" || entry.type === \"branch_summary\"\n\t\t\t\t\t\t? entry.usage\n\t\t\t\t\t\t: undefined;\n\t\t\tif (\n\t\t\t\t!usage ||\n\t\t\t\ttypeof usage.input !== \"number\" ||\n\t\t\t\ttypeof usage.output !== \"number\" ||\n\t\t\t\ttypeof usage.cacheRead !== \"number\" ||\n\t\t\t\ttypeof usage.cacheWrite !== \"number\" ||\n\t\t\t\ttypeof usage.cost?.total !== \"number\"\n\t\t\t) {\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tcachedTokens += usage.cacheRead;\n\t\t\tuncachedTokens += usage.input + usage.cacheWrite;\n\t\t\ttotalTokens += usage.input + usage.output + usage.cacheRead + usage.cacheWrite;\n\t\t\tcostTotal += usage.cost.total;\n\t\t}\n\t\treturn {\n\t\t\tmessageCount,\n\t\t\tcachedTokens,\n\t\t\tuncachedTokens,\n\t\t\ttotalTokens,\n\t\t\tcostTotal,\n\t\t};\n\t}\n\n\tasync getPathToRootOrCompaction(leafId: string | null): Promise<SessionTreeEntry[]> {\n\t\tif (leafId === null) return [];\n\t\tconst path: SessionTreeEntry[] = [];\n\t\tlet stopAtEntryId: string | null = null;\n\t\tlet current = this.byId.get(leafId);\n\t\tif (!current) throw new SessionError(\"not_found\", `Entry ${leafId} not found`);\n\t\twhile (current) {\n\t\t\tpath.unshift(current);\n\t\t\tif (stopAtEntryId !== null && current.id === stopAtEntryId) break;\n\t\t\tif (current.type === \"compaction\") {\n\t\t\t\tif (current.retainedTail) break;\n\t\t\t\tstopAtEntryId = current.firstKeptEntryId ?? null;\n\t\t\t}\n\t\t\tif (!current.parentId) break;\n\t\t\tconst parent = this.byId.get(current.parentId);\n\t\t\tif (!parent) throw new SessionError(\"invalid_session\", `Entry ${current.parentId} not found`);\n\t\t\tcurrent = parent;\n\t\t}\n\t\treturn path;\n\t}\n\n\tasync getEntries(options?: SessionEntryCursorOptions): Promise<SessionTreeEntry[]> {\n\t\tconst start = options?.afterEntrySeq ?? 0;\n\t\tconst end = options?.limit === undefined ? undefined : start + options.limit;\n\t\treturn this.entries.slice(start, end);\n\t}\n}\n"]}
|