@earendil-works/pi-agent-core 0.79.10 → 0.80.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (50) hide show
  1. package/README.md +0 -18
  2. package/dist/agent-loop.d.ts +1 -1
  3. package/dist/agent-loop.d.ts.map +1 -1
  4. package/dist/agent-loop.js +1 -1
  5. package/dist/agent-loop.js.map +1 -1
  6. package/dist/agent.d.ts +1 -1
  7. package/dist/agent.d.ts.map +1 -1
  8. package/dist/agent.js +1 -1
  9. package/dist/agent.js.map +1 -1
  10. package/dist/harness/agent-harness.d.ts +2 -2
  11. package/dist/harness/agent-harness.d.ts.map +1 -1
  12. package/dist/harness/agent-harness.js +6 -30
  13. package/dist/harness/agent-harness.js.map +1 -1
  14. package/dist/harness/compaction/branch-summarization.d.ts +3 -5
  15. package/dist/harness/compaction/branch-summarization.d.ts.map +1 -1
  16. package/dist/harness/compaction/branch-summarization.js +2 -3
  17. package/dist/harness/compaction/branch-summarization.js.map +1 -1
  18. package/dist/harness/compaction/compaction.d.ts +4 -4
  19. package/dist/harness/compaction/compaction.d.ts.map +1 -1
  20. package/dist/harness/compaction/compaction.js +17 -15
  21. package/dist/harness/compaction/compaction.js.map +1 -1
  22. package/dist/harness/compaction/utils.d.ts +1 -1
  23. package/dist/harness/compaction/utils.d.ts.map +1 -1
  24. package/dist/harness/compaction/utils.js.map +1 -1
  25. package/dist/harness/messages.d.ts +1 -1
  26. package/dist/harness/messages.d.ts.map +1 -1
  27. package/dist/harness/messages.js.map +1 -1
  28. package/dist/harness/session/session.d.ts +1 -1
  29. package/dist/harness/session/session.d.ts.map +1 -1
  30. package/dist/harness/session/session.js +2 -1
  31. package/dist/harness/session/session.js.map +1 -1
  32. package/dist/harness/types.d.ts +8 -6
  33. package/dist/harness/types.d.ts.map +1 -1
  34. package/dist/harness/types.js.map +1 -1
  35. package/dist/index.d.ts +19 -2
  36. package/dist/index.d.ts.map +1 -1
  37. package/dist/index.js +24 -4
  38. package/dist/index.js.map +1 -1
  39. package/dist/proxy.d.ts +1 -1
  40. package/dist/proxy.d.ts.map +1 -1
  41. package/dist/proxy.js +1 -1
  42. package/dist/proxy.js.map +1 -1
  43. package/dist/types.d.ts +4 -3
  44. package/dist/types.d.ts.map +1 -1
  45. package/dist/types.js.map +1 -1
  46. package/package.json +2 -6
  47. package/dist/base.d.ts +0 -20
  48. package/dist/base.d.ts.map +0 -1
  49. package/dist/base.js +0 -20
  50. package/dist/base.js.map +0 -1
@@ -1 +1 @@
1
- {"version":3,"file":"types.js","sourceRoot":"","sources":["../../src/harness/types.ts"],"names":[],"mappings":"AAOA,0CAA0C;AAC1C,MAAM,UAAU,EAAE,CAAiB,KAAa,EAA0B;IACzE,OAAO,EAAE,EAAE,EAAE,IAAI,EAAE,KAAK,EAAE,CAAC;AAAA,CAC3B;AAED,sCAAsC;AACtC,MAAM,UAAU,GAAG,CAAiB,KAAa,EAA0B;IAC1E,OAAO,EAAE,EAAE,EAAE,KAAK,EAAE,KAAK,EAAE,CAAC;AAAA,CAC5B;AAED,+GAA+G;AAC/G,MAAM,UAAU,UAAU,CAAiB,MAA8B,EAAU;IAClF,IAAI,CAAC,MAAM,CAAC,EAAE;QAAE,MAAM,MAAM,CAAC,KAAK,CAAC;IACnC,OAAO,MAAM,CAAC,KAAK,CAAC;AAAA,CACpB;AAED,wHAAwH;AACxH,MAAM,UAAU,cAAc,CAAgC,MAA8B,EAAsB;IACjH,OAAO,MAAM,CAAC,EAAE,CAAC,CAAC,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC,CAAC,SAAS,CAAC;AAAA,CAC5C;AAED,oGAAoG;AACpG,MAAM,UAAU,OAAO,CAAC,KAAc,EAAS;IAC9C,IAAI,KAAK,YAAY,KAAK;QAAE,OAAO,KAAK,CAAC;IACzC,IAAI,OAAO,KAAK,KAAK,QAAQ;QAAE,OAAO,IAAI,KAAK,CAAC,KAAK,CAAC,CAAC;IACvD,IAAI,CAAC;QACJ,O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, Model, SimpleStreamOptions, TextContent, Transport } from \"@earendil-works/pi-ai/base\";\nimport type { AgentEvent, AgentMessage, AgentTool, QueueMode, ThinkingLevel } from \"../types.ts\";\nimport type { Session } from \"./session/session.ts\";\n\n/** Result of a fallible operation. Expected failures are returned as `ok: false` instead of thrown. */\nexport type Result<TValue, TError> = { ok: true; value: TValue } | { ok: false; error: TError };\n\n/** Create a successful {@link Result}. */\nexport function ok<TValue, TError>(value: TValue): Result<TValue, TError> {\n\treturn { ok: true, value };\n}\n\n/** Create a failed {@link Result}. */\nexport function err<TValue, TError>(error: TError): Result<TValue, TError> {\n\treturn { ok: false, error };\n}\n\n/** Return the success value or throw the failure error. Intended for tests and explicit adapter boundaries. */\nexport function getOrThrow<TValue, TError>(result: Result<TValue, TError>): TValue {\n\tif (!result.ok) throw result.error;\n\treturn result.value;\n}\n\n/** Return the success value or `undefined`. Only object values are allowed to avoid truthiness bugs with primitives. */\nexport function getOrUndefined<TValue extends object, TError>(result: Result<TValue, TError>): TValue | undefined {\n\treturn result.ok ? result.value : undefined;\n}\n\n/** Normalize unknown thrown values into Error instances before using them as typed error causes. */\nexport function toError(error: unknown): Error {\n\tif (error instanceof Error) return error;\n\tif (typeof error === \"string\") return new Error(error);\n\ttry {\n\t\treturn new Error(JSON.stringify(error));\n\t} catch {\n\t\treturn new Error(String(error));\n\t}\n}\n\n/**\n * Skill loaded from a `SKILL.md` file or provided by an application.\n *\n * `name`, `description`, and `filePath` are inserted into the system prompt in an XML-formatted block as suggested by agentskills.io.\n * Use {@link formatSkillsForSystemPrompt} to generate the spec-compatible system prompt block.\n */\nexport interface Skill {\n\t/** Stable skill name used for lookup and model-visible listings. */\n\tname: string;\n\t/** Short model-visible description of when to use the skill. */\n\tdescription: string;\n\t/** Full skill instructions. */\n\tcontent: string;\n\t/** Absolute path to the skill file. Used for model-visible location and resolving relative references. */\n\tfilePath: string;\n\t/** Exclude this skill from model-visible skill lists while still allowing explicit application invocation. */\n\tdisableModelInvocation?: boolean;\n}\n\n/** Prompt template that can be formatted into a prompt for explicit invocation. */\nexport interface PromptTemplate {\n\t/** Stable template name used for lookup or application command routing. */\n\tname: string;\n\t/** Optional description for command lists or autocomplete. */\n\tdescription?: string;\n\t/** Template content. Argument placeholders are formatted by `formatPromptTemplateInvocation`. */\n\tcontent: string;\n}\n\n/** Resources made available to explicit invocation methods and system-prompt callbacks. */\nexport interface AgentHarnessResources<\n\tTSkill extends Skill = Skill,\n\tTPromptTemplate extends PromptTemplate = PromptTemplate,\n> {\n\t/** Prompt templates available for explicit invocation. */\n\tpromptTemplates?: TPromptTemplate[];\n\t/** Skills available to the model and explicit skill invocation. */\n\tskills?: TSkill[];\n}\n\n/** Curated provider request options owned by the harness and snapshotted per turn. */\nexport interface AgentHarnessStreamOptions {\n\t/** Preferred transport forwarded to the stream function. */\n\ttransport?: Transport;\n\t/** Provider request timeout in milliseconds. */\n\ttimeoutMs?: number;\n\t/** Maximum provider retry attempts. */\n\tmaxRetries?: number;\n\t/** Optional cap for provider-requested retry delays. */\n\tmaxRetryDelayMs?: number;\n\t/** Additional request headers merged with auth and lifecycle headers. */\n\theaders?: Record<string, string>;\n\t/** Provider metadata forwarded with requests. */\n\tmetadata?: SimpleStreamOptions[\"metadata\"];\n\t/** Provider cache retention hint. */\n\tcacheRetention?: SimpleStreamOptions[\"cacheRetention\"];\n}\n\n/** Per-request stream option patch returned by provider hooks. */\nexport interface AgentHarnessStreamOptionsPatch\n\textends Omit<Partial<AgentHarnessStreamOptions>, \"headers\" | \"metadata\"> {\n\t/** Header patch. `undefined` values delete keys; explicit `headers: undefined` clears all headers. */\n\theaders?: Record<string, string | undefined>;\n\t/** Metadata patch. `undefined` values delete keys; explicit `metadata: undefined` clears all metadata. */\n\tmetadata?: Record<string, unknown | undefined>;\n}\n\n/** Kind of filesystem object as addressed by a {@link FileSystem}. Symlinks are not followed automatically. */\nexport type FileKind = \"file\" | \"directory\" | \"symlink\";\n\n/** Stable, backend-independent file error codes returned by {@link FileSystem} file operations. */\nexport type FileErrorCode =\n\t| \"aborted\"\n\t| \"not_found\"\n\t| \"permission_denied\"\n\t| \"not_directory\"\n\t| \"is_directory\"\n\t| \"invalid\"\n\t| \"not_supported\"\n\t| \"unknown\";\n\n/** Error returned by {@link FileSystem} file operations. */\nexport class FileError extends Error {\n\t/** Backend-independent error code. */\n\tpublic code: FileErrorCode;\n\t/** Absolute addressed path associated with the failure, when available. */\n\tpublic path?: string;\n\n\tconstructor(code: FileErrorCode, message: string, path?: string, cause?: Error) {\n\t\tsuper(message, cause === undefined ? undefined : { cause });\n\t\tthis.name = \"FileError\";\n\t\tthis.code = code;\n\t\tthis.path = path;\n\t}\n}\n\n/** Stable, backend-independent execution error codes returned by {@link ExecutionEnv.exec}. */\nexport type ExecutionErrorCode =\n\t| \"aborted\"\n\t| \"timeout\"\n\t| \"shell_unavailable\"\n\t| \"spawn_error\"\n\t| \"callback_error\"\n\t| \"unknown\";\n\n/** Error returned by {@link ExecutionEnv.exec}. */\nexport class ExecutionError extends Error {\n\t/** Backend-independent error code. */\n\tpublic code: ExecutionErrorCode;\n\n\tconstructor(code: ExecutionErrorCode, message: string, cause?: Error) {\n\t\tsuper(message, cause === undefined ? undefined : { cause });\n\t\tthis.name = \"ExecutionError\";\n\t\tthis.code = code;\n\t}\n}\n\n/** Stable compaction error codes returned by compaction helpers. */\nexport type CompactionErrorCode = \"aborted\" | \"summarization_failed\" | \"invalid_session\" | \"unknown\";\n\n/** Error returned by compaction helpers. */\nexport class CompactionError extends Error {\n\t/** Backend-independent error code. */\n\tpublic code: CompactionErrorCode;\n\n\tconstructor(code: CompactionErrorCode, message: string, cause?: Error) {\n\t\tsuper(message, cause === undefined ? undefined : { cause });\n\t\tthis.name = \"CompactionError\";\n\t\tthis.code = code;\n\t}\n}\n\n/** Stable branch-summary error codes returned by branch summarization helpers. */\nexport type BranchSummaryErrorCode = \"aborted\" | \"summarization_failed\" | \"invalid_session\";\n\n/** Error returned by branch summarization helpers. */\nexport class BranchSummaryError extends Error {\n\t/** Backend-independent error code. */\n\tpublic code: BranchSummaryErrorCode;\n\n\tconstructor(code: BranchSummaryErrorCode, message: string, cause?: Error) {\n\t\tsuper(message, cause === undefined ? undefined : { cause });\n\t\tthis.name = \"BranchSummaryError\";\n\t\tthis.code = code;\n\t}\n}\n\nexport type SessionErrorCode =\n\t| \"not_found\"\n\t| \"invalid_session\"\n\t| \"invalid_entry\"\n\t| \"invalid_fork_target\"\n\t| \"storage\"\n\t| \"unknown\";\n\n/** Error thrown by session storage, repositories, and session tree operations. */\nexport class SessionError extends Error {\n\t/** Session subsystem error code. */\n\tpublic code: SessionErrorCode;\n\n\tconstructor(code: SessionErrorCode, message: string, cause?: Error) {\n\t\tsuper(message, cause === undefined ? undefined : { cause });\n\t\tthis.name = \"SessionError\";\n\t\tthis.code = code;\n\t}\n}\n\nexport type AgentHarnessErrorCode =\n\t| \"busy\"\n\t| \"invalid_state\"\n\t| \"invalid_argument\"\n\t| \"session\"\n\t| \"hook\"\n\t| \"auth\"\n\t| \"compaction\"\n\t| \"branch_summary\"\n\t| \"unknown\";\n\n/** Public AgentHarness failure with a stable top-level classification. */\nexport class AgentHarnessError extends Error {\n\tpublic code: AgentHarnessErrorCode;\n\n\tconstructor(code: AgentHarnessErrorCode, message: string, cause?: Error) {\n\t\tsuper(message, cause === undefined ? undefined : { cause });\n\t\tthis.name = \"AgentHarnessError\";\n\t\tthis.code = code;\n\t}\n}\n\n/** Metadata for one filesystem object in a {@link FileSystem}. */\nexport interface FileInfo {\n\t/** Basename of {@link path}. */\n\tname: string;\n\t/** Absolute, syntactically normalized addressed path in the execution environment. Symlinks are not followed. */\n\tpath: string;\n\t/** Object kind. Symlink targets are not followed; use {@link FileSystem.canonicalPath} explicitly. */\n\tkind: FileKind;\n\t/** Size in bytes for the addressed filesystem object. */\n\tsize: number;\n\t/** Modification time as milliseconds since Unix epoch. */\n\tmtimeMs: number;\n}\n\n/** Options for {@link Shell.exec}. */\nexport interface ExecutionEnvExecOptions {\n\t/** Working directory for the command. Relative paths are resolved against {@link ExecutionEnv.cwd}. Defaults to {@link ExecutionEnv.cwd}. */\n\tcwd?: string;\n\t/** Additional environment variables for the command. Values override the environment defaults. Defaults to no overrides. */\n\tenv?: Record<string, string>;\n\t/** Timeout in seconds. Implementations should return a timeout error when the command exceeds this duration. Defaults to no timeout. */\n\ttimeout?: number;\n\t/** Abort signal used to terminate the command. Defaults to no abort signal. */\n\tabortSignal?: AbortSignal;\n\t/** Called with stdout chunks as they are produced. */\n\tonStdout?: (chunk: string) => void;\n\t/** Called with stderr chunks as they are produced. */\n\tonStderr?: (chunk: string) => void;\n}\n\n/**\n * Filesystem capability used by the harness.\n *\n * Paths passed to methods may be absolute or relative to {@link cwd}. Paths returned by file operations are addressed paths\n * in the filesystem namespace, but are not canonicalized through symlinks unless returned by {@link canonicalPath}.\n *\n * Operation methods must never throw or reject. All filesystem failures, including unexpected backend failures, must be\n * encoded in the returned {@link Result}. Implementations must preserve this invariant.\n */\nexport interface FileSystem {\n\t/** Current working directory for relative paths. */\n\tcwd: string;\n\n\t/** Return an absolute addressed path without requiring it to exist and without resolving symlinks. */\n\tabsolutePath(path: string, abortSignal?: AbortSignal): Promise<Result<string, FileError>>;\n\t/** Join path segments in the filesystem namespace without requiring the result to exist. */\n\tjoinPath(parts: string[], abortSignal?: AbortSignal): Promise<Result<string, FileError>>;\n\t/** Read a UTF-8 text file. */\n\treadTextFile(path: string, abortSignal?: AbortSignal): Promise<Result<string, FileError>>;\n\t/** Read UTF-8 text lines. Implementations should stop once `maxLines` lines have been read. */\n\treadTextLines(\n\t\tpath: string,\n\t\toptions?: { maxLines?: number; abortSignal?: AbortSignal },\n\t): Promise<Result<string[], FileError>>;\n\t/** Read a binary file. */\n\treadBinaryFile(path: string, abortSignal?: AbortSignal): Promise<Result<Uint8Array, FileError>>;\n\t/** Create or overwrite a file, creating parent directories when supported. */\n\twriteFile(path: string, content: string | Uint8Array, abortSignal?: AbortSignal): Promise<Result<void, FileError>>;\n\t/** Create or append to a file, creating parent directories when supported. */\n\tappendFile(path: string, content: string | Uint8Array, abortSignal?: AbortSignal): Promise<Result<void, FileError>>;\n\t/** Return metadata for the addressed path without following symlinks. */\n\tfileInfo(path: string, abortSignal?: AbortSignal): Promise<Result<FileInfo, FileError>>;\n\t/** List direct children of a directory without following symlinks. */\n\tlistDir(path: string, abortSignal?: AbortSignal): Promise<Result<FileInfo[], FileError>>;\n\t/** Return the canonical path for an existing path, resolving symlinks where supported. */\n\tcanonicalPath(path: string, abortSignal?: AbortSignal): Promise<Result<string, FileError>>;\n\t/** Return false for missing paths. Other errors, such as permission failures, return a {@link FileError}. */\n\texists(path: string, abortSignal?: AbortSignal): Promise<Result<boolean, FileError>>;\n\t/** Create a directory. Defaults: `recursive: true`, no abort signal. */\n\tcreateDir(\n\t\tpath: string,\n\t\toptions?: { recursive?: boolean; abortSignal?: AbortSignal },\n\t): Promise<Result<void, FileError>>;\n\t/** Remove a file or directory. Defaults: `recursive: false`, `force: false`, no abort signal. */\n\tremove(\n\t\tpath: string,\n\t\toptions?: { recursive?: boolean; force?: boolean; abortSignal?: AbortSignal },\n\t): Promise<Result<void, FileError>>;\n\t/** Create a temporary directory and return its absolute path. Defaults: `prefix: \"tmp-\"`, no abort signal. */\n\tcreateTempDir(prefix?: string, abortSignal?: AbortSignal): Promise<Result<string, FileError>>;\n\t/** Create a temporary file and return its absolute path. Defaults: `prefix: \"\"`, `suffix: \"\"`, no abort signal. */\n\tcreateTempFile(options?: {\n\t\tprefix?: string;\n\t\tsuffix?: string;\n\t\tabortSignal?: AbortSignal;\n\t}): Promise<Result<string, FileError>>;\n\n\t/** Release filesystem resources. Must be best-effort and must not throw or reject. */\n\tcleanup(): Promise<void>;\n}\n\n/** Shell execution capability used by the harness. */\nexport interface Shell {\n\t/** Execute a shell command in {@link FileSystem.cwd} unless `options.cwd` is provided. */\n\texec(\n\t\tcommand: string,\n\t\toptions?: ExecutionEnvExecOptions,\n\t): Promise<Result<{ stdout: string; stderr: string; exitCode: number }, ExecutionError>>;\n\t/** Release shell resources. Must be best-effort and must not throw or reject. */\n\tcleanup(): Promise<void>;\n}\n\n/** Filesystem and process execution environment used by the harness. */\nexport interface ExecutionEnv extends FileSystem, Shell {}\n\nexport interface SessionTreeEntryBase {\n\ttype: string;\n\tid: string;\n\tparentId: string | null;\n\ttimestamp: string;\n}\n\nexport interface MessageEntry extends SessionTreeEntryBase {\n\ttype: \"message\";\n\tmessage: AgentMessage;\n}\n\nexport interface ThinkingLevelChangeEntry extends SessionTreeEntryBase {\n\ttype: \"thinking_level_change\";\n\tthinkingLevel: string;\n}\n\nexport interface ModelChangeEntry extends SessionTreeEntryBase {\n\ttype: \"model_change\";\n\tprovider: string;\n\tmodelId: string;\n}\n\nexport interface ActiveToolsChangeEntry extends SessionTreeEntryBase {\n\ttype: \"active_tools_change\";\n\tactiveToolNames: string[];\n}\n\nexport interface CompactionEntry<T = unknown> extends SessionTreeEntryBase {\n\ttype: \"compaction\";\n\tsummary: string;\n\tfirstKeptEntryId: string;\n\ttokensBefore: number;\n\tdetails?: T;\n\tfromHook?: boolean;\n}\n\nexport interface BranchSummaryEntry<T = unknown> extends SessionTreeEntryBase {\n\ttype: \"branch_summary\";\n\tfromId: string;\n\tsummary: string;\n\tdetails?: T;\n\tfromHook?: boolean;\n}\n\nexport interface CustomEntry<T = unknown> extends SessionTreeEntryBase {\n\ttype: \"custom\";\n\tcustomType: string;\n\tdata?: T;\n}\n\nexport interface CustomMessageEntry<T = unknown> extends SessionTreeEntryBase {\n\ttype: \"custom_message\";\n\tcustomType: string;\n\tcontent: string | (TextContent | ImageContent)[];\n\tdetails?: T;\n\tdisplay: boolean;\n}\n\nexport interface LabelEntry extends SessionTreeEntryBase {\n\ttype: \"label\";\n\ttargetId: string;\n\tlabel: string | undefined;\n}\n\nexport interface SessionInfoEntry extends SessionTreeEntryBase {\n\ttype: \"session_info\"; // legacy name, kept for backwards compatibility\n\tname?: string;\n}\n\nexport interface LeafEntry extends SessionTreeEntryBase {\n\ttype: \"leaf\";\n\ttargetId: string | null;\n}\n\nexport type SessionTreeEntry =\n\t| MessageEntry\n\t| ThinkingLevelChangeEntry\n\t| ModelChangeEntry\n\t| ActiveToolsChangeEntry\n\t| CompactionEntry\n\t| BranchSummaryEntry\n\t| CustomEntry\n\t| CustomMessageEntry\n\t| LabelEntry\n\t| SessionInfoEntry\n\t| LeafEntry;\n\nexport interface SessionContext {\n\tmessages: AgentMessage[];\n\tthinkingLevel: string;\n\tmodel: { provider: string; modelId: string } | null;\n\tactiveToolNames: string[] | null;\n}\n\nexport interface SessionMetadata {\n\tid: string;\n\tcreatedAt: string;\n}\n\nexport interface JsonlSessionMetadata extends SessionMetadata {\n\tcwd: string;\n\tpath: string;\n\tparentSessionPath?: string;\n}\n\nexport interface SessionStorage<TMetadata extends SessionMetadata = SessionMetadata> {\n\tgetMetadata(): Promise<TMetadata>;\n\tgetLeafId(): Promise<string | null>;\n\t/** Persist a leaf entry that records the active session-tree leaf. */\n\tsetLeafId(leafId: string | null): Promise<void>;\n\tcreateEntryId(): Promise<string>;\n\tappendEntry(entry: SessionTreeEntry): Promise<void>;\n\tgetEntry(id: string): Promise<SessionTreeEntry | undefined>;\n\tfindEntries<TType extends SessionTreeEntry[\"type\"]>(\n\t\ttype: TType,\n\t): Promise<Array<Extract<SessionTreeEntry, { type: TType }>>>;\n\tgetLabel(id: string): Promise<string | undefined>;\n\tgetPathToRoot(leafId: string | null): Promise<SessionTreeEntry[]>;\n\tgetEntries(): Promise<SessionTreeEntry[]>;\n}\n\nexport type { Session } from \"./session/session.ts\";\n\nexport interface SessionCreateOptions {\n\tid?: string;\n}\n\nexport interface SessionForkOptions {\n\tentryId?: string;\n\tposition?: \"before\" | \"at\";\n\tid?: string;\n}\n\nexport interface SessionRepo<\n\tTMetadata extends SessionMetadata = SessionMetadata,\n\tTCreateOptions extends SessionCreateOptions = SessionCreateOptions,\n\tTListOptions = void,\n> {\n\tcreate(options: TCreateOptions): Promise<Session<TMetadata>>;\n\topen(metadata: TMetadata): Promise<Session<TMetadata>>;\n\tlist(options?: TListOptions): Promise<TMetadata[]>;\n\tdelete(metadata: TMetadata): Promise<void>;\n\tfork(source: TMetadata, options: SessionForkOptions & TCreateOptions): Promise<Session<TMetadata>>;\n}\n\nexport interface JsonlSessionCreateOptions extends SessionCreateOptions {\n\tcwd: string;\n\tparentSessionPath?: string;\n}\n\nexport interface JsonlSessionListOptions {\n\tcwd?: string;\n}\n\nexport interface JsonlSessionRepoApi\n\textends SessionRepo<JsonlSessionMetadata, JsonlSessionCreateOptions, JsonlSessionListOptions> {}\n\nexport type AgentHarnessPhase = \"idle\" | \"turn\" | \"compaction\" | \"branch_summary\" | \"retry\";\n\nexport type PendingSessionWrite = SessionTreeEntry extends infer TEntry\n\t? TEntry extends SessionTreeEntry\n\t\t? Omit<TEntry, \"id\" | \"parentId\" | \"timestamp\">\n\t\t: never\n\t: never;\n\nexport interface QueueUpdateEvent {\n\ttype: \"queue_update\";\n\tsteer: AgentMessage[];\n\tfollowUp: AgentMessage[];\n\tnextTurn: AgentMessage[];\n}\n\nexport interface SavePointEvent {\n\ttype: \"save_point\";\n\thadPendingMutations: boolean;\n}\n\nexport interface AbortEvent {\n\ttype: \"abort\";\n\tclearedSteer: AgentMessage[];\n\tclearedFollowUp: AgentMessage[];\n}\n\nexport interface SettledEvent {\n\ttype: \"settled\";\n\tnextTurnCount: number;\n}\n\nexport interface BeforeAgentStartEvent<\n\tTSkill extends Skill = Skill,\n\tTPromptTemplate extends PromptTemplate = PromptTemplate,\n> {\n\ttype: \"before_agent_start\";\n\tprompt: string;\n\timages?: ImageContent[];\n\tsystemPrompt: string;\n\tresources: AgentHarnessResources<TSkill, TPromptTemplate>;\n}\n\nexport interface ContextEvent {\n\ttype: \"context\";\n\tmessages: AgentMessage[];\n}\n\nexport interface BeforeProviderRequestEvent {\n\ttype: \"before_provider_request\";\n\tmodel: Model<any>;\n\tsessionId: string;\n\tstreamOptions: AgentHarnessStreamOptions;\n}\n\nexport interface BeforeProviderPayloadEvent {\n\ttype: \"before_provider_payload\";\n\tmodel: Model<any>;\n\tpayload: unknown;\n}\n\nexport interface AfterProviderResponseEvent {\n\ttype: \"after_provider_response\";\n\tstatus: number;\n\theaders: Record<string, string>;\n}\n\nexport interface ToolCallEvent {\n\ttype: \"tool_call\";\n\ttoolCallId: string;\n\ttoolName: string;\n\tinput: Record<string, unknown>;\n}\n\nexport interface ToolResultEvent {\n\ttype: \"tool_result\";\n\ttoolCallId: string;\n\ttoolName: string;\n\tinput: Record<string, unknown>;\n\tcontent: Array<TextContent | ImageContent>;\n\tdetails: unknown;\n\tisError: boolean;\n}\n\nexport interface SessionBeforeCompactEvent {\n\ttype: \"session_before_compact\";\n\tpreparation: CompactionPreparation;\n\tbranchEntries: SessionTreeEntry[];\n\tcustomInstructions?: string;\n\tsignal: AbortSignal;\n}\n\nexport interface SessionCompactEvent {\n\ttype: \"session_compact\";\n\tcompactionEntry: CompactionEntry;\n\tfromHook: boolean;\n}\n\nexport interface SessionBeforeTreeEvent {\n\ttype: \"session_before_tree\";\n\tpreparation: TreePreparation;\n\tsignal: AbortSignal;\n}\n\nexport interface SessionTreeEvent {\n\ttype: \"session_tree\";\n\tnewLeafId: string | null;\n\toldLeafId: string | null;\n\tsummaryEntry?: BranchSummaryEntry;\n\tfromHook?: boolean;\n}\n\nexport interface ModelUpdateEvent {\n\ttype: \"model_update\";\n\tmodel: Model<any>;\n\tpreviousModel: Model<any> | undefined;\n\tsource: \"set\" | \"restore\";\n}\n\nexport interface ThinkingLevelUpdateEvent {\n\ttype: \"thinking_level_update\";\n\tlevel: ThinkingLevel;\n\tpreviousLevel: ThinkingLevel;\n}\n\nexport interface ToolsUpdateEvent {\n\ttype: \"tools_update\";\n\ttoolNames: string[];\n\tpreviousToolNames: string[];\n\tactiveToolNames: string[];\n\tpreviousActiveToolNames: string[];\n\tsource: \"set\" | \"restore\";\n}\n\nexport interface ResourcesUpdateEvent<\n\tTSkill extends Skill = Skill,\n\tTPromptTemplate extends PromptTemplate = PromptTemplate,\n> {\n\ttype: \"resources_update\";\n\tresources: AgentHarnessResources<TSkill, TPromptTemplate>;\n\tpreviousResources: AgentHarnessResources<TSkill, TPromptTemplate>;\n}\n\nexport type AgentHarnessOwnEvent<\n\tTSkill extends Skill = Skill,\n\tTPromptTemplate extends PromptTemplate = PromptTemplate,\n> =\n\t| QueueUpdateEvent\n\t| SavePointEvent\n\t| AbortEvent\n\t| SettledEvent\n\t| BeforeAgentStartEvent<TSkill, TPromptTemplate>\n\t| ContextEvent\n\t| BeforeProviderRequestEvent\n\t| BeforeProviderPayloadEvent\n\t| AfterProviderResponseEvent\n\t| ToolCallEvent\n\t| ToolResultEvent\n\t| SessionBeforeCompactEvent\n\t| SessionCompactEvent\n\t| SessionBeforeTreeEvent\n\t| SessionTreeEvent\n\t| ModelUpdateEvent\n\t| ThinkingLevelUpdateEvent\n\t| ResourcesUpdateEvent<TSkill, TPromptTemplate>\n\t| ToolsUpdateEvent;\n\nexport type AgentHarnessEvent<TSkill extends Skill = Skill, TPromptTemplate extends PromptTemplate = PromptTemplate> =\n\t| AgentEvent\n\t| AgentHarnessOwnEvent<TSkill, TPromptTemplate>;\n\nexport interface BeforeAgentStartResult {\n\tmessages?: AgentMessage[];\n\tsystemPrompt?: string;\n}\n\nexport interface ContextResult {\n\tmessages: AgentMessage[];\n}\n\nexport interface BeforeProviderRequestResult {\n\tstreamOptions?: AgentHarnessStreamOptionsPatch;\n}\n\nexport interface BeforeProviderPayloadResult {\n\tpayload: unknown;\n}\n\nexport interface ToolCallResult {\n\tblock?: boolean;\n\treason?: string;\n}\n\nexport interface ToolResultPatch {\n\tcontent?: Array<TextContent | ImageContent>;\n\tdetails?: unknown;\n\tisError?: boolean;\n\tterminate?: boolean;\n}\n\nexport interface SessionBeforeCompactResult {\n\tcancel?: boolean;\n\tcompaction?: CompactResult;\n}\n\nexport interface SessionBeforeTreeResult {\n\tcancel?: boolean;\n\tsummary?: { summary: string; details?: unknown };\n\tcustomInstructions?: string;\n\treplaceInstructions?: boolean;\n\tlabel?: string;\n}\n\nexport type AgentHarnessEventResultMap = {\n\tbefore_agent_start: BeforeAgentStartResult | undefined;\n\tcontext: ContextResult | undefined;\n\tbefore_provider_request: BeforeProviderRequestResult | undefined;\n\tbefore_provider_payload: BeforeProviderPayloadResult | undefined;\n\tafter_provider_response: undefined;\n\ttool_call: ToolCallResult | undefined;\n\ttool_result: ToolResultPatch | undefined;\n\tsession_before_compact: SessionBeforeCompactResult | undefined;\n\tsession_compact: undefined;\n\tsession_before_tree: SessionBeforeTreeResult | undefined;\n\tsession_tree: undefined;\n\tmodel_update: undefined;\n\tthinking_level_update: undefined;\n\tresources_update: undefined;\n\ttools_update: undefined;\n\tqueue_update: undefined;\n\tsave_point: undefined;\n\tabort: undefined;\n\tsettled: undefined;\n};\n\nexport interface AgentHarnessPromptOptions {\n\timages?: ImageContent[];\n}\n\nexport interface AbortResult {\n\tclearedSteer: AgentMessage[];\n\tclearedFollowUp: AgentMessage[];\n}\n\nexport interface CompactResult {\n\tsummary: string;\n\tfirstKeptEntryId: string;\n\ttokensBefore: number;\n\tdetails?: unknown;\n}\n\nexport interface NavigateTreeResult {\n\tcancelled: boolean;\n\teditorText?: string;\n\tsummaryEntry?: BranchSummaryEntry;\n}\n\nexport interface CompactionSettings {\n\tenabled: boolean;\n\treserveTokens: number;\n\tkeepRecentTokens: number;\n}\n\nexport interface CompactionPreparation {\n\tfirstKeptEntryId: string;\n\tmessagesToSummarize: AgentMessage[];\n\tturnPrefixMessages: AgentMessage[];\n\tisSplitTurn: boolean;\n\ttokensBefore: number;\n\tpreviousSummary?: string;\n\tfileOps: FileOperations;\n\tsettings: CompactionSettings;\n}\n\nexport interface FileOperations {\n\tread: Set<string>;\n\twritten: Set<string>;\n\tedited: Set<string>;\n}\n\nexport interface TreePreparation {\n\ttargetId: string;\n\toldLeafId: string | null;\n\tcommonAncestorId: string | null;\n\tentriesToSummarize: SessionTreeEntry[];\n\tuserWantsSummary: boolean;\n\tcustomInstructions?: string;\n\treplaceInstructions?: boolean;\n\tlabel?: string;\n}\n\nexport interface GenerateBranchSummaryOptions {\n\tmodel: Model<any>;\n\tapiKey: string;\n\theaders?: Record<string, string>;\n\tsignal: AbortSignal;\n\tcustomInstructions?: string;\n\treplaceInstructions?: boolean;\n\treserveTokens?: number;\n}\n\nexport interface BranchSummaryResult {\n\tsummary: string;\n\treadFiles: string[];\n\tmodifiedFiles: string[];\n}\n\nexport interface AgentHarnessOptions<\n\tTSkill extends Skill = Skill,\n\tTPromptTemplate extends PromptTemplate = PromptTemplate,\n\tTTool extends AgentTool = AgentTool,\n> {\n\tenv: ExecutionEnv;\n\tsession: Session;\n\ttools?: TTool[];\n\t/**\n\t * Concrete resources available to explicit invocation methods and system-prompt callbacks.\n\t * Applications own loading/reloading resources and should call `setResources()` with new values.\n\t */\n\tresources?: AgentHarnessResources<TSkill, TPromptTemplate>;\n\tsystemPrompt?:\n\t\t| string\n\t\t| ((context: {\n\t\t\t\tenv: ExecutionEnv;\n\t\t\t\tsession: Session;\n\t\t\t\tmodel: Model<any>;\n\t\t\t\tthinkingLevel: ThinkingLevel;\n\t\t\t\tactiveTools: TTool[];\n\t\t\t\tresources: AgentHarnessResources<TSkill, TPromptTemplate>;\n\t\t }) => string | Promise<string>);\n\tgetApiKeyAndHeaders?: (\n\t\tmodel: Model<any>,\n\t) => Promise<{ apiKey: string; headers?: Record<string, string> } | undefined>;\n\t/** Curated stream/provider request options. Snapshotted at turn start. */\n\tstreamOptions?: AgentHarnessStreamOptions;\n\tmodel: Model<any>;\n\tthinkingLevel?: ThinkingLevel;\n\tactiveToolNames?: string[];\n\tsteeringMode?: QueueMode;\n\tfollowUpMode?: QueueMode;\n}\n\nexport type { AgentHarness } from \"./agent-harness.ts\";\n"]}
1
+ {"version":3,"file":"types.js","sourceRoot":"","sources":["../../src/harness/types.ts"],"names":[],"mappings":"AAOA,0CAA0C;AAC1C,MAAM,UAAU,EAA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B,CAAC;QACjC,IAAI,CAAC,IAAI,GAAG,IAAI,CAAC;IAAA,CACjB;CACD;AAUD,kFAAkF;AAClF,MAAM,OAAO,YAAa,SAAQ,KAAK;IACtC,oCAAoC;IAC7B,IAAI,CAAmB;IAE9B,YAAY,IAAsB,EAAE,OAAe,EAAE,KAAa,EAAE;QACnE,KAAK,CAAC,OAAO,EAAE,KAAK,KAAK,SAAS,CAAC,CAAC,CAAC,SAAS,CAAC,CAAC,CAAC,EAAE,KAAK,EAAE,CAAC,CAAC;QAC5D,IAAI,CAAC,IAAI,GAAG,cAAc,CAAC;QAC3B,IAAI,CAAC,IAAI,GAAG,IAAI,CAAC;IAAA,CACjB;CACD;AAaD,0EAA0E;AAC1E,MAAM,OAAO,iBAAkB,SAAQ,KAAK;IACpC,IAAI,CAAwB;IAEnC,YAAY,IAA2B,EAAE,OAAe,EAAE,KAAa,EAAE;QACxE,KAAK,CAAC,OAAO,EAAE,KAAK,KAAK,SAAS,CAAC,CAAC,CAAC,SAAS,CAAC,CAAC,CAAC,EAAE,KAAK,EAAE,CAAC,CAAC;QAC5D,IAAI,CAAC,IAAI,GAAG,mBAAmB,CAAC;QAChC,IAAI,CAAC,IAAI,GAAG,IAAI,CAAC;IAAA,CACjB;CACD","sourcesContent":["import type { ImageContent, Model, Models, SimpleStreamOptions, TextContent, Transport } from \"@earendil-works/pi-ai\";\nimport type { AgentEvent, AgentMessage, AgentTool, QueueMode, ThinkingLevel } from \"../index.ts\";\nimport type { Session } from \"./session/session.ts\";\n\n/** Result of a fallible operation. Expected failures are returned as `ok: false` instead of thrown. */\nexport type Result<TValue, TError> = { ok: true; value: TValue } | { ok: false; error: TError };\n\n/** Create a successful {@link Result}. */\nexport function ok<TValue, TError>(value: TValue): Result<TValue, TError> {\n\treturn { ok: true, value };\n}\n\n/** Create a failed {@link Result}. */\nexport function err<TValue, TError>(error: TError): Result<TValue, TError> {\n\treturn { ok: false, error };\n}\n\n/** Return the success value or throw the failure error. Intended for tests and explicit adapter boundaries. */\nexport function getOrThrow<TValue, TError>(result: Result<TValue, TError>): TValue {\n\tif (!result.ok) throw result.error;\n\treturn result.value;\n}\n\n/** Return the success value or `undefined`. Only object values are allowed to avoid truthiness bugs with primitives. */\nexport function getOrUndefined<TValue extends object, TError>(result: Result<TValue, TError>): TValue | undefined {\n\treturn result.ok ? result.value : undefined;\n}\n\n/** Normalize unknown thrown values into Error instances before using them as typed error causes. */\nexport function toError(error: unknown): Error {\n\tif (error instanceof Error) return error;\n\tif (typeof error === \"string\") return new Error(error);\n\ttry {\n\t\treturn new Error(JSON.stringify(error));\n\t} catch {\n\t\treturn new Error(String(error));\n\t}\n}\n\n/**\n * Skill loaded from a `SKILL.md` file or provided by an application.\n *\n * `name`, `description`, and `filePath` are inserted into the system prompt in an XML-formatted block as suggested by agentskills.io.\n * Use {@link formatSkillsForSystemPrompt} to generate the spec-compatible system prompt block.\n */\nexport interface Skill {\n\t/** Stable skill name used for lookup and model-visible listings. */\n\tname: string;\n\t/** Short model-visible description of when to use the skill. */\n\tdescription: string;\n\t/** Full skill instructions. */\n\tcontent: string;\n\t/** Absolute path to the skill file. Used for model-visible location and resolving relative references. */\n\tfilePath: string;\n\t/** Exclude this skill from model-visible skill lists while still allowing explicit application invocation. */\n\tdisableModelInvocation?: boolean;\n}\n\n/** Prompt template that can be formatted into a prompt for explicit invocation. */\nexport interface PromptTemplate {\n\t/** Stable template name used for lookup or application command routing. */\n\tname: string;\n\t/** Optional description for command lists or autocomplete. */\n\tdescription?: string;\n\t/** Template content. Argument placeholders are formatted by `formatPromptTemplateInvocation`. */\n\tcontent: string;\n}\n\n/** Resources made available to explicit invocation methods and system-prompt callbacks. */\nexport interface AgentHarnessResources<\n\tTSkill extends Skill = Skill,\n\tTPromptTemplate extends PromptTemplate = PromptTemplate,\n> {\n\t/** Prompt templates available for explicit invocation. */\n\tpromptTemplates?: TPromptTemplate[];\n\t/** Skills available to the model and explicit skill invocation. */\n\tskills?: TSkill[];\n}\n\n/** Curated provider request options owned by the harness and snapshotted per turn. */\nexport interface AgentHarnessStreamOptions {\n\t/** Preferred transport forwarded to the stream function. */\n\ttransport?: Transport;\n\t/** Provider request timeout in milliseconds. */\n\ttimeoutMs?: number;\n\t/** Maximum provider retry attempts. */\n\tmaxRetries?: number;\n\t/** Optional cap for provider-requested retry delays. */\n\tmaxRetryDelayMs?: number;\n\t/** Additional request headers merged with auth and lifecycle headers. */\n\theaders?: Record<string, string>;\n\t/** Provider metadata forwarded with requests. */\n\tmetadata?: SimpleStreamOptions[\"metadata\"];\n\t/** Provider cache retention hint. */\n\tcacheRetention?: SimpleStreamOptions[\"cacheRetention\"];\n}\n\n/** Per-request stream option patch returned by provider hooks. */\nexport interface AgentHarnessStreamOptionsPatch\n\textends Omit<Partial<AgentHarnessStreamOptions>, \"headers\" | \"metadata\"> {\n\t/** Header patch. `undefined` values delete keys; explicit `headers: undefined` clears all headers. */\n\theaders?: Record<string, string | undefined>;\n\t/** Metadata patch. `undefined` values delete keys; explicit `metadata: undefined` clears all metadata. */\n\tmetadata?: Record<string, unknown | undefined>;\n}\n\n/** Kind of filesystem object as addressed by a {@link FileSystem}. Symlinks are not followed automatically. */\nexport type FileKind = \"file\" | \"directory\" | \"symlink\";\n\n/** Stable, backend-independent file error codes returned by {@link FileSystem} file operations. */\nexport type FileErrorCode =\n\t| \"aborted\"\n\t| \"not_found\"\n\t| \"permission_denied\"\n\t| \"not_directory\"\n\t| \"is_directory\"\n\t| \"invalid\"\n\t| \"not_supported\"\n\t| \"unknown\";\n\n/** Error returned by {@link FileSystem} file operations. */\nexport class FileError extends Error {\n\t/** Backend-independent error code. */\n\tpublic code: FileErrorCode;\n\t/** Absolute addressed path associated with the failure, when available. */\n\tpublic path?: string;\n\n\tconstructor(code: FileErrorCode, message: string, path?: string, cause?: Error) {\n\t\tsuper(message, cause === undefined ? undefined : { cause });\n\t\tthis.name = \"FileError\";\n\t\tthis.code = code;\n\t\tthis.path = path;\n\t}\n}\n\n/** Stable, backend-independent execution error codes returned by {@link ExecutionEnv.exec}. */\nexport type ExecutionErrorCode =\n\t| \"aborted\"\n\t| \"timeout\"\n\t| \"shell_unavailable\"\n\t| \"spawn_error\"\n\t| \"callback_error\"\n\t| \"unknown\";\n\n/** Error returned by {@link ExecutionEnv.exec}. */\nexport class ExecutionError extends Error {\n\t/** Backend-independent error code. */\n\tpublic code: ExecutionErrorCode;\n\n\tconstructor(code: ExecutionErrorCode, message: string, cause?: Error) {\n\t\tsuper(message, cause === undefined ? undefined : { cause });\n\t\tthis.name = \"ExecutionError\";\n\t\tthis.code = code;\n\t}\n}\n\n/** Stable compaction error codes returned by compaction helpers. */\nexport type CompactionErrorCode = \"aborted\" | \"summarization_failed\" | \"invalid_session\" | \"unknown\";\n\n/** Error returned by compaction helpers. */\nexport class CompactionError extends Error {\n\t/** Backend-independent error code. */\n\tpublic code: CompactionErrorCode;\n\n\tconstructor(code: CompactionErrorCode, message: string, cause?: Error) {\n\t\tsuper(message, cause === undefined ? undefined : { cause });\n\t\tthis.name = \"CompactionError\";\n\t\tthis.code = code;\n\t}\n}\n\n/** Stable branch-summary error codes returned by branch summarization helpers. */\nexport type BranchSummaryErrorCode = \"aborted\" | \"summarization_failed\" | \"invalid_session\";\n\n/** Error returned by branch summarization helpers. */\nexport class BranchSummaryError extends Error {\n\t/** Backend-independent error code. */\n\tpublic code: BranchSummaryErrorCode;\n\n\tconstructor(code: BranchSummaryErrorCode, message: string, cause?: Error) {\n\t\tsuper(message, cause === undefined ? undefined : { cause });\n\t\tthis.name = \"BranchSummaryError\";\n\t\tthis.code = code;\n\t}\n}\n\nexport type SessionErrorCode =\n\t| \"not_found\"\n\t| \"invalid_session\"\n\t| \"invalid_entry\"\n\t| \"invalid_fork_target\"\n\t| \"storage\"\n\t| \"unknown\";\n\n/** Error thrown by session storage, repositories, and session tree operations. */\nexport class SessionError extends Error {\n\t/** Session subsystem error code. */\n\tpublic code: SessionErrorCode;\n\n\tconstructor(code: SessionErrorCode, message: string, cause?: Error) {\n\t\tsuper(message, cause === undefined ? undefined : { cause });\n\t\tthis.name = \"SessionError\";\n\t\tthis.code = code;\n\t}\n}\n\nexport type AgentHarnessErrorCode =\n\t| \"busy\"\n\t| \"invalid_state\"\n\t| \"invalid_argument\"\n\t| \"session\"\n\t| \"hook\"\n\t| \"auth\"\n\t| \"compaction\"\n\t| \"branch_summary\"\n\t| \"unknown\";\n\n/** Public AgentHarness failure with a stable top-level classification. */\nexport class AgentHarnessError extends Error {\n\tpublic code: AgentHarnessErrorCode;\n\n\tconstructor(code: AgentHarnessErrorCode, message: string, cause?: Error) {\n\t\tsuper(message, cause === undefined ? undefined : { cause });\n\t\tthis.name = \"AgentHarnessError\";\n\t\tthis.code = code;\n\t}\n}\n\n/** Metadata for one filesystem object in a {@link FileSystem}. */\nexport interface FileInfo {\n\t/** Basename of {@link path}. */\n\tname: string;\n\t/** Absolute, syntactically normalized addressed path in the execution environment. Symlinks are not followed. */\n\tpath: string;\n\t/** Object kind. Symlink targets are not followed; use {@link FileSystem.canonicalPath} explicitly. */\n\tkind: FileKind;\n\t/** Size in bytes for the addressed filesystem object. */\n\tsize: number;\n\t/** Modification time as milliseconds since Unix epoch. */\n\tmtimeMs: number;\n}\n\n/** Options for {@link Shell.exec}. */\nexport interface ExecutionEnvExecOptions {\n\t/** Working directory for the command. Relative paths are resolved against {@link ExecutionEnv.cwd}. Defaults to {@link ExecutionEnv.cwd}. */\n\tcwd?: string;\n\t/** Additional environment variables for the command. Values override the environment defaults. Defaults to no overrides. */\n\tenv?: Record<string, string>;\n\t/** Timeout in seconds. Implementations should return a timeout error when the command exceeds this duration. Defaults to no timeout. */\n\ttimeout?: number;\n\t/** Abort signal used to terminate the command. Defaults to no abort signal. */\n\tabortSignal?: AbortSignal;\n\t/** Called with stdout chunks as they are produced. */\n\tonStdout?: (chunk: string) => void;\n\t/** Called with stderr chunks as they are produced. */\n\tonStderr?: (chunk: string) => void;\n}\n\n/**\n * Filesystem capability used by the harness.\n *\n * Paths passed to methods may be absolute or relative to {@link cwd}. Paths returned by file operations are addressed paths\n * in the filesystem namespace, but are not canonicalized through symlinks unless returned by {@link canonicalPath}.\n *\n * Operation methods must never throw or reject. All filesystem failures, including unexpected backend failures, must be\n * encoded in the returned {@link Result}. Implementations must preserve this invariant.\n */\nexport interface FileSystem {\n\t/** Current working directory for relative paths. */\n\tcwd: string;\n\n\t/** Return an absolute addressed path without requiring it to exist and without resolving symlinks. */\n\tabsolutePath(path: string, abortSignal?: AbortSignal): Promise<Result<string, FileError>>;\n\t/** Join path segments in the filesystem namespace without requiring the result to exist. */\n\tjoinPath(parts: string[], abortSignal?: AbortSignal): Promise<Result<string, FileError>>;\n\t/** Read a UTF-8 text file. */\n\treadTextFile(path: string, abortSignal?: AbortSignal): Promise<Result<string, FileError>>;\n\t/** Read UTF-8 text lines. Implementations should stop once `maxLines` lines have been read. */\n\treadTextLines(\n\t\tpath: string,\n\t\toptions?: { maxLines?: number; abortSignal?: AbortSignal },\n\t): Promise<Result<string[], FileError>>;\n\t/** Read a binary file. */\n\treadBinaryFile(path: string, abortSignal?: AbortSignal): Promise<Result<Uint8Array, FileError>>;\n\t/** Create or overwrite a file, creating parent directories when supported. */\n\twriteFile(path: string, content: string | Uint8Array, abortSignal?: AbortSignal): Promise<Result<void, FileError>>;\n\t/** Create or append to a file, creating parent directories when supported. */\n\tappendFile(path: string, content: string | Uint8Array, abortSignal?: AbortSignal): Promise<Result<void, FileError>>;\n\t/** Return metadata for the addressed path without following symlinks. */\n\tfileInfo(path: string, abortSignal?: AbortSignal): Promise<Result<FileInfo, FileError>>;\n\t/** List direct children of a directory without following symlinks. */\n\tlistDir(path: string, abortSignal?: AbortSignal): Promise<Result<FileInfo[], FileError>>;\n\t/** Return the canonical path for an existing path, resolving symlinks where supported. */\n\tcanonicalPath(path: string, abortSignal?: AbortSignal): Promise<Result<string, FileError>>;\n\t/** Return false for missing paths. Other errors, such as permission failures, return a {@link FileError}. */\n\texists(path: string, abortSignal?: AbortSignal): Promise<Result<boolean, FileError>>;\n\t/** Create a directory. Defaults: `recursive: true`, no abort signal. */\n\tcreateDir(\n\t\tpath: string,\n\t\toptions?: { recursive?: boolean; abortSignal?: AbortSignal },\n\t): Promise<Result<void, FileError>>;\n\t/** Remove a file or directory. Defaults: `recursive: false`, `force: false`, no abort signal. */\n\tremove(\n\t\tpath: string,\n\t\toptions?: { recursive?: boolean; force?: boolean; abortSignal?: AbortSignal },\n\t): Promise<Result<void, FileError>>;\n\t/** Create a temporary directory and return its absolute path. Defaults: `prefix: \"tmp-\"`, no abort signal. */\n\tcreateTempDir(prefix?: string, abortSignal?: AbortSignal): Promise<Result<string, FileError>>;\n\t/** Create a temporary file and return its absolute path. Defaults: `prefix: \"\"`, `suffix: \"\"`, no abort signal. */\n\tcreateTempFile(options?: {\n\t\tprefix?: string;\n\t\tsuffix?: string;\n\t\tabortSignal?: AbortSignal;\n\t}): Promise<Result<string, FileError>>;\n\n\t/** Release filesystem resources. Must be best-effort and must not throw or reject. */\n\tcleanup(): Promise<void>;\n}\n\n/** Shell execution capability used by the harness. */\nexport interface Shell {\n\t/** Execute a shell command in {@link FileSystem.cwd} unless `options.cwd` is provided. */\n\texec(\n\t\tcommand: string,\n\t\toptions?: ExecutionEnvExecOptions,\n\t): Promise<Result<{ stdout: string; stderr: string; exitCode: number }, ExecutionError>>;\n\t/** Release shell resources. Must be best-effort and must not throw or reject. */\n\tcleanup(): Promise<void>;\n}\n\n/** Filesystem and process execution environment used by the harness. */\nexport interface ExecutionEnv extends FileSystem, Shell {}\n\nexport interface SessionTreeEntryBase {\n\ttype: string;\n\tid: string;\n\tparentId: string | null;\n\ttimestamp: string;\n}\n\nexport interface MessageEntry extends SessionTreeEntryBase {\n\ttype: \"message\";\n\tmessage: AgentMessage;\n}\n\nexport interface ThinkingLevelChangeEntry extends SessionTreeEntryBase {\n\ttype: \"thinking_level_change\";\n\tthinkingLevel: string;\n}\n\nexport interface ModelChangeEntry extends SessionTreeEntryBase {\n\ttype: \"model_change\";\n\tprovider: string;\n\tmodelId: string;\n}\n\nexport interface ActiveToolsChangeEntry extends SessionTreeEntryBase {\n\ttype: \"active_tools_change\";\n\tactiveToolNames: string[];\n}\n\nexport interface CompactionEntry<T = unknown> extends SessionTreeEntryBase {\n\ttype: \"compaction\";\n\tsummary: string;\n\tfirstKeptEntryId: string;\n\ttokensBefore: number;\n\tdetails?: T;\n\tfromHook?: boolean;\n}\n\nexport interface BranchSummaryEntry<T = unknown> extends SessionTreeEntryBase {\n\ttype: \"branch_summary\";\n\tfromId: string;\n\tsummary: string;\n\tdetails?: T;\n\tfromHook?: boolean;\n}\n\nexport interface CustomEntry<T = unknown> extends SessionTreeEntryBase {\n\ttype: \"custom\";\n\tcustomType: string;\n\tdata?: T;\n}\n\nexport interface CustomMessageEntry<T = unknown> extends SessionTreeEntryBase {\n\ttype: \"custom_message\";\n\tcustomType: string;\n\tcontent: string | (TextContent | ImageContent)[];\n\tdetails?: T;\n\tdisplay: boolean;\n}\n\nexport interface LabelEntry extends SessionTreeEntryBase {\n\ttype: \"label\";\n\ttargetId: string;\n\tlabel: string | undefined;\n}\n\nexport interface SessionInfoEntry extends SessionTreeEntryBase {\n\ttype: \"session_info\"; // legacy name, kept for backwards compatibility\n\tname?: string;\n}\n\nexport interface LeafEntry extends SessionTreeEntryBase {\n\ttype: \"leaf\";\n\ttargetId: string | null;\n}\n\nexport type SessionTreeEntry =\n\t| MessageEntry\n\t| ThinkingLevelChangeEntry\n\t| ModelChangeEntry\n\t| ActiveToolsChangeEntry\n\t| CompactionEntry\n\t| BranchSummaryEntry\n\t| CustomEntry\n\t| CustomMessageEntry\n\t| LabelEntry\n\t| SessionInfoEntry\n\t| LeafEntry;\n\nexport interface SessionContext {\n\tmessages: AgentMessage[];\n\tthinkingLevel: string;\n\tmodel: { provider: string; modelId: string } | null;\n\tactiveToolNames: string[] | null;\n}\n\nexport interface SessionMetadata {\n\tid: string;\n\tcreatedAt: string;\n}\n\nexport interface JsonlSessionMetadata extends SessionMetadata {\n\tcwd: string;\n\tpath: string;\n\tparentSessionPath?: string;\n}\n\nexport interface SessionStorage<TMetadata extends SessionMetadata = SessionMetadata> {\n\tgetMetadata(): Promise<TMetadata>;\n\tgetLeafId(): Promise<string | null>;\n\t/** Persist a leaf entry that records the active session-tree leaf. */\n\tsetLeafId(leafId: string | null): Promise<void>;\n\tcreateEntryId(): Promise<string>;\n\tappendEntry(entry: SessionTreeEntry): Promise<void>;\n\tgetEntry(id: string): Promise<SessionTreeEntry | undefined>;\n\tfindEntries<TType extends SessionTreeEntry[\"type\"]>(\n\t\ttype: TType,\n\t): Promise<Array<Extract<SessionTreeEntry, { type: TType }>>>;\n\tgetLabel(id: string): Promise<string | undefined>;\n\tgetPathToRoot(leafId: string | null): Promise<SessionTreeEntry[]>;\n\tgetEntries(): Promise<SessionTreeEntry[]>;\n}\n\nexport type { Session } from \"./session/session.ts\";\n\nexport interface SessionCreateOptions {\n\tid?: string;\n}\n\nexport interface SessionForkOptions {\n\tentryId?: string;\n\tposition?: \"before\" | \"at\";\n\tid?: string;\n}\n\nexport interface SessionRepo<\n\tTMetadata extends SessionMetadata = SessionMetadata,\n\tTCreateOptions extends SessionCreateOptions = SessionCreateOptions,\n\tTListOptions = void,\n> {\n\tcreate(options: TCreateOptions): Promise<Session<TMetadata>>;\n\topen(metadata: TMetadata): Promise<Session<TMetadata>>;\n\tlist(options?: TListOptions): Promise<TMetadata[]>;\n\tdelete(metadata: TMetadata): Promise<void>;\n\tfork(source: TMetadata, options: SessionForkOptions & TCreateOptions): Promise<Session<TMetadata>>;\n}\n\nexport interface JsonlSessionCreateOptions extends SessionCreateOptions {\n\tcwd: string;\n\tparentSessionPath?: string;\n}\n\nexport interface JsonlSessionListOptions {\n\tcwd?: string;\n}\n\nexport interface JsonlSessionRepoApi\n\textends SessionRepo<JsonlSessionMetadata, JsonlSessionCreateOptions, JsonlSessionListOptions> {}\n\nexport type AgentHarnessPhase = \"idle\" | \"turn\" | \"compaction\" | \"branch_summary\" | \"retry\";\n\nexport type PendingSessionWrite = SessionTreeEntry extends infer TEntry\n\t? TEntry extends SessionTreeEntry\n\t\t? Omit<TEntry, \"id\" | \"parentId\" | \"timestamp\">\n\t\t: never\n\t: never;\n\nexport interface QueueUpdateEvent {\n\ttype: \"queue_update\";\n\tsteer: AgentMessage[];\n\tfollowUp: AgentMessage[];\n\tnextTurn: AgentMessage[];\n}\n\nexport interface SavePointEvent {\n\ttype: \"save_point\";\n\thadPendingMutations: boolean;\n}\n\nexport interface AbortEvent {\n\ttype: \"abort\";\n\tclearedSteer: AgentMessage[];\n\tclearedFollowUp: AgentMessage[];\n}\n\nexport interface SettledEvent {\n\ttype: \"settled\";\n\tnextTurnCount: number;\n}\n\nexport interface BeforeAgentStartEvent<\n\tTSkill extends Skill = Skill,\n\tTPromptTemplate extends PromptTemplate = PromptTemplate,\n> {\n\ttype: \"before_agent_start\";\n\tprompt: string;\n\timages?: ImageContent[];\n\tsystemPrompt: string;\n\tresources: AgentHarnessResources<TSkill, TPromptTemplate>;\n}\n\nexport interface ContextEvent {\n\ttype: \"context\";\n\tmessages: AgentMessage[];\n}\n\nexport interface BeforeProviderRequestEvent {\n\ttype: \"before_provider_request\";\n\tmodel: Model<any>;\n\tsessionId: string;\n\tstreamOptions: AgentHarnessStreamOptions;\n}\n\nexport interface BeforeProviderPayloadEvent {\n\ttype: \"before_provider_payload\";\n\tmodel: Model<any>;\n\tpayload: unknown;\n}\n\nexport interface AfterProviderResponseEvent {\n\ttype: \"after_provider_response\";\n\tstatus: number;\n\theaders: Record<string, string>;\n}\n\nexport interface ToolCallEvent {\n\ttype: \"tool_call\";\n\ttoolCallId: string;\n\ttoolName: string;\n\tinput: Record<string, unknown>;\n}\n\nexport interface ToolResultEvent {\n\ttype: \"tool_result\";\n\ttoolCallId: string;\n\ttoolName: string;\n\tinput: Record<string, unknown>;\n\tcontent: Array<TextContent | ImageContent>;\n\tdetails: unknown;\n\tisError: boolean;\n}\n\nexport interface SessionBeforeCompactEvent {\n\ttype: \"session_before_compact\";\n\tpreparation: CompactionPreparation;\n\tbranchEntries: SessionTreeEntry[];\n\tcustomInstructions?: string;\n\tsignal: AbortSignal;\n}\n\nexport interface SessionCompactEvent {\n\ttype: \"session_compact\";\n\tcompactionEntry: CompactionEntry;\n\tfromHook: boolean;\n}\n\nexport interface SessionBeforeTreeEvent {\n\ttype: \"session_before_tree\";\n\tpreparation: TreePreparation;\n\tsignal: AbortSignal;\n}\n\nexport interface SessionTreeEvent {\n\ttype: \"session_tree\";\n\tnewLeafId: string | null;\n\toldLeafId: string | null;\n\tsummaryEntry?: BranchSummaryEntry;\n\tfromHook?: boolean;\n}\n\nexport interface ModelUpdateEvent {\n\ttype: \"model_update\";\n\tmodel: Model<any>;\n\tpreviousModel: Model<any> | undefined;\n\tsource: \"set\" | \"restore\";\n}\n\nexport interface ThinkingLevelUpdateEvent {\n\ttype: \"thinking_level_update\";\n\tlevel: ThinkingLevel;\n\tpreviousLevel: ThinkingLevel;\n}\n\nexport interface ToolsUpdateEvent {\n\ttype: \"tools_update\";\n\ttoolNames: string[];\n\tpreviousToolNames: string[];\n\tactiveToolNames: string[];\n\tpreviousActiveToolNames: string[];\n\tsource: \"set\" | \"restore\";\n}\n\nexport interface ResourcesUpdateEvent<\n\tTSkill extends Skill = Skill,\n\tTPromptTemplate extends PromptTemplate = PromptTemplate,\n> {\n\ttype: \"resources_update\";\n\tresources: AgentHarnessResources<TSkill, TPromptTemplate>;\n\tpreviousResources: AgentHarnessResources<TSkill, TPromptTemplate>;\n}\n\nexport type AgentHarnessOwnEvent<\n\tTSkill extends Skill = Skill,\n\tTPromptTemplate extends PromptTemplate = PromptTemplate,\n> =\n\t| QueueUpdateEvent\n\t| SavePointEvent\n\t| AbortEvent\n\t| SettledEvent\n\t| BeforeAgentStartEvent<TSkill, TPromptTemplate>\n\t| ContextEvent\n\t| BeforeProviderRequestEvent\n\t| BeforeProviderPayloadEvent\n\t| AfterProviderResponseEvent\n\t| ToolCallEvent\n\t| ToolResultEvent\n\t| SessionBeforeCompactEvent\n\t| SessionCompactEvent\n\t| SessionBeforeTreeEvent\n\t| SessionTreeEvent\n\t| ModelUpdateEvent\n\t| ThinkingLevelUpdateEvent\n\t| ResourcesUpdateEvent<TSkill, TPromptTemplate>\n\t| ToolsUpdateEvent;\n\nexport type AgentHarnessEvent<TSkill extends Skill = Skill, TPromptTemplate extends PromptTemplate = PromptTemplate> =\n\t| AgentEvent\n\t| AgentHarnessOwnEvent<TSkill, TPromptTemplate>;\n\nexport interface BeforeAgentStartResult {\n\tmessages?: AgentMessage[];\n\tsystemPrompt?: string;\n}\n\nexport interface ContextResult {\n\tmessages: AgentMessage[];\n}\n\nexport interface BeforeProviderRequestResult {\n\tstreamOptions?: AgentHarnessStreamOptionsPatch;\n}\n\nexport interface BeforeProviderPayloadResult {\n\tpayload: unknown;\n}\n\nexport interface ToolCallResult {\n\tblock?: boolean;\n\treason?: string;\n}\n\nexport interface ToolResultPatch {\n\tcontent?: Array<TextContent | ImageContent>;\n\tdetails?: unknown;\n\tisError?: boolean;\n\tterminate?: boolean;\n}\n\nexport interface SessionBeforeCompactResult {\n\tcancel?: boolean;\n\tcompaction?: CompactResult;\n}\n\nexport interface SessionBeforeTreeResult {\n\tcancel?: boolean;\n\tsummary?: { summary: string; details?: unknown };\n\tcustomInstructions?: string;\n\treplaceInstructions?: boolean;\n\tlabel?: string;\n}\n\nexport type AgentHarnessEventResultMap = {\n\tbefore_agent_start: BeforeAgentStartResult | undefined;\n\tcontext: ContextResult | undefined;\n\tbefore_provider_request: BeforeProviderRequestResult | undefined;\n\tbefore_provider_payload: BeforeProviderPayloadResult | undefined;\n\tafter_provider_response: undefined;\n\ttool_call: ToolCallResult | undefined;\n\ttool_result: ToolResultPatch | undefined;\n\tsession_before_compact: SessionBeforeCompactResult | undefined;\n\tsession_compact: undefined;\n\tsession_before_tree: SessionBeforeTreeResult | undefined;\n\tsession_tree: undefined;\n\tmodel_update: undefined;\n\tthinking_level_update: undefined;\n\tresources_update: undefined;\n\ttools_update: undefined;\n\tqueue_update: undefined;\n\tsave_point: undefined;\n\tabort: undefined;\n\tsettled: undefined;\n};\n\nexport interface AgentHarnessPromptOptions {\n\timages?: ImageContent[];\n}\n\nexport interface AbortResult {\n\tclearedSteer: AgentMessage[];\n\tclearedFollowUp: AgentMessage[];\n}\n\nexport interface CompactResult {\n\tsummary: string;\n\tfirstKeptEntryId: string;\n\ttokensBefore: number;\n\tdetails?: unknown;\n}\n\nexport interface NavigateTreeResult {\n\tcancelled: boolean;\n\teditorText?: string;\n\tsummaryEntry?: BranchSummaryEntry;\n}\n\nexport interface CompactionSettings {\n\tenabled: boolean;\n\treserveTokens: number;\n\tkeepRecentTokens: number;\n}\n\nexport interface CompactionPreparation {\n\tfirstKeptEntryId: string;\n\tmessagesToSummarize: AgentMessage[];\n\tturnPrefixMessages: AgentMessage[];\n\tisSplitTurn: boolean;\n\ttokensBefore: number;\n\tpreviousSummary?: string;\n\tfileOps: FileOperations;\n\tsettings: CompactionSettings;\n}\n\nexport interface FileOperations {\n\tread: Set<string>;\n\twritten: Set<string>;\n\tedited: Set<string>;\n}\n\nexport interface TreePreparation {\n\ttargetId: string;\n\toldLeafId: string | null;\n\tcommonAncestorId: string | null;\n\tentriesToSummarize: SessionTreeEntry[];\n\tuserWantsSummary: boolean;\n\tcustomInstructions?: string;\n\treplaceInstructions?: boolean;\n\tlabel?: string;\n}\n\nexport interface GenerateBranchSummaryOptions {\n\tmodel: Model<any>;\n\tapiKey: string;\n\theaders?: Record<string, string>;\n\tsignal: AbortSignal;\n\tcustomInstructions?: string;\n\treplaceInstructions?: boolean;\n\treserveTokens?: number;\n}\n\nexport interface BranchSummaryResult {\n\tsummary: string;\n\treadFiles: string[];\n\tmodifiedFiles: string[];\n}\n\nexport interface AgentHarnessOptions<\n\tTSkill extends Skill = Skill,\n\tTPromptTemplate extends PromptTemplate = PromptTemplate,\n\tTTool extends AgentTool = AgentTool,\n> {\n\tenv: ExecutionEnv;\n\tsession: Session;\n\t/**\n\t * Provider collection used for all model requests (turn streaming,\n\t * compaction, branch summarization). Auth resolves through the providers'\n\t * auth.\n\t */\n\tmodels: Models;\n\ttools?: TTool[];\n\t/**\n\t * Concrete resources available to explicit invocation methods and system-prompt callbacks.\n\t * Applications own loading/reloading resources and should call `setResources()` with new values.\n\t */\n\tresources?: AgentHarnessResources<TSkill, TPromptTemplate>;\n\tsystemPrompt?:\n\t\t| string\n\t\t| ((context: {\n\t\t\t\tenv: ExecutionEnv;\n\t\t\t\tsession: Session;\n\t\t\t\tmodel: Model<any>;\n\t\t\t\tthinkingLevel: ThinkingLevel;\n\t\t\t\tactiveTools: TTool[];\n\t\t\t\tresources: AgentHarnessResources<TSkill, TPromptTemplate>;\n\t\t }) => string | Promise<string>);\n\t/** Curated stream/provider request options. Snapshotted at turn start. */\n\tstreamOptions?: AgentHarnessStreamOptions;\n\tmodel: Model<any>;\n\tthinkingLevel?: ThinkingLevel;\n\tactiveToolNames?: string[];\n\tsteeringMode?: QueueMode;\n\tfollowUpMode?: QueueMode;\n}\n\nexport type { AgentHarness } from \"./agent-harness.ts\";\n"]}
package/dist/index.d.ts CHANGED
@@ -1,3 +1,20 @@
1
- import "@earendil-works/pi-ai";
2
- export * from "./base.ts";
1
+ export * from "./agent.ts";
2
+ export * from "./agent-loop.ts";
3
+ export * from "./harness/agent-harness.ts";
4
+ export { type BranchPreparation, type BranchSummaryDetails, type CollectEntriesResult, collectEntriesForBranchSummary, generateBranchSummary, prepareBranchEntries, } from "./harness/compaction/branch-summarization.ts";
5
+ export { calculateContextTokens, compact, DEFAULT_COMPACTION_SETTINGS, estimateContextTokens, estimateTokens, findCutPoint, findTurnStartIndex, generateSummary, getLastAssistantUsage, prepareCompaction, serializeConversation, shouldCompact, } from "./harness/compaction/compaction.ts";
6
+ export * from "./harness/messages.ts";
7
+ export * from "./harness/prompt-templates.ts";
8
+ export * from "./harness/session/jsonl-repo.ts";
9
+ export * from "./harness/session/memory-repo.ts";
10
+ export * from "./harness/session/repo-utils.ts";
11
+ export * from "./harness/session/session.ts";
12
+ export { uuidv7 } from "./harness/session/uuid.ts";
13
+ export * from "./harness/skills.ts";
14
+ export * from "./harness/system-prompt.ts";
15
+ export * from "./harness/types.ts";
16
+ export * from "./harness/utils/shell-output.ts";
17
+ export * from "./harness/utils/truncate.ts";
18
+ export * from "./proxy.ts";
19
+ export * from "./types.ts";
3
20
  //# sourceMappingURL=index.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAEA,OAAO,uBAAuB,CAAC;AAE/B,cAAc,WAAW,CAAC","sourcesContent":["// Import the default pi-ai entrypoint so that all built-in providers register\n// automatically. Unlike \"@earendil-works/pi-ai/base\" which does not.\nimport \"@earendil-works/pi-ai\";\n\nexport * from \"./base.ts\";\n"]}
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AACA,cAAc,YAAY,CAAC;AAE3B,cAAc,iBAAiB,CAAC;AAChC,cAAc,4BAA4B,CAAC;AAC3C,OAAO,EACN,KAAK,iBAAiB,EACtB,KAAK,oBAAoB,EACzB,KAAK,oBAAoB,EACzB,8BAA8B,EAC9B,qBAAqB,EACrB,oBAAoB,GACpB,MAAM,8CAA8C,CAAC;AACtD,OAAO,EACN,sBAAsB,EACtB,OAAO,EACP,2BAA2B,EAC3B,qBAAqB,EACrB,cAAc,EACd,YAAY,EACZ,kBAAkB,EAClB,eAAe,EACf,qBAAqB,EACrB,iBAAiB,EACjB,qBAAqB,EACrB,aAAa,GACb,MAAM,oCAAoC,CAAC;AAC5C,cAAc,uBAAuB,CAAC;AACtC,cAAc,+BAA+B,CAAC;AAC9C,cAAc,iCAAiC,CAAC;AAChD,cAAc,kCAAkC,CAAC;AACjD,cAAc,iCAAiC,CAAC;AAChD,cAAc,8BAA8B,CAAC;AAC7C,OAAO,EAAE,MAAM,EAAE,MAAM,2BAA2B,CAAC;AACnD,cAAc,qBAAqB,CAAC;AACpC,cAAc,4BAA4B,CAAC;AAE3C,cAAc,oBAAoB,CAAC;AACnC,cAAc,iCAAiC,CAAC;AAChD,cAAc,6BAA6B,CAAC;AAE5C,cAAc,YAAY,CAAC;AAE3B,cAAc,YAAY,CAAC","sourcesContent":["// Core Agent\nexport * from \"./agent.ts\";\n// Loop functions\nexport * from \"./agent-loop.ts\";\nexport * from \"./harness/agent-harness.ts\";\nexport {\n\ttype BranchPreparation,\n\ttype BranchSummaryDetails,\n\ttype CollectEntriesResult,\n\tcollectEntriesForBranchSummary,\n\tgenerateBranchSummary,\n\tprepareBranchEntries,\n} from \"./harness/compaction/branch-summarization.ts\";\nexport {\n\tcalculateContextTokens,\n\tcompact,\n\tDEFAULT_COMPACTION_SETTINGS,\n\testimateContextTokens,\n\testimateTokens,\n\tfindCutPoint,\n\tfindTurnStartIndex,\n\tgenerateSummary,\n\tgetLastAssistantUsage,\n\tprepareCompaction,\n\tserializeConversation,\n\tshouldCompact,\n} from \"./harness/compaction/compaction.ts\";\nexport * from \"./harness/messages.ts\";\nexport * from \"./harness/prompt-templates.ts\";\nexport * from \"./harness/session/jsonl-repo.ts\";\nexport * from \"./harness/session/memory-repo.ts\";\nexport * from \"./harness/session/repo-utils.ts\";\nexport * from \"./harness/session/session.ts\";\nexport { uuidv7 } from \"./harness/session/uuid.ts\";\nexport * from \"./harness/skills.ts\";\nexport * from \"./harness/system-prompt.ts\";\n// Harness\nexport * from \"./harness/types.ts\";\nexport * from \"./harness/utils/shell-output.ts\";\nexport * from \"./harness/utils/truncate.ts\";\n// Proxy utilities\nexport * from \"./proxy.ts\";\n// Types\nexport * from \"./types.ts\";\n"]}
package/dist/index.js CHANGED
@@ -1,5 +1,25 @@
1
- // Import the default pi-ai entrypoint so that all built-in providers register
2
- // automatically. Unlike "@earendil-works/pi-ai/base" which does not.
3
- import "@earendil-works/pi-ai";
4
- export * from "./base.js";
1
+ // Core Agent
2
+ export * from "./agent.js";
3
+ // Loop functions
4
+ export * from "./agent-loop.js";
5
+ export * from "./harness/agent-harness.js";
6
+ export { collectEntriesForBranchSummary, generateBranchSummary, prepareBranchEntries, } from "./harness/compaction/branch-summarization.js";
7
+ export { calculateContextTokens, compact, DEFAULT_COMPACTION_SETTINGS, estimateContextTokens, estimateTokens, findCutPoint, findTurnStartIndex, generateSummary, getLastAssistantUsage, prepareCompaction, serializeConversation, shouldCompact, } from "./harness/compaction/compaction.js";
8
+ export * from "./harness/messages.js";
9
+ export * from "./harness/prompt-templates.js";
10
+ export * from "./harness/session/jsonl-repo.js";
11
+ export * from "./harness/session/memory-repo.js";
12
+ export * from "./harness/session/repo-utils.js";
13
+ export * from "./harness/session/session.js";
14
+ export { uuidv7 } from "./harness/session/uuid.js";
15
+ export * from "./harness/skills.js";
16
+ export * from "./harness/system-prompt.js";
17
+ // Harness
18
+ export * from "./harness/types.js";
19
+ export * from "./harness/utils/shell-output.js";
20
+ export * from "./harness/utils/truncate.js";
21
+ // Proxy utilities
22
+ export * from "./proxy.js";
23
+ // Types
24
+ export * from "./types.js";
5
25
  //# sourceMappingURL=index.js.map
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,8EAA8E;AAC9E,qEAAqE;AACrE,OAAO,uBAAuB,CAAC;AAE/B,cAAc,WAAW,CAAC","sourcesContent":["// Import the default pi-ai entrypoint so that all built-in providers register\n// automatically. Unlike \"@earendil-works/pi-ai/base\" which does not.\nimport \"@earendil-works/pi-ai\";\n\nexport * from \"./base.ts\";\n"]}
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,aAAa;AACb,cAAc,YAAY,CAAC;AAC3B,iBAAiB;AACjB,cAAc,iBAAiB,CAAC;AAChC,cAAc,4BAA4B,CAAC;AAC3C,OAAO,EAIN,8BAA8B,EAC9B,qBAAqB,EACrB,oBAAoB,GACpB,MAAM,8CAA8C,CAAC;AACtD,OAAO,EACN,sBAAsB,EACtB,OAAO,EACP,2BAA2B,EAC3B,qBAAqB,EACrB,cAAc,EACd,YAAY,EACZ,kBAAkB,EAClB,eAAe,EACf,qBAAqB,EACrB,iBAAiB,EACjB,qBAAqB,EACrB,aAAa,GACb,MAAM,oCAAoC,CAAC;AAC5C,cAAc,uBAAuB,CAAC;AACtC,cAAc,+BAA+B,CAAC;AAC9C,cAAc,iCAAiC,CAAC;AAChD,cAAc,kCAAkC,CAAC;AACjD,cAAc,iCAAiC,CAAC;AAChD,cAAc,8BAA8B,CAAC;AAC7C,OAAO,EAAE,MAAM,EAAE,MAAM,2BAA2B,CAAC;AACnD,cAAc,qBAAqB,CAAC;AACpC,cAAc,4BAA4B,CAAC;AAC3C,UAAU;AACV,cAAc,oBAAoB,CAAC;AACnC,cAAc,iCAAiC,CAAC;AAChD,cAAc,6BAA6B,CAAC;AAC5C,kBAAkB;AAClB,cAAc,YAAY,CAAC;AAC3B,QAAQ;AACR,cAAc,YAAY,CAAC","sourcesContent":["// Core Agent\nexport * from \"./agent.ts\";\n// Loop functions\nexport * from \"./agent-loop.ts\";\nexport * from \"./harness/agent-harness.ts\";\nexport {\n\ttype BranchPreparation,\n\ttype BranchSummaryDetails,\n\ttype CollectEntriesResult,\n\tcollectEntriesForBranchSummary,\n\tgenerateBranchSummary,\n\tprepareBranchEntries,\n} from \"./harness/compaction/branch-summarization.ts\";\nexport {\n\tcalculateContextTokens,\n\tcompact,\n\tDEFAULT_COMPACTION_SETTINGS,\n\testimateContextTokens,\n\testimateTokens,\n\tfindCutPoint,\n\tfindTurnStartIndex,\n\tgenerateSummary,\n\tgetLastAssistantUsage,\n\tprepareCompaction,\n\tserializeConversation,\n\tshouldCompact,\n} from \"./harness/compaction/compaction.ts\";\nexport * from \"./harness/messages.ts\";\nexport * from \"./harness/prompt-templates.ts\";\nexport * from \"./harness/session/jsonl-repo.ts\";\nexport * from \"./harness/session/memory-repo.ts\";\nexport * from \"./harness/session/repo-utils.ts\";\nexport * from \"./harness/session/session.ts\";\nexport { uuidv7 } from \"./harness/session/uuid.ts\";\nexport * from \"./harness/skills.ts\";\nexport * from \"./harness/system-prompt.ts\";\n// Harness\nexport * from \"./harness/types.ts\";\nexport * from \"./harness/utils/shell-output.ts\";\nexport * from \"./harness/utils/truncate.ts\";\n// Proxy utilities\nexport * from \"./proxy.ts\";\n// Types\nexport * from \"./types.ts\";\n"]}
package/dist/proxy.d.ts CHANGED
@@ -2,7 +2,7 @@
2
2
  * Proxy stream function for apps that route LLM calls through a server.
3
3
  * The server manages auth and proxies requests to LLM providers.
4
4
  */
5
- import { type AssistantMessage, type AssistantMessageEvent, type Context, EventStream, type Model, type SimpleStreamOptions, type StopReason } from "@earendil-works/pi-ai/base";
5
+ import { type AssistantMessage, type AssistantMessageEvent, type Context, EventStream, type Model, type SimpleStreamOptions, type StopReason } from "@earendil-works/pi-ai";
6
6
  declare class ProxyMessageEventStream extends EventStream<AssistantMessageEvent, AssistantMessage> {
7
7
  constructor();
8
8
  }
@@ -1 +1 @@
1
- {"version":3,"file":"proxy.d.ts","sourceRoot":"","sources":["../src/proxy.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAGH,OAAO,EACN,KAAK,gBAAgB,EACrB,KAAK,qBAAqB,EAC1B,KAAK,OAAO,EACZ,WAAW,EACX,KAAK,KAAK,EAEV,KAAK,mBAAmB,EACxB,KAAK,UAAU,EAEf,MAAM,4BAA4B,CAAC;AAGpC,cAAM,uBAAwB,SAAQ,WAAW,CAAC,qBAAqB,EAAE,gBAAgB,CAAC;IACzF,cASC;CACD;AAED;;GAEG;AACH,MAAM,MAAM,0BAA0B,GACnC;IAAE,IAAI,EAAE,OAAO,CAAA;CAAE,GACjB;IAAE,IAAI,EAAE,YAAY,CAAC;IAAC,YAAY,EAAE,MAAM,CAAA;CAAE,GAC5C;IAAE,IAAI,EAAE,YAAY,CAAC;IAAC,YAAY,EAAE,MAAM,CAAC;IAAC,KAAK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ACX,SAAS,GACT,UAAU,GACV,WAAW,GACX,iBAAiB,GACjB,iBAAiB,CACnB,CAAC;AAEF,MAAM,WAAW,kBAAmB,SAAQ,8BAA8B;IACzE,+CAA+C;IAC/C,MAAM,CAAC,EAAE,WAAW,CAAC;IACrB,sCAAsC;IACtC,SAAS,EAAE,MAAM,CAAC;IAClB,2DAA2D;IAC3D,QAAQ,EAAE,MAAM,CAAC;CACjB;AAoCD,wBAAgB,WAAW,CAAC,KAAK,EAAE,KAAK,CAAC,GAAG,CAAC,EAAE,OAAO,EAAE,OAAO,EAAE,OAAO,EAAE,kBAAkB,GAAG,uBAAuB,CAqHrH","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/base\";\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: \"stop\",\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.d.ts","sourceRoot":"","sources":["../src/proxy.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAGH,OAAO,EACN,KAAK,gBAAgB,EACrB,KAAK,qBAAqB,EAC1B,KAAK,OAAO,EACZ,WAAW,EACX,KAAK,KAAK,EAEV,KAAK,mBAAmB,EACxB,KAAK,UAAU,EAEf,MAAM,uBAAuB,CAAC;AAG/B,cAAM,uBAAwB,SAAQ,WAAW,CAAC,qBAAqB,EAAE,gBAAgB,CAAC;IACzF,cASC;CACD;AAED;;GAEG;AACH,MAAM,MAAM,0BAA0B,GACnC;IAAE,IAAI,EAAE,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ACtB,KAAK,EAAE,gBAAgB,CAAC,OAAO,CAAC,CAAC;CAChC,CAAC;AAEL,KAAK,8BAA8B,GAAG,IAAI,CACzC,mBAAmB,EACjB,aAAa,GACb,WAAW,GACX,WAAW,GACX,gBAAgB,GAChB,WAAW,GACX,SAAS,GACT,UAAU,GACV,WAAW,GACX,iBAAiB,GACjB,iBAAiB,CACnB,CAAC;AAEF,MAAM,WAAW,kBAAmB,SAAQ,8BAA8B;IACzE,+CAA+C;IAC/C,MAAM,CAAC,EAAE,WAAW,CAAC;IACrB,sCAAsC;IACtC,SAAS,EAAE,MAAM,CAAC;IAClB,2DAA2D;IAC3D,QAAQ,EAAE,MAAM,CAAC;CACjB;AAoCD,wBAAgB,WAAW,CAAC,KAAK,EAAE,KAAK,CAAC,GAAG,CAAC,EAAE,OAAO,EAAE,OAAO,EAAE,OAAO,EAAE,kBAAkB,GAAG,uBAAuB,CAqHrH","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: \"stop\",\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/dist/proxy.js CHANGED
@@ -3,7 +3,7 @@
3
3
  * The server manages auth and proxies requests to LLM providers.
4
4
  */
5
5
  // Internal import for JSON parsing utility
6
- import { EventStream, parseStreamingJson, } from "@earendil-works/pi-ai/base";
6
+ import { EventStream, parseStreamingJson, } from "@earendil-works/pi-ai";
7
7
  // Create stream class matching ProxyMessageEventStream
8
8
  class ProxyMessageEventStream extends EventStream {
9
9
  constructor() {
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,4BAA4B,CAAC;AAEpC,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,SAAS,wBAAwB,CAAC,OAA2B,EAAkC;IAC9F,OAAO;QACN,WAAW,EAAE,OAAO,CAAC,WAAW;QAChC,SAAS,EAAE,OAAO,CAAC,SAAS;QAC5B,SAAS,EAAE,OAAO,CAAC,SAAS;QAC5B,cAAc,EAAE,OAAO,CAAC,cAAc;QACtC,SAAS,EAAE,OAAO,CAAC,SAAS;QAC5B,OAAO,EAAE,OAAO,CAAC,OAAO;QACxB,QAAQ,EAAE,OAAO,CAAC,QAAQ;QAC1B,SAAS,EAAE,OAAO,CAAC,SAAS;QAC5B,eAAe,EAAE,OAAO,CAAC,eAAe;QACxC,eAAe,EAAE,OAAO,CAAC,eAAe;KACxC,CAAC;AAAA,CACF;AAED,MAAM,UAAU,WAAW,CAAC,KAAiB,EAAE,OAAgB,EAAE,OAA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AY,CAAC,CAAC;YACzD,IAAI,OAAO,EAAE,IAAI,KAAK,UAAU,EAAE,CAAC;gBAClC,OAAQ,OAAe,CAAC,WAAW,CAAC;gBACpC,OAAO;oBACN,IAAI,EAAE,cAAc;oBACpB,YAAY,EAAE,UAAU,CAAC,YAAY;oBACrC,QAAQ,EAAE,OAAO;oBACjB,OAAO;iBACP,CAAC;YACH,CAAC;YACD,OAAO,SAAS,CAAC;QAClB,CAAC;QAED,KAAK,MAAM;YACV,OAAO,CAAC,UAAU,GAAG,UAAU,CAAC,MAAM,CAAC;YACvC,OAAO,CAAC,KAAK,GAAG,UAAU,CAAC,KAAK,CAAC;YACjC,OAAO,EAAE,IAAI,EAAE,MAAM,EAAE,MAAM,EAAE,UAAU,CAAC,MAAM,EAAE,OAAO,EAAE,OAAO,EAAE,CAAC;QAEtE,KAAK,OAAO;YACX,OAAO,CAAC,UAAU,GAAG,UAAU,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/base\";\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: \"stop\",\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,CAAC;YAC/C,MAAM,IAAI,KAAK,CAAC,uBAAuB,CAAC,CAAC;QAAA,CACzC,CACD,CAAC;IAAA,CACF;CACD;AAmDD;;;;;;;;;;;;;;;;;;GAkBG;AACH,SAAS,wBAAwB,CAAC,OAA2B,EAAkC;IAC9F,OAAO;QACN,WAAW,EAAE,OAAO,CAAC,WAAW;QAChC,SAAS,EAAE,OAAO,CAAC,SAAS;QAC5B,SAAS,EAAE,OAAO,CAAC,SAAS;QAC5B,cAAc,EAAE,OAAO,CAAC,cAAc;QACtC,SAAS,EAAE,OAAO,CAAC,SAAS;QAC5B,OAAO,EAAE,OAAO,CAAC,OAAO;QACxB,QAAQ,EAAE,OAAO,CAAC,QAAQ;QAC1B,SAAS,EAAE,OAAO,CAAC,SAAS;QAC5B,eAAe,EAAE,OAAO,CAA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C,kDAAkD,CAAC,CAAC;QACrE,CAAC;QAED,KAAK,cAAc,EAAE,CAAC;YACrB,MAAM,OAAO,GAAG,OAAO,CAAC,OAAO,CAAC,UAAU,CAAC,YAAY,CAAC,CAAC;YACzD,IAAI,OAAO,EAAE,IAAI,KAAK,UAAU,EAAE,CAAC;gBAClC,OAAQ,OAAe,CAAC,WAAW,CAAC;gBACpC,OAAO;oBACN,IAAI,EAAE,cAAc;oBACpB,YAAY,EAAE,UAAU,CAAC,YAAY;oBACrC,QAAQ,EAAE,OAAO;oBACjB,OAAO;iBACP,CAAC;YACH,CAAC;YACD,OAAO,SAAS,CAAC;QAClB,CAAC;QAED,KAAK,MAAM;YACV,OAAO,CAAC,UAAU,GAAG,UAAU,CAAC,MAAM,CAAC;YACvC,OAAO,CAAC,KAAK,GAAG,UAAU,CAAC,KAAK,CAAC;YACjC,OAAO,EAAE,IAAI,EAAE,MAAM,EAAE,MAAM,EAAE,UAAU,CAAC,MAAM,EAAE,OAAO,EAAE,OAAO,EAAE,CAAC;QAEtE,KAAK,OAAO;YACX,OAAO,CAAC,UAAU,GAAG,UAAU,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| \"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: \"stop\",\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/dist/types.d.ts CHANGED
@@ -1,7 +1,8 @@
1
- import type { AssistantMessage, AssistantMessageEvent, ImageContent, Message, Model, SimpleStreamOptions, streamSimple, TextContent, Tool, ToolResultMessage } from "@earendil-works/pi-ai/base";
1
+ import type { Api, AssistantMessage, AssistantMessageEvent, AssistantMessageEventStream, Context, ImageContent, Message, Model, SimpleStreamOptions, TextContent, Tool, ToolResultMessage } from "@earendil-works/pi-ai";
2
2
  import type { Static, TSchema } from "typebox";
3
3
  /**
4
- * Stream function used by the agent loop.
4
+ * Stream function used by the agent loop. `Models.streamSimple` satisfies
5
+ * this shape.
5
6
  *
6
7
  * Contract:
7
8
  * - Must not throw or return a rejected promise for request/model/runtime failures.
@@ -9,7 +10,7 @@ import type { Static, TSchema } from "typebox";
9
10
  * - Failures must be encoded in the returned stream via protocol events and a
10
11
  * final AssistantMessage with stopReason "error" or "aborted" and errorMessage.
11
12
  */
12
- export type StreamFn = (...args: Parameters<typeof streamSimple>) => ReturnType<typeof streamSimple> | Promise<ReturnType<typeof streamSimple>>;
13
+ export type StreamFn = (model: Model<Api>, context: Context, options?: SimpleStreamOptions) => AssistantMessageEventStream | Promise<AssistantMessageEventStream>;
13
14
  /**
14
15
  * Configuration for how tool calls from a single assistant message are executed.
15
16
  *
@@ -1 +1 @@
1
- {"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../src/types.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EACX,gBAAgB,EAChB,qBAAqB,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CAAA;CAAE,GAC/F;IAAE,IAAI,EAAE,aAAa,CAAC;IAAC,OAAO,EAAE,YAAY,CAAA;CAAE,GAE9C;IAAE,IAAI,EAAE,sBAAsB,CAAC;IAAC,UAAU,EAAE,MAAM,CAAC;IAAC,QAAQ,EAAE,MAAM,CAAC;IAAC,IAAI,EAAE,GAAG,CAAA;CAAE,GACjF;IAAE,IAAI,EAAE,uBAAuB,CAAC;IAAC,UAAU,EAAE,MAAM,CAAC;IAAC,QAAQ,EAAE,MAAM,CAAC;IAAC,IAAI,EAAE,GAAG,CAAC;IAAC,aAAa,EAAE,GAAG,CAAA;CAAE,GACtG;IAAE,IAAI,EAAE,oBAAoB,CAAC;IAAC,UAAU,EAAE,MAAM,CAAC;IAAC,QAAQ,EAAE,MAAM,CAAC;IAAC,MAAM,EAAE,GAAG,CAAC;IAAC,OAAO,EAAE,OAAO,CAAA;CAAE,CAAC","sourcesContent":["import type {\n\tAssistantMessage,\n\tAssistantMessageEvent,\n\tImageContent,\n\tMessage,\n\tModel,\n\tSimpleStreamOptions,\n\tstreamSimple,\n\tTextContent,\n\tTool,\n\tToolResultMessage,\n} from \"@earendil-works/pi-ai/base\";\nimport type { Static, TSchema } from \"typebox\";\n\n/**\n * Stream function used by the agent loop.\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\t...args: Parameters<typeof streamSimple>\n) => ReturnType<typeof streamSimple> | Promise<ReturnType<typeof streamSimple>>;\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 allowed tools execute concurrently.\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 * - `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` or `details`.\n */\nexport interface AfterToolCallResult {\n\tcontent?: (TextContent | ImageContent)[];\n\tdetails?: unknown;\n\tisError?: boolean;\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}\n\nexport interface PrepareNextTurnContext extends ShouldStopAfterTurnContext {}\n\nexport interface AgentLoopConfig extends SimpleStreamOptions {\n\tmodel: Model<any>;\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 * Tool execution mode.\n\t * - \"sequential\": execute tool calls one by one\n\t * - \"parallel\": preflight tool calls sequentially, then execute allowed tools concurrently;\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 * 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 * - `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\" is only supported by selected model families. Use model thinking-level metadata\n * from @earendil-works/pi-ai to detect support for a concrete model.\n */\nexport type ThinkingLevel = \"off\" | \"minimal\" | \"low\" | \"medium\" | \"high\" | \"xhigh\";\n\n/**\n * Extensible interface for custom app messages.\n * Apps can extend via declaration merging:\n *\n * @example\n * ```typescript\n * declare module \"@mariozechner/agent\" {\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/**\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 must execute one at a time with other tool calls.\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.d.ts","sourceRoot":"","sources":["../src/types.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EACX,GAAG,EACH,gBAAgB,EAChB,qBAAqB,EACrB,2BAA2B,EAC3B,OAAO,EACP,YAAY,EACZ,OAAO,EACP,KAAK,EACL,mBAAmB,EACnB,WAAW,EACX,IAAI,EACJ,iBAAiB,EACjB,MAAM,uBAAuB,CAAC;AAC/B,OAAO,KAAK,EAAE,MAAM,EAAE,OAAO,EAAE,MAAM,SAAS,CAAC;AAE/C;;;;;;;;;GASG;AACH,MAAM,MAAM,QAAQ,GAAG,CACtB,KAAK,EAAE,KAAK,CAAC,GAAG,CAAC,EACjB,OAAO,EAAE,OAAO,EAChB,OAAO,CAAC,EAAE,mBAAmB,KACzB,2BAA2B,GAAG,OAAO,CAAC,2BAA2B,CAAC,CAAC;AAExE;;;;;;;GAOG;AACH,MAAM,MAAM,iBAAiB,GAAG,YAAY,GAAG,UAAU,CAAC;AAE1D;;;;;GAKG;AACH,MAAM,MAAM,SAAS,GAAG,KAAK,GAAG,eAAe,CAAC;AAEhD,wEAAwE;AACxE,MAAM,MAAM,aAAa,GAAG,OAAO,CAAC,gBAAgB,CAAC,SAAS,CAAC,CAAC,MAAM,CAA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Context,\n\tImageContent,\n\tMessage,\n\tModel,\n\tSimpleStreamOptions,\n\tTextContent,\n\tTool,\n\tToolResultMessage,\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 allowed tools execute concurrently.\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 * - `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` or `details`.\n */\nexport interface AfterToolCallResult {\n\tcontent?: (TextContent | ImageContent)[];\n\tdetails?: unknown;\n\tisError?: boolean;\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}\n\nexport interface PrepareNextTurnContext extends ShouldStopAfterTurnContext {}\n\nexport interface AgentLoopConfig extends SimpleStreamOptions {\n\tmodel: Model<any>;\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 * Tool execution mode.\n\t * - \"sequential\": execute tool calls one by one\n\t * - \"parallel\": preflight tool calls sequentially, then execute allowed tools concurrently;\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 * 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 * - `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\" is only supported by selected model families. Use model thinking-level metadata\n * from @earendil-works/pi-ai to detect support for a concrete model.\n */\nexport type ThinkingLevel = \"off\" | \"minimal\" | \"low\" | \"medium\" | \"high\" | \"xhigh\";\n\n/**\n * Extensible interface for custom app messages.\n * Apps can extend via declaration merging:\n *\n * @example\n * ```typescript\n * declare module \"@mariozechner/agent\" {\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/**\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 must execute one at a time with other tool calls.\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"]}