@code-yeongyu/senpi-agent-core 2026.8.12 → 2026.8.13

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (153) hide show
  1. package/README.md +13 -7
  2. package/dist/agent-loop.js +5 -1
  3. package/dist/agent-loop.js.map +1 -1
  4. package/dist/agent.d.ts +3 -1
  5. package/dist/agent.d.ts.map +1 -1
  6. package/dist/agent.js +8 -0
  7. package/dist/agent.js.map +1 -1
  8. package/dist/harness/agent-harness.d.ts +452 -96
  9. package/dist/harness/agent-harness.d.ts.map +1 -1
  10. package/dist/harness/agent-harness.js +162 -1005
  11. package/dist/harness/agent-harness.js.map +1 -1
  12. package/dist/harness/compaction/branch-summarization.d.ts +13 -6
  13. package/dist/harness/compaction/branch-summarization.d.ts.map +1 -1
  14. package/dist/harness/compaction/branch-summarization.js +10 -14
  15. package/dist/harness/compaction/branch-summarization.js.map +1 -1
  16. package/dist/harness/compaction/compaction.d.ts +14 -17
  17. package/dist/harness/compaction/compaction.d.ts.map +1 -1
  18. package/dist/harness/compaction/compaction.js +23 -36
  19. package/dist/harness/compaction/compaction.js.map +1 -1
  20. package/dist/harness/env/nodejs.d.ts +1 -0
  21. package/dist/harness/env/nodejs.d.ts.map +1 -1
  22. package/dist/harness/env/nodejs.js +23 -7
  23. package/dist/harness/env/nodejs.js.map +1 -1
  24. package/dist/harness/messages.d.ts +3 -3
  25. package/dist/harness/messages.d.ts.map +1 -1
  26. package/dist/harness/messages.js +3 -3
  27. package/dist/harness/messages.js.map +1 -1
  28. package/dist/harness/prompt-templates.d.ts.map +1 -1
  29. package/dist/harness/prompt-templates.js +4 -9
  30. package/dist/harness/prompt-templates.js.map +1 -1
  31. package/dist/harness/reducer.d.ts +100 -0
  32. package/dist/harness/reducer.d.ts.map +1 -0
  33. package/dist/harness/reducer.js +414 -0
  34. package/dist/harness/reducer.js.map +1 -0
  35. package/dist/harness/result.d.ts +40 -0
  36. package/dist/harness/result.d.ts.map +1 -0
  37. package/dist/harness/result.js +41 -0
  38. package/dist/harness/result.js.map +1 -0
  39. package/dist/harness/session/context.d.ts +22 -0
  40. package/dist/harness/session/context.d.ts.map +1 -0
  41. package/dist/harness/session/context.js +67 -0
  42. package/dist/harness/session/context.js.map +1 -0
  43. package/dist/harness/session/index.d.ts +7 -0
  44. package/dist/harness/session/index.d.ts.map +1 -0
  45. package/dist/harness/session/index.js +6 -0
  46. package/dist/harness/session/index.js.map +1 -0
  47. package/dist/harness/session/jsonl/codec.d.ts +8 -0
  48. package/dist/harness/session/jsonl/codec.d.ts.map +1 -0
  49. package/dist/harness/session/jsonl/codec.js +190 -0
  50. package/dist/harness/session/jsonl/codec.js.map +1 -0
  51. package/dist/harness/session/jsonl/errors.d.ts +5 -0
  52. package/dist/harness/session/jsonl/errors.d.ts.map +1 -0
  53. package/dist/harness/session/jsonl/errors.js +11 -0
  54. package/dist/harness/session/jsonl/errors.js.map +1 -0
  55. package/dist/harness/session/jsonl/repo.d.ts +23 -0
  56. package/dist/harness/session/jsonl/repo.d.ts.map +1 -0
  57. package/dist/harness/session/jsonl/repo.js +129 -0
  58. package/dist/harness/session/jsonl/repo.js.map +1 -0
  59. package/dist/harness/session/jsonl/storage.d.ts +43 -0
  60. package/dist/harness/session/jsonl/storage.d.ts.map +1 -0
  61. package/dist/harness/session/jsonl/storage.js +206 -0
  62. package/dist/harness/session/jsonl/storage.js.map +1 -0
  63. package/dist/harness/session/jsonl/types.d.ts +38 -0
  64. package/dist/harness/session/jsonl/types.d.ts.map +1 -0
  65. package/dist/harness/session/jsonl/types.js +2 -0
  66. package/dist/harness/session/jsonl/types.js.map +1 -0
  67. package/dist/harness/session/jsonl.d.ts +3 -0
  68. package/dist/harness/session/jsonl.d.ts.map +1 -0
  69. package/dist/harness/session/jsonl.js +2 -0
  70. package/dist/harness/session/jsonl.js.map +1 -0
  71. package/dist/harness/session/memory.d.ts +44 -0
  72. package/dist/harness/session/memory.d.ts.map +1 -0
  73. package/dist/harness/session/memory.js +142 -0
  74. package/dist/harness/session/memory.js.map +1 -0
  75. package/dist/harness/session/search.d.ts +19 -0
  76. package/dist/harness/session/search.d.ts.map +1 -0
  77. package/dist/harness/session/search.js +41 -0
  78. package/dist/harness/session/search.js.map +1 -0
  79. package/dist/harness/session/session.d.ts +43 -38
  80. package/dist/harness/session/session.d.ts.map +1 -1
  81. package/dist/harness/session/session.js +186 -304
  82. package/dist/harness/session/session.js.map +1 -1
  83. package/dist/harness/session/state.d.ts +65 -0
  84. package/dist/harness/session/state.d.ts.map +1 -0
  85. package/dist/harness/session/state.js +320 -0
  86. package/dist/harness/session/state.js.map +1 -0
  87. package/dist/harness/session/testing/conformance.d.ts +4 -0
  88. package/dist/harness/session/testing/conformance.d.ts.map +1 -0
  89. package/dist/harness/session/testing/conformance.js +743 -0
  90. package/dist/harness/session/testing/conformance.js.map +1 -0
  91. package/dist/harness/session/testing/index.d.ts +3 -0
  92. package/dist/harness/session/testing/index.d.ts.map +1 -0
  93. package/dist/harness/session/testing/index.js +2 -0
  94. package/dist/harness/session/testing/index.js.map +1 -0
  95. package/dist/harness/session/testing/types.d.ts +14 -0
  96. package/dist/harness/session/testing/types.d.ts.map +1 -0
  97. package/dist/harness/session/testing/types.js +2 -0
  98. package/dist/harness/session/testing/types.js.map +1 -0
  99. package/dist/harness/session/types.d.ts +333 -0
  100. package/dist/harness/session/types.d.ts.map +1 -0
  101. package/dist/harness/session/types.js +9 -0
  102. package/dist/harness/session/types.js.map +1 -0
  103. package/dist/harness/skills.js +21 -19
  104. package/dist/harness/skills.js.map +1 -1
  105. package/dist/harness/telemetry.d.ts +1221 -0
  106. package/dist/harness/telemetry.d.ts.map +1 -0
  107. package/dist/harness/telemetry.js +508 -0
  108. package/dist/harness/telemetry.js.map +1 -0
  109. package/dist/harness/types.d.ts +8 -485
  110. package/dist/harness/types.d.ts.map +1 -1
  111. package/dist/harness/types.js +4 -16
  112. package/dist/harness/types.js.map +1 -1
  113. package/dist/harness/utils/truncate.js.map +1 -1
  114. package/dist/index.d.ts +10 -9
  115. package/dist/index.d.ts.map +1 -1
  116. package/dist/index.js +7 -8
  117. package/dist/index.js.map +1 -1
  118. package/dist/proxy.d.ts +1 -1
  119. package/dist/proxy.d.ts.map +1 -1
  120. package/dist/proxy.js +1 -0
  121. package/dist/proxy.js.map +1 -1
  122. package/dist/types.d.ts +6 -0
  123. package/dist/types.d.ts.map +1 -1
  124. package/dist/types.js.map +1 -1
  125. package/package.json +9 -2
  126. package/dist/harness/session/array-session-reader.d.ts +0 -3
  127. package/dist/harness/session/array-session-reader.d.ts.map +0 -1
  128. package/dist/harness/session/array-session-reader.js +0 -70
  129. package/dist/harness/session/array-session-reader.js.map +0 -1
  130. package/dist/harness/session/fork.d.ts +0 -4
  131. package/dist/harness/session/fork.d.ts.map +0 -1
  132. package/dist/harness/session/fork.js +0 -22
  133. package/dist/harness/session/fork.js.map +0 -1
  134. package/dist/harness/session/jsonl-store.d.ts +0 -13
  135. package/dist/harness/session/jsonl-store.d.ts.map +0 -1
  136. package/dist/harness/session/jsonl-store.js +0 -304
  137. package/dist/harness/session/jsonl-store.js.map +0 -1
  138. package/dist/harness/session/keyed-operation-queue.d.ts +0 -17
  139. package/dist/harness/session/keyed-operation-queue.d.ts.map +0 -1
  140. package/dist/harness/session/keyed-operation-queue.js +0 -60
  141. package/dist/harness/session/keyed-operation-queue.js.map +0 -1
  142. package/dist/harness/session/memory-store.d.ts +0 -6
  143. package/dist/harness/session/memory-store.d.ts.map +0 -1
  144. package/dist/harness/session/memory-store.js +0 -107
  145. package/dist/harness/session/memory-store.js.map +0 -1
  146. package/dist/harness/session/repository.d.ts +0 -28
  147. package/dist/harness/session/repository.d.ts.map +0 -1
  148. package/dist/harness/session/repository.js +0 -61
  149. package/dist/harness/session/repository.js.map +0 -1
  150. package/dist/harness/session/search-backend.d.ts +0 -8
  151. package/dist/harness/session/search-backend.d.ts.map +0 -1
  152. package/dist/harness/session/search-backend.js +0 -22
  153. package/dist/harness/session/search-backend.js.map +0 -1
package/dist/types.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"types.js","sourceRoot":"","sources":["../src/types.ts"],"names":[],"mappings":"","sourcesContent":["import type {\n\tApi,\n\tAssistantMessage,\n\tAssistantMessageEvent,\n\tAssistantMessageEventStream,\n\tContext,\n\tImageContent,\n\tMessage,\n\tModel,\n\tSimpleStreamOptions,\n\tTextContent,\n\tTool,\n\tToolResultMessage,\n\tUsage,\n} from \"@earendil-works/pi-ai\";\nimport type { Static, TSchema } from \"typebox\";\n\n/**\n * Stream function used by the agent loop. `Models.streamSimple` satisfies\n * this shape.\n *\n * Contract:\n * - Must not throw or return a rejected promise for request/model/runtime failures.\n * - Must return an AssistantMessageEventStream.\n * - Failures must be encoded in the returned stream via protocol events and a\n * final AssistantMessage with stopReason \"error\" or \"aborted\" and errorMessage.\n */\nexport type StreamFn = (\n\tmodel: Model<Api>,\n\tcontext: Context,\n\toptions?: SimpleStreamOptions,\n) => AssistantMessageEventStream | Promise<AssistantMessageEventStream>;\n\n/**\n * Configuration for how tool calls from a single assistant message are executed.\n *\n * - \"sequential\": each tool call is prepared, executed, and finalized before the next one starts.\n * - \"parallel\": tool calls are prepared sequentially, then scheduled in concurrent waves.\n * Tools with `executionMode: \"sequential\"` run as exclusive barriers; parallel tools before\n * or after the barrier can still execute concurrently with each other.\n * `tool_execution_end` is emitted in tool completion order after each tool is finalized,\n * while tool-result message artifacts are emitted later in assistant source order.\n */\nexport type ToolExecutionMode = \"sequential\" | \"parallel\";\n\n/**\n * Controls how many queued user messages are injected when the agent loop reaches a queue drain point.\n *\n * - \"all\": drain and inject every queued message at that point.\n * - \"one-at-a-time\": drain and inject only the oldest queued message, leaving the rest queued for later drain points.\n */\nexport type QueueMode = \"all\" | \"one-at-a-time\";\n\n/** A single tool call content block emitted by an assistant message. */\nexport type AgentToolCall = Extract<AssistantMessage[\"content\"][number], { type: \"toolCall\" }>;\n\n/**\n * Result returned from `beforeToolCall`.\n *\n * Returning `{ block: true }` prevents the tool from executing. The loop emits an error tool result instead.\n * `reason` becomes the text shown in that error result. If omitted, a default blocked message is used.\n */\nexport interface BeforeToolCallResult {\n\tblock?: boolean;\n\treason?: string;\n}\n\n/**\n * Partial override returned from `afterToolCall`.\n *\n * Merge semantics are field-by-field:\n * - `content`: if provided, replaces the tool result content array in full\n * - `details`: if provided, replaces the tool result details value in full\n * - `isError`: if provided, replaces the tool result error flag\n * - `usage`: if provided, replaces the tool result usage\n * - `terminate`: if provided, replaces the early-termination hint\n *\n * Omitted fields keep the original executed tool result values.\n * There is no deep merge for `content`, `details`, or `usage`.\n */\nexport interface AfterToolCallResult {\n\tcontent?: (TextContent | ImageContent)[];\n\tdetails?: unknown;\n\tisError?: boolean;\n\t/** Usage from the final tool execution itself, if available. Not used for main LLM context accounting. */\n\tusage?: Usage;\n\t/**\n\t * Hint that the agent should stop after the current tool batch.\n\t * Early termination only happens when every finalized tool result in the batch sets this to true.\n\t */\n\tterminate?: boolean;\n}\n\n/** Context passed to `beforeToolCall`. */\nexport interface BeforeToolCallContext {\n\t/** The assistant message that requested the tool call. */\n\tassistantMessage: AssistantMessage;\n\t/** The raw tool call block from `assistantMessage.content`. */\n\ttoolCall: AgentToolCall;\n\t/** Validated tool arguments for the target tool schema. */\n\targs: unknown;\n\t/** Current agent context at the time the tool call is prepared. */\n\tcontext: AgentContext;\n}\n\n/** Context passed to `afterToolCall`. */\nexport interface AfterToolCallContext {\n\t/** The assistant message that requested the tool call. */\n\tassistantMessage: AssistantMessage;\n\t/** The raw tool call block from `assistantMessage.content`. */\n\ttoolCall: AgentToolCall;\n\t/** Validated tool arguments for the target tool schema. */\n\targs: unknown;\n\t/** The executed tool result before any `afterToolCall` overrides are applied. */\n\tresult: AgentToolResult<any>;\n\t/** Whether the executed tool result is currently treated as an error. */\n\tisError: boolean;\n\t/** Current agent context at the time the tool call is finalized. */\n\tcontext: AgentContext;\n}\n\n/** Context passed to `shouldStopAfterTurn`. */\nexport interface ShouldStopAfterTurnContext {\n\t/** The assistant message that completed the turn. */\n\tmessage: AssistantMessage;\n\t/** Tool result messages passed to the preceding `turn_end` event. */\n\ttoolResults: ToolResultMessage[];\n\t/** Current agent context after the turn's assistant message and tool results have been appended. */\n\tcontext: AgentContext;\n\t/** Messages that this loop invocation will return if it exits at this point. Prompt runs include the initial prompt messages; continuation runs do not include pre-existing context messages. */\n\tnewMessages: AgentMessage[];\n}\n\n/** Replacement runtime state used by the agent loop before starting another provider request. */\nexport interface AgentLoopTurnUpdate {\n\t/** Context for the next provider request. */\n\tcontext?: AgentContext;\n\t/** Model for the next provider request. */\n\tmodel?: Model<any>;\n\t/** Thinking level for the next provider request. */\n\tthinkingLevel?: ThinkingLevel;\n\t/** Whether the next provider request should abort a server-selected fallback. */\n\tabortServerSideFallback?: boolean;\n}\n\nexport interface PrepareNextTurnContext extends ShouldStopAfterTurnContext {}\n\nexport interface AgentLoopConfig extends SimpleStreamOptions {\n\tmodel: Model<any>;\n\n\t/**\n\t * Maximum time in milliseconds to wait for the FIRST provider stream event.\n\t * Providers emit their first event only once the HTTP response begins, so a\n\t * dead upstream that accepts the request but never answers is otherwise only\n\t * bounded by `timeoutMs` (the idle timeout, default 5 minutes). After the\n\t * first event arrives, `timeoutMs` governs inter-event idleness as before.\n\t * Unset or non-positive values disable the start bound.\n\t */\n\tstreamStartTimeoutMs?: number;\n\n\t/** Provider/SDK timeout override for only the first request in this loop invocation. */\n\tinitialRequestTimeoutMs?: number;\n\n\t/** Stream-start timeout override for only the first request in this loop invocation. */\n\tinitialRequestStreamStartTimeoutMs?: number;\n\n\t/**\n\t * Converts AgentMessage[] to LLM-compatible Message[] before each LLM call.\n\t *\n\t * Each AgentMessage must be converted to a UserMessage, AssistantMessage, or ToolResultMessage\n\t * that the LLM can understand. AgentMessages that cannot be converted (e.g., UI-only notifications,\n\t * status messages) should be filtered out.\n\t *\n\t * Contract: must not throw or reject. Return a safe fallback value instead.\n\t * Throwing interrupts the low-level agent loop without producing a normal event sequence.\n\t *\n\t * @example\n\t * ```typescript\n\t * convertToLlm: (messages) => messages.flatMap(m => {\n\t * if (m.role === \"custom\") {\n\t * // Convert custom message to user message\n\t * return [{ role: \"user\", content: m.content, timestamp: m.timestamp }];\n\t * }\n\t * if (m.role === \"notification\") {\n\t * // Filter out UI-only messages\n\t * return [];\n\t * }\n\t * // Pass through standard LLM messages\n\t * return [m];\n\t * })\n\t * ```\n\t */\n\tconvertToLlm: (messages: AgentMessage[]) => Message[] | Promise<Message[]>;\n\n\t/**\n\t * Optional transform applied to the context before `convertToLlm`.\n\t *\n\t * Use this for operations that work at the AgentMessage level:\n\t * - Context window management (pruning old messages)\n\t * - Injecting context from external sources\n\t *\n\t * Contract: must not throw or reject. Return the original messages or another\n\t * safe fallback value instead.\n\t *\n\t * @example\n\t * ```typescript\n\t * transformContext: async (messages) => {\n\t * if (estimateTokens(messages) > MAX_TOKENS) {\n\t * return pruneOldMessages(messages);\n\t * }\n\t * return messages;\n\t * }\n\t * ```\n\t */\n\ttransformContext?: (messages: AgentMessage[], signal?: AbortSignal) => Promise<AgentMessage[]>;\n\n\t/**\n\t * Resolves an API key dynamically for each LLM call.\n\t *\n\t * Useful for short-lived OAuth tokens (e.g., GitHub Copilot) that may expire\n\t * during long-running tool execution phases.\n\t *\n\t * Contract: must not throw or reject. Return undefined when no key is available.\n\t */\n\tgetApiKey?: (provider: string) => Promise<string | undefined> | string | undefined;\n\n\t/**\n\t * Called after each turn fully completes and `turn_end` has been emitted.\n\t *\n\t * If it returns true, the loop emits `agent_end` and exits before polling steering or follow-up queues,\n\t * without starting another LLM call. The current assistant response and any tool executions finish normally.\n\t *\n\t * Use this to request a graceful stop after the current turn, e.g. before context gets too full.\n\t *\n\t * Contract: must not throw or reject. Throwing interrupts the low-level agent loop without producing a normal event sequence.\n\t */\n\tshouldStopAfterTurn?: (context: ShouldStopAfterTurnContext) => boolean | Promise<boolean>;\n\n\t/**\n\t * Called after `turn_end` and before the loop decides whether another provider request should start.\n\t * Return replacement context/model/thinking state to affect the next turn in this run.\n\t * Return undefined to keep using the current context/config.\n\t */\n\tprepareNextTurn?: (\n\t\tcontext: PrepareNextTurnContext,\n\t) => AgentLoopTurnUpdate | undefined | Promise<AgentLoopTurnUpdate | undefined>;\n\n\t/**\n\t * Returns steering messages to inject into the conversation mid-run.\n\t *\n\t * Called after the current assistant turn finishes executing its tool calls, unless `shouldStopAfterTurn` exits first.\n\t * If messages are returned, they are added to the context before the next LLM call.\n\t * Tool calls from the current assistant message are not skipped.\n\t *\n\t * Use this for \"steering\" the agent while it's working.\n\t *\n\t * Contract: must not throw or reject. Return [] when no steering messages are available.\n\t */\n\tgetSteeringMessages?: () => Promise<AgentMessage[]>;\n\n\t/**\n\t * Returns follow-up messages to process after the agent would otherwise stop.\n\t *\n\t * Called when the agent has no more tool calls and no steering messages.\n\t * If messages are returned, they're added to the context and the agent\n\t * continues with another turn.\n\t *\n\t * Use this for follow-up messages that should wait until the agent finishes.\n\t *\n\t * Contract: must not throw or reject. Return [] when no follow-up messages are available.\n\t */\n\tgetFollowUpMessages?: () => Promise<AgentMessage[]>;\n\n\t/**\n\t * Restores messages previously returned by a queue callback when next-turn preparation cannot continue.\n\t * Restored messages must be placed before messages queued after the drain.\n\t */\n\trestorePendingMessages?: (queue: \"steering\" | \"followUp\", messages: AgentMessage[]) => Promise<void> | void;\n\n\t/**\n\t * Tool execution mode.\n\t * - \"sequential\": execute tool calls one by one\n\t * - \"parallel\": preflight tool calls sequentially, then execute allowed tools in concurrent waves;\n\t * per-tool `executionMode: \"sequential\"` calls act as exclusive barriers,\n\t * emit `tool_execution_end` in tool completion order after each tool is finalized,\n\t * then emit tool-result message artifacts later in assistant source order\n\t *\n\t * Default: \"parallel\"\n\t */\n\ttoolExecution?: ToolExecutionMode;\n\n\t/**\n\t * Optional migration guidance for tool names intentionally removed by an extension.\n\t * The matching hint is appended to the normal unknown-tool error before hooks run.\n\t */\n\tremovedToolHints?: Record<string, string>;\n\n\t/**\n\t * Called when a model names a tool absent from the current context snapshot.\n\t * Return a newly available tool to continue normal validation and execution, or\n\t * undefined to emit the existing unknown-tool result. Hosts may use this to\n\t * activate a registered lazy tool at call time.\n\t */\n\tresolveUnknownToolCall?: (\n\t\ttoolName: string,\n\t\tcontext: AgentContext,\n\t) => AgentTool | undefined | Promise<AgentTool | undefined>;\n\n\t/**\n\t * Called before a tool is executed, after arguments have been validated.\n\t *\n\t * Return `{ block: true }` to prevent execution. The loop emits an error tool result instead.\n\t * The hook receives the agent abort signal and is responsible for honoring it.\n\t */\n\tbeforeToolCall?: (context: BeforeToolCallContext, signal?: AbortSignal) => Promise<BeforeToolCallResult | undefined>;\n\n\t/**\n\t * Called after a tool finishes executing, before `tool_execution_end` and tool-result message events are emitted.\n\t *\n\t * Return an `AfterToolCallResult` to override parts of the executed tool result:\n\t * - `content` replaces the full content array\n\t * - `details` replaces the full details payload\n\t * - `isError` replaces the error flag\n\t * - `usage` replaces the tool result usage\n\t * - `terminate` replaces the early-termination hint\n\t *\n\t * Any omitted fields keep their original values. No deep merge is performed.\n\t * The hook receives the agent abort signal and is responsible for honoring it.\n\t */\n\tafterToolCall?: (context: AfterToolCallContext, signal?: AbortSignal) => Promise<AfterToolCallResult | undefined>;\n}\n\n/**\n * Thinking/reasoning level for models that support it.\n * Note: \"xhigh\" and \"max\" are only supported by selected model families. Use model\n * thinking-level metadata from @earendil-works/pi-ai to detect support for a concrete model.\n */\nexport type ThinkingLevel = \"off\" | \"minimal\" | \"low\" | \"medium\" | \"high\" | \"xhigh\" | \"max\";\n\n/**\n * Extensible interface for custom app messages.\n * Apps can extend via declaration merging:\n *\n * @example\n * ```typescript\n * declare module \"@earendil-works/pi-agent-core\" {\n * interface CustomAgentMessages {\n * artifact: ArtifactMessage;\n * notification: NotificationMessage;\n * }\n * }\n * ```\n */\nexport interface CustomAgentMessages {\n\t// Empty by default - apps extend via declaration merging\n}\n\n/**\n * AgentMessage: Union of LLM messages + custom messages.\n * This abstraction allows apps to add custom message types while maintaining\n * type safety and compatibility with the base LLM messages.\n */\nexport type AgentMessage = Message | CustomAgentMessages[keyof CustomAgentMessages];\n\n/**\n * Public agent state.\n *\n * `tools` and `messages` use accessor properties so implementations can copy\n * assigned arrays before storing them.\n */\nexport interface AgentState {\n\t/** System prompt sent with each model request. */\n\tsystemPrompt: string;\n\t/** Active model used for future turns. */\n\tmodel: Model<any>;\n\t/** Requested reasoning level for future turns. */\n\tthinkingLevel: ThinkingLevel;\n\t/** Available tools. Assigning a new array copies the top-level array. */\n\tset tools(tools: AgentTool<any>[]);\n\tget tools(): AgentTool<any>[];\n\t/** Conversation transcript. Assigning a new array copies the top-level array. */\n\tset messages(messages: AgentMessage[]);\n\tget messages(): AgentMessage[];\n\t/**\n\t * True while the agent is processing a prompt or continuation.\n\t *\n\t * This remains true until awaited `agent_end` listeners settle.\n\t */\n\treadonly isStreaming: boolean;\n\t/** Partial assistant message for the current streamed response, if any. */\n\treadonly streamingMessage?: AgentMessage;\n\t/** Tool call ids currently executing. */\n\treadonly pendingToolCalls: ReadonlySet<string>;\n\t/** Error message from the most recent failed or aborted assistant turn, if any. */\n\treadonly errorMessage?: string;\n}\n\n/** Final or partial result produced by a tool. */\nexport interface AgentToolResult<T> {\n\t/** Text or image content returned to the model. */\n\tcontent: (TextContent | ImageContent)[];\n\t/** Arbitrary structured details for logs or UI rendering. */\n\tdetails: T;\n\t/** Usage from the final tool execution itself, if available. Not used for main LLM context accounting. */\n\tusage?: Usage;\n\t/** Names of tools introduced by this result and available from this transcript point onward. */\n\taddedToolNames?: string[];\n\t/**\n\t * Hint that the agent should stop after the current tool batch.\n\t * Early termination only happens when every finalized tool result in the batch sets this to true.\n\t */\n\tterminate?: boolean;\n}\n\n/**\n * Callback used by tools to stream partial execution updates.\n *\n * The callback is scoped to the current `execute()` invocation. Calls made after\n * the tool promise settles are ignored.\n */\nexport type AgentToolUpdateCallback<T = any> = (partialResult: AgentToolResult<T>) => void;\n\n/** Tool definition used by the agent runtime. */\nexport interface AgentTool<TParameters extends TSchema = TSchema, TDetails = any> extends Tool<TParameters> {\n\t/** Human-readable label for UI display. */\n\tlabel: string;\n\t/**\n\t * Optional compatibility shim for raw tool-call arguments before schema validation.\n\t * Must return an object that matches `TParameters`.\n\t */\n\tprepareArguments?: (args: unknown) => Static<TParameters>;\n\t/** Execute the tool call. Throw on failure instead of encoding errors in `content`. */\n\texecute: (\n\t\ttoolCallId: string,\n\t\tparams: Static<TParameters>,\n\t\tsignal?: AbortSignal,\n\t\tonUpdate?: AgentToolUpdateCallback<TDetails>,\n\t) => Promise<AgentToolResult<TDetails>>;\n\t/**\n\t * Per-tool execution mode override.\n\t * - \"sequential\": this tool acts as an exclusive barrier in parallel batches.\n\t * - \"parallel\": this tool can execute concurrently with other tool calls.\n\t *\n\t * If omitted, the default execution mode applies.\n\t */\n\texecutionMode?: ToolExecutionMode;\n}\n\n/** Context snapshot passed into the low-level agent loop. */\nexport interface AgentContext {\n\t/** System prompt included with the request. */\n\tsystemPrompt: string;\n\t/** Transcript visible to the model. */\n\tmessages: AgentMessage[];\n\t/** Tools available for this run. */\n\ttools?: AgentTool<any>[];\n}\n\n/**\n * Events emitted by the Agent for UI updates.\n *\n * `agent_end` is the last event emitted for a run, but awaited `Agent.subscribe()`\n * listeners for that event are still part of run settlement. The agent becomes\n * idle only after those listeners finish.\n */\nexport type AgentEvent =\n\t// Agent lifecycle\n\t| { type: \"agent_start\" }\n\t| { type: \"agent_end\"; messages: AgentMessage[] }\n\t// Turn lifecycle - a turn is one assistant response + any tool calls/results\n\t| { type: \"turn_start\" }\n\t| { type: \"turn_end\"; message: AgentMessage; toolResults: ToolResultMessage[] }\n\t// Message lifecycle - emitted for user, assistant, and toolResult messages\n\t| { type: \"message_start\"; message: AgentMessage }\n\t// Only emitted for assistant messages during streaming\n\t| { type: \"message_update\"; message: AgentMessage; assistantMessageEvent: AssistantMessageEvent }\n\t| { type: \"message_end\"; message: AgentMessage }\n\t// Tool execution lifecycle\n\t| { type: \"tool_execution_start\"; toolCallId: string; toolName: string; args: any }\n\t| { type: \"tool_execution_update\"; toolCallId: string; toolName: string; args: any; partialResult: any }\n\t| { type: \"tool_execution_end\"; toolCallId: string; toolName: string; result: any; isError: boolean };\n"]}
1
+ {"version":3,"file":"types.js","sourceRoot":"","sources":["../src/types.ts"],"names":[],"mappings":"","sourcesContent":["import type {\n\tApi,\n\tAssistantMessage,\n\tAssistantMessageEvent,\n\tAssistantMessageEventStream,\n\tContext,\n\tImageContent,\n\tMessage,\n\tModel,\n\tSimpleStreamOptions,\n\tTextContent,\n\tTool,\n\tToolResultMessage,\n\tUsage,\n} from \"@earendil-works/pi-ai\";\nimport type { Static, TSchema } from \"typebox\";\n\n/**\n * Stream function used by the agent loop. `Models.streamSimple` satisfies\n * this shape.\n *\n * Contract:\n * - Must not throw or return a rejected promise for request/model/runtime failures.\n * - Must return an AssistantMessageEventStream.\n * - Failures must be encoded in the returned stream via protocol events and a\n * final AssistantMessage with stopReason \"error\" or \"aborted\" and errorMessage.\n */\nexport type StreamFn = (\n\tmodel: Model<Api>,\n\tcontext: Context,\n\toptions?: SimpleStreamOptions,\n) => AssistantMessageEventStream | Promise<AssistantMessageEventStream>;\n\n/**\n * Configuration for how tool calls from a single assistant message are executed.\n *\n * - \"sequential\": each tool call is prepared, executed, and finalized before the next one starts.\n * - \"parallel\": tool calls are prepared sequentially, then scheduled in concurrent waves.\n * Tools with `executionMode: \"sequential\"` run as exclusive barriers; parallel tools before\n * or after the barrier can still execute concurrently with each other.\n * `tool_execution_end` is emitted in tool completion order after each tool is finalized,\n * while tool-result message artifacts are emitted later in assistant source order.\n */\nexport type ToolExecutionMode = \"sequential\" | \"parallel\";\n\n/**\n * Controls how many queued user messages are injected when the agent loop reaches a queue drain point.\n *\n * - \"all\": drain and inject every queued message at that point.\n * - \"one-at-a-time\": drain and inject only the oldest queued message, leaving the rest queued for later drain points.\n */\nexport type QueueMode = \"all\" | \"one-at-a-time\";\n\n/** A single tool call content block emitted by an assistant message. */\nexport type AgentToolCall = Extract<AssistantMessage[\"content\"][number], { type: \"toolCall\" }>;\n\n/**\n * Result returned from `beforeToolCall`.\n *\n * Returning `{ block: true }` prevents the tool from executing. The loop emits an error tool result instead.\n * `reason` becomes the text shown in that error result. If omitted, a default blocked message is used.\n */\nexport interface BeforeToolCallResult {\n\tblock?: boolean;\n\treason?: string;\n\t/**\n\t * Hint that the agent should stop after the current tool batch when this call is blocked.\n\t * Early termination only happens when every finalized tool result in the batch sets this to true.\n\t */\n\tterminate?: boolean;\n}\n\n/**\n * Partial override returned from `afterToolCall`.\n *\n * Merge semantics are field-by-field:\n * - `content`: if provided, replaces the tool result content array in full\n * - `details`: if provided, replaces the tool result details value in full\n * - `isError`: if provided, replaces the tool result error flag\n * - `usage`: if provided, replaces the tool result usage\n * - `terminate`: if provided, replaces the early-termination hint\n *\n * Omitted fields keep the original executed tool result values.\n * There is no deep merge for `content`, `details`, or `usage`.\n */\nexport interface AfterToolCallResult {\n\tcontent?: (TextContent | ImageContent)[];\n\tdetails?: unknown;\n\tisError?: boolean;\n\t/** Usage from the final tool execution itself, if available. Not used for main LLM context accounting. */\n\tusage?: Usage;\n\t/**\n\t * Hint that the agent should stop after the current tool batch.\n\t * Early termination only happens when every finalized tool result in the batch sets this to true.\n\t */\n\tterminate?: boolean;\n}\n\n/** Context passed to `beforeToolCall`. */\nexport interface BeforeToolCallContext {\n\t/** The assistant message that requested the tool call. */\n\tassistantMessage: AssistantMessage;\n\t/** The raw tool call block from `assistantMessage.content`. */\n\ttoolCall: AgentToolCall;\n\t/** Validated tool arguments for the target tool schema. */\n\targs: unknown;\n\t/** Current agent context at the time the tool call is prepared. */\n\tcontext: AgentContext;\n}\n\n/** Context passed to `afterToolCall`. */\nexport interface AfterToolCallContext {\n\t/** The assistant message that requested the tool call. */\n\tassistantMessage: AssistantMessage;\n\t/** The raw tool call block from `assistantMessage.content`. */\n\ttoolCall: AgentToolCall;\n\t/** Validated tool arguments for the target tool schema. */\n\targs: unknown;\n\t/** The executed tool result before any `afterToolCall` overrides are applied. */\n\tresult: AgentToolResult<any>;\n\t/** Whether the executed tool result is currently treated as an error. */\n\tisError: boolean;\n\t/** Current agent context at the time the tool call is finalized. */\n\tcontext: AgentContext;\n}\n\n/** Context passed to `shouldStopAfterTurn`. */\nexport interface ShouldStopAfterTurnContext {\n\t/** The assistant message that completed the turn. */\n\tmessage: AssistantMessage;\n\t/** Tool result messages passed to the preceding `turn_end` event. */\n\ttoolResults: ToolResultMessage[];\n\t/** Current agent context after the turn's assistant message and tool results have been appended. */\n\tcontext: AgentContext;\n\t/** Messages that this loop invocation will return if it exits at this point. Prompt runs include the initial prompt messages; continuation runs do not include pre-existing context messages. */\n\tnewMessages: AgentMessage[];\n}\n\n/** Replacement runtime state used by the agent loop before starting another provider request. */\nexport interface AgentLoopTurnUpdate {\n\t/** Context for the next provider request. */\n\tcontext?: AgentContext;\n\t/** Model for the next provider request. */\n\tmodel?: Model<any>;\n\t/** Thinking level for the next provider request. */\n\tthinkingLevel?: ThinkingLevel;\n\t/** Whether the next provider request should abort a server-selected fallback. */\n\tabortServerSideFallback?: boolean;\n}\n\nexport interface PrepareNextTurnContext extends ShouldStopAfterTurnContext {}\n\nexport interface AgentLoopConfig extends SimpleStreamOptions {\n\tmodel: Model<any>;\n\n\t/**\n\t * Maximum time in milliseconds to wait for the FIRST provider stream event.\n\t * Providers emit their first event only once the HTTP response begins, so a\n\t * dead upstream that accepts the request but never answers is otherwise only\n\t * bounded by `timeoutMs` (the idle timeout, default 5 minutes). After the\n\t * first event arrives, `timeoutMs` governs inter-event idleness as before.\n\t * Unset or non-positive values disable the start bound.\n\t */\n\tstreamStartTimeoutMs?: number;\n\n\t/** Provider/SDK timeout override for only the first request in this loop invocation. */\n\tinitialRequestTimeoutMs?: number;\n\n\t/** Stream-start timeout override for only the first request in this loop invocation. */\n\tinitialRequestStreamStartTimeoutMs?: number;\n\n\t/**\n\t * Converts AgentMessage[] to LLM-compatible Message[] before each LLM call.\n\t *\n\t * Each AgentMessage must be converted to a UserMessage, AssistantMessage, or ToolResultMessage\n\t * that the LLM can understand. AgentMessages that cannot be converted (e.g., UI-only notifications,\n\t * status messages) should be filtered out.\n\t *\n\t * Contract: must not throw or reject. Return a safe fallback value instead.\n\t * Throwing interrupts the low-level agent loop without producing a normal event sequence.\n\t *\n\t * @example\n\t * ```typescript\n\t * convertToLlm: (messages) => messages.flatMap(m => {\n\t * if (m.role === \"custom\") {\n\t * // Convert custom message to user message\n\t * return [{ role: \"user\", content: m.content, timestamp: m.timestamp }];\n\t * }\n\t * if (m.role === \"notification\") {\n\t * // Filter out UI-only messages\n\t * return [];\n\t * }\n\t * // Pass through standard LLM messages\n\t * return [m];\n\t * })\n\t * ```\n\t */\n\tconvertToLlm: (messages: AgentMessage[]) => Message[] | Promise<Message[]>;\n\n\t/**\n\t * Optional transform applied to the context before `convertToLlm`.\n\t *\n\t * Use this for operations that work at the AgentMessage level:\n\t * - Context window management (pruning old messages)\n\t * - Injecting context from external sources\n\t *\n\t * Contract: must not throw or reject. Return the original messages or another\n\t * safe fallback value instead.\n\t *\n\t * @example\n\t * ```typescript\n\t * transformContext: async (messages) => {\n\t * if (estimateTokens(messages) > MAX_TOKENS) {\n\t * return pruneOldMessages(messages);\n\t * }\n\t * return messages;\n\t * }\n\t * ```\n\t */\n\ttransformContext?: (messages: AgentMessage[], signal?: AbortSignal) => Promise<AgentMessage[]>;\n\n\t/**\n\t * Resolves an API key dynamically for each LLM call.\n\t *\n\t * Useful for short-lived OAuth tokens (e.g., GitHub Copilot) that may expire\n\t * during long-running tool execution phases.\n\t *\n\t * Contract: must not throw or reject. Return undefined when no key is available.\n\t */\n\tgetApiKey?: (provider: string) => Promise<string | undefined> | string | undefined;\n\n\t/**\n\t * Called after each turn fully completes and `turn_end` has been emitted.\n\t *\n\t * If it returns true, the loop emits `agent_end` and exits before polling steering or follow-up queues,\n\t * without starting another LLM call. The current assistant response and any tool executions finish normally.\n\t *\n\t * Use this to request a graceful stop after the current turn, e.g. before context gets too full.\n\t *\n\t * Contract: must not throw or reject. Throwing interrupts the low-level agent loop without producing a normal event sequence.\n\t */\n\tshouldStopAfterTurn?: (context: ShouldStopAfterTurnContext) => boolean | Promise<boolean>;\n\n\t/**\n\t * Called after `turn_end` and before the loop decides whether another provider request should start.\n\t * Return replacement context/model/thinking state to affect the next turn in this run.\n\t * Return undefined to keep using the current context/config.\n\t */\n\tprepareNextTurn?: (\n\t\tcontext: PrepareNextTurnContext,\n\t) => AgentLoopTurnUpdate | undefined | Promise<AgentLoopTurnUpdate | undefined>;\n\n\t/**\n\t * Returns steering messages to inject into the conversation mid-run.\n\t *\n\t * Called after the current assistant turn finishes executing its tool calls, unless `shouldStopAfterTurn` exits first.\n\t * If messages are returned, they are added to the context before the next LLM call.\n\t * Tool calls from the current assistant message are not skipped.\n\t *\n\t * Use this for \"steering\" the agent while it's working.\n\t *\n\t * Contract: must not throw or reject. Return [] when no steering messages are available.\n\t */\n\tgetSteeringMessages?: () => Promise<AgentMessage[]>;\n\n\t/**\n\t * Returns follow-up messages to process after the agent would otherwise stop.\n\t *\n\t * Called when the agent has no more tool calls and no steering messages.\n\t * If messages are returned, they're added to the context and the agent\n\t * continues with another turn.\n\t *\n\t * Use this for follow-up messages that should wait until the agent finishes.\n\t *\n\t * Contract: must not throw or reject. Return [] when no follow-up messages are available.\n\t */\n\tgetFollowUpMessages?: () => Promise<AgentMessage[]>;\n\n\t/**\n\t * Restores messages previously returned by a queue callback when next-turn preparation cannot continue.\n\t * Restored messages must be placed before messages queued after the drain.\n\t */\n\trestorePendingMessages?: (queue: \"steering\" | \"followUp\", messages: AgentMessage[]) => Promise<void> | void;\n\n\t/**\n\t * Tool execution mode.\n\t * - \"sequential\": execute tool calls one by one\n\t * - \"parallel\": preflight tool calls sequentially, then execute allowed tools in concurrent waves;\n\t * per-tool `executionMode: \"sequential\"` calls act as exclusive barriers,\n\t * emit `tool_execution_end` in tool completion order after each tool is finalized,\n\t * then emit tool-result message artifacts later in assistant source order\n\t *\n\t * Default: \"parallel\"\n\t */\n\ttoolExecution?: ToolExecutionMode;\n\n\t/**\n\t * Optional migration guidance for tool names intentionally removed by an extension.\n\t * The matching hint is appended to the normal unknown-tool error before hooks run.\n\t */\n\tremovedToolHints?: Record<string, string>;\n\n\t/**\n\t * Called when a model names a tool absent from the current context snapshot.\n\t * Return a newly available tool to continue normal validation and execution, or\n\t * undefined to emit the existing unknown-tool result. Hosts may use this to\n\t * activate a registered lazy tool at call time.\n\t */\n\tresolveUnknownToolCall?: (\n\t\ttoolName: string,\n\t\tcontext: AgentContext,\n\t) => AgentTool | undefined | Promise<AgentTool | undefined>;\n\n\t/**\n\t * Called before a tool is executed, after arguments have been validated.\n\t *\n\t * Return `{ block: true }` to prevent execution. The loop emits an error tool result instead.\n\t * A blocked result can also set `terminate: true` to participate in the batch early-termination rule.\n\t * The hook receives the agent abort signal and is responsible for honoring it.\n\t */\n\tbeforeToolCall?: (context: BeforeToolCallContext, signal?: AbortSignal) => Promise<BeforeToolCallResult | undefined>;\n\n\t/**\n\t * Called after a tool finishes executing, before `tool_execution_end` and tool-result message events are emitted.\n\t *\n\t * Return an `AfterToolCallResult` to override parts of the executed tool result:\n\t * - `content` replaces the full content array\n\t * - `details` replaces the full details payload\n\t * - `isError` replaces the error flag\n\t * - `usage` replaces the tool result usage\n\t * - `terminate` replaces the early-termination hint\n\t *\n\t * Any omitted fields keep their original values. No deep merge is performed.\n\t * The hook receives the agent abort signal and is responsible for honoring it.\n\t */\n\tafterToolCall?: (context: AfterToolCallContext, signal?: AbortSignal) => Promise<AfterToolCallResult | undefined>;\n}\n\n/**\n * Thinking/reasoning level for models that support it.\n * Note: \"xhigh\" and \"max\" are only supported by selected model families. Use model\n * thinking-level metadata from @earendil-works/pi-ai to detect support for a concrete model.\n */\nexport type ThinkingLevel = \"off\" | \"minimal\" | \"low\" | \"medium\" | \"high\" | \"xhigh\" | \"max\";\n\n/**\n * Extensible interface for custom app messages.\n * Apps can extend via declaration merging:\n *\n * @example\n * ```typescript\n * declare module \"@earendil-works/pi-agent-core\" {\n * interface CustomAgentMessages {\n * artifact: ArtifactMessage;\n * notification: NotificationMessage;\n * }\n * }\n * ```\n */\nexport interface CustomAgentMessages {\n\t// Empty by default - apps extend via declaration merging\n}\n\n/**\n * AgentMessage: Union of LLM messages + custom messages.\n * This abstraction allows apps to add custom message types while maintaining\n * type safety and compatibility with the base LLM messages.\n */\nexport type AgentMessage = Message | CustomAgentMessages[keyof CustomAgentMessages];\n\n/**\n * Public agent state.\n *\n * `tools` and `messages` use accessor properties so implementations can copy\n * assigned arrays before storing them.\n */\nexport interface AgentState {\n\t/** System prompt sent with each model request. */\n\tsystemPrompt: string;\n\t/** Active model used for future turns. */\n\tmodel: Model<any>;\n\t/** Requested reasoning level for future turns. */\n\tthinkingLevel: ThinkingLevel;\n\t/** Available tools. Assigning a new array copies the top-level array. */\n\tset tools(tools: AgentTool<any>[]);\n\tget tools(): AgentTool<any>[];\n\t/** Conversation transcript. Assigning a new array copies the top-level array. */\n\tset messages(messages: AgentMessage[]);\n\tget messages(): AgentMessage[];\n\t/**\n\t * True while the agent is processing a prompt or continuation.\n\t *\n\t * This remains true until awaited `agent_end` listeners settle.\n\t */\n\treadonly isStreaming: boolean;\n\t/** Partial assistant message for the current streamed response, if any. */\n\treadonly streamingMessage?: AgentMessage;\n\t/** Tool call ids currently executing. */\n\treadonly pendingToolCalls: ReadonlySet<string>;\n\t/** Error message from the most recent failed or aborted assistant turn, if any. */\n\treadonly errorMessage?: string;\n}\n\n/** Final or partial result produced by a tool. */\nexport interface AgentToolResult<T> {\n\t/** Text or image content returned to the model. */\n\tcontent: (TextContent | ImageContent)[];\n\t/** Arbitrary structured details for logs or UI rendering. */\n\tdetails: T;\n\t/** Usage from the final tool execution itself, if available. Not used for main LLM context accounting. */\n\tusage?: Usage;\n\t/** Names of tools introduced by this result and available from this transcript point onward. */\n\taddedToolNames?: string[];\n\t/**\n\t * Hint that the agent should stop after the current tool batch.\n\t * Early termination only happens when every finalized tool result in the batch sets this to true.\n\t */\n\tterminate?: boolean;\n}\n\n/**\n * Callback used by tools to stream partial execution updates.\n *\n * The callback is scoped to the current `execute()` invocation. Calls made after\n * the tool promise settles are ignored.\n */\nexport type AgentToolUpdateCallback<T = any> = (partialResult: AgentToolResult<T>) => void;\n\n/** Tool definition used by the agent runtime. */\nexport interface AgentTool<TParameters extends TSchema = TSchema, TDetails = any> extends Tool<TParameters> {\n\t/** Human-readable label for UI display. */\n\tlabel: string;\n\t/**\n\t * Optional compatibility shim for raw tool-call arguments before schema validation.\n\t * Must return an object that matches `TParameters`.\n\t */\n\tprepareArguments?: (args: unknown) => Static<TParameters>;\n\t/** Execute the tool call. Throw on failure instead of encoding errors in `content`. */\n\texecute: (\n\t\ttoolCallId: string,\n\t\tparams: Static<TParameters>,\n\t\tsignal?: AbortSignal,\n\t\tonUpdate?: AgentToolUpdateCallback<TDetails>,\n\t) => Promise<AgentToolResult<TDetails>>;\n\t/**\n\t * Per-tool execution mode override.\n\t * - \"sequential\": this tool acts as an exclusive barrier in parallel batches.\n\t * - \"parallel\": this tool can execute concurrently with other tool calls.\n\t *\n\t * If omitted, the default execution mode applies.\n\t */\n\texecutionMode?: ToolExecutionMode;\n}\n\n/** Context snapshot passed into the low-level agent loop. */\nexport interface AgentContext {\n\t/** System prompt included with the request. */\n\tsystemPrompt: string;\n\t/** Transcript visible to the model. */\n\tmessages: AgentMessage[];\n\t/** Tools available for this run. */\n\ttools?: AgentTool<any>[];\n}\n\n/**\n * Events emitted by the Agent for UI updates.\n *\n * `agent_end` is the last event emitted for a run, but awaited `Agent.subscribe()`\n * listeners for that event are still part of run settlement. The agent becomes\n * idle only after those listeners finish.\n */\nexport type AgentEvent =\n\t// Agent lifecycle\n\t| { type: \"agent_start\" }\n\t| { type: \"agent_end\"; messages: AgentMessage[] }\n\t// Turn lifecycle - a turn is one assistant response + any tool calls/results\n\t| { type: \"turn_start\" }\n\t| { type: \"turn_end\"; message: AgentMessage; toolResults: ToolResultMessage[] }\n\t// Message lifecycle - emitted for user, assistant, and toolResult messages\n\t| { type: \"message_start\"; message: AgentMessage }\n\t// Only emitted for assistant messages during streaming\n\t| { type: \"message_update\"; message: AgentMessage; assistantMessageEvent: AssistantMessageEvent }\n\t| { type: \"message_end\"; message: AgentMessage }\n\t// Tool execution lifecycle\n\t| { type: \"tool_execution_start\"; toolCallId: string; toolName: string; args: any }\n\t| { type: \"tool_execution_update\"; toolCallId: string; toolName: string; args: any; partialResult: any }\n\t| { type: \"tool_execution_end\"; toolCallId: string; toolName: string; result: any; isError: boolean };\n"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@code-yeongyu/senpi-agent-core",
3
- "version": "2026.8.12",
3
+ "version": "2026.8.13",
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": "tsc -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": "npm:@code-yeongyu/senpi-ai@2026.8.12",
38
+ "@earendil-works/pi-ai": "npm:@code-yeongyu/senpi-ai@2026.8.13",
39
+ "@earendil-works/pi-telemetry": "npm:@code-yeongyu/senpi-telemetry@2026.8.13",
33
40
  "diff": "9.0.0",
34
41
  "ignore": "7.0.6",
35
42
  "typebox": "1.3.8",
@@ -1,3 +0,0 @@
1
- import type { SessionMetadata, SessionReader, SessionTreeEntry } from "../types.ts";
2
- export declare function createArraySessionReader<TMetadata extends SessionMetadata>(metadata: TMetadata, readCurrentEntries: () => readonly SessionTreeEntry[]): SessionReader<TMetadata>;
3
- //# sourceMappingURL=array-session-reader.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"array-session-reader.d.ts","sourceRoot":"","sources":["../../../src/harness/session/array-session-reader.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAA6B,eAAe,EAAE,aAAa,EAAE,gBAAgB,EAAE,MAAM,aAAa,CAAC;AAG/G,wBAAgB,wBAAwB,CAAC,SAAS,SAAS,eAAe,EACzE,QAAQ,EAAE,SAAS,EACnB,kBAAkB,EAAE,MAAM,SAAS,gBAAgB,EAAE,GACnD,aAAa,CAAC,SAAS,CAAC,CA+D1B"}
@@ -1,70 +0,0 @@
1
- import { SessionError } from "../types.js";
2
- export function createArraySessionReader(metadata, readCurrentEntries) {
3
- let indexedCount = 0;
4
- let indexedEntries;
5
- let leafId = null;
6
- const byId = new Map();
7
- const updateIndex = () => {
8
- const entries = readCurrentEntries();
9
- if (entries !== indexedEntries || entries.length < indexedCount) {
10
- indexedCount = 0;
11
- leafId = null;
12
- byId.clear();
13
- indexedEntries = entries;
14
- }
15
- for (; indexedCount < entries.length; indexedCount++) {
16
- const entry = entries[indexedCount];
17
- byId.set(entry.id, entry);
18
- leafId = entry.type === "leaf" ? entry.targetId : entry.id;
19
- }
20
- return entries;
21
- };
22
- return {
23
- metadata,
24
- async readHead() {
25
- updateIndex();
26
- if (leafId !== null && !byId.has(leafId)) {
27
- throw new SessionError("invalid_session", `Entry ${leafId} not found`);
28
- }
29
- return { leafId };
30
- },
31
- async readEntry(id) {
32
- updateIndex();
33
- return byId.get(id);
34
- },
35
- async readEntries(options) {
36
- const entries = updateIndex();
37
- const start = options?.afterEntrySeq ?? 0;
38
- const end = options?.limit === undefined ? undefined : start + options.limit;
39
- return entries.slice(start, end);
40
- },
41
- async readPathToRootOrCompaction(requestedLeafId) {
42
- updateIndex();
43
- if (requestedLeafId === null)
44
- return [];
45
- const path = [];
46
- let stopAtEntryId = null;
47
- let current = byId.get(requestedLeafId);
48
- if (!current)
49
- throw new SessionError("not_found", `Entry ${requestedLeafId} not found`);
50
- while (current) {
51
- path.push(current);
52
- if (stopAtEntryId !== null && current.id === stopAtEntryId)
53
- break;
54
- if (current.type === "compaction") {
55
- if (current.retainedTail)
56
- break;
57
- stopAtEntryId = current.firstKeptEntryId ?? null;
58
- }
59
- if (!current.parentId)
60
- break;
61
- const parent = byId.get(current.parentId);
62
- if (!parent)
63
- throw new SessionError("invalid_session", `Entry ${current.parentId} not found`);
64
- current = parent;
65
- }
66
- return path.reverse();
67
- },
68
- };
69
- }
70
- //# sourceMappingURL=array-session-reader.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"array-session-reader.js","sourceRoot":"","sources":["../../../src/harness/session/array-session-reader.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,YAAY,EAAE,MAAM,aAAa,CAAC;AAE3C,MAAM,UAAU,wBAAwB,CACvC,QAAmB,EACnB,kBAAqD;IAErD,IAAI,YAAY,GAAG,CAAC,CAAC;IACrB,IAAI,cAAuD,CAAC;IAC5D,IAAI,MAAM,GAAkB,IAAI,CAAC;IACjC,MAAM,IAAI,GAAG,IAAI,GAAG,EAA4B,CAAC;IAEjD,MAAM,WAAW,GAAG,GAAgC,EAAE;QACrD,MAAM,OAAO,GAAG,kBAAkB,EAAE,CAAC;QACrC,IAAI,OAAO,KAAK,cAAc,IAAI,OAAO,CAAC,MAAM,GAAG,YAAY,EAAE,CAAC;YACjE,YAAY,GAAG,CAAC,CAAC;YACjB,MAAM,GAAG,IAAI,CAAC;YACd,IAAI,CAAC,KAAK,EAAE,CAAC;YACb,cAAc,GAAG,OAAO,CAAC;QAC1B,CAAC;QACD,OAAO,YAAY,GAAG,OAAO,CAAC,MAAM,EAAE,YAAY,EAAE,EAAE,CAAC;YACtD,MAAM,KAAK,GAAG,OAAO,CAAC,YAAY,CAAE,CAAC;YACrC,IAAI,CAAC,GAAG,CAAC,KAAK,CAAC,EAAE,EAAE,KAAK,CAAC,CAAC;YAC1B,MAAM,GAAG,KAAK,CAAC,IAAI,KAAK,MAAM,CAAC,CAAC,CAAC,KAAK,CAAC,QAAQ,CAAC,CAAC,CAAC,KAAK,CAAC,EAAE,CAAC;QAC5D,CAAC;QACD,OAAO,OAAO,CAAC;IAChB,CAAC,CAAC;IAEF,OAAO;QACN,QAAQ;QACR,KAAK,CAAC,QAAQ;YACb,WAAW,EAAE,CAAC;YACd,IAAI,MAAM,KAAK,IAAI,IAAI,CAAC,IAAI,CAAC,GAAG,CAAC,MAAM,CAAC,EAAE,CAAC;gBAC1C,MAAM,IAAI,YAAY,CAAC,iBAAiB,EAAE,SAAS,MAAM,YAAY,CAAC,CAAC;YACxE,CAAC;YACD,OAAO,EAAE,MAAM,EAAE,CAAC;QACnB,CAAC;QACD,KAAK,CAAC,SAAS,CAAC,EAAE;YACjB,WAAW,EAAE,CAAC;YACd,OAAO,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,CAAC;QACrB,CAAC;QACD,KAAK,CAAC,WAAW,CAAC,OAAmC;YACpD,MAAM,OAAO,GAAG,WAAW,EAAE,CAAC;YAC9B,MAAM,KAAK,GAAG,OAAO,EAAE,aAAa,IAAI,CAAC,CAAC;YAC1C,MAAM,GAAG,GAAG,OAAO,EAAE,KAAK,KAAK,SAAS,CAAC,CAAC,CAAC,SAAS,CAAC,CAAC,CAAC,KAAK,GAAG,OAAO,CAAC,KAAK,CAAC;YAC7E,OAAO,OAAO,CAAC,KAAK,CAAC,KAAK,EAAE,GAAG,CAAC,CAAC;QAClC,CAAC;QACD,KAAK,CAAC,0BAA0B,CAAC,eAAe;YAC/C,WAAW,EAAE,CAAC;YACd,IAAI,eAAe,KAAK,IAAI;gBAAE,OAAO,EAAE,CAAC;YACxC,MAAM,IAAI,GAAuB,EAAE,CAAC;YACpC,IAAI,aAAa,GAAkB,IAAI,CAAC;YACxC,IAAI,OAAO,GAAG,IAAI,CAAC,GAAG,CAAC,eAAe,CAAC,CAAC;YACxC,IAAI,CAAC,OAAO;gBAAE,MAAM,IAAI,YAAY,CAAC,WAAW,EAAE,SAAS,eAAe,YAAY,CAAC,CAAC;YACxF,OAAO,OAAO,EAAE,CAAC;gBAChB,IAAI,CAAC,IAAI,CAAC,OAAO,CAAC,CAAC;gBACnB,IAAI,aAAa,KAAK,IAAI,IAAI,OAAO,CAAC,EAAE,KAAK,aAAa;oBAAE,MAAM;gBAClE,IAAI,OAAO,CAAC,IAAI,KAAK,YAAY,EAAE,CAAC;oBACnC,IAAI,OAAO,CAAC,YAAY;wBAAE,MAAM;oBAChC,aAAa,GAAG,OAAO,CAAC,gBAAgB,IAAI,IAAI,CAAC;gBAClD,CAAC;gBACD,IAAI,CAAC,OAAO,CAAC,QAAQ;oBAAE,MAAM;gBAC7B,MAAM,MAAM,GAAG,IAAI,CAAC,GAAG,CAAC,OAAO,CAAC,QAAQ,CAAC,CAAC;gBAC1C,IAAI,CAAC,MAAM;oBAAE,MAAM,IAAI,YAAY,CAAC,iBAAiB,EAAE,SAAS,OAAO,CAAC,QAAQ,YAAY,CAAC,CAAC;gBAC9F,OAAO,GAAG,MAAM,CAAC;YAClB,CAAC;YACD,OAAO,IAAI,CAAC,OAAO,EAAE,CAAC;QACvB,CAAC;KACD,CAAC;AACH,CAAC","sourcesContent":["import type { SessionEntryCursorOptions, SessionMetadata, SessionReader, SessionTreeEntry } from \"../types.ts\";\nimport { SessionError } from \"../types.ts\";\n\nexport function createArraySessionReader<TMetadata extends SessionMetadata>(\n\tmetadata: TMetadata,\n\treadCurrentEntries: () => readonly SessionTreeEntry[],\n): SessionReader<TMetadata> {\n\tlet indexedCount = 0;\n\tlet indexedEntries: readonly SessionTreeEntry[] | undefined;\n\tlet leafId: string | null = null;\n\tconst byId = new Map<string, SessionTreeEntry>();\n\n\tconst updateIndex = (): readonly SessionTreeEntry[] => {\n\t\tconst entries = readCurrentEntries();\n\t\tif (entries !== indexedEntries || entries.length < indexedCount) {\n\t\t\tindexedCount = 0;\n\t\t\tleafId = null;\n\t\t\tbyId.clear();\n\t\t\tindexedEntries = entries;\n\t\t}\n\t\tfor (; indexedCount < entries.length; indexedCount++) {\n\t\t\tconst entry = entries[indexedCount]!;\n\t\t\tbyId.set(entry.id, entry);\n\t\t\tleafId = entry.type === \"leaf\" ? entry.targetId : entry.id;\n\t\t}\n\t\treturn entries;\n\t};\n\n\treturn {\n\t\tmetadata,\n\t\tasync readHead() {\n\t\t\tupdateIndex();\n\t\t\tif (leafId !== null && !byId.has(leafId)) {\n\t\t\t\tthrow new SessionError(\"invalid_session\", `Entry ${leafId} not found`);\n\t\t\t}\n\t\t\treturn { leafId };\n\t\t},\n\t\tasync readEntry(id) {\n\t\t\tupdateIndex();\n\t\t\treturn byId.get(id);\n\t\t},\n\t\tasync readEntries(options?: SessionEntryCursorOptions) {\n\t\t\tconst entries = updateIndex();\n\t\t\tconst start = options?.afterEntrySeq ?? 0;\n\t\t\tconst end = options?.limit === undefined ? undefined : start + options.limit;\n\t\t\treturn entries.slice(start, end);\n\t\t},\n\t\tasync readPathToRootOrCompaction(requestedLeafId) {\n\t\t\tupdateIndex();\n\t\t\tif (requestedLeafId === null) return [];\n\t\t\tconst path: SessionTreeEntry[] = [];\n\t\t\tlet stopAtEntryId: string | null = null;\n\t\t\tlet current = byId.get(requestedLeafId);\n\t\t\tif (!current) throw new SessionError(\"not_found\", `Entry ${requestedLeafId} not found`);\n\t\t\twhile (current) {\n\t\t\t\tpath.push(current);\n\t\t\t\tif (stopAtEntryId !== null && current.id === stopAtEntryId) break;\n\t\t\t\tif (current.type === \"compaction\") {\n\t\t\t\t\tif (current.retainedTail) break;\n\t\t\t\t\tstopAtEntryId = current.firstKeptEntryId ?? null;\n\t\t\t\t}\n\t\t\t\tif (!current.parentId) break;\n\t\t\t\tconst parent = byId.get(current.parentId);\n\t\t\t\tif (!parent) throw new SessionError(\"invalid_session\", `Entry ${current.parentId} not found`);\n\t\t\t\tcurrent = parent;\n\t\t\t}\n\t\t\treturn path.reverse();\n\t\t},\n\t};\n}\n"]}
@@ -1,4 +0,0 @@
1
- import type { SessionForkOptions, SessionForkSelection, SessionReader, SessionTreeEntry } from "../types.ts";
2
- export declare function createSessionForkSelection(options: SessionForkOptions): SessionForkSelection;
3
- export declare function readSessionEntriesForFork(reader: SessionReader, selection: SessionForkSelection): Promise<readonly SessionTreeEntry[]>;
4
- //# sourceMappingURL=fork.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"fork.d.ts","sourceRoot":"","sources":["../../../src/harness/session/fork.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,kBAAkB,EAAE,oBAAoB,EAAE,aAAa,EAAE,gBAAgB,EAAE,MAAM,aAAa,CAAC;AAG7G,wBAAgB,0BAA0B,CAAC,OAAO,EAAE,kBAAkB,GAAG,oBAAoB,CAK5F;AAED,wBAAsB,yBAAyB,CAC9C,MAAM,EAAE,aAAa,EACrB,SAAS,EAAE,oBAAoB,GAC7B,OAAO,CAAC,SAAS,gBAAgB,EAAE,CAAC,CAStC"}
@@ -1,22 +0,0 @@
1
- import { SessionError } from "../types.js";
2
- export function createSessionForkSelection(options) {
3
- if (!options.entryId)
4
- return { kind: "all" };
5
- return (options.position ?? "before") === "at"
6
- ? { kind: "through_entry", entryId: options.entryId }
7
- : { kind: "before_user_message", entryId: options.entryId };
8
- }
9
- export async function readSessionEntriesForFork(reader, selection) {
10
- if (selection.kind === "all")
11
- return reader.readEntries();
12
- const target = await reader.readEntry(selection.entryId);
13
- if (!target)
14
- throw new SessionError("invalid_fork_target", `Entry ${selection.entryId} not found`);
15
- if (selection.kind === "through_entry")
16
- return reader.readPathToRootOrCompaction(target.id);
17
- if (target.type !== "message" || target.message.role !== "user") {
18
- throw new SessionError("invalid_fork_target", `Entry ${selection.entryId} is not a user message`);
19
- }
20
- return reader.readPathToRootOrCompaction(target.parentId);
21
- }
22
- //# sourceMappingURL=fork.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"fork.js","sourceRoot":"","sources":["../../../src/harness/session/fork.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,YAAY,EAAE,MAAM,aAAa,CAAC;AAE3C,MAAM,UAAU,0BAA0B,CAAC,OAA2B;IACrE,IAAI,CAAC,OAAO,CAAC,OAAO;QAAE,OAAO,EAAE,IAAI,EAAE,KAAK,EAAE,CAAC;IAC7C,OAAO,CAAC,OAAO,CAAC,QAAQ,IAAI,QAAQ,CAAC,KAAK,IAAI;QAC7C,CAAC,CAAC,EAAE,IAAI,EAAE,eAAe,EAAE,OAAO,EAAE,OAAO,CAAC,OAAO,EAAE;QACrD,CAAC,CAAC,EAAE,IAAI,EAAE,qBAAqB,EAAE,OAAO,EAAE,OAAO,CAAC,OAAO,EAAE,CAAC;AAC9D,CAAC;AAED,MAAM,CAAC,KAAK,UAAU,yBAAyB,CAC9C,MAAqB,EACrB,SAA+B;IAE/B,IAAI,SAAS,CAAC,IAAI,KAAK,KAAK;QAAE,OAAO,MAAM,CAAC,WAAW,EAAE,CAAC;IAC1D,MAAM,MAAM,GAAG,MAAM,MAAM,CAAC,SAAS,CAAC,SAAS,CAAC,OAAO,CAAC,CAAC;IACzD,IAAI,CAAC,MAAM;QAAE,MAAM,IAAI,YAAY,CAAC,qBAAqB,EAAE,SAAS,SAAS,CAAC,OAAO,YAAY,CAAC,CAAC;IACnG,IAAI,SAAS,CAAC,IAAI,KAAK,eAAe;QAAE,OAAO,MAAM,CAAC,0BAA0B,CAAC,MAAM,CAAC,EAAE,CAAC,CAAC;IAC5F,IAAI,MAAM,CAAC,IAAI,KAAK,SAAS,IAAI,MAAM,CAAC,OAAO,CAAC,IAAI,KAAK,MAAM,EAAE,CAAC;QACjE,MAAM,IAAI,YAAY,CAAC,qBAAqB,EAAE,SAAS,SAAS,CAAC,OAAO,wBAAwB,CAAC,CAAC;IACnG,CAAC;IACD,OAAO,MAAM,CAAC,0BAA0B,CAAC,MAAM,CAAC,QAAQ,CAAC,CAAC;AAC3D,CAAC","sourcesContent":["import type { SessionForkOptions, SessionForkSelection, SessionReader, SessionTreeEntry } from \"../types.ts\";\nimport { SessionError } from \"../types.ts\";\n\nexport function createSessionForkSelection(options: SessionForkOptions): SessionForkSelection {\n\tif (!options.entryId) return { kind: \"all\" };\n\treturn (options.position ?? \"before\") === \"at\"\n\t\t? { kind: \"through_entry\", entryId: options.entryId }\n\t\t: { kind: \"before_user_message\", entryId: options.entryId };\n}\n\nexport async function readSessionEntriesForFork(\n\treader: SessionReader,\n\tselection: SessionForkSelection,\n): Promise<readonly SessionTreeEntry[]> {\n\tif (selection.kind === \"all\") return reader.readEntries();\n\tconst target = await reader.readEntry(selection.entryId);\n\tif (!target) throw new SessionError(\"invalid_fork_target\", `Entry ${selection.entryId} not found`);\n\tif (selection.kind === \"through_entry\") return reader.readPathToRootOrCompaction(target.id);\n\tif (target.type !== \"message\" || target.message.role !== \"user\") {\n\t\tthrow new SessionError(\"invalid_fork_target\", `Entry ${selection.entryId} is not a user message`);\n\t}\n\treturn reader.readPathToRootOrCompaction(target.parentId);\n}\n"]}
@@ -1,13 +0,0 @@
1
- import type { FileSystem, JsonlSessionCreateOptions, JsonlSessionListOptions, JsonlSessionMetadata, SessionStore } from "../types.ts";
2
- export interface JsonlSessionStoreOptions {
3
- fs: JsonlSessionStoreFileSystem;
4
- sessionsRoot: string;
5
- /** Maximum active operations across session keys. Defaults to 4. */
6
- maxConcurrentOperations?: number;
7
- }
8
- export type JsonlSessionStoreFileSystem = Pick<FileSystem, "absolutePath" | "joinPath" | "readTextFile" | "readTextLines" | "writeFile" | "appendFile" | "listDir" | "exists" | "createDir" | "remove">;
9
- type JsonlSessionFileSystem = Pick<FileSystem, "readTextFile" | "readTextLines" | "writeFile" | "appendFile">;
10
- export declare function loadJsonlSessionMetadata(fs: JsonlSessionFileSystem, path: string): Promise<JsonlSessionMetadata>;
11
- export declare function createJsonlSessionStore(options: JsonlSessionStoreOptions): SessionStore<JsonlSessionMetadata, JsonlSessionCreateOptions, JsonlSessionListOptions>;
12
- export {};
13
- //# sourceMappingURL=jsonl-store.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"jsonl-store.d.ts","sourceRoot":"","sources":["../../../src/harness/session/jsonl-store.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EACX,UAAU,EACV,yBAAyB,EACzB,uBAAuB,EACvB,oBAAoB,EAGpB,YAAY,EAEZ,MAAM,aAAa,CAAC;AAOrB,MAAM,WAAW,wBAAwB;IACxC,EAAE,EAAE,2BAA2B,CAAC;IAChC,YAAY,EAAE,MAAM,CAAC;IACrB,oEAAoE;IACpE,uBAAuB,CAAC,EAAE,MAAM,CAAC;CACjC;AACD,MAAM,MAAM,2BAA2B,GAAG,IAAI,CAC7C,UAAU,EACR,cAAc,GACd,UAAU,GACV,cAAc,GACd,eAAe,GACf,WAAW,GACX,YAAY,GACZ,SAAS,GACT,QAAQ,GACR,WAAW,GACX,QAAQ,CACV,CAAC;AAEF,KAAK,sBAAsB,GAAG,IAAI,CAAC,UAAU,EAAE,cAAc,GAAG,eAAe,GAAG,WAAW,GAAG,YAAY,CAAC,CAAC;AA2G9G,wBAAsB,wBAAwB,CAC7C,EAAE,EAAE,sBAAsB,EAC1B,IAAI,EAAE,MAAM,GACV,OAAO,CAAC,oBAAoB,CAAC,CAO/B;AAwRD,wBAAgB,uBAAuB,CACtC,OAAO,EAAE,wBAAwB,GAC/B,YAAY,CAAC,oBAAoB,EAAE,yBAAyB,EAAE,uBAAuB,CAAC,CAExF"}
@@ -1,304 +0,0 @@
1
- import { SessionError, toError } from "../types.js";
2
- import { createArraySessionReader } from "./array-session-reader.js";
3
- import { readSessionEntriesForFork } from "./fork.js";
4
- import { KeyedOperationQueue } from "./keyed-operation-queue.js";
5
- import { createSessionId, createTimestamp, getFileSystemResultOrThrow } from "./repository.js";
6
- const DEFAULT_MAX_CONCURRENT_OPERATIONS = 4;
7
- function invalidSession(path, message, cause) {
8
- return new SessionError("invalid_session", `Invalid JSONL session file ${path}: ${message}`, cause);
9
- }
10
- function invalidEntry(path, line, message, cause) {
11
- return new SessionError("invalid_entry", `Invalid JSONL session file ${path}: line ${line} ${message}`, cause);
12
- }
13
- function parseHeader(line, path) {
14
- let value;
15
- try {
16
- value = JSON.parse(line);
17
- }
18
- catch (error) {
19
- throw invalidSession(path, "first line is not a valid session header", toError(error));
20
- }
21
- if (typeof value !== "object" || value === null)
22
- throw invalidSession(path, "first line is not a valid session header");
23
- const header = value;
24
- if (header.type !== "session" || header.version !== 3) {
25
- throw invalidSession(path, header.type === "session" ? "unsupported session version" : "first line is not a valid session header");
26
- }
27
- if (typeof header.id !== "string" || !header.id)
28
- throw invalidSession(path, "session header is missing id");
29
- if (typeof header.timestamp !== "string" || !header.timestamp)
30
- throw invalidSession(path, "session header is missing timestamp");
31
- if (typeof header.cwd !== "string" || !header.cwd)
32
- throw invalidSession(path, "session header is missing cwd");
33
- if (header.parentSession !== undefined && typeof header.parentSession !== "string") {
34
- throw invalidSession(path, "session header parentSession must be a string");
35
- }
36
- if (header.metadata !== undefined &&
37
- (typeof header.metadata !== "object" || header.metadata === null || Array.isArray(header.metadata))) {
38
- throw invalidSession(path, "session header metadata must be an object");
39
- }
40
- return {
41
- type: "session",
42
- version: 3,
43
- id: header.id,
44
- timestamp: header.timestamp,
45
- cwd: header.cwd,
46
- parentSession: header.parentSession,
47
- metadata: header.metadata,
48
- };
49
- }
50
- function parseEntry(line, path, lineNumber) {
51
- let value;
52
- try {
53
- value = JSON.parse(line);
54
- }
55
- catch (error) {
56
- throw invalidEntry(path, lineNumber, "is not valid JSON", toError(error));
57
- }
58
- if (typeof value !== "object" || value === null)
59
- throw invalidEntry(path, lineNumber, "is not a valid session entry");
60
- const entry = value;
61
- if (typeof entry.type !== "string")
62
- throw invalidEntry(path, lineNumber, "is missing entry type");
63
- if (typeof entry.id !== "string" || !entry.id)
64
- throw invalidEntry(path, lineNumber, "is missing entry id");
65
- if (entry.parentId !== null && typeof entry.parentId !== "string")
66
- throw invalidEntry(path, lineNumber, "has invalid parentId");
67
- if (typeof entry.timestamp !== "string" || !entry.timestamp)
68
- throw invalidEntry(path, lineNumber, "is missing timestamp");
69
- if (entry.type === "leaf" && entry.targetId !== null && typeof entry.targetId !== "string") {
70
- throw invalidEntry(path, lineNumber, "has invalid targetId");
71
- }
72
- return entry;
73
- }
74
- function metadataFromHeader(header, path) {
75
- return {
76
- id: header.id,
77
- createdAt: header.timestamp,
78
- cwd: header.cwd,
79
- path,
80
- parentSessionPath: header.parentSession,
81
- metadata: header.metadata,
82
- };
83
- }
84
- export async function loadJsonlSessionMetadata(fs, path) {
85
- const lines = getFileSystemResultOrThrow(await fs.readTextLines(path, { maxLines: 1 }), `Failed to read session header ${path}`);
86
- if (!lines[0]?.trim())
87
- throw invalidSession(path, "missing session header");
88
- return metadataFromHeader(parseHeader(lines[0], path), path);
89
- }
90
- async function loadJsonlSession(fs, path) {
91
- const content = getFileSystemResultOrThrow(await fs.readTextFile(path), `Failed to read session ${path}`);
92
- const lines = content.split("\n").filter((line) => line.trim());
93
- if (lines.length === 0)
94
- throw invalidSession(path, "missing session header");
95
- const header = parseHeader(lines[0], path);
96
- const entries = lines.slice(1).map((line, index) => parseEntry(line, path, index + 2));
97
- const entryIds = new Set();
98
- for (const entry of entries) {
99
- if (entryIds.has(entry.id))
100
- throw invalidSession(path, `duplicate entry id ${entry.id}`);
101
- entryIds.add(entry.id);
102
- }
103
- return {
104
- metadata: metadataFromHeader(header, path),
105
- entries,
106
- };
107
- }
108
- function encodeCwd(cwd) {
109
- return `--${cwd.replace(/^[/\\]/, "").replace(/[/\\:]/g, "-")}--`;
110
- }
111
- function createDocumentDescriptor(options) {
112
- const id = options.id ?? createSessionId();
113
- if (!id)
114
- throw new SessionError("invalid_session", "Session id cannot be empty");
115
- let encodedId;
116
- try {
117
- encodedId = encodeURIComponent(id);
118
- }
119
- catch (error) {
120
- throw new SessionError("invalid_session", `Invalid session id ${JSON.stringify(id)}`, toError(error));
121
- }
122
- const timestamp = createTimestamp();
123
- const fileName = `${timestamp.replace(/[:.]/g, "-")}_${encodedId}.jsonl`;
124
- return {
125
- id,
126
- timestamp,
127
- fileName,
128
- operationKey: `document:${JSON.stringify([encodeCwd(options.cwd), fileName])}`,
129
- };
130
- }
131
- class JsonlSessionStore {
132
- constructor(options) {
133
- this.entryIdsByPath = new Map();
134
- this.entriesByPath = new Map();
135
- this.operationKeysByPath = new Map();
136
- this.disposed = false;
137
- this.fs = options.fs;
138
- this.sessionsRootInput = options.sessionsRoot;
139
- this.operations = new KeyedOperationQueue({
140
- maxConcurrentOperations: options.maxConcurrentOperations ?? DEFAULT_MAX_CONCURRENT_OPERATIONS,
141
- });
142
- }
143
- create(options) {
144
- this.assertOpen();
145
- const descriptor = createDocumentDescriptor(options);
146
- return this.operations.enqueue(descriptor.operationKey, () => this.createDocument(descriptor, options, options.parentSessionPath, options.metadata, []));
147
- }
148
- load(metadata) {
149
- this.assertOpen();
150
- return this.operations.enqueue(this.operationKey(metadata), () => this.loadDocument(metadata));
151
- }
152
- async loadDocument(metadata) {
153
- if (!getFileSystemResultOrThrow(await this.fs.exists(metadata.path), `Failed to check session ${metadata.path}`)) {
154
- throw new SessionError("not_found", `Session not found: ${metadata.path}`);
155
- }
156
- const document = await loadJsonlSession(this.fs, metadata.path);
157
- this.entriesByPath.set(metadata.path, document.entries);
158
- this.entryIdsByPath.set(metadata.path, new Set(document.entries.map((entry) => entry.id)));
159
- return this.reader(document.metadata);
160
- }
161
- list(options = {}) {
162
- this.assertOpen();
163
- return this.operations.enqueueBarrier(() => this.listSessions(options));
164
- }
165
- async listSessions(options) {
166
- const dirs = options.cwd ? [await this.getSessionDir(options.cwd)] : await this.listSessionDirs();
167
- const sessions = [];
168
- for (const dir of dirs) {
169
- if (!getFileSystemResultOrThrow(await this.fs.exists(dir), `Failed to check session directory ${dir}`))
170
- continue;
171
- const files = getFileSystemResultOrThrow(await this.fs.listDir(dir), `Failed to list sessions in ${dir}`).filter((file) => file.kind !== "directory" && file.name.endsWith(".jsonl"));
172
- for (const file of files)
173
- sessions.push(await loadJsonlSessionMetadata(this.fs, file.path));
174
- }
175
- return sessions.sort((a, b) => new Date(b.createdAt).getTime() - new Date(a.createdAt).getTime());
176
- }
177
- appendEntry(metadata, entry) {
178
- this.assertOpen();
179
- return this.operations.enqueue(this.operationKey(metadata), async () => {
180
- if (!getFileSystemResultOrThrow(await this.fs.exists(metadata.path), `Failed to check session ${metadata.path}`)) {
181
- throw new SessionError("not_found", `Session not found: ${metadata.path}`);
182
- }
183
- let entryIds = this.entryIdsByPath.get(metadata.path);
184
- if (!entryIds) {
185
- await this.loadDocument(metadata);
186
- entryIds = this.entryIdsByPath.get(metadata.path);
187
- }
188
- if (entryIds.has(entry.id))
189
- throw new SessionError("invalid_entry", `Entry ${entry.id} already exists`);
190
- getFileSystemResultOrThrow(await this.fs.appendFile(metadata.path, `${JSON.stringify(entry)}\n`), `Failed to append session entry ${entry.id}`);
191
- entryIds.add(entry.id);
192
- this.entryIdsByPath.set(metadata.path, entryIds);
193
- this.entriesByPath.get(metadata.path).push(entry);
194
- });
195
- }
196
- delete(metadata) {
197
- this.assertOpen();
198
- return this.operations.enqueue(this.operationKey(metadata), async () => {
199
- getFileSystemResultOrThrow(await this.fs.remove(metadata.path, { force: true }), `Failed to delete session ${metadata.path}`);
200
- this.entryIdsByPath.delete(metadata.path);
201
- this.entriesByPath.delete(metadata.path);
202
- this.operationKeysByPath.delete(metadata.path);
203
- });
204
- }
205
- fork(source, options, selection) {
206
- this.assertOpen();
207
- const descriptor = createDocumentDescriptor(options);
208
- const sourceEntries = this.operations.enqueue(this.operationKey(source), async () => {
209
- if (!getFileSystemResultOrThrow(await this.fs.exists(source.path), `Failed to check session ${source.path}`)) {
210
- throw new SessionError("not_found", `Session not found: ${source.path}`);
211
- }
212
- const document = await loadJsonlSession(this.fs, source.path);
213
- this.entriesByPath.set(source.path, document.entries);
214
- this.entryIdsByPath.set(source.path, new Set(document.entries.map((entry) => entry.id)));
215
- return readSessionEntriesForFork(createArraySessionReader(document.metadata, () => document.entries), selection);
216
- });
217
- return this.operations.enqueue(descriptor.operationKey, async () => this.createDocument(descriptor, options, options.parentSessionPath ?? source.path, options.metadata ?? source.metadata, await sourceEntries));
218
- }
219
- async [Symbol.asyncDispose]() {
220
- if (!this.disposePromise) {
221
- this.disposed = true;
222
- this.disposePromise = this.operations.drain();
223
- }
224
- await this.disposePromise;
225
- }
226
- assertOpen() {
227
- if (this.disposed)
228
- throw new SessionError("storage", "JSONL session store is disposed");
229
- }
230
- operationKey(metadata) {
231
- return this.operationKeysByPath.get(metadata.path) ?? metadata.path;
232
- }
233
- async createDocument(descriptor, options, parentSessionPath, metadata, entries) {
234
- const dir = await this.getSessionDir(options.cwd);
235
- getFileSystemResultOrThrow(await this.fs.createDir(dir, { recursive: true }), `Failed to create session directory ${dir}`);
236
- const path = getFileSystemResultOrThrow(await this.fs.joinPath([dir, descriptor.fileName]), `Failed to resolve session file path for ${descriptor.id}`);
237
- if (getFileSystemResultOrThrow(await this.fs.exists(path), `Failed to check session ${path}`)) {
238
- throw new SessionError("invalid_session", `Session already exists: ${path}`);
239
- }
240
- const header = {
241
- type: "session",
242
- version: 3,
243
- id: descriptor.id,
244
- timestamp: descriptor.timestamp,
245
- cwd: options.cwd,
246
- parentSession: parentSessionPath,
247
- metadata,
248
- };
249
- const content = [JSON.stringify(header), ...entries.map((entry) => JSON.stringify(entry)), ""].join("\n");
250
- getFileSystemResultOrThrow(await this.fs.writeFile(path, content), `Failed to create session ${path}`);
251
- const storedEntries = [...entries];
252
- this.entriesByPath.set(path, storedEntries);
253
- this.entryIdsByPath.set(path, new Set(storedEntries.map((entry) => entry.id)));
254
- this.operationKeysByPath.set(path, descriptor.operationKey);
255
- return this.reader(metadataFromHeader(header, path));
256
- }
257
- reader(metadata) {
258
- const reader = createArraySessionReader(metadata, () => {
259
- const entries = this.entriesByPath.get(metadata.path);
260
- if (!entries)
261
- throw new SessionError("not_found", `Session not found: ${metadata.path}`);
262
- return entries;
263
- });
264
- const operationKey = this.operationKey(metadata);
265
- return {
266
- metadata: reader.metadata,
267
- readHead: () => {
268
- this.assertOpen();
269
- return this.operations.enqueue(operationKey, () => reader.readHead());
270
- },
271
- readEntry: (id) => {
272
- this.assertOpen();
273
- return this.operations.enqueue(operationKey, () => reader.readEntry(id));
274
- },
275
- readEntries: (options) => {
276
- this.assertOpen();
277
- return this.operations.enqueue(operationKey, () => reader.readEntries(options));
278
- },
279
- readPathToRootOrCompaction: (leafId) => {
280
- this.assertOpen();
281
- return this.operations.enqueue(operationKey, () => reader.readPathToRootOrCompaction(leafId));
282
- },
283
- };
284
- }
285
- async getSessionsRoot() {
286
- this.sessionsRoot ??= getFileSystemResultOrThrow(await this.fs.absolutePath(this.sessionsRootInput), `Failed to resolve sessions root ${this.sessionsRootInput}`);
287
- return this.sessionsRoot;
288
- }
289
- async getSessionDir(cwd) {
290
- return getFileSystemResultOrThrow(await this.fs.joinPath([await this.getSessionsRoot(), encodeCwd(cwd)]), `Failed to resolve session directory for ${cwd}`);
291
- }
292
- async listSessionDirs() {
293
- const root = await this.getSessionsRoot();
294
- if (!getFileSystemResultOrThrow(await this.fs.exists(root), `Failed to check sessions root ${root}`))
295
- return [];
296
- return getFileSystemResultOrThrow(await this.fs.listDir(root), `Failed to list sessions root ${root}`)
297
- .filter((entry) => entry.kind === "directory")
298
- .map((entry) => entry.path);
299
- }
300
- }
301
- export function createJsonlSessionStore(options) {
302
- return new JsonlSessionStore(options);
303
- }
304
- //# sourceMappingURL=jsonl-store.js.map