@averyyy/pi-coding-agent 0.82.1-piclient.4 → 0.82.1-piclient.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1 +1 @@
1
- {"version":3,"file":"sdk.d.ts","sourceRoot":"","sources":["../../src/core/sdk.ts"],"names":[],"mappings":"AAEA,OAAO,EAKN,KAAK,aAAa,EAClB,MAAM,+BAA+B,CAAC;AACvC,OAAO,EAAsB,KAAK,OAAO,EAAE,KAAK,KAAK,EAAgB,MAAM,8BAA8B,CAAC;AAG1G,OAAO,EAAE,YAAY,EAAE,MAAM,oBAAoB,CAAC;AAGlD,OAAO,KAAK,EAAmB,oBAAoB,EAAE,iBAAiB,EAAE,cAAc,EAAE,MAAM,uBAAuB,CAAC;AAGtH,OAAO,EAAE,YAAY,EAAE,MAAM,oBAAoB,CAAC;AAClD,OAAO,EAAgC,KAAK,oBAAoB,EAAkB,MAAM,uBAAuB,CAAC;AAIhH,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,sBAAsB,CAAC;AAE3D,OAAO,EAAwB,cAAc,EAAE,MAAM,sBAAsB,CAAC;AAC5E,OAAO,EAAE,eAAe,EAAE,MAAM,uBAAuB,CAAC;AAExD,OAAO,EACN,cAAc,EACd,iBAAiB,EACjB,cAAc,EACd,cAAc,EACd,cAAc,EACd,YAAY,EACZ,mBAAmB,EACnB,cAAc,EACd,eAAe,EAEf,qBAAqB,EACrB,MAAM,kBAAkB,CAAC;AAO1B,MAAM,WAAW,yBAAyB;IACzC,4EAA4E;IAC5E,GAAG,CAAC,EAAE,MAAM,CAAC;IACb,oDAAoD;IACpD,QAAQ,CAAC,EAAE,MAAM,CAAC;IAElB,oGAAoG;IACpG,YAAY,CAAC,EAAE,YAAY,CAAC;IAE5B,iEAAiE;IACjE,KAAK,CAAC,EAAE,KAAK,CAAC,GAAG,CAAC,CAAC;IACnB,4FAA4F;IAC5F,aAAa,CAAC,EAAE,aAAa,CAAC;IAC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EACnB,cAAc,EACd,cAAc,EACd,cAAc,EACd,eAAe,EACf,cAAc,EACd,cAAc,EACd,YAAY,GACZ,CAAC;AAYF,MAAM,WAAW,mBAAmB;IACnC,WAAW,EAAE,oBAAoB,CAAC;IAClC,iBAAiB,CAAC,EAAE,OAAO,EAAE,CAAC;IAC9B,cAAc,CAAC,EAAE,OAAO,EAAE,CAAC;CAC3B;AAED,wBAAgB,wBAAwB,CACvC,cAAc,EAAE,cAAc,EAC9B,eAAe,EAAE,OAAO,EAAE,GACxB,mBAAmB,CAqBrB;AAED;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAkCG;AACH,wBAAsB,kBAAkB,CAAC,OAAO,GAAE,yBAA8B,GAAG,OAAO,CAAC,wBAAwB,CAAC,CAoSnH","sourcesContent":["import { randomUUID } from \"node:crypto\";\nimport { join } from \"node:path\";\nimport {\n\tAgent,\n\ttype AgentMessage,\n\ttype StreamFn,\n\tsetDefaultStreamFn,\n\ttype ThinkingLevel,\n} from \"@earendil-works/pi-agent-core\";\nimport { clampThinkingLevel, type Message, type Model, streamSimple } from \"@earendil-works/pi-ai/compat\";\nimport { getAgentDir } from \"../config.ts\";\nimport { resolvePath } from \"../utils/paths.ts\";\nimport { AgentSession } from \"./agent-session.ts\";\nimport { formatNoModelsAvailableMessage } from \"./auth-guidance.ts\";\nimport { DEFAULT_THINKING_LEVEL } from \"./defaults.ts\";\nimport type { ExtensionRunner, LoadExtensionsResult, SessionStartEvent, ToolDefinition } from \"./extensions/index.ts\";\nimport { convertToLlm } from \"./messages.ts\";\nimport { findInitialModel } from \"./model-resolver.ts\";\nimport { ModelRuntime } from \"./model-runtime.ts\";\nimport { type PiServerHistorySnapshot, type PiServerTreeSnapshot, streamPiServer } from \"./pi-server-client.ts\";\nimport { assertPiServerProviderExecution } from \"./pi-server-provider-execution.ts\";\nimport { getPiServerRunStatePath } from \"./pi-server-run-state.ts\";\nimport { mergeProviderAttributionHeaders } from \"./provider-attribution.ts\";\nimport type { ResourceLoader } from \"./resource-loader.ts\";\nimport { DefaultResourceLoader } from \"./resource-loader.ts\";\nimport { getDefaultSessionDir, SessionManager } from \"./session-manager.ts\";\nimport { SettingsManager } from \"./settings-manager.ts\";\nimport { time } from \"./timings.ts\";\nimport {\n\tcreateBashTool,\n\tcreateCodingTools,\n\tcreateEditTool,\n\tcreateFindTool,\n\tcreateGrepTool,\n\tcreateLsTool,\n\tcreateReadOnlyTools,\n\tcreateReadTool,\n\tcreateWriteTool,\n\ttype ToolName,\n\twithFileMutationQueue,\n} from \"./tools/index.ts\";\n\n// Preserve the pre-0.81 fallback for extensions that construct Agent instances\n// or invoke low-level agent loops without supplying streamFn. Agent core remains\n// provider-agnostic and does not import pi-ai/compat itself.\nsetDefaultStreamFn(streamSimple);\n\nexport interface CreateAgentSessionOptions {\n\t/** Working directory for project-local discovery. Default: process.cwd() */\n\tcwd?: string;\n\t/** Global config directory. Default: ~/.pi/agent */\n\tagentDir?: string;\n\n\t/** Canonical model/auth runtime. Defaults to a runtime using agentDir/auth.json and models.json. */\n\tmodelRuntime?: ModelRuntime;\n\n\t/** Model to use. Default: from settings, else first available */\n\tmodel?: Model<any>;\n\t/** Thinking level. Default: from settings, else 'medium' (clamped to model capabilities) */\n\tthinkingLevel?: ThinkingLevel;\n\t/** Models available for cycling (Ctrl+P in interactive mode) */\n\tscopedModels?: Array<{ model: Model<any>; thinkingLevel?: ThinkingLevel }>;\n\n\t/**\n\t * Optional default tool suppression mode when no explicit allowlist is provided.\n\t *\n\t * - \"all\": start with no tools enabled\n\t * - \"builtin\": disable the default built-in tools (read, bash, edit, write)\n\t * but keep extension/custom tools enabled\n\t */\n\tnoTools?: \"all\" | \"builtin\";\n\t/**\n\t * Optional allowlist of tool names.\n\t *\n\t * When omitted, pi enables the default built-in tools (read, bash, edit, write)\n\t * and leaves extension/custom tools enabled unless `noTools` changes that default.\n\t * When provided, only the listed tool names are enabled.\n\t */\n\ttools?: string[];\n\t/** Optional denylist of tool names to disable. Applies after `tools` when both are provided. */\n\texcludeTools?: string[];\n\t/** Custom tools to register (in addition to built-in tools). */\n\tcustomTools?: ToolDefinition[];\n\n\t/** Resource loader. When omitted, DefaultResourceLoader is used. */\n\tresourceLoader?: ResourceLoader;\n\n\t/** Session manager. Default: SessionManager.create(cwd) */\n\tsessionManager?: SessionManager;\n\n\t/** Settings manager. Default: SettingsManager.create(cwd, agentDir) */\n\tsettingsManager?: SettingsManager;\n\t/** Session start event metadata for extension runtime startup. */\n\tsessionStartEvent?: SessionStartEvent;\n\t/** Whether to generate a display name with an extra provider request after the first turn. */\n\tautoSessionName?: boolean;\n}\n\n/** Result from createAgentSession */\nexport interface CreateAgentSessionResult {\n\t/** The created session */\n\tsession: AgentSession;\n\t/** Extensions result (for UI context setup in interactive mode) */\n\textensionsResult: LoadExtensionsResult;\n\t/** Warning if session was restored with a different model than saved */\n\tmodelFallbackMessage?: string;\n}\n\n// Re-exports\n\nexport * from \"./agent-session-runtime.ts\";\nexport type {\n\tExtensionAPI,\n\tExtensionCommandContext,\n\tExtensionContext,\n\tExtensionFactory,\n\tInlineExtension,\n\tSlashCommandInfo,\n\tSlashCommandSource,\n\tToolDefinition,\n} from \"./extensions/index.ts\";\nexport type { PromptTemplate } from \"./prompt-templates.ts\";\nexport type { Skill } from \"./skills.ts\";\nexport type { Tool } from \"./tools/index.ts\";\n\nexport {\n\twithFileMutationQueue,\n\t// Tool factories (for custom cwd)\n\tcreateCodingTools,\n\tcreateReadOnlyTools,\n\tcreateReadTool,\n\tcreateBashTool,\n\tcreateEditTool,\n\tcreateWriteTool,\n\tcreateGrepTool,\n\tcreateFindTool,\n\tcreateLsTool,\n};\n\n// Helper Functions\n\nfunction getDefaultAgentDir(): string {\n\treturn getAgentDir();\n}\n\nfunction messagesEqual(left: Message[], right: Message[]): boolean {\n\treturn JSON.stringify(left) === JSON.stringify(right);\n}\n\nexport interface PiServerContextSync {\n\tsessionTree: PiServerTreeSnapshot;\n\tephemeralMessages?: Message[];\n\tcontextOverlay?: Message[];\n}\n\nexport function buildPiServerContextSync(\n\tsessionManager: SessionManager,\n\tcontextMessages: Message[],\n): PiServerContextSync {\n\tconst entries = sessionManager.getEntries();\n\tconst localContextMessages = convertToLlm(sessionManager.buildSessionContext().messages);\n\tif (messagesEqual(localContextMessages, contextMessages)) {\n\t\treturn { sessionTree: { entries, leafId: sessionManager.getLeafId() } };\n\t}\n\n\tconst hasLocalPrefix =\n\t\tlocalContextMessages.length <= contextMessages.length &&\n\t\tmessagesEqual(localContextMessages, contextMessages.slice(0, localContextMessages.length));\n\tif (hasLocalPrefix) {\n\t\treturn {\n\t\t\tsessionTree: { entries, leafId: sessionManager.getLeafId() },\n\t\t\tephemeralMessages: contextMessages.slice(localContextMessages.length),\n\t\t};\n\t}\n\n\treturn {\n\t\tsessionTree: { entries, leafId: sessionManager.getLeafId() },\n\t\tcontextOverlay: contextMessages,\n\t};\n}\n\n/**\n * Create an AgentSession with the specified options.\n *\n * @example\n * ```typescript\n * // Minimal - uses defaults\n * const { session } = await createAgentSession();\n *\n * // With explicit model\n * import { getModel } from '@earendil-works/pi-ai';\n * const { session } = await createAgentSession({\n * model: getModel('anthropic', 'claude-opus-4-5'),\n * thinkingLevel: 'high',\n * });\n *\n * // Continue previous session\n * const { session, modelFallbackMessage } = await createAgentSession({\n * continueSession: true,\n * });\n *\n * // Full control\n * const loader = new DefaultResourceLoader({\n * cwd: process.cwd(),\n * agentDir: getAgentDir(),\n * settingsManager: SettingsManager.create(),\n * });\n * await loader.reload();\n * const { session } = await createAgentSession({\n * model: myModel,\n * tools: [\"read\", \"bash\"],\n * resourceLoader: loader,\n * sessionManager: SessionManager.inMemory(),\n * });\n * ```\n */\nexport async function createAgentSession(options: CreateAgentSessionOptions = {}): Promise<CreateAgentSessionResult> {\n\tconst cwd = resolvePath(options.cwd ?? options.sessionManager?.getCwd() ?? process.cwd());\n\tconst agentDir = options.agentDir ? resolvePath(options.agentDir) : getDefaultAgentDir();\n\tlet resourceLoader = options.resourceLoader;\n\n\tconst authPath = options.agentDir ? join(agentDir, \"auth.json\") : undefined;\n\tconst modelsPath = options.agentDir ? join(agentDir, \"models.json\") : undefined;\n\tconst modelRuntime = options.modelRuntime ?? (await ModelRuntime.create({ authPath, modelsPath }));\n\n\tconst settingsManager = options.settingsManager ?? SettingsManager.create(cwd, agentDir);\n\tconst sessionManager = options.sessionManager ?? SessionManager.create(cwd, getDefaultSessionDir(cwd, agentDir));\n\n\tif (!resourceLoader) {\n\t\tresourceLoader = new DefaultResourceLoader({ cwd, agentDir, settingsManager });\n\t\tawait resourceLoader.reload();\n\t\ttime(\"resourceLoader.reload\");\n\t}\n\n\t// Check if session has existing data to restore\n\tconst existingSession = sessionManager.buildSessionContext();\n\tconst hasExistingSession = existingSession.messages.length > 0;\n\tconst hasThinkingEntry = sessionManager.getBranch().some((entry) => entry.type === \"thinking_level_change\");\n\n\tlet model = options.model;\n\tlet modelFallbackMessage: string | undefined;\n\n\t// If session has data, try to restore model from it\n\tif (!model && hasExistingSession && existingSession.model) {\n\t\tconst restoredModel = modelRuntime.getModel(existingSession.model.provider, existingSession.model.modelId);\n\t\tif (restoredModel && modelRuntime.hasConfiguredAuth(restoredModel.provider)) {\n\t\t\tmodel = restoredModel;\n\t\t}\n\t\tif (!model) {\n\t\t\tmodelFallbackMessage = `Could not restore model ${existingSession.model.provider}/${existingSession.model.modelId}`;\n\t\t}\n\t}\n\n\t// If still no model, use findInitialModel (checks settings default, then provider defaults)\n\tif (!model) {\n\t\tconst result = await findInitialModel({\n\t\t\tscopedModels: [],\n\t\t\tisContinuing: hasExistingSession,\n\t\t\tdefaultProvider: settingsManager.getDefaultProvider(),\n\t\t\tdefaultModelId: settingsManager.getDefaultModel(),\n\t\t\tdefaultThinkingLevel: settingsManager.getDefaultThinkingLevel(),\n\t\t\tmodelRuntime,\n\t\t});\n\t\tmodel = result.model;\n\t\tif (!model) {\n\t\t\tmodelFallbackMessage = formatNoModelsAvailableMessage();\n\t\t} else if (modelFallbackMessage) {\n\t\t\tmodelFallbackMessage += `. Using ${model.provider}/${model.id}`;\n\t\t}\n\t}\n\n\tlet thinkingLevel = options.thinkingLevel;\n\n\t// If session has data, restore thinking level from it\n\tif (thinkingLevel === undefined && hasExistingSession) {\n\t\tthinkingLevel = hasThinkingEntry\n\t\t\t? (existingSession.thinkingLevel as ThinkingLevel)\n\t\t\t: (settingsManager.getDefaultThinkingLevel() ?? DEFAULT_THINKING_LEVEL);\n\t}\n\n\t// Fall back to settings default\n\tif (thinkingLevel === undefined) {\n\t\tthinkingLevel = settingsManager.getDefaultThinkingLevel() ?? DEFAULT_THINKING_LEVEL;\n\t}\n\n\t// Clamp to model capabilities\n\tif (!model) {\n\t\tthinkingLevel = \"off\";\n\t} else {\n\t\tthinkingLevel = clampThinkingLevel(model, thinkingLevel) as ThinkingLevel;\n\t}\n\n\tconst defaultActiveToolNames: ToolName[] = [\"read\", \"bash\", \"edit\", \"write\"];\n\tconst allowedToolNames = options.tools ?? (options.noTools === \"all\" ? [] : undefined);\n\tconst excludedToolNames = options.excludeTools;\n\tconst excludedToolNameSet = excludedToolNames ? new Set(excludedToolNames) : undefined;\n\tconst initialActiveToolNames: string[] = (\n\t\toptions.tools ? [...options.tools] : options.noTools ? [] : defaultActiveToolNames\n\t).filter((name) => !excludedToolNameSet?.has(name));\n\n\tlet agent: Agent;\n\tlet agentSession: AgentSession | undefined;\n\n\t// Create convertToLlm wrapper that filters images if blockImages is enabled (defense-in-depth)\n\tconst convertToLlmWithBlockImages = (messages: AgentMessage[]): Message[] => {\n\t\tconst converted = convertToLlm(messages);\n\t\t// Check setting dynamically so mid-session changes take effect\n\t\tif (!settingsManager.getBlockImages()) {\n\t\t\treturn converted;\n\t\t}\n\t\t// Filter out ImageContent from all messages, replacing with text placeholder\n\t\treturn converted.map((msg) => {\n\t\t\tif (msg.role === \"user\" || msg.role === \"toolResult\") {\n\t\t\t\tconst content = msg.content;\n\t\t\t\tif (Array.isArray(content)) {\n\t\t\t\t\tconst hasImages = content.some((c) => c.type === \"image\");\n\t\t\t\t\tif (hasImages) {\n\t\t\t\t\t\tconst filteredContent = content\n\t\t\t\t\t\t\t.map((c) =>\n\t\t\t\t\t\t\t\tc.type === \"image\" ? { type: \"text\" as const, text: \"Image reading is disabled.\" } : c,\n\t\t\t\t\t\t\t)\n\t\t\t\t\t\t\t.filter(\n\t\t\t\t\t\t\t\t(c, i, arr) =>\n\t\t\t\t\t\t\t\t\t// Dedupe consecutive \"Image reading is disabled.\" texts\n\t\t\t\t\t\t\t\t\t!(\n\t\t\t\t\t\t\t\t\t\tc.type === \"text\" &&\n\t\t\t\t\t\t\t\t\t\tc.text === \"Image reading is disabled.\" &&\n\t\t\t\t\t\t\t\t\t\ti > 0 &&\n\t\t\t\t\t\t\t\t\t\tarr[i - 1].type === \"text\" &&\n\t\t\t\t\t\t\t\t\t\t(arr[i - 1] as { type: \"text\"; text: string }).text === \"Image reading is disabled.\"\n\t\t\t\t\t\t\t\t\t),\n\t\t\t\t\t\t\t);\n\t\t\t\t\t\treturn { ...msg, content: filteredContent };\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn msg;\n\t\t});\n\t};\n\n\tconst extensionRunnerRef: { current?: ExtensionRunner } = {};\n\n\tconst streamWithPiServerRunMode =\n\t\t(runMode: \"main-durable\" | \"auxiliary-transient\"): StreamFn =>\n\t\tasync (model, context, options) => {\n\t\t\tconst headerRunner = extensionRunnerRef.current;\n\t\t\tconst piServerExecution =\n\t\t\t\tprocess.env.PI_SERVER_MODE === \"true\"\n\t\t\t\t\t? assertPiServerProviderExecution(modelRuntime, model, headerRunner)\n\t\t\t\t\t: undefined;\n\t\t\tconst providerRetrySettings = settingsManager.getProviderRetrySettings();\n\t\t\tconst httpIdleTimeoutMs = settingsManager.getHttpIdleTimeoutMs();\n\t\t\t// SDKs treat timeout=0 as 0ms (immediate timeout), not \"no timeout\".\n\t\t\t// Use max int32 to effectively disable the timeout.\n\t\t\tconst effectiveTimeoutMs = httpIdleTimeoutMs === 0 ? 2147483647 : httpIdleTimeoutMs;\n\t\t\tconst timeoutMs = options?.timeoutMs ?? providerRetrySettings.timeoutMs ?? effectiveTimeoutMs;\n\t\t\tconst websocketConnectTimeoutMs =\n\t\t\t\toptions?.websocketConnectTimeoutMs ?? settingsManager.getWebSocketConnectTimeoutMs();\n\t\t\tconst activeAgentSession = agentSession;\n\t\t\tconst piServerContext =\n\t\t\t\trunMode === \"main-durable\" && activeAgentSession\n\t\t\t\t\t? buildPiServerContextSync(activeAgentSession.sessionManager, context.messages as Message[])\n\t\t\t\t\t: undefined;\n\t\t\tconst mainSessionId = sessionManager.getSessionId();\n\t\t\tconst piServerSessionId = runMode === \"main-durable\" ? mainSessionId : (options?.sessionId ?? randomUUID());\n\t\t\tif (runMode === \"auxiliary-transient\" && piServerSessionId === mainSessionId) {\n\t\t\t\tthrow new Error(\"Auxiliary provider streams must use a session id independent from the main session\");\n\t\t\t}\n\t\t\tconst piServerSessionFile =\n\t\t\t\trunMode === \"main-durable\" ? activeAgentSession?.sessionManager.getSessionFile() : undefined;\n\t\t\tconst commonOptions = {\n\t\t\t\t...options,\n\t\t\t\tsessionId: piServerSessionId,\n\t\t\t\ttimeoutMs,\n\t\t\t\twebsocketConnectTimeoutMs,\n\t\t\t\tmaxRetries: options?.maxRetries ?? providerRetrySettings.maxRetries,\n\t\t\t\tmaxRetryDelayMs: options?.maxRetryDelayMs ?? providerRetrySettings.maxRetryDelayMs,\n\t\t\t};\n\t\t\tif (process.env.PI_SERVER_MODE === \"true\") {\n\t\t\t\tconst auth = await modelRuntime.getAuth(model, { apiKey: options?.apiKey, env: options?.env });\n\t\t\t\tif (!auth) {\n\t\t\t\t\tthrow new Error(`Provider is not configured: ${model.provider}`);\n\t\t\t\t}\n\t\t\t\tlet headers = mergeProviderAttributionHeaders(\n\t\t\t\t\tmodel,\n\t\t\t\t\tsettingsManager,\n\t\t\t\t\tpiServerSessionId,\n\t\t\t\t\tauth.auth.headers,\n\t\t\t\t\toptions?.headers,\n\t\t\t\t);\n\t\t\t\tif (headerRunner?.hasHandlers(\"before_provider_headers\")) {\n\t\t\t\t\theaders = await headerRunner.emitBeforeProviderHeaders(headers ?? {});\n\t\t\t\t}\n\t\t\t\tconst requestModel = auth.auth.baseUrl ? { ...model, baseUrl: auth.auth.baseUrl } : model;\n\t\t\t\treturn streamPiServer(requestModel, context, {\n\t\t\t\t\t...commonOptions,\n\t\t\t\t\trunMode,\n\t\t\t\t\tsessionTree: piServerContext?.sessionTree,\n\t\t\t\t\tephemeralMessages: piServerContext?.ephemeralMessages,\n\t\t\t\t\tcontextOverlay: piServerContext?.contextOverlay,\n\t\t\t\t\tproviderExecutionFingerprint: piServerExecution?.providerExecutionFingerprint,\n\t\t\t\t\tpiServerRunStatePath: piServerSessionFile ? getPiServerRunStatePath(piServerSessionFile) : undefined,\n\t\t\t\t\tonHistoryReconciled:\n\t\t\t\t\t\trunMode === \"main-durable\" && activeAgentSession\n\t\t\t\t\t\t\t? (snapshot: PiServerHistorySnapshot) => activeAgentSession.reconcilePiServerHistory(snapshot)\n\t\t\t\t\t\t\t: undefined,\n\t\t\t\t\tapiKey: auth.auth.apiKey,\n\t\t\t\t\tenv: auth.env || options?.env ? { ...(auth.env ?? {}), ...(options?.env ?? {}) } : undefined,\n\t\t\t\t\theaders,\n\t\t\t\t});\n\t\t\t}\n\t\t\treturn modelRuntime.streamSimple(model, context, {\n\t\t\t\t...commonOptions,\n\t\t\t\ttransformHeaders: async (requestHeaders) => {\n\t\t\t\t\tconst headers = mergeProviderAttributionHeaders(\n\t\t\t\t\t\tmodel,\n\t\t\t\t\t\tsettingsManager,\n\t\t\t\t\t\tpiServerSessionId,\n\t\t\t\t\t\trequestHeaders,\n\t\t\t\t\t);\n\t\t\t\t\treturn headerRunner?.hasHandlers(\"before_provider_headers\")\n\t\t\t\t\t\t? headerRunner.emitBeforeProviderHeaders(headers ?? {})\n\t\t\t\t\t\t: (headers ?? {});\n\t\t\t\t},\n\t\t\t});\n\t\t};\n\tconst mainStreamFunction = streamWithPiServerRunMode(\"main-durable\");\n\tconst auxiliaryStreamFunction = streamWithPiServerRunMode(\"auxiliary-transient\");\n\n\tagent = new Agent({\n\t\tinitialState: {\n\t\t\tsystemPrompt: \"\",\n\t\t\tmodel,\n\t\t\tthinkingLevel,\n\t\t\ttools: [],\n\t\t},\n\t\tconvertToLlm: convertToLlmWithBlockImages,\n\t\tstreamFn: mainStreamFunction,\n\t\tonPayload: async (payload, _model) => {\n\t\t\tconst runner = extensionRunnerRef.current;\n\t\t\tif (!runner?.hasHandlers(\"before_provider_request\")) {\n\t\t\t\treturn payload;\n\t\t\t}\n\t\t\treturn runner.emitBeforeProviderRequest(payload);\n\t\t},\n\t\tonResponse: async (response, _model) => {\n\t\t\tconst runner = extensionRunnerRef.current;\n\t\t\tif (!runner?.hasHandlers(\"after_provider_response\")) {\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tawait runner.emit({\n\t\t\t\ttype: \"after_provider_response\",\n\t\t\t\tstatus: response.status,\n\t\t\t\theaders: response.headers,\n\t\t\t});\n\t\t},\n\t\tsessionId: sessionManager.getSessionId(),\n\t\ttransformContext: async (messages) => {\n\t\t\tconst runner = extensionRunnerRef.current;\n\t\t\tif (!runner) return messages;\n\t\t\treturn runner.emitContext(messages);\n\t\t},\n\t\tsteeringMode: settingsManager.getSteeringMode(),\n\t\tfollowUpMode: settingsManager.getFollowUpMode(),\n\t\ttransport: settingsManager.getTransport(),\n\t\tthinkingBudgets: settingsManager.getThinkingBudgets(),\n\t\tmaxRetryDelayMs: settingsManager.getProviderRetrySettings().maxRetryDelayMs,\n\t});\n\n\t// Restore messages if session has existing data\n\tif (hasExistingSession) {\n\t\tagent.state.messages = existingSession.messages;\n\t\tif (!hasThinkingEntry) {\n\t\t\tsessionManager.appendThinkingLevelChange(thinkingLevel);\n\t\t}\n\t} else {\n\t\t// Save initial model and thinking level for new sessions so they can be restored on resume\n\t\tif (model) {\n\t\t\tsessionManager.appendModelChange(model.provider, model.id);\n\t\t}\n\t\tsessionManager.appendThinkingLevelChange(thinkingLevel);\n\t}\n\n\tconst session = new AgentSession({\n\t\tagent,\n\t\tsessionManager,\n\t\tsettingsManager,\n\t\tcwd,\n\t\tscopedModels: options.scopedModels,\n\t\tresourceLoader,\n\t\tcustomTools: options.customTools,\n\t\tmodelRuntime,\n\t\tinitialActiveToolNames,\n\t\tallowedToolNames,\n\t\texcludedToolNames,\n\t\textensionRunnerRef,\n\t\tauxiliaryStreamFunction: process.env.PI_SERVER_MODE === \"true\" ? auxiliaryStreamFunction : undefined,\n\t\tsessionStartEvent: options.sessionStartEvent,\n\t\tautoSessionName: options.autoSessionName,\n\t});\n\tagentSession = session;\n\tconst extensionsResult = resourceLoader.getExtensions();\n\n\treturn {\n\t\tsession,\n\t\textensionsResult,\n\t\tmodelFallbackMessage,\n\t};\n}\n"]}
1
+ {"version":3,"file":"sdk.d.ts","sourceRoot":"","sources":["../../src/core/sdk.ts"],"names":[],"mappings":"AAEA,OAAO,EAKN,KAAK,aAAa,EAClB,MAAM,+BAA+B,CAAC;AACvC,OAAO,EAAsB,KAAK,OAAO,EAAE,KAAK,KAAK,EAAgB,MAAM,8BAA8B,CAAC;AAG1G,OAAO,EAAE,YAAY,EAAE,MAAM,oBAAoB,CAAC;AAGlD,OAAO,KAAK,EAAmB,oBAAoB,EAAE,iBAAiB,EAAE,cAAc,EAAE,MAAM,uBAAuB,CAAC;AAGtH,OAAO,EAAE,YAAY,EAAE,MAAM,oBAAoB,CAAC;AAClD,OAAO,EAAgC,KAAK,oBAAoB,EAAkB,MAAM,uBAAuB,CAAC;AAGhH,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,sBAAsB,CAAC;AAE3D,OAAO,EAAwB,cAAc,EAAE,MAAM,sBAAsB,CAAC;AAC5E,OAAO,EAAE,eAAe,EAAE,MAAM,uBAAuB,CAAC;AAExD,OAAO,EACN,cAAc,EACd,iBAAiB,EACjB,cAAc,EACd,cAAc,EACd,cAAc,E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AM,CAAC;CAC9B;AAID,cAAc,4BAA4B,CAAC;AAC3C,YAAY,EACX,YAAY,EACZ,uBAAuB,EACvB,gBAAgB,EAChB,gBAAgB,EAChB,eAAe,EACf,gBAAgB,EAChB,kBAAkB,EAClB,cAAc,GACd,MAAM,uBAAuB,CAAC;AAC/B,YAAY,EAAE,cAAc,EAAE,MAAM,uBAAuB,CAAC;AAC5D,YAAY,EAAE,KAAK,EAAE,MAAM,aAAa,CAAC;AACzC,YAAY,EAAE,IAAI,EAAE,MAAM,kBAAkB,CAAC;AAE7C,OAAO,EACN,qBAAqB,EAErB,iBAAiB,EACjB,mBAAmB,EACnB,cAAc,EACd,cAAc,EACd,cAAc,EACd,eAAe,EACf,cAAc,EACd,cAAc,EACd,YAAY,GACZ,CAAC;AAYF,MAAM,WAAW,mBAAmB;IACnC,WAAW,EAAE,oBAAoB,CAAC;IAClC,iBAAiB,CAAC,EAAE,OAAO,EAAE,CAAC;IAC9B,cAAc,CAAC,EAAE,OAAO,EAAE,CAAC;CAC3B;AAED,wBAAgB,wBAAwB,CACvC,cAAc,EAAE,cAAc,EAC9B,eAAe,EAAE,OAAO,EAAE,GACxB,mBAAmB,CAqBrB;AAED;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAkCG;AACH,wBAAsB,kBAAkB,CAAC,OAAO,GAAE,yBAA8B,GAAG,OAAO,CAAC,wBAAwB,CAAC,CA+RnH","sourcesContent":["import { randomUUID } from \"node:crypto\";\nimport { join } from \"node:path\";\nimport {\n\tAgent,\n\ttype AgentMessage,\n\ttype StreamFn,\n\tsetDefaultStreamFn,\n\ttype ThinkingLevel,\n} from \"@earendil-works/pi-agent-core\";\nimport { clampThinkingLevel, type Message, type Model, streamSimple } from \"@earendil-works/pi-ai/compat\";\nimport { getAgentDir } from \"../config.ts\";\nimport { resolvePath } from \"../utils/paths.ts\";\nimport { AgentSession } from \"./agent-session.ts\";\nimport { formatNoModelsAvailableMessage } from \"./auth-guidance.ts\";\nimport { DEFAULT_THINKING_LEVEL } from \"./defaults.ts\";\nimport type { ExtensionRunner, LoadExtensionsResult, SessionStartEvent, ToolDefinition } from \"./extensions/index.ts\";\nimport { convertToLlm } from \"./messages.ts\";\nimport { findInitialModel } from \"./model-resolver.ts\";\nimport { ModelRuntime } from \"./model-runtime.ts\";\nimport { type PiServerHistorySnapshot, type PiServerTreeSnapshot, streamPiServer } from \"./pi-server-client.ts\";\nimport { getPiServerRunStatePath } from \"./pi-server-run-state.ts\";\nimport { mergeProviderAttributionHeaders } from \"./provider-attribution.ts\";\nimport type { ResourceLoader } from \"./resource-loader.ts\";\nimport { DefaultResourceLoader } from \"./resource-loader.ts\";\nimport { getDefaultSessionDir, SessionManager } from \"./session-manager.ts\";\nimport { SettingsManager } from \"./settings-manager.ts\";\nimport { time } from \"./timings.ts\";\nimport {\n\tcreateBashTool,\n\tcreateCodingTools,\n\tcreateEditTool,\n\tcreateFindTool,\n\tcreateGrepTool,\n\tcreateLsTool,\n\tcreateReadOnlyTools,\n\tcreateReadTool,\n\tcreateWriteTool,\n\ttype ToolName,\n\twithFileMutationQueue,\n} from \"./tools/index.ts\";\n\n// Preserve the pre-0.81 fallback for extensions that construct Agent instances\n// or invoke low-level agent loops without supplying streamFn. Agent core remains\n// provider-agnostic and does not import pi-ai/compat itself.\nsetDefaultStreamFn(streamSimple);\n\nexport interface CreateAgentSessionOptions {\n\t/** Working directory for project-local discovery. Default: process.cwd() */\n\tcwd?: string;\n\t/** Global config directory. Default: ~/.pi/agent */\n\tagentDir?: string;\n\n\t/** Canonical model/auth runtime. Defaults to a runtime using agentDir/auth.json and models.json. */\n\tmodelRuntime?: ModelRuntime;\n\n\t/** Model to use. Default: from settings, else first available */\n\tmodel?: Model<any>;\n\t/** Thinking level. Default: from settings, else 'medium' (clamped to model capabilities) */\n\tthinkingLevel?: ThinkingLevel;\n\t/** Models available for cycling (Ctrl+P in interactive mode) */\n\tscopedModels?: Array<{ model: Model<any>; thinkingLevel?: ThinkingLevel }>;\n\n\t/**\n\t * Optional default tool suppression mode when no explicit allowlist is provided.\n\t *\n\t * - \"all\": start with no tools enabled\n\t * - \"builtin\": disable the default built-in tools (read, bash, edit, write)\n\t * but keep extension/custom tools enabled\n\t */\n\tnoTools?: \"all\" | \"builtin\";\n\t/**\n\t * Optional allowlist of tool names.\n\t *\n\t * When omitted, pi enables the default built-in tools (read, bash, edit, write)\n\t * and leaves extension/custom tools enabled unless `noTools` changes that default.\n\t * When provided, only the listed tool names are enabled.\n\t */\n\ttools?: string[];\n\t/** Optional denylist of tool names to disable. Applies after `tools` when both are provided. */\n\texcludeTools?: string[];\n\t/** Custom tools to register (in addition to built-in tools). */\n\tcustomTools?: ToolDefinition[];\n\n\t/** Resource loader. When omitted, DefaultResourceLoader is used. */\n\tresourceLoader?: ResourceLoader;\n\n\t/** Session manager. Default: SessionManager.create(cwd) */\n\tsessionManager?: SessionManager;\n\n\t/** Settings manager. Default: SettingsManager.create(cwd, agentDir) */\n\tsettingsManager?: SettingsManager;\n\t/** Session start event metadata for extension runtime startup. */\n\tsessionStartEvent?: SessionStartEvent;\n\t/** Whether to generate a display name with an extra provider request after the first turn. */\n\tautoSessionName?: boolean;\n}\n\n/** Result from createAgentSession */\nexport interface CreateAgentSessionResult {\n\t/** The created session */\n\tsession: AgentSession;\n\t/** Extensions result (for UI context setup in interactive mode) */\n\textensionsResult: LoadExtensionsResult;\n\t/** Warning if session was restored with a different model than saved */\n\tmodelFallbackMessage?: string;\n}\n\n// Re-exports\n\nexport * from \"./agent-session-runtime.ts\";\nexport type {\n\tExtensionAPI,\n\tExtensionCommandContext,\n\tExtensionContext,\n\tExtensionFactory,\n\tInlineExtension,\n\tSlashCommandInfo,\n\tSlashCommandSource,\n\tToolDefinition,\n} from \"./extensions/index.ts\";\nexport type { PromptTemplate } from \"./prompt-templates.ts\";\nexport type { Skill } from \"./skills.ts\";\nexport type { Tool } from \"./tools/index.ts\";\n\nexport {\n\twithFileMutationQueue,\n\t// Tool factories (for custom cwd)\n\tcreateCodingTools,\n\tcreateReadOnlyTools,\n\tcreateReadTool,\n\tcreateBashTool,\n\tcreateEditTool,\n\tcreateWriteTool,\n\tcreateGrepTool,\n\tcreateFindTool,\n\tcreateLsTool,\n};\n\n// Helper Functions\n\nfunction getDefaultAgentDir(): string {\n\treturn getAgentDir();\n}\n\nfunction messagesEqual(left: Message[], right: Message[]): boolean {\n\treturn JSON.stringify(left) === JSON.stringify(right);\n}\n\nexport interface PiServerContextSync {\n\tsessionTree: PiServerTreeSnapshot;\n\tephemeralMessages?: Message[];\n\tcontextOverlay?: Message[];\n}\n\nexport function buildPiServerContextSync(\n\tsessionManager: SessionManager,\n\tcontextMessages: Message[],\n): PiServerContextSync {\n\tconst entries = sessionManager.getEntries();\n\tconst localContextMessages = convertToLlm(sessionManager.buildSessionContext().messages);\n\tif (messagesEqual(localContextMessages, contextMessages)) {\n\t\treturn { sessionTree: { entries, leafId: sessionManager.getLeafId() } };\n\t}\n\n\tconst hasLocalPrefix =\n\t\tlocalContextMessages.length <= contextMessages.length &&\n\t\tmessagesEqual(localContextMessages, contextMessages.slice(0, localContextMessages.length));\n\tif (hasLocalPrefix) {\n\t\treturn {\n\t\t\tsessionTree: { entries, leafId: sessionManager.getLeafId() },\n\t\t\tephemeralMessages: contextMessages.slice(localContextMessages.length),\n\t\t};\n\t}\n\n\treturn {\n\t\tsessionTree: { entries, leafId: sessionManager.getLeafId() },\n\t\tcontextOverlay: contextMessages,\n\t};\n}\n\n/**\n * Create an AgentSession with the specified options.\n *\n * @example\n * ```typescript\n * // Minimal - uses defaults\n * const { session } = await createAgentSession();\n *\n * // With explicit model\n * import { getModel } from '@earendil-works/pi-ai';\n * const { session } = await createAgentSession({\n * model: getModel('anthropic', 'claude-opus-4-5'),\n * thinkingLevel: 'high',\n * });\n *\n * // Continue previous session\n * const { session, modelFallbackMessage } = await createAgentSession({\n * continueSession: true,\n * });\n *\n * // Full control\n * const loader = new DefaultResourceLoader({\n * cwd: process.cwd(),\n * agentDir: getAgentDir(),\n * settingsManager: SettingsManager.create(),\n * });\n * await loader.reload();\n * const { session } = await createAgentSession({\n * model: myModel,\n * tools: [\"read\", \"bash\"],\n * resourceLoader: loader,\n * sessionManager: SessionManager.inMemory(),\n * });\n * ```\n */\nexport async function createAgentSession(options: CreateAgentSessionOptions = {}): Promise<CreateAgentSessionResult> {\n\tconst cwd = resolvePath(options.cwd ?? options.sessionManager?.getCwd() ?? process.cwd());\n\tconst agentDir = options.agentDir ? resolvePath(options.agentDir) : getDefaultAgentDir();\n\tlet resourceLoader = options.resourceLoader;\n\n\tconst authPath = options.agentDir ? join(agentDir, \"auth.json\") : undefined;\n\tconst modelsPath = options.agentDir ? join(agentDir, \"models.json\") : undefined;\n\tconst modelRuntime = options.modelRuntime ?? (await ModelRuntime.create({ authPath, modelsPath }));\n\n\tconst settingsManager = options.settingsManager ?? SettingsManager.create(cwd, agentDir);\n\tconst sessionManager = options.sessionManager ?? SessionManager.create(cwd, getDefaultSessionDir(cwd, agentDir));\n\n\tif (!resourceLoader) {\n\t\tresourceLoader = new DefaultResourceLoader({ cwd, agentDir, settingsManager });\n\t\tawait resourceLoader.reload();\n\t\ttime(\"resourceLoader.reload\");\n\t}\n\n\t// Check if session has existing data to restore\n\tconst existingSession = sessionManager.buildSessionContext();\n\tconst hasExistingSession = existingSession.messages.length > 0;\n\tconst hasThinkingEntry = sessionManager.getBranch().some((entry) => entry.type === \"thinking_level_change\");\n\n\tlet model = options.model;\n\tlet modelFallbackMessage: string | undefined;\n\n\t// If session has data, try to restore model from it\n\tif (!model && hasExistingSession && existingSession.model) {\n\t\tconst restoredModel = modelRuntime.getModel(existingSession.model.provider, existingSession.model.modelId);\n\t\tif (restoredModel && modelRuntime.hasConfiguredAuth(restoredModel.provider)) {\n\t\t\tmodel = restoredModel;\n\t\t}\n\t\tif (!model) {\n\t\t\tmodelFallbackMessage = `Could not restore model ${existingSession.model.provider}/${existingSession.model.modelId}`;\n\t\t}\n\t}\n\n\t// If still no model, use findInitialModel (checks settings default, then provider defaults)\n\tif (!model) {\n\t\tconst result = await findInitialModel({\n\t\t\tscopedModels: [],\n\t\t\tisContinuing: hasExistingSession,\n\t\t\tdefaultProvider: settingsManager.getDefaultProvider(),\n\t\t\tdefaultModelId: settingsManager.getDefaultModel(),\n\t\t\tdefaultThinkingLevel: settingsManager.getDefaultThinkingLevel(),\n\t\t\tmodelRuntime,\n\t\t});\n\t\tmodel = result.model;\n\t\tif (!model) {\n\t\t\tmodelFallbackMessage = formatNoModelsAvailableMessage();\n\t\t} else if (modelFallbackMessage) {\n\t\t\tmodelFallbackMessage += `. Using ${model.provider}/${model.id}`;\n\t\t}\n\t}\n\n\tlet thinkingLevel = options.thinkingLevel;\n\n\t// If session has data, restore thinking level from it\n\tif (thinkingLevel === undefined && hasExistingSession) {\n\t\tthinkingLevel = hasThinkingEntry\n\t\t\t? (existingSession.thinkingLevel as ThinkingLevel)\n\t\t\t: (settingsManager.getDefaultThinkingLevel() ?? DEFAULT_THINKING_LEVEL);\n\t}\n\n\t// Fall back to settings default\n\tif (thinkingLevel === undefined) {\n\t\tthinkingLevel = settingsManager.getDefaultThinkingLevel() ?? DEFAULT_THINKING_LEVEL;\n\t}\n\n\t// Clamp to model capabilities\n\tif (!model) {\n\t\tthinkingLevel = \"off\";\n\t} else {\n\t\tthinkingLevel = clampThinkingLevel(model, thinkingLevel) as ThinkingLevel;\n\t}\n\n\tconst defaultActiveToolNames: ToolName[] = [\"read\", \"bash\", \"edit\", \"write\"];\n\tconst allowedToolNames = options.tools ?? (options.noTools === \"all\" ? [] : undefined);\n\tconst excludedToolNames = options.excludeTools;\n\tconst excludedToolNameSet = excludedToolNames ? new Set(excludedToolNames) : undefined;\n\tconst initialActiveToolNames: string[] = (\n\t\toptions.tools ? [...options.tools] : options.noTools ? [] : defaultActiveToolNames\n\t).filter((name) => !excludedToolNameSet?.has(name));\n\n\tlet agent: Agent;\n\tlet agentSession: AgentSession | undefined;\n\n\t// Create convertToLlm wrapper that filters images if blockImages is enabled (defense-in-depth)\n\tconst convertToLlmWithBlockImages = (messages: AgentMessage[]): Message[] => {\n\t\tconst converted = convertToLlm(messages);\n\t\t// Check setting dynamically so mid-session changes take effect\n\t\tif (!settingsManager.getBlockImages()) {\n\t\t\treturn converted;\n\t\t}\n\t\t// Filter out ImageContent from all messages, replacing with text placeholder\n\t\treturn converted.map((msg) => {\n\t\t\tif (msg.role === \"user\" || msg.role === \"toolResult\") {\n\t\t\t\tconst content = msg.content;\n\t\t\t\tif (Array.isArray(content)) {\n\t\t\t\t\tconst hasImages = content.some((c) => c.type === \"image\");\n\t\t\t\t\tif (hasImages) {\n\t\t\t\t\t\tconst filteredContent = content\n\t\t\t\t\t\t\t.map((c) =>\n\t\t\t\t\t\t\t\tc.type === \"image\" ? { type: \"text\" as const, text: \"Image reading is disabled.\" } : c,\n\t\t\t\t\t\t\t)\n\t\t\t\t\t\t\t.filter(\n\t\t\t\t\t\t\t\t(c, i, arr) =>\n\t\t\t\t\t\t\t\t\t// Dedupe consecutive \"Image reading is disabled.\" texts\n\t\t\t\t\t\t\t\t\t!(\n\t\t\t\t\t\t\t\t\t\tc.type === \"text\" &&\n\t\t\t\t\t\t\t\t\t\tc.text === \"Image reading is disabled.\" &&\n\t\t\t\t\t\t\t\t\t\ti > 0 &&\n\t\t\t\t\t\t\t\t\t\tarr[i - 1].type === \"text\" &&\n\t\t\t\t\t\t\t\t\t\t(arr[i - 1] as { type: \"text\"; text: string }).text === \"Image reading is disabled.\"\n\t\t\t\t\t\t\t\t\t),\n\t\t\t\t\t\t\t);\n\t\t\t\t\t\treturn { ...msg, content: filteredContent };\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn msg;\n\t\t});\n\t};\n\n\tconst extensionRunnerRef: { current?: ExtensionRunner } = {};\n\n\tconst streamWithPiServerRunMode =\n\t\t(runMode: \"main-durable\" | \"auxiliary-transient\"): StreamFn =>\n\t\tasync (model, context, options) => {\n\t\t\tconst headerRunner = extensionRunnerRef.current;\n\t\t\tconst providerRetrySettings = settingsManager.getProviderRetrySettings();\n\t\t\tconst httpIdleTimeoutMs = settingsManager.getHttpIdleTimeoutMs();\n\t\t\t// SDKs treat timeout=0 as 0ms (immediate timeout), not \"no timeout\".\n\t\t\t// Use max int32 to effectively disable the timeout.\n\t\t\tconst effectiveTimeoutMs = httpIdleTimeoutMs === 0 ? 2147483647 : httpIdleTimeoutMs;\n\t\t\tconst timeoutMs = options?.timeoutMs ?? providerRetrySettings.timeoutMs ?? effectiveTimeoutMs;\n\t\t\tconst websocketConnectTimeoutMs =\n\t\t\t\toptions?.websocketConnectTimeoutMs ?? settingsManager.getWebSocketConnectTimeoutMs();\n\t\t\tconst activeAgentSession = agentSession;\n\t\t\tconst piServerContext =\n\t\t\t\trunMode === \"main-durable\" && activeAgentSession\n\t\t\t\t\t? buildPiServerContextSync(activeAgentSession.sessionManager, context.messages as Message[])\n\t\t\t\t\t: undefined;\n\t\t\tconst mainSessionId = sessionManager.getSessionId();\n\t\t\tconst piServerSessionId = runMode === \"main-durable\" ? mainSessionId : (options?.sessionId ?? randomUUID());\n\t\t\tif (runMode === \"auxiliary-transient\" && piServerSessionId === mainSessionId) {\n\t\t\t\tthrow new Error(\"Auxiliary provider streams must use a session id independent from the main session\");\n\t\t\t}\n\t\t\tconst piServerSessionFile =\n\t\t\t\trunMode === \"main-durable\" ? activeAgentSession?.sessionManager.getSessionFile() : undefined;\n\t\t\tconst commonOptions = {\n\t\t\t\t...options,\n\t\t\t\tsessionId: piServerSessionId,\n\t\t\t\ttimeoutMs,\n\t\t\t\twebsocketConnectTimeoutMs,\n\t\t\t\tmaxRetries: options?.maxRetries ?? providerRetrySettings.maxRetries,\n\t\t\t\tmaxRetryDelayMs: options?.maxRetryDelayMs ?? providerRetrySettings.maxRetryDelayMs,\n\t\t\t};\n\t\t\tif (process.env.PI_SERVER_MODE === \"true\") {\n\t\t\t\tconst auth = await modelRuntime.getAuth(model, { apiKey: options?.apiKey, env: options?.env });\n\t\t\t\tif (!auth) {\n\t\t\t\t\tthrow new Error(`Provider is not configured: ${model.provider}`);\n\t\t\t\t}\n\t\t\t\tlet headers = mergeProviderAttributionHeaders(\n\t\t\t\t\tmodel,\n\t\t\t\t\tsettingsManager,\n\t\t\t\t\tpiServerSessionId,\n\t\t\t\t\tauth.auth.headers,\n\t\t\t\t\toptions?.headers,\n\t\t\t\t);\n\t\t\t\tif (headerRunner?.hasHandlers(\"before_provider_headers\")) {\n\t\t\t\t\theaders = await headerRunner.emitBeforeProviderHeaders(headers ?? {});\n\t\t\t\t}\n\t\t\t\tconst requestModel = auth.auth.baseUrl ? { ...model, baseUrl: auth.auth.baseUrl } : model;\n\t\t\t\treturn streamPiServer(requestModel, context, {\n\t\t\t\t\t...commonOptions,\n\t\t\t\t\trunMode,\n\t\t\t\t\tsessionTree: piServerContext?.sessionTree,\n\t\t\t\t\tephemeralMessages: piServerContext?.ephemeralMessages,\n\t\t\t\t\tcontextOverlay: piServerContext?.contextOverlay,\n\t\t\t\t\tpiServerRunStatePath: piServerSessionFile ? getPiServerRunStatePath(piServerSessionFile) : undefined,\n\t\t\t\t\tonHistoryReconciled:\n\t\t\t\t\t\trunMode === \"main-durable\" && activeAgentSession\n\t\t\t\t\t\t\t? (snapshot: PiServerHistorySnapshot) => activeAgentSession.reconcilePiServerHistory(snapshot)\n\t\t\t\t\t\t\t: undefined,\n\t\t\t\t\tapiKey: auth.auth.apiKey,\n\t\t\t\t\tenv: auth.env || options?.env ? { ...(auth.env ?? {}), ...(options?.env ?? {}) } : undefined,\n\t\t\t\t\theaders,\n\t\t\t\t});\n\t\t\t}\n\t\t\treturn modelRuntime.streamSimple(model, context, {\n\t\t\t\t...commonOptions,\n\t\t\t\ttransformHeaders: async (requestHeaders) => {\n\t\t\t\t\tconst headers = mergeProviderAttributionHeaders(\n\t\t\t\t\t\tmodel,\n\t\t\t\t\t\tsettingsManager,\n\t\t\t\t\t\tpiServerSessionId,\n\t\t\t\t\t\trequestHeaders,\n\t\t\t\t\t);\n\t\t\t\t\treturn headerRunner?.hasHandlers(\"before_provider_headers\")\n\t\t\t\t\t\t? headerRunner.emitBeforeProviderHeaders(headers ?? {})\n\t\t\t\t\t\t: (headers ?? {});\n\t\t\t\t},\n\t\t\t});\n\t\t};\n\tconst mainStreamFunction = streamWithPiServerRunMode(\"main-durable\");\n\tconst auxiliaryStreamFunction = streamWithPiServerRunMode(\"auxiliary-transient\");\n\n\tagent = new Agent({\n\t\tinitialState: {\n\t\t\tsystemPrompt: \"\",\n\t\t\tmodel,\n\t\t\tthinkingLevel,\n\t\t\ttools: [],\n\t\t},\n\t\tconvertToLlm: convertToLlmWithBlockImages,\n\t\tstreamFn: mainStreamFunction,\n\t\tonPayload: async (payload, _model) => {\n\t\t\tconst runner = extensionRunnerRef.current;\n\t\t\tif (!runner?.hasHandlers(\"before_provider_request\")) {\n\t\t\t\treturn payload;\n\t\t\t}\n\t\t\treturn runner.emitBeforeProviderRequest(payload);\n\t\t},\n\t\tonResponse: async (response, _model) => {\n\t\t\tconst runner = extensionRunnerRef.current;\n\t\t\tif (!runner?.hasHandlers(\"after_provider_response\")) {\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tawait runner.emit({\n\t\t\t\ttype: \"after_provider_response\",\n\t\t\t\tstatus: response.status,\n\t\t\t\theaders: response.headers,\n\t\t\t});\n\t\t},\n\t\tsessionId: sessionManager.getSessionId(),\n\t\ttransformContext: async (messages) => {\n\t\t\tconst runner = extensionRunnerRef.current;\n\t\t\tif (!runner) return messages;\n\t\t\treturn runner.emitContext(messages);\n\t\t},\n\t\tsteeringMode: settingsManager.getSteeringMode(),\n\t\tfollowUpMode: settingsManager.getFollowUpMode(),\n\t\ttransport: settingsManager.getTransport(),\n\t\tthinkingBudgets: settingsManager.getThinkingBudgets(),\n\t\tmaxRetryDelayMs: settingsManager.getProviderRetrySettings().maxRetryDelayMs,\n\t});\n\n\t// Restore messages if session has existing data\n\tif (hasExistingSession) {\n\t\tagent.state.messages = existingSession.messages;\n\t\tif (!hasThinkingEntry) {\n\t\t\tsessionManager.appendThinkingLevelChange(thinkingLevel);\n\t\t}\n\t} else {\n\t\t// Save initial model and thinking level for new sessions so they can be restored on resume\n\t\tif (model) {\n\t\t\tsessionManager.appendModelChange(model.provider, model.id);\n\t\t}\n\t\tsessionManager.appendThinkingLevelChange(thinkingLevel);\n\t}\n\n\tconst session = new AgentSession({\n\t\tagent,\n\t\tsessionManager,\n\t\tsettingsManager,\n\t\tcwd,\n\t\tscopedModels: options.scopedModels,\n\t\tresourceLoader,\n\t\tcustomTools: options.customTools,\n\t\tmodelRuntime,\n\t\tinitialActiveToolNames,\n\t\tallowedToolNames,\n\t\texcludedToolNames,\n\t\textensionRunnerRef,\n\t\tauxiliaryStreamFunction: process.env.PI_SERVER_MODE === \"true\" ? auxiliaryStreamFunction : undefined,\n\t\tsessionStartEvent: options.sessionStartEvent,\n\t\tautoSessionName: options.autoSessionName,\n\t});\n\tagentSession = session;\n\tconst extensionsResult = resourceLoader.getExtensions();\n\n\treturn {\n\t\tsession,\n\t\textensionsResult,\n\t\tmodelFallbackMessage,\n\t};\n}\n"]}
package/dist/core/sdk.js CHANGED
@@ -11,7 +11,6 @@ import { convertToLlm } from "./messages.js";
11
11
  import { findInitialModel } from "./model-resolver.js";
12
12
  import { ModelRuntime } from "./model-runtime.js";
13
13
  import { streamPiServer } from "./pi-server-client.js";
14
- import { assertPiServerProviderExecution } from "./pi-server-provider-execution.js";
15
14
  import { getPiServerRunStatePath } from "./pi-server-run-state.js";
16
15
  import { mergeProviderAttributionHeaders } from "./provider-attribution.js";
17
16
  import { DefaultResourceLoader } from "./resource-loader.js";
@@ -195,9 +194,6 @@ export async function createAgentSession(options = {}) {
195
194
  const extensionRunnerRef = {};
196
195
  const streamWithPiServerRunMode = (runMode) => async (model, context, options) => {
197
196
  const headerRunner = extensionRunnerRef.current;
198
- const piServerExecution = process.env.PI_SERVER_MODE === "true"
199
- ? assertPiServerProviderExecution(modelRuntime, model, headerRunner)
200
- : undefined;
201
197
  const providerRetrySettings = settingsManager.getProviderRetrySettings();
202
198
  const httpIdleTimeoutMs = settingsManager.getHttpIdleTimeoutMs();
203
199
  // SDKs treat timeout=0 as 0ms (immediate timeout), not "no timeout".
@@ -239,7 +235,6 @@ export async function createAgentSession(options = {}) {
239
235
  sessionTree: piServerContext?.sessionTree,
240
236
  ephemeralMessages: piServerContext?.ephemeralMessages,
241
237
  contextOverlay: piServerContext?.contextOverlay,
242
- providerExecutionFingerprint: piServerExecution?.providerExecutionFingerprint,
243
238
  piServerRunStatePath: piServerSessionFile ? getPiServerRunStatePath(piServerSessionFile) : undefined,
244
239
  onHistoryReconciled: runMode === "main-durable" && activeAgentSession
245
240
  ? (snapshot) => activeAgentSession.reconcilePiServerHistory(snapshot)
@@ -1 +1 @@
1
- {"version":3,"file":"sdk.js","sourceRoot":"","sources":["../../src/core/sdk.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AACzC,OAAO,EAAE,IAAI,EAAE,MAAM,WAAW,CAAC;AACjC,OAAO,EACN,KAAK,EAGL,kBAAkB,GAElB,MAAM,+BAA+B,CAAC;AACvC,OAAO,EAAE,kBAAkB,EAA4B,YAAY,EAAE,MAAM,8BAA8B,CAAC;AAC1G,OAAO,EAAE,WAAW,EAAE,MAAM,cAAc,CAAC;AAC3C,OAAO,EAAE,WAAW,EAAE,MAAM,mBAAmB,CAAC;AAChD,OAAO,EAAE,YAAY,EAAE,MAAM,oBAAoB,CAAC;AAClD,OAAO,EAAE,8BAA8B,EAAE,MAAM,oBAAoB,CAAC;AACpE,OAAO,EAAE,sBAAsB,EAAE,MAAM,eAAe,CAAC;AAEvD,OAAO,EAAE,YAAY,EAAE,MAAM,eAAe,CAAC;AAC7C,OAAO,EAAE,gBAAgB,EAAE,MAAM,qBAAqB,CAAC;AACvD,OAAO,EAAE,YAAY,EAAE,MAAM,oBAAoB,CAAC;AAClD,OAAO,EAA2D,cAAc,E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K,MAAM,CAAC,CAAC,CAAC,uBAAuB,CAAC,CAAC,CAAC,SAAS;QACpG,iBAAiB,EAAE,OAAO,CAAC,iBAAiB;QAC5C,eAAe,EAAE,OAAO,CAAC,eAAe;KACxC,CAAC,CAAC;IACH,YAAY,GAAG,OAAO,CAAC;IACvB,MAAM,gBAAgB,GAAG,cAAc,CAAC,aAAa,EAAE,CAAC;IAExD,OAAO;QACN,OAAO;QACP,gBAAgB;QAChB,oBAAoB;KACpB,CAAC;AAAA,CACF","sourcesContent":["import { randomUUID } from \"node:crypto\";\nimport { join } from \"node:path\";\nimport {\n\tAgent,\n\ttype AgentMessage,\n\ttype StreamFn,\n\tsetDefaultStreamFn,\n\ttype ThinkingLevel,\n} from \"@earendil-works/pi-agent-core\";\nimport { clampThinkingLevel, type Message, type Model, streamSimple } from \"@earendil-works/pi-ai/compat\";\nimport { getAgentDir } from \"../config.ts\";\nimport { resolvePath } from \"../utils/paths.ts\";\nimport { AgentSession } from \"./agent-session.ts\";\nimport { formatNoModelsAvailableMessage } from \"./auth-guidance.ts\";\nimport { DEFAULT_THINKING_LEVEL } from \"./defaults.ts\";\nimport type { ExtensionRunner, LoadExtensionsResult, SessionStartEvent, ToolDefinition } from \"./extensions/index.ts\";\nimport { convertToLlm } from \"./messages.ts\";\nimport { findInitialModel } from \"./model-resolver.ts\";\nimport { ModelRuntime } from \"./model-runtime.ts\";\nimport { type PiServerHistorySnapshot, type PiServerTreeSnapshot, streamPiServer } from \"./pi-server-client.ts\";\nimport { assertPiServerProviderExecution } from \"./pi-server-provider-execution.ts\";\nimport { getPiServerRunStatePath } from \"./pi-server-run-state.ts\";\nimport { mergeProviderAttributionHeaders } from \"./provider-attribution.ts\";\nimport type { ResourceLoader } from \"./resource-loader.ts\";\nimport { DefaultResourceLoader } from \"./resource-loader.ts\";\nimport { getDefaultSessionDir, SessionManager } from \"./session-manager.ts\";\nimport { SettingsManager } from \"./settings-manager.ts\";\nimport { time } from \"./timings.ts\";\nimport {\n\tcreateBashTool,\n\tcreateCodingTools,\n\tcreateEditTool,\n\tcreateFindTool,\n\tcreateGrepTool,\n\tcreateLsTool,\n\tcreateReadOnlyTools,\n\tcreateReadTool,\n\tcreateWriteTool,\n\ttype ToolName,\n\twithFileMutationQueue,\n} from \"./tools/index.ts\";\n\n// Preserve the pre-0.81 fallback for extensions that construct Agent instances\n// or invoke low-level agent loops without supplying streamFn. Agent core remains\n// provider-agnostic and does not import pi-ai/compat itself.\nsetDefaultStreamFn(streamSimple);\n\nexport interface CreateAgentSessionOptions {\n\t/** Working directory for project-local discovery. Default: process.cwd() */\n\tcwd?: string;\n\t/** Global config directory. Default: ~/.pi/agent */\n\tagentDir?: string;\n\n\t/** Canonical model/auth runtime. Defaults to a runtime using agentDir/auth.json and models.json. */\n\tmodelRuntime?: ModelRuntime;\n\n\t/** Model to use. Default: from settings, else first available */\n\tmodel?: Model<any>;\n\t/** Thinking level. Default: from settings, else 'medium' (clamped to model capabilities) */\n\tthinkingLevel?: ThinkingLevel;\n\t/** Models available for cycling (Ctrl+P in interactive mode) */\n\tscopedModels?: Array<{ model: Model<any>; thinkingLevel?: ThinkingLevel }>;\n\n\t/**\n\t * Optional default tool suppression mode when no explicit allowlist is provided.\n\t *\n\t * - \"all\": start with no tools enabled\n\t * - \"builtin\": disable the default built-in tools (read, bash, edit, write)\n\t * but keep extension/custom tools enabled\n\t */\n\tnoTools?: \"all\" | \"builtin\";\n\t/**\n\t * Optional allowlist of tool names.\n\t *\n\t * When omitted, pi enables the default built-in tools (read, bash, edit, write)\n\t * and leaves extension/custom tools enabled unless `noTools` changes that default.\n\t * When provided, only the listed tool names are enabled.\n\t */\n\ttools?: string[];\n\t/** Optional denylist of tool names to disable. Applies after `tools` when both are provided. */\n\texcludeTools?: string[];\n\t/** Custom tools to register (in addition to built-in tools). */\n\tcustomTools?: ToolDefinition[];\n\n\t/** Resource loader. When omitted, DefaultResourceLoader is used. */\n\tresourceLoader?: ResourceLoader;\n\n\t/** Session manager. Default: SessionManager.create(cwd) */\n\tsessionManager?: SessionManager;\n\n\t/** Settings manager. Default: SettingsManager.create(cwd, agentDir) */\n\tsettingsManager?: SettingsManager;\n\t/** Session start event metadata for extension runtime startup. */\n\tsessionStartEvent?: SessionStartEvent;\n\t/** Whether to generate a display name with an extra provider request after the first turn. */\n\tautoSessionName?: boolean;\n}\n\n/** Result from createAgentSession */\nexport interface CreateAgentSessionResult {\n\t/** The created session */\n\tsession: AgentSession;\n\t/** Extensions result (for UI context setup in interactive mode) */\n\textensionsResult: LoadExtensionsResult;\n\t/** Warning if session was restored with a different model than saved */\n\tmodelFallbackMessage?: string;\n}\n\n// Re-exports\n\nexport * from \"./agent-session-runtime.ts\";\nexport type {\n\tExtensionAPI,\n\tExtensionCommandContext,\n\tExtensionContext,\n\tExtensionFactory,\n\tInlineExtension,\n\tSlashCommandInfo,\n\tSlashCommandSource,\n\tToolDefinition,\n} from \"./extensions/index.ts\";\nexport type { PromptTemplate } from \"./prompt-templates.ts\";\nexport type { Skill } from \"./skills.ts\";\nexport type { Tool } from \"./tools/index.ts\";\n\nexport {\n\twithFileMutationQueue,\n\t// Tool factories (for custom cwd)\n\tcreateCodingTools,\n\tcreateReadOnlyTools,\n\tcreateReadTool,\n\tcreateBashTool,\n\tcreateEditTool,\n\tcreateWriteTool,\n\tcreateGrepTool,\n\tcreateFindTool,\n\tcreateLsTool,\n};\n\n// Helper Functions\n\nfunction getDefaultAgentDir(): string {\n\treturn getAgentDir();\n}\n\nfunction messagesEqual(left: Message[], right: Message[]): boolean {\n\treturn JSON.stringify(left) === JSON.stringify(right);\n}\n\nexport interface PiServerContextSync {\n\tsessionTree: PiServerTreeSnapshot;\n\tephemeralMessages?: Message[];\n\tcontextOverlay?: Message[];\n}\n\nexport function buildPiServerContextSync(\n\tsessionManager: SessionManager,\n\tcontextMessages: Message[],\n): PiServerContextSync {\n\tconst entries = sessionManager.getEntries();\n\tconst localContextMessages = convertToLlm(sessionManager.buildSessionContext().messages);\n\tif (messagesEqual(localContextMessages, contextMessages)) {\n\t\treturn { sessionTree: { entries, leafId: sessionManager.getLeafId() } };\n\t}\n\n\tconst hasLocalPrefix =\n\t\tlocalContextMessages.length <= contextMessages.length &&\n\t\tmessagesEqual(localContextMessages, contextMessages.slice(0, localContextMessages.length));\n\tif (hasLocalPrefix) {\n\t\treturn {\n\t\t\tsessionTree: { entries, leafId: sessionManager.getLeafId() },\n\t\t\tephemeralMessages: contextMessages.slice(localContextMessages.length),\n\t\t};\n\t}\n\n\treturn {\n\t\tsessionTree: { entries, leafId: sessionManager.getLeafId() },\n\t\tcontextOverlay: contextMessages,\n\t};\n}\n\n/**\n * Create an AgentSession with the specified options.\n *\n * @example\n * ```typescript\n * // Minimal - uses defaults\n * const { session } = await createAgentSession();\n *\n * // With explicit model\n * import { getModel } from '@earendil-works/pi-ai';\n * const { session } = await createAgentSession({\n * model: getModel('anthropic', 'claude-opus-4-5'),\n * thinkingLevel: 'high',\n * });\n *\n * // Continue previous session\n * const { session, modelFallbackMessage } = await createAgentSession({\n * continueSession: true,\n * });\n *\n * // Full control\n * const loader = new DefaultResourceLoader({\n * cwd: process.cwd(),\n * agentDir: getAgentDir(),\n * settingsManager: SettingsManager.create(),\n * });\n * await loader.reload();\n * const { session } = await createAgentSession({\n * model: myModel,\n * tools: [\"read\", \"bash\"],\n * resourceLoader: loader,\n * sessionManager: SessionManager.inMemory(),\n * });\n * ```\n */\nexport async function createAgentSession(options: CreateAgentSessionOptions = {}): Promise<CreateAgentSessionResult> {\n\tconst cwd = resolvePath(options.cwd ?? options.sessionManager?.getCwd() ?? process.cwd());\n\tconst agentDir = options.agentDir ? resolvePath(options.agentDir) : getDefaultAgentDir();\n\tlet resourceLoader = options.resourceLoader;\n\n\tconst authPath = options.agentDir ? join(agentDir, \"auth.json\") : undefined;\n\tconst modelsPath = options.agentDir ? join(agentDir, \"models.json\") : undefined;\n\tconst modelRuntime = options.modelRuntime ?? (await ModelRuntime.create({ authPath, modelsPath }));\n\n\tconst settingsManager = options.settingsManager ?? SettingsManager.create(cwd, agentDir);\n\tconst sessionManager = options.sessionManager ?? SessionManager.create(cwd, getDefaultSessionDir(cwd, agentDir));\n\n\tif (!resourceLoader) {\n\t\tresourceLoader = new DefaultResourceLoader({ cwd, agentDir, settingsManager });\n\t\tawait resourceLoader.reload();\n\t\ttime(\"resourceLoader.reload\");\n\t}\n\n\t// Check if session has existing data to restore\n\tconst existingSession = sessionManager.buildSessionContext();\n\tconst hasExistingSession = existingSession.messages.length > 0;\n\tconst hasThinkingEntry = sessionManager.getBranch().some((entry) => entry.type === \"thinking_level_change\");\n\n\tlet model = options.model;\n\tlet modelFallbackMessage: string | undefined;\n\n\t// If session has data, try to restore model from it\n\tif (!model && hasExistingSession && existingSession.model) {\n\t\tconst restoredModel = modelRuntime.getModel(existingSession.model.provider, existingSession.model.modelId);\n\t\tif (restoredModel && modelRuntime.hasConfiguredAuth(restoredModel.provider)) {\n\t\t\tmodel = restoredModel;\n\t\t}\n\t\tif (!model) {\n\t\t\tmodelFallbackMessage = `Could not restore model ${existingSession.model.provider}/${existingSession.model.modelId}`;\n\t\t}\n\t}\n\n\t// If still no model, use findInitialModel (checks settings default, then provider defaults)\n\tif (!model) {\n\t\tconst result = await findInitialModel({\n\t\t\tscopedModels: [],\n\t\t\tisContinuing: hasExistingSession,\n\t\t\tdefaultProvider: settingsManager.getDefaultProvider(),\n\t\t\tdefaultModelId: settingsManager.getDefaultModel(),\n\t\t\tdefaultThinkingLevel: settingsManager.getDefaultThinkingLevel(),\n\t\t\tmodelRuntime,\n\t\t});\n\t\tmodel = result.model;\n\t\tif (!model) {\n\t\t\tmodelFallbackMessage = formatNoModelsAvailableMessage();\n\t\t} else if (modelFallbackMessage) {\n\t\t\tmodelFallbackMessage += `. Using ${model.provider}/${model.id}`;\n\t\t}\n\t}\n\n\tlet thinkingLevel = options.thinkingLevel;\n\n\t// If session has data, restore thinking level from it\n\tif (thinkingLevel === undefined && hasExistingSession) {\n\t\tthinkingLevel = hasThinkingEntry\n\t\t\t? (existingSession.thinkingLevel as ThinkingLevel)\n\t\t\t: (settingsManager.getDefaultThinkingLevel() ?? DEFAULT_THINKING_LEVEL);\n\t}\n\n\t// Fall back to settings default\n\tif (thinkingLevel === undefined) {\n\t\tthinkingLevel = settingsManager.getDefaultThinkingLevel() ?? DEFAULT_THINKING_LEVEL;\n\t}\n\n\t// Clamp to model capabilities\n\tif (!model) {\n\t\tthinkingLevel = \"off\";\n\t} else {\n\t\tthinkingLevel = clampThinkingLevel(model, thinkingLevel) as ThinkingLevel;\n\t}\n\n\tconst defaultActiveToolNames: ToolName[] = [\"read\", \"bash\", \"edit\", \"write\"];\n\tconst allowedToolNames = options.tools ?? (options.noTools === \"all\" ? [] : undefined);\n\tconst excludedToolNames = options.excludeTools;\n\tconst excludedToolNameSet = excludedToolNames ? new Set(excludedToolNames) : undefined;\n\tconst initialActiveToolNames: string[] = (\n\t\toptions.tools ? [...options.tools] : options.noTools ? [] : defaultActiveToolNames\n\t).filter((name) => !excludedToolNameSet?.has(name));\n\n\tlet agent: Agent;\n\tlet agentSession: AgentSession | undefined;\n\n\t// Create convertToLlm wrapper that filters images if blockImages is enabled (defense-in-depth)\n\tconst convertToLlmWithBlockImages = (messages: AgentMessage[]): Message[] => {\n\t\tconst converted = convertToLlm(messages);\n\t\t// Check setting dynamically so mid-session changes take effect\n\t\tif (!settingsManager.getBlockImages()) {\n\t\t\treturn converted;\n\t\t}\n\t\t// Filter out ImageContent from all messages, replacing with text placeholder\n\t\treturn converted.map((msg) => {\n\t\t\tif (msg.role === \"user\" || msg.role === \"toolResult\") {\n\t\t\t\tconst content = msg.content;\n\t\t\t\tif (Array.isArray(content)) {\n\t\t\t\t\tconst hasImages = content.some((c) => c.type === \"image\");\n\t\t\t\t\tif (hasImages) {\n\t\t\t\t\t\tconst filteredContent = content\n\t\t\t\t\t\t\t.map((c) =>\n\t\t\t\t\t\t\t\tc.type === \"image\" ? { type: \"text\" as const, text: \"Image reading is disabled.\" } : c,\n\t\t\t\t\t\t\t)\n\t\t\t\t\t\t\t.filter(\n\t\t\t\t\t\t\t\t(c, i, arr) =>\n\t\t\t\t\t\t\t\t\t// Dedupe consecutive \"Image reading is disabled.\" texts\n\t\t\t\t\t\t\t\t\t!(\n\t\t\t\t\t\t\t\t\t\tc.type === \"text\" &&\n\t\t\t\t\t\t\t\t\t\tc.text === \"Image reading is disabled.\" &&\n\t\t\t\t\t\t\t\t\t\ti > 0 &&\n\t\t\t\t\t\t\t\t\t\tarr[i - 1].type === \"text\" &&\n\t\t\t\t\t\t\t\t\t\t(arr[i - 1] as { type: \"text\"; text: string }).text === \"Image reading is disabled.\"\n\t\t\t\t\t\t\t\t\t),\n\t\t\t\t\t\t\t);\n\t\t\t\t\t\treturn { ...msg, content: filteredContent };\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn msg;\n\t\t});\n\t};\n\n\tconst extensionRunnerRef: { current?: ExtensionRunner } = {};\n\n\tconst streamWithPiServerRunMode =\n\t\t(runMode: \"main-durable\" | \"auxiliary-transient\"): StreamFn =>\n\t\tasync (model, context, options) => {\n\t\t\tconst headerRunner = extensionRunnerRef.current;\n\t\t\tconst piServerExecution =\n\t\t\t\tprocess.env.PI_SERVER_MODE === \"true\"\n\t\t\t\t\t? assertPiServerProviderExecution(modelRuntime, model, headerRunner)\n\t\t\t\t\t: undefined;\n\t\t\tconst providerRetrySettings = settingsManager.getProviderRetrySettings();\n\t\t\tconst httpIdleTimeoutMs = settingsManager.getHttpIdleTimeoutMs();\n\t\t\t// SDKs treat timeout=0 as 0ms (immediate timeout), not \"no timeout\".\n\t\t\t// Use max int32 to effectively disable the timeout.\n\t\t\tconst effectiveTimeoutMs = httpIdleTimeoutMs === 0 ? 2147483647 : httpIdleTimeoutMs;\n\t\t\tconst timeoutMs = options?.timeoutMs ?? providerRetrySettings.timeoutMs ?? effectiveTimeoutMs;\n\t\t\tconst websocketConnectTimeoutMs =\n\t\t\t\toptions?.websocketConnectTimeoutMs ?? settingsManager.getWebSocketConnectTimeoutMs();\n\t\t\tconst activeAgentSession = agentSession;\n\t\t\tconst piServerContext =\n\t\t\t\trunMode === \"main-durable\" && activeAgentSession\n\t\t\t\t\t? buildPiServerContextSync(activeAgentSession.sessionManager, context.messages as Message[])\n\t\t\t\t\t: undefined;\n\t\t\tconst mainSessionId = sessionManager.getSessionId();\n\t\t\tconst piServerSessionId = runMode === \"main-durable\" ? mainSessionId : (options?.sessionId ?? randomUUID());\n\t\t\tif (runMode === \"auxiliary-transient\" && piServerSessionId === mainSessionId) {\n\t\t\t\tthrow new Error(\"Auxiliary provider streams must use a session id independent from the main session\");\n\t\t\t}\n\t\t\tconst piServerSessionFile =\n\t\t\t\trunMode === \"main-durable\" ? activeAgentSession?.sessionManager.getSessionFile() : undefined;\n\t\t\tconst commonOptions = {\n\t\t\t\t...options,\n\t\t\t\tsessionId: piServerSessionId,\n\t\t\t\ttimeoutMs,\n\t\t\t\twebsocketConnectTimeoutMs,\n\t\t\t\tmaxRetries: options?.maxRetries ?? providerRetrySettings.maxRetries,\n\t\t\t\tmaxRetryDelayMs: options?.maxRetryDelayMs ?? providerRetrySettings.maxRetryDelayMs,\n\t\t\t};\n\t\t\tif (process.env.PI_SERVER_MODE === \"true\") {\n\t\t\t\tconst auth = await modelRuntime.getAuth(model, { apiKey: options?.apiKey, env: options?.env });\n\t\t\t\tif (!auth) {\n\t\t\t\t\tthrow new Error(`Provider is not configured: ${model.provider}`);\n\t\t\t\t}\n\t\t\t\tlet headers = mergeProviderAttributionHeaders(\n\t\t\t\t\tmodel,\n\t\t\t\t\tsettingsManager,\n\t\t\t\t\tpiServerSessionId,\n\t\t\t\t\tauth.auth.headers,\n\t\t\t\t\toptions?.headers,\n\t\t\t\t);\n\t\t\t\tif (headerRunner?.hasHandlers(\"before_provider_headers\")) {\n\t\t\t\t\theaders = await headerRunner.emitBeforeProviderHeaders(headers ?? {});\n\t\t\t\t}\n\t\t\t\tconst requestModel = auth.auth.baseUrl ? { ...model, baseUrl: auth.auth.baseUrl } : model;\n\t\t\t\treturn streamPiServer(requestModel, context, {\n\t\t\t\t\t...commonOptions,\n\t\t\t\t\trunMode,\n\t\t\t\t\tsessionTree: piServerContext?.sessionTree,\n\t\t\t\t\tephemeralMessages: piServerContext?.ephemeralMessages,\n\t\t\t\t\tcontextOverlay: piServerContext?.contextOverlay,\n\t\t\t\t\tproviderExecutionFingerprint: piServerExecution?.providerExecutionFingerprint,\n\t\t\t\t\tpiServerRunStatePath: piServerSessionFile ? getPiServerRunStatePath(piServerSessionFile) : undefined,\n\t\t\t\t\tonHistoryReconciled:\n\t\t\t\t\t\trunMode === \"main-durable\" && activeAgentSession\n\t\t\t\t\t\t\t? (snapshot: PiServerHistorySnapshot) => activeAgentSession.reconcilePiServerHistory(snapshot)\n\t\t\t\t\t\t\t: undefined,\n\t\t\t\t\tapiKey: auth.auth.apiKey,\n\t\t\t\t\tenv: auth.env || options?.env ? { ...(auth.env ?? {}), ...(options?.env ?? {}) } : undefined,\n\t\t\t\t\theaders,\n\t\t\t\t});\n\t\t\t}\n\t\t\treturn modelRuntime.streamSimple(model, context, {\n\t\t\t\t...commonOptions,\n\t\t\t\ttransformHeaders: async (requestHeaders) => {\n\t\t\t\t\tconst headers = mergeProviderAttributionHeaders(\n\t\t\t\t\t\tmodel,\n\t\t\t\t\t\tsettingsManager,\n\t\t\t\t\t\tpiServerSessionId,\n\t\t\t\t\t\trequestHeaders,\n\t\t\t\t\t);\n\t\t\t\t\treturn headerRunner?.hasHandlers(\"before_provider_headers\")\n\t\t\t\t\t\t? headerRunner.emitBeforeProviderHeaders(headers ?? {})\n\t\t\t\t\t\t: (headers ?? {});\n\t\t\t\t},\n\t\t\t});\n\t\t};\n\tconst mainStreamFunction = streamWithPiServerRunMode(\"main-durable\");\n\tconst auxiliaryStreamFunction = streamWithPiServerRunMode(\"auxiliary-transient\");\n\n\tagent = new Agent({\n\t\tinitialState: {\n\t\t\tsystemPrompt: \"\",\n\t\t\tmodel,\n\t\t\tthinkingLevel,\n\t\t\ttools: [],\n\t\t},\n\t\tconvertToLlm: convertToLlmWithBlockImages,\n\t\tstreamFn: mainStreamFunction,\n\t\tonPayload: async (payload, _model) => {\n\t\t\tconst runner = extensionRunnerRef.current;\n\t\t\tif (!runner?.hasHandlers(\"before_provider_request\")) {\n\t\t\t\treturn payload;\n\t\t\t}\n\t\t\treturn runner.emitBeforeProviderRequest(payload);\n\t\t},\n\t\tonResponse: async (response, _model) => {\n\t\t\tconst runner = extensionRunnerRef.current;\n\t\t\tif (!runner?.hasHandlers(\"after_provider_response\")) {\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tawait runner.emit({\n\t\t\t\ttype: \"after_provider_response\",\n\t\t\t\tstatus: response.status,\n\t\t\t\theaders: response.headers,\n\t\t\t});\n\t\t},\n\t\tsessionId: sessionManager.getSessionId(),\n\t\ttransformContext: async (messages) => {\n\t\t\tconst runner = extensionRunnerRef.current;\n\t\t\tif (!runner) return messages;\n\t\t\treturn runner.emitContext(messages);\n\t\t},\n\t\tsteeringMode: settingsManager.getSteeringMode(),\n\t\tfollowUpMode: settingsManager.getFollowUpMode(),\n\t\ttransport: settingsManager.getTransport(),\n\t\tthinkingBudgets: settingsManager.getThinkingBudgets(),\n\t\tmaxRetryDelayMs: settingsManager.getProviderRetrySettings().maxRetryDelayMs,\n\t});\n\n\t// Restore messages if session has existing data\n\tif (hasExistingSession) {\n\t\tagent.state.messages = existingSession.messages;\n\t\tif (!hasThinkingEntry) {\n\t\t\tsessionManager.appendThinkingLevelChange(thinkingLevel);\n\t\t}\n\t} else {\n\t\t// Save initial model and thinking level for new sessions so they can be restored on resume\n\t\tif (model) {\n\t\t\tsessionManager.appendModelChange(model.provider, model.id);\n\t\t}\n\t\tsessionManager.appendThinkingLevelChange(thinkingLevel);\n\t}\n\n\tconst session = new AgentSession({\n\t\tagent,\n\t\tsessionManager,\n\t\tsettingsManager,\n\t\tcwd,\n\t\tscopedModels: options.scopedModels,\n\t\tresourceLoader,\n\t\tcustomTools: options.customTools,\n\t\tmodelRuntime,\n\t\tinitialActiveToolNames,\n\t\tallowedToolNames,\n\t\texcludedToolNames,\n\t\textensionRunnerRef,\n\t\tauxiliaryStreamFunction: process.env.PI_SERVER_MODE === \"true\" ? auxiliaryStreamFunction : undefined,\n\t\tsessionStartEvent: options.sessionStartEvent,\n\t\tautoSessionName: options.autoSessionName,\n\t});\n\tagentSession = session;\n\tconst extensionsResult = resourceLoader.getExtensions();\n\n\treturn {\n\t\tsession,\n\t\textensionsResult,\n\t\tmodelFallbackMessage,\n\t};\n}\n"]}
1
+ {"version":3,"file":"sdk.js","sourceRoot":"","sources":["../../src/core/sdk.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AACzC,OAAO,EAAE,IAAI,EAAE,MAAM,WAAW,CAAC;AACjC,OAAO,EACN,KAAK,EAGL,kBAAkB,GAElB,MAAM,+BAA+B,CAAC;AACvC,OAAO,EAAE,kBAAkB,EAA4B,YAAY,EAAE,MAAM,8BAA8B,CAAC;AAC1G,OAAO,EAAE,WAAW,EAAE,MAAM,cAAc,CAAC;AAC3C,OAAO,EAAE,WAAW,EAAE,MAAM,mBAAmB,CAAC;AAChD,OAAO,EAAE,YAAY,EAAE,MAAM,oBAAoB,CAAC;AAClD,OAAO,EAAE,8BAA8B,EAAE,MAAM,oBAAoB,CAAC;AACpE,OAAO,EAAE,sBAAsB,EAAE,MAAM,eAAe,CAAC;AAEvD,OAAO,EAAE,YAAY,EAAE,MAAM,eAAe,CAAC;AAC7C,OAAO,EAAE,gBAAgB,EAAE,MAAM,qBAAqB,CAAC;AACvD,OAAO,EAAE,YAAY,EAAE,MAAM,oBAAoB,CAAC;AAClD,OAAO,EAA2D,cAAc,EAAE,MAAM,uBAAuB,CAAC;AAChH,OAAO,EAAE,uBAAuB,EAAE,MAAM,0BAA0B,CAAC;AACnE,OAAO,EAAE,+BAA+B,EAAE,MAAM,2BAA2B,CAAC;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Ae,CAAC,kBAAkB,EAAE;QACrD,eAAe,EAAE,eAAe,CAAC,wBAAwB,EAAE,CAAC,eAAe;KAC3E,CAAC,CAAC;IAEH,gDAAgD;IAChD,IAAI,kBAAkB,EAAE,CAAC;QACxB,KAAK,CAAC,KAAK,CAAC,QAAQ,GAAG,eAAe,CAAC,QAAQ,CAAC;QAChD,IAAI,CAAC,gBAAgB,EAAE,CAAC;YACvB,cAAc,CAAC,yBAAyB,CAAC,aAAa,CAAC,CAAC;QACzD,CAAC;IACF,CAAC;SAAM,CAAC;QACP,2FAA2F;QAC3F,IAAI,KAAK,EAAE,CAAC;YACX,cAAc,CAAC,iBAAiB,CAAC,KAAK,CAAC,QAAQ,EAAE,KAAK,CAAC,EAAE,CAAC,CAAC;QAC5D,CAAC;QACD,cAAc,CAAC,yBAAyB,CAAC,aAAa,CAAC,CAAC;IACzD,CAAC;IAED,MAAM,OAAO,GAAG,IAAI,YAAY,CAAC;QAChC,KAAK;QACL,cAAc;QACd,eAAe;QACf,GAAG;QACH,YAAY,EAAE,OAAO,CAAC,YAAY;QAClC,cAAc;QACd,WAAW,EAAE,OAAO,CAAC,WAAW;QAChC,YAAY;QACZ,sBAAsB;QACtB,gBAAgB;QAChB,iBAAiB;QACjB,kBAAkB;QAClB,uBAAuB,EAAE,OAAO,CAAC,GAAG,CAAC,cAAc,KAAK,MAAM,CAAC,CAAC,CAAC,uBAAuB,CAAC,CAAC,CAAC,SAAS;QACpG,iBAAiB,EAAE,OAAO,CAAC,iBAAiB;QAC5C,eAAe,EAAE,OAAO,CAAC,eAAe;KACxC,CAAC,CAAC;IACH,YAAY,GAAG,OAAO,CAAC;IACvB,MAAM,gBAAgB,GAAG,cAAc,CAAC,aAAa,EAAE,CAAC;IAExD,OAAO;QACN,OAAO;QACP,gBAAgB;QAChB,oBAAoB;KACpB,CAAC;AAAA,CACF","sourcesContent":["import { randomUUID } from \"node:crypto\";\nimport { join } from \"node:path\";\nimport {\n\tAgent,\n\ttype AgentMessage,\n\ttype StreamFn,\n\tsetDefaultStreamFn,\n\ttype ThinkingLevel,\n} from \"@earendil-works/pi-agent-core\";\nimport { clampThinkingLevel, type Message, type Model, streamSimple } from \"@earendil-works/pi-ai/compat\";\nimport { getAgentDir } from \"../config.ts\";\nimport { resolvePath } from \"../utils/paths.ts\";\nimport { AgentSession } from \"./agent-session.ts\";\nimport { formatNoModelsAvailableMessage } from \"./auth-guidance.ts\";\nimport { DEFAULT_THINKING_LEVEL } from \"./defaults.ts\";\nimport type { ExtensionRunner, LoadExtensionsResult, SessionStartEvent, ToolDefinition } from \"./extensions/index.ts\";\nimport { convertToLlm } from \"./messages.ts\";\nimport { findInitialModel } from \"./model-resolver.ts\";\nimport { ModelRuntime } from \"./model-runtime.ts\";\nimport { type PiServerHistorySnapshot, type PiServerTreeSnapshot, streamPiServer } from \"./pi-server-client.ts\";\nimport { getPiServerRunStatePath } from \"./pi-server-run-state.ts\";\nimport { mergeProviderAttributionHeaders } from \"./provider-attribution.ts\";\nimport type { ResourceLoader } from \"./resource-loader.ts\";\nimport { DefaultResourceLoader } from \"./resource-loader.ts\";\nimport { getDefaultSessionDir, SessionManager } from \"./session-manager.ts\";\nimport { SettingsManager } from \"./settings-manager.ts\";\nimport { time } from \"./timings.ts\";\nimport {\n\tcreateBashTool,\n\tcreateCodingTools,\n\tcreateEditTool,\n\tcreateFindTool,\n\tcreateGrepTool,\n\tcreateLsTool,\n\tcreateReadOnlyTools,\n\tcreateReadTool,\n\tcreateWriteTool,\n\ttype ToolName,\n\twithFileMutationQueue,\n} from \"./tools/index.ts\";\n\n// Preserve the pre-0.81 fallback for extensions that construct Agent instances\n// or invoke low-level agent loops without supplying streamFn. Agent core remains\n// provider-agnostic and does not import pi-ai/compat itself.\nsetDefaultStreamFn(streamSimple);\n\nexport interface CreateAgentSessionOptions {\n\t/** Working directory for project-local discovery. Default: process.cwd() */\n\tcwd?: string;\n\t/** Global config directory. Default: ~/.pi/agent */\n\tagentDir?: string;\n\n\t/** Canonical model/auth runtime. Defaults to a runtime using agentDir/auth.json and models.json. */\n\tmodelRuntime?: ModelRuntime;\n\n\t/** Model to use. Default: from settings, else first available */\n\tmodel?: Model<any>;\n\t/** Thinking level. Default: from settings, else 'medium' (clamped to model capabilities) */\n\tthinkingLevel?: ThinkingLevel;\n\t/** Models available for cycling (Ctrl+P in interactive mode) */\n\tscopedModels?: Array<{ model: Model<any>; thinkingLevel?: ThinkingLevel }>;\n\n\t/**\n\t * Optional default tool suppression mode when no explicit allowlist is provided.\n\t *\n\t * - \"all\": start with no tools enabled\n\t * - \"builtin\": disable the default built-in tools (read, bash, edit, write)\n\t * but keep extension/custom tools enabled\n\t */\n\tnoTools?: \"all\" | \"builtin\";\n\t/**\n\t * Optional allowlist of tool names.\n\t *\n\t * When omitted, pi enables the default built-in tools (read, bash, edit, write)\n\t * and leaves extension/custom tools enabled unless `noTools` changes that default.\n\t * When provided, only the listed tool names are enabled.\n\t */\n\ttools?: string[];\n\t/** Optional denylist of tool names to disable. Applies after `tools` when both are provided. */\n\texcludeTools?: string[];\n\t/** Custom tools to register (in addition to built-in tools). */\n\tcustomTools?: ToolDefinition[];\n\n\t/** Resource loader. When omitted, DefaultResourceLoader is used. */\n\tresourceLoader?: ResourceLoader;\n\n\t/** Session manager. Default: SessionManager.create(cwd) */\n\tsessionManager?: SessionManager;\n\n\t/** Settings manager. Default: SettingsManager.create(cwd, agentDir) */\n\tsettingsManager?: SettingsManager;\n\t/** Session start event metadata for extension runtime startup. */\n\tsessionStartEvent?: SessionStartEvent;\n\t/** Whether to generate a display name with an extra provider request after the first turn. */\n\tautoSessionName?: boolean;\n}\n\n/** Result from createAgentSession */\nexport interface CreateAgentSessionResult {\n\t/** The created session */\n\tsession: AgentSession;\n\t/** Extensions result (for UI context setup in interactive mode) */\n\textensionsResult: LoadExtensionsResult;\n\t/** Warning if session was restored with a different model than saved */\n\tmodelFallbackMessage?: string;\n}\n\n// Re-exports\n\nexport * from \"./agent-session-runtime.ts\";\nexport type {\n\tExtensionAPI,\n\tExtensionCommandContext,\n\tExtensionContext,\n\tExtensionFactory,\n\tInlineExtension,\n\tSlashCommandInfo,\n\tSlashCommandSource,\n\tToolDefinition,\n} from \"./extensions/index.ts\";\nexport type { PromptTemplate } from \"./prompt-templates.ts\";\nexport type { Skill } from \"./skills.ts\";\nexport type { Tool } from \"./tools/index.ts\";\n\nexport {\n\twithFileMutationQueue,\n\t// Tool factories (for custom cwd)\n\tcreateCodingTools,\n\tcreateReadOnlyTools,\n\tcreateReadTool,\n\tcreateBashTool,\n\tcreateEditTool,\n\tcreateWriteTool,\n\tcreateGrepTool,\n\tcreateFindTool,\n\tcreateLsTool,\n};\n\n// Helper Functions\n\nfunction getDefaultAgentDir(): string {\n\treturn getAgentDir();\n}\n\nfunction messagesEqual(left: Message[], right: Message[]): boolean {\n\treturn JSON.stringify(left) === JSON.stringify(right);\n}\n\nexport interface PiServerContextSync {\n\tsessionTree: PiServerTreeSnapshot;\n\tephemeralMessages?: Message[];\n\tcontextOverlay?: Message[];\n}\n\nexport function buildPiServerContextSync(\n\tsessionManager: SessionManager,\n\tcontextMessages: Message[],\n): PiServerContextSync {\n\tconst entries = sessionManager.getEntries();\n\tconst localContextMessages = convertToLlm(sessionManager.buildSessionContext().messages);\n\tif (messagesEqual(localContextMessages, contextMessages)) {\n\t\treturn { sessionTree: { entries, leafId: sessionManager.getLeafId() } };\n\t}\n\n\tconst hasLocalPrefix =\n\t\tlocalContextMessages.length <= contextMessages.length &&\n\t\tmessagesEqual(localContextMessages, contextMessages.slice(0, localContextMessages.length));\n\tif (hasLocalPrefix) {\n\t\treturn {\n\t\t\tsessionTree: { entries, leafId: sessionManager.getLeafId() },\n\t\t\tephemeralMessages: contextMessages.slice(localContextMessages.length),\n\t\t};\n\t}\n\n\treturn {\n\t\tsessionTree: { entries, leafId: sessionManager.getLeafId() },\n\t\tcontextOverlay: contextMessages,\n\t};\n}\n\n/**\n * Create an AgentSession with the specified options.\n *\n * @example\n * ```typescript\n * // Minimal - uses defaults\n * const { session } = await createAgentSession();\n *\n * // With explicit model\n * import { getModel } from '@earendil-works/pi-ai';\n * const { session } = await createAgentSession({\n * model: getModel('anthropic', 'claude-opus-4-5'),\n * thinkingLevel: 'high',\n * });\n *\n * // Continue previous session\n * const { session, modelFallbackMessage } = await createAgentSession({\n * continueSession: true,\n * });\n *\n * // Full control\n * const loader = new DefaultResourceLoader({\n * cwd: process.cwd(),\n * agentDir: getAgentDir(),\n * settingsManager: SettingsManager.create(),\n * });\n * await loader.reload();\n * const { session } = await createAgentSession({\n * model: myModel,\n * tools: [\"read\", \"bash\"],\n * resourceLoader: loader,\n * sessionManager: SessionManager.inMemory(),\n * });\n * ```\n */\nexport async function createAgentSession(options: CreateAgentSessionOptions = {}): Promise<CreateAgentSessionResult> {\n\tconst cwd = resolvePath(options.cwd ?? options.sessionManager?.getCwd() ?? process.cwd());\n\tconst agentDir = options.agentDir ? resolvePath(options.agentDir) : getDefaultAgentDir();\n\tlet resourceLoader = options.resourceLoader;\n\n\tconst authPath = options.agentDir ? join(agentDir, \"auth.json\") : undefined;\n\tconst modelsPath = options.agentDir ? join(agentDir, \"models.json\") : undefined;\n\tconst modelRuntime = options.modelRuntime ?? (await ModelRuntime.create({ authPath, modelsPath }));\n\n\tconst settingsManager = options.settingsManager ?? SettingsManager.create(cwd, agentDir);\n\tconst sessionManager = options.sessionManager ?? SessionManager.create(cwd, getDefaultSessionDir(cwd, agentDir));\n\n\tif (!resourceLoader) {\n\t\tresourceLoader = new DefaultResourceLoader({ cwd, agentDir, settingsManager });\n\t\tawait resourceLoader.reload();\n\t\ttime(\"resourceLoader.reload\");\n\t}\n\n\t// Check if session has existing data to restore\n\tconst existingSession = sessionManager.buildSessionContext();\n\tconst hasExistingSession = existingSession.messages.length > 0;\n\tconst hasThinkingEntry = sessionManager.getBranch().some((entry) => entry.type === \"thinking_level_change\");\n\n\tlet model = options.model;\n\tlet modelFallbackMessage: string | undefined;\n\n\t// If session has data, try to restore model from it\n\tif (!model && hasExistingSession && existingSession.model) {\n\t\tconst restoredModel = modelRuntime.getModel(existingSession.model.provider, existingSession.model.modelId);\n\t\tif (restoredModel && modelRuntime.hasConfiguredAuth(restoredModel.provider)) {\n\t\t\tmodel = restoredModel;\n\t\t}\n\t\tif (!model) {\n\t\t\tmodelFallbackMessage = `Could not restore model ${existingSession.model.provider}/${existingSession.model.modelId}`;\n\t\t}\n\t}\n\n\t// If still no model, use findInitialModel (checks settings default, then provider defaults)\n\tif (!model) {\n\t\tconst result = await findInitialModel({\n\t\t\tscopedModels: [],\n\t\t\tisContinuing: hasExistingSession,\n\t\t\tdefaultProvider: settingsManager.getDefaultProvider(),\n\t\t\tdefaultModelId: settingsManager.getDefaultModel(),\n\t\t\tdefaultThinkingLevel: settingsManager.getDefaultThinkingLevel(),\n\t\t\tmodelRuntime,\n\t\t});\n\t\tmodel = result.model;\n\t\tif (!model) {\n\t\t\tmodelFallbackMessage = formatNoModelsAvailableMessage();\n\t\t} else if (modelFallbackMessage) {\n\t\t\tmodelFallbackMessage += `. Using ${model.provider}/${model.id}`;\n\t\t}\n\t}\n\n\tlet thinkingLevel = options.thinkingLevel;\n\n\t// If session has data, restore thinking level from it\n\tif (thinkingLevel === undefined && hasExistingSession) {\n\t\tthinkingLevel = hasThinkingEntry\n\t\t\t? (existingSession.thinkingLevel as ThinkingLevel)\n\t\t\t: (settingsManager.getDefaultThinkingLevel() ?? DEFAULT_THINKING_LEVEL);\n\t}\n\n\t// Fall back to settings default\n\tif (thinkingLevel === undefined) {\n\t\tthinkingLevel = settingsManager.getDefaultThinkingLevel() ?? DEFAULT_THINKING_LEVEL;\n\t}\n\n\t// Clamp to model capabilities\n\tif (!model) {\n\t\tthinkingLevel = \"off\";\n\t} else {\n\t\tthinkingLevel = clampThinkingLevel(model, thinkingLevel) as ThinkingLevel;\n\t}\n\n\tconst defaultActiveToolNames: ToolName[] = [\"read\", \"bash\", \"edit\", \"write\"];\n\tconst allowedToolNames = options.tools ?? (options.noTools === \"all\" ? [] : undefined);\n\tconst excludedToolNames = options.excludeTools;\n\tconst excludedToolNameSet = excludedToolNames ? new Set(excludedToolNames) : undefined;\n\tconst initialActiveToolNames: string[] = (\n\t\toptions.tools ? [...options.tools] : options.noTools ? [] : defaultActiveToolNames\n\t).filter((name) => !excludedToolNameSet?.has(name));\n\n\tlet agent: Agent;\n\tlet agentSession: AgentSession | undefined;\n\n\t// Create convertToLlm wrapper that filters images if blockImages is enabled (defense-in-depth)\n\tconst convertToLlmWithBlockImages = (messages: AgentMessage[]): Message[] => {\n\t\tconst converted = convertToLlm(messages);\n\t\t// Check setting dynamically so mid-session changes take effect\n\t\tif (!settingsManager.getBlockImages()) {\n\t\t\treturn converted;\n\t\t}\n\t\t// Filter out ImageContent from all messages, replacing with text placeholder\n\t\treturn converted.map((msg) => {\n\t\t\tif (msg.role === \"user\" || msg.role === \"toolResult\") {\n\t\t\t\tconst content = msg.content;\n\t\t\t\tif (Array.isArray(content)) {\n\t\t\t\t\tconst hasImages = content.some((c) => c.type === \"image\");\n\t\t\t\t\tif (hasImages) {\n\t\t\t\t\t\tconst filteredContent = content\n\t\t\t\t\t\t\t.map((c) =>\n\t\t\t\t\t\t\t\tc.type === \"image\" ? { type: \"text\" as const, text: \"Image reading is disabled.\" } : c,\n\t\t\t\t\t\t\t)\n\t\t\t\t\t\t\t.filter(\n\t\t\t\t\t\t\t\t(c, i, arr) =>\n\t\t\t\t\t\t\t\t\t// Dedupe consecutive \"Image reading is disabled.\" texts\n\t\t\t\t\t\t\t\t\t!(\n\t\t\t\t\t\t\t\t\t\tc.type === \"text\" &&\n\t\t\t\t\t\t\t\t\t\tc.text === \"Image reading is disabled.\" &&\n\t\t\t\t\t\t\t\t\t\ti > 0 &&\n\t\t\t\t\t\t\t\t\t\tarr[i - 1].type === \"text\" &&\n\t\t\t\t\t\t\t\t\t\t(arr[i - 1] as { type: \"text\"; text: string }).text === \"Image reading is disabled.\"\n\t\t\t\t\t\t\t\t\t),\n\t\t\t\t\t\t\t);\n\t\t\t\t\t\treturn { ...msg, content: filteredContent };\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn msg;\n\t\t});\n\t};\n\n\tconst extensionRunnerRef: { current?: ExtensionRunner } = {};\n\n\tconst streamWithPiServerRunMode =\n\t\t(runMode: \"main-durable\" | \"auxiliary-transient\"): StreamFn =>\n\t\tasync (model, context, options) => {\n\t\t\tconst headerRunner = extensionRunnerRef.current;\n\t\t\tconst providerRetrySettings = settingsManager.getProviderRetrySettings();\n\t\t\tconst httpIdleTimeoutMs = settingsManager.getHttpIdleTimeoutMs();\n\t\t\t// SDKs treat timeout=0 as 0ms (immediate timeout), not \"no timeout\".\n\t\t\t// Use max int32 to effectively disable the timeout.\n\t\t\tconst effectiveTimeoutMs = httpIdleTimeoutMs === 0 ? 2147483647 : httpIdleTimeoutMs;\n\t\t\tconst timeoutMs = options?.timeoutMs ?? providerRetrySettings.timeoutMs ?? effectiveTimeoutMs;\n\t\t\tconst websocketConnectTimeoutMs =\n\t\t\t\toptions?.websocketConnectTimeoutMs ?? settingsManager.getWebSocketConnectTimeoutMs();\n\t\t\tconst activeAgentSession = agentSession;\n\t\t\tconst piServerContext =\n\t\t\t\trunMode === \"main-durable\" && activeAgentSession\n\t\t\t\t\t? buildPiServerContextSync(activeAgentSession.sessionManager, context.messages as Message[])\n\t\t\t\t\t: undefined;\n\t\t\tconst mainSessionId = sessionManager.getSessionId();\n\t\t\tconst piServerSessionId = runMode === \"main-durable\" ? mainSessionId : (options?.sessionId ?? randomUUID());\n\t\t\tif (runMode === \"auxiliary-transient\" && piServerSessionId === mainSessionId) {\n\t\t\t\tthrow new Error(\"Auxiliary provider streams must use a session id independent from the main session\");\n\t\t\t}\n\t\t\tconst piServerSessionFile =\n\t\t\t\trunMode === \"main-durable\" ? activeAgentSession?.sessionManager.getSessionFile() : undefined;\n\t\t\tconst commonOptions = {\n\t\t\t\t...options,\n\t\t\t\tsessionId: piServerSessionId,\n\t\t\t\ttimeoutMs,\n\t\t\t\twebsocketConnectTimeoutMs,\n\t\t\t\tmaxRetries: options?.maxRetries ?? providerRetrySettings.maxRetries,\n\t\t\t\tmaxRetryDelayMs: options?.maxRetryDelayMs ?? providerRetrySettings.maxRetryDelayMs,\n\t\t\t};\n\t\t\tif (process.env.PI_SERVER_MODE === \"true\") {\n\t\t\t\tconst auth = await modelRuntime.getAuth(model, { apiKey: options?.apiKey, env: options?.env });\n\t\t\t\tif (!auth) {\n\t\t\t\t\tthrow new Error(`Provider is not configured: ${model.provider}`);\n\t\t\t\t}\n\t\t\t\tlet headers = mergeProviderAttributionHeaders(\n\t\t\t\t\tmodel,\n\t\t\t\t\tsettingsManager,\n\t\t\t\t\tpiServerSessionId,\n\t\t\t\t\tauth.auth.headers,\n\t\t\t\t\toptions?.headers,\n\t\t\t\t);\n\t\t\t\tif (headerRunner?.hasHandlers(\"before_provider_headers\")) {\n\t\t\t\t\theaders = await headerRunner.emitBeforeProviderHeaders(headers ?? {});\n\t\t\t\t}\n\t\t\t\tconst requestModel = auth.auth.baseUrl ? { ...model, baseUrl: auth.auth.baseUrl } : model;\n\t\t\t\treturn streamPiServer(requestModel, context, {\n\t\t\t\t\t...commonOptions,\n\t\t\t\t\trunMode,\n\t\t\t\t\tsessionTree: piServerContext?.sessionTree,\n\t\t\t\t\tephemeralMessages: piServerContext?.ephemeralMessages,\n\t\t\t\t\tcontextOverlay: piServerContext?.contextOverlay,\n\t\t\t\t\tpiServerRunStatePath: piServerSessionFile ? getPiServerRunStatePath(piServerSessionFile) : undefined,\n\t\t\t\t\tonHistoryReconciled:\n\t\t\t\t\t\trunMode === \"main-durable\" && activeAgentSession\n\t\t\t\t\t\t\t? (snapshot: PiServerHistorySnapshot) => activeAgentSession.reconcilePiServerHistory(snapshot)\n\t\t\t\t\t\t\t: undefined,\n\t\t\t\t\tapiKey: auth.auth.apiKey,\n\t\t\t\t\tenv: auth.env || options?.env ? { ...(auth.env ?? {}), ...(options?.env ?? {}) } : undefined,\n\t\t\t\t\theaders,\n\t\t\t\t});\n\t\t\t}\n\t\t\treturn modelRuntime.streamSimple(model, context, {\n\t\t\t\t...commonOptions,\n\t\t\t\ttransformHeaders: async (requestHeaders) => {\n\t\t\t\t\tconst headers = mergeProviderAttributionHeaders(\n\t\t\t\t\t\tmodel,\n\t\t\t\t\t\tsettingsManager,\n\t\t\t\t\t\tpiServerSessionId,\n\t\t\t\t\t\trequestHeaders,\n\t\t\t\t\t);\n\t\t\t\t\treturn headerRunner?.hasHandlers(\"before_provider_headers\")\n\t\t\t\t\t\t? headerRunner.emitBeforeProviderHeaders(headers ?? {})\n\t\t\t\t\t\t: (headers ?? {});\n\t\t\t\t},\n\t\t\t});\n\t\t};\n\tconst mainStreamFunction = streamWithPiServerRunMode(\"main-durable\");\n\tconst auxiliaryStreamFunction = streamWithPiServerRunMode(\"auxiliary-transient\");\n\n\tagent = new Agent({\n\t\tinitialState: {\n\t\t\tsystemPrompt: \"\",\n\t\t\tmodel,\n\t\t\tthinkingLevel,\n\t\t\ttools: [],\n\t\t},\n\t\tconvertToLlm: convertToLlmWithBlockImages,\n\t\tstreamFn: mainStreamFunction,\n\t\tonPayload: async (payload, _model) => {\n\t\t\tconst runner = extensionRunnerRef.current;\n\t\t\tif (!runner?.hasHandlers(\"before_provider_request\")) {\n\t\t\t\treturn payload;\n\t\t\t}\n\t\t\treturn runner.emitBeforeProviderRequest(payload);\n\t\t},\n\t\tonResponse: async (response, _model) => {\n\t\t\tconst runner = extensionRunnerRef.current;\n\t\t\tif (!runner?.hasHandlers(\"after_provider_response\")) {\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tawait runner.emit({\n\t\t\t\ttype: \"after_provider_response\",\n\t\t\t\tstatus: response.status,\n\t\t\t\theaders: response.headers,\n\t\t\t});\n\t\t},\n\t\tsessionId: sessionManager.getSessionId(),\n\t\ttransformContext: async (messages) => {\n\t\t\tconst runner = extensionRunnerRef.current;\n\t\t\tif (!runner) return messages;\n\t\t\treturn runner.emitContext(messages);\n\t\t},\n\t\tsteeringMode: settingsManager.getSteeringMode(),\n\t\tfollowUpMode: settingsManager.getFollowUpMode(),\n\t\ttransport: settingsManager.getTransport(),\n\t\tthinkingBudgets: settingsManager.getThinkingBudgets(),\n\t\tmaxRetryDelayMs: settingsManager.getProviderRetrySettings().maxRetryDelayMs,\n\t});\n\n\t// Restore messages if session has existing data\n\tif (hasExistingSession) {\n\t\tagent.state.messages = existingSession.messages;\n\t\tif (!hasThinkingEntry) {\n\t\t\tsessionManager.appendThinkingLevelChange(thinkingLevel);\n\t\t}\n\t} else {\n\t\t// Save initial model and thinking level for new sessions so they can be restored on resume\n\t\tif (model) {\n\t\t\tsessionManager.appendModelChange(model.provider, model.id);\n\t\t}\n\t\tsessionManager.appendThinkingLevelChange(thinkingLevel);\n\t}\n\n\tconst session = new AgentSession({\n\t\tagent,\n\t\tsessionManager,\n\t\tsettingsManager,\n\t\tcwd,\n\t\tscopedModels: options.scopedModels,\n\t\tresourceLoader,\n\t\tcustomTools: options.customTools,\n\t\tmodelRuntime,\n\t\tinitialActiveToolNames,\n\t\tallowedToolNames,\n\t\texcludedToolNames,\n\t\textensionRunnerRef,\n\t\tauxiliaryStreamFunction: process.env.PI_SERVER_MODE === \"true\" ? auxiliaryStreamFunction : undefined,\n\t\tsessionStartEvent: options.sessionStartEvent,\n\t\tautoSessionName: options.autoSessionName,\n\t});\n\tagentSession = session;\n\tconst extensionsResult = resourceLoader.getExtensions();\n\n\treturn {\n\t\tsession,\n\t\textensionsResult,\n\t\tmodelFallbackMessage,\n\t};\n}\n"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@averyyy/pi-coding-agent",
3
- "version": "0.82.1-piclient.4",
3
+ "version": "0.82.1-piclient.5",
4
4
  "description": "Coding agent CLI with read, bash, edit, write tools and session management",
5
5
  "type": "module",
6
6
  "piConfig": {
@@ -46,9 +46,9 @@
46
46
  "prepublishOnly": "npm run clean && npm run build && npm run shrinkwrap"
47
47
  },
48
48
  "dependencies": {
49
- "@earendil-works/pi-agent-core": "npm:@averyyy/pi-agent-core@0.82.1-piclient.4",
50
- "@earendil-works/pi-ai": "npm:@averyyy/pi-ai@0.82.1-piclient.4",
51
- "@earendil-works/pi-tui": "npm:@averyyy/pi-tui@0.82.1-piclient.4",
49
+ "@earendil-works/pi-agent-core": "npm:@averyyy/pi-agent-core@0.82.1-piclient.5",
50
+ "@earendil-works/pi-ai": "npm:@averyyy/pi-ai@0.82.1-piclient.5",
51
+ "@earendil-works/pi-tui": "npm:@averyyy/pi-tui@0.82.1-piclient.5",
52
52
  "@silvia-odwyer/photon-node": "0.3.4",
53
53
  "chalk": "5.6.2",
54
54
  "cross-spawn": "7.0.6",
@@ -1,19 +0,0 @@
1
- import type { Api, Model } from "@earendil-works/pi-ai";
2
- import type { ModelRuntime } from "./model-runtime.ts";
3
- import type { ProviderExecutionContract } from "./provider-execution-contract.ts";
4
- interface ProviderHookRegistry {
5
- hasHandlers(eventType: string): boolean;
6
- }
7
- export interface PiServerProviderExecutionPreflight {
8
- contract: ProviderExecutionContract;
9
- providerExecutionFingerprint: string;
10
- }
11
- /**
12
- * Reject execution paths that pi-server cannot reproduce exactly.
13
- *
14
- * This preflight is synchronous and credential-free so callers can run it
15
- * before extension hooks, auth resolution, session mutation, or network I/O.
16
- */
17
- export declare function assertPiServerProviderExecution(modelRuntime: ModelRuntime, model: Model<Api>, hooks?: ProviderHookRegistry): PiServerProviderExecutionPreflight;
18
- export {};
19
- //# sourceMappingURL=pi-server-provider-execution.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"pi-server-provider-execution.d.ts","sourceRoot":"","sources":["../../src/core/pi-server-provider-execution.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,GAAG,EAAE,KAAK,EAAE,MAAM,uBAAuB,CAAC;AAGxD,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,oBAAoB,CAAC;AACvD,OAAO,KAAK,EAAE,yBAAyB,EAAE,MAAM,kCAAkC,CAAC;AAQlF,UAAU,oBAAoB;IAC7B,WAAW,CAAC,SAAS,EAAE,MAAM,GAAG,OAAO,CAAC;CACxC;AAED,MAAM,WAAW,kCAAkC;IAClD,QAAQ,EAAE,yBAAyB,CAAC;IACpC,4BAA4B,EAAE,MAAM,CAAC;CACrC;AAED;;;;;GAKG;AACH,wBAAgB,+BAA+B,CAC9C,YAAY,EAAE,YAAY,EAC1B,KAAK,EAAE,KAAK,CAAC,GAAG,CAAC,EACjB,KAAK,CAAC,EAAE,oBAAoB,GAC1B,kCAAkC,CAwCpC","sourcesContent":["import type { Api, Model } from \"@earendil-works/pi-ai\";\nimport { getCompatProviderExecutionRoute } from \"@earendil-works/pi-ai/compat\";\nimport { hashRemoteProviderExecution } from \"@earendil-works/pi-ai/provider-execution-node\";\nimport type { ModelRuntime } from \"./model-runtime.ts\";\nimport type { ProviderExecutionContract } from \"./provider-execution-contract.ts\";\n\nconst PI_SERVER_UNSUPPORTED_PROVIDER_HOOKS = [\n\t\"before_provider_request\",\n\t\"before_provider_headers\",\n\t\"after_provider_response\",\n] as const;\n\ninterface ProviderHookRegistry {\n\thasHandlers(eventType: string): boolean;\n}\n\nexport interface PiServerProviderExecutionPreflight {\n\tcontract: ProviderExecutionContract;\n\tproviderExecutionFingerprint: string;\n}\n\n/**\n * Reject execution paths that pi-server cannot reproduce exactly.\n *\n * This preflight is synchronous and credential-free so callers can run it\n * before extension hooks, auth resolution, session mutation, or network I/O.\n */\nexport function assertPiServerProviderExecution(\n\tmodelRuntime: ModelRuntime,\n\tmodel: Model<Api>,\n\thooks?: ProviderHookRegistry,\n): PiServerProviderExecutionPreflight {\n\tconst contract = modelRuntime.getProviderExecutionContract(model);\n\tif (!contract.descriptor.piServerCompatible) {\n\t\tthrow new Error(\n\t\t\t`pi-server mode cannot preserve native pi provider execution for ${model.provider}/${model.id}: ` +\n\t\t\t\t`mode=${contract.descriptor.mode}, executor=${contract.descriptor.executor.kind}. ` +\n\t\t\t\t\"Run this model with plain pi or remove the custom provider executor.\",\n\t\t);\n\t}\n\n\tconst activeHooks = PI_SERVER_UNSUPPORTED_PROVIDER_HOOKS.filter((eventType) => hooks?.hasHandlers(eventType));\n\tif (activeHooks.length > 0) {\n\t\tthrow new Error(\n\t\t\t`pi-server mode cannot preserve native pi provider hooks for ${model.provider}/${model.id}: ` +\n\t\t\t\t`${activeHooks.join(\", \")}. Run this model with plain pi or disable these hooks.`,\n\t\t);\n\t}\n\tconst executor = contract.descriptor.executor;\n\tif (executor.kind !== \"builtin_provider\" && executor.kind !== \"builtin_api\") {\n\t\tthrow new Error(\n\t\t\t`pi-server mode cannot serialize provider executor ${executor.kind} for ${model.provider}/${model.id}`,\n\t\t);\n\t}\n\tconst activeRoute = getCompatProviderExecutionRoute(model);\n\tif (\n\t\t(activeRoute.kind !== \"builtin_provider\" && activeRoute.kind !== \"builtin_api\") ||\n\t\tactiveRoute.kind !== executor.kind ||\n\t\tactiveRoute.id !== executor.id\n\t) {\n\t\tthrow new Error(\n\t\t\t`pi-server mode cannot preserve native pi provider execution for ${model.provider}/${model.id}: ` +\n\t\t\t\t`model runtime selected ${executor.kind}/${executor.id}, but active pi-ai compat route is ` +\n\t\t\t\t`${activeRoute.kind}/${activeRoute.id}. Remove the runtime API override or use plain pi.`,\n\t\t);\n\t}\n\n\treturn {\n\t\tcontract,\n\t\tproviderExecutionFingerprint: hashRemoteProviderExecution(model, activeRoute),\n\t};\n}\n"]}
@@ -1,43 +0,0 @@
1
- import { getCompatProviderExecutionRoute } from "@earendil-works/pi-ai/compat";
2
- import { hashRemoteProviderExecution } from "@earendil-works/pi-ai/provider-execution-node";
3
- const PI_SERVER_UNSUPPORTED_PROVIDER_HOOKS = [
4
- "before_provider_request",
5
- "before_provider_headers",
6
- "after_provider_response",
7
- ];
8
- /**
9
- * Reject execution paths that pi-server cannot reproduce exactly.
10
- *
11
- * This preflight is synchronous and credential-free so callers can run it
12
- * before extension hooks, auth resolution, session mutation, or network I/O.
13
- */
14
- export function assertPiServerProviderExecution(modelRuntime, model, hooks) {
15
- const contract = modelRuntime.getProviderExecutionContract(model);
16
- if (!contract.descriptor.piServerCompatible) {
17
- throw new Error(`pi-server mode cannot preserve native pi provider execution for ${model.provider}/${model.id}: ` +
18
- `mode=${contract.descriptor.mode}, executor=${contract.descriptor.executor.kind}. ` +
19
- "Run this model with plain pi or remove the custom provider executor.");
20
- }
21
- const activeHooks = PI_SERVER_UNSUPPORTED_PROVIDER_HOOKS.filter((eventType) => hooks?.hasHandlers(eventType));
22
- if (activeHooks.length > 0) {
23
- throw new Error(`pi-server mode cannot preserve native pi provider hooks for ${model.provider}/${model.id}: ` +
24
- `${activeHooks.join(", ")}. Run this model with plain pi or disable these hooks.`);
25
- }
26
- const executor = contract.descriptor.executor;
27
- if (executor.kind !== "builtin_provider" && executor.kind !== "builtin_api") {
28
- throw new Error(`pi-server mode cannot serialize provider executor ${executor.kind} for ${model.provider}/${model.id}`);
29
- }
30
- const activeRoute = getCompatProviderExecutionRoute(model);
31
- if ((activeRoute.kind !== "builtin_provider" && activeRoute.kind !== "builtin_api") ||
32
- activeRoute.kind !== executor.kind ||
33
- activeRoute.id !== executor.id) {
34
- throw new Error(`pi-server mode cannot preserve native pi provider execution for ${model.provider}/${model.id}: ` +
35
- `model runtime selected ${executor.kind}/${executor.id}, but active pi-ai compat route is ` +
36
- `${activeRoute.kind}/${activeRoute.id}. Remove the runtime API override or use plain pi.`);
37
- }
38
- return {
39
- contract,
40
- providerExecutionFingerprint: hashRemoteProviderExecution(model, activeRoute),
41
- };
42
- }
43
- //# sourceMappingURL=pi-server-provider-execution.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"pi-server-provider-execution.js","sourceRoot":"","sources":["../../src/core/pi-server-provider-execution.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,+BAA+B,EAAE,MAAM,8BAA8B,CAAC;AAC/E,OAAO,EAAE,2BAA2B,EAAE,MAAM,+CAA+C,CAAC;AAI5F,MAAM,oC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CAAC,WAAW,CAAC,IAAI,KAAK,kBAAkB,IAAI,WAAW,CAAC,IAAI,KAAK,aAAa,CAAC;QAC/E,WAAW,CAAC,IAAI,KAAK,QAAQ,CAAC,IAAI;QAClC,WAAW,CAAC,EAAE,KAAK,QAAQ,CAAC,EAAE,EAC7B,CAAC;QACF,MAAM,IAAI,KAAK,CACd,mEAAmE,KAAK,CAAC,QAAQ,IAAI,KAAK,CAAC,EAAE,IAAI;YAChG,0BAA0B,QAAQ,CAAC,IAAI,IAAI,QAAQ,CAAC,EAAE,qCAAqC;YAC3F,GAAG,WAAW,CAAC,IAAI,IAAI,WAAW,CAAC,EAAE,oDAAoD,CAC1F,CAAC;IACH,CAAC;IAED,OAAO;QACN,QAAQ;QACR,4BAA4B,EAAE,2BAA2B,CAAC,KAAK,EAAE,WAAW,CAAC;KAC7E,CAAC;AAAA,CACF","sourcesContent":["import type { Api, Model } from \"@earendil-works/pi-ai\";\nimport { getCompatProviderExecutionRoute } from \"@earendil-works/pi-ai/compat\";\nimport { hashRemoteProviderExecution } from \"@earendil-works/pi-ai/provider-execution-node\";\nimport type { ModelRuntime } from \"./model-runtime.ts\";\nimport type { ProviderExecutionContract } from \"./provider-execution-contract.ts\";\n\nconst PI_SERVER_UNSUPPORTED_PROVIDER_HOOKS = [\n\t\"before_provider_request\",\n\t\"before_provider_headers\",\n\t\"after_provider_response\",\n] as const;\n\ninterface ProviderHookRegistry {\n\thasHandlers(eventType: string): boolean;\n}\n\nexport interface PiServerProviderExecutionPreflight {\n\tcontract: ProviderExecutionContract;\n\tproviderExecutionFingerprint: string;\n}\n\n/**\n * Reject execution paths that pi-server cannot reproduce exactly.\n *\n * This preflight is synchronous and credential-free so callers can run it\n * before extension hooks, auth resolution, session mutation, or network I/O.\n */\nexport function assertPiServerProviderExecution(\n\tmodelRuntime: ModelRuntime,\n\tmodel: Model<Api>,\n\thooks?: ProviderHookRegistry,\n): PiServerProviderExecutionPreflight {\n\tconst contract = modelRuntime.getProviderExecutionContract(model);\n\tif (!contract.descriptor.piServerCompatible) {\n\t\tthrow new Error(\n\t\t\t`pi-server mode cannot preserve native pi provider execution for ${model.provider}/${model.id}: ` +\n\t\t\t\t`mode=${contract.descriptor.mode}, executor=${contract.descriptor.executor.kind}. ` +\n\t\t\t\t\"Run this model with plain pi or remove the custom provider executor.\",\n\t\t);\n\t}\n\n\tconst activeHooks = PI_SERVER_UNSUPPORTED_PROVIDER_HOOKS.filter((eventType) => hooks?.hasHandlers(eventType));\n\tif (activeHooks.length > 0) {\n\t\tthrow new Error(\n\t\t\t`pi-server mode cannot preserve native pi provider hooks for ${model.provider}/${model.id}: ` +\n\t\t\t\t`${activeHooks.join(\", \")}. Run this model with plain pi or disable these hooks.`,\n\t\t);\n\t}\n\tconst executor = contract.descriptor.executor;\n\tif (executor.kind !== \"builtin_provider\" && executor.kind !== \"builtin_api\") {\n\t\tthrow new Error(\n\t\t\t`pi-server mode cannot serialize provider executor ${executor.kind} for ${model.provider}/${model.id}`,\n\t\t);\n\t}\n\tconst activeRoute = getCompatProviderExecutionRoute(model);\n\tif (\n\t\t(activeRoute.kind !== \"builtin_provider\" && activeRoute.kind !== \"builtin_api\") ||\n\t\tactiveRoute.kind !== executor.kind ||\n\t\tactiveRoute.id !== executor.id\n\t) {\n\t\tthrow new Error(\n\t\t\t`pi-server mode cannot preserve native pi provider execution for ${model.provider}/${model.id}: ` +\n\t\t\t\t`model runtime selected ${executor.kind}/${executor.id}, but active pi-ai compat route is ` +\n\t\t\t\t`${activeRoute.kind}/${activeRoute.id}. Remove the runtime API override or use plain pi.`,\n\t\t);\n\t}\n\n\treturn {\n\t\tcontract,\n\t\tproviderExecutionFingerprint: hashRemoteProviderExecution(model, activeRoute),\n\t};\n}\n"]}
@@ -1,36 +0,0 @@
1
- import type { Api } from "@earendil-works/pi-ai";
2
- export type ProviderExecutionMode = "builtin" | "serializable_overlay" | "provider_config_stream_simple" | "native_provider";
3
- export type ProviderExecutionKind = "builtin_provider" | "builtin_api" | "provider_config_stream_simple" | "native_provider";
4
- export type ProviderExecutionExecutor = {
5
- kind: "builtin_provider";
6
- id: string;
7
- } | {
8
- kind: "builtin_api";
9
- id: Api;
10
- } | {
11
- kind: "provider_config_stream_simple";
12
- id: string;
13
- } | {
14
- kind: "native_provider";
15
- id: string;
16
- };
17
- export interface ProviderExecutionContractDescriptor {
18
- version: 1;
19
- mode: ProviderExecutionMode;
20
- providerId: string;
21
- modelId: string;
22
- api: Api;
23
- executor: ProviderExecutionExecutor;
24
- overlays: {
25
- modelsJson: boolean;
26
- extensionConfig: boolean;
27
- };
28
- piServerCompatible: boolean;
29
- }
30
- export interface ProviderExecutionContract {
31
- descriptor: ProviderExecutionContractDescriptor;
32
- fingerprint: string;
33
- }
34
- export declare function hashProviderExecutionContract(descriptor: ProviderExecutionContractDescriptor): string;
35
- export declare function createProviderExecutionContract(descriptor: ProviderExecutionContractDescriptor): ProviderExecutionContract;
36
- //# sourceMappingURL=provider-execution-contract.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"provider-execution-contract.d.ts","sourceRoot":"","sources":["../../src/core/provider-execution-contract.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,GAAG,EAAE,MAAM,uBAAuB,CAAC;AAEjD,MAAM,MAAM,qBAAqB,GAC9B,SAAS,GACT,sBAAsB,GACtB,+BAA+B,GAC/B,iBAAiB,CAAC;AAErB,MAAM,MAAM,qBAAqB,GAC9B,kBAAkB,GAClB,aAAa,GACb,+BAA+B,GAC/B,iBAAiB,CAAC;AAErB,MAAM,MAAM,yBAAyB,GAClC;IAAE,IAAI,EAAE,kBAAkB,CAAC;IAAC,EAAE,EAAE,MAAM,CAAA;CAAE,GACxC;IAAE,IAAI,EAAE,aAAa,CAAC;IAAC,EAAE,EAAE,GAAG,CAAA;CAAE,GAChC;IAAE,IAAI,EAAE,+BAA+B,CAAC;IAAC,EAAE,EAAE,MAAM,CAAA;CAAE,GACrD;IAAE,IAAI,EAAE,iBAAiB,CAAC;IAAC,EAAE,EAAE,MAAM,CAAA;CAAE,CAAC;AAE3C,MAAM,WAAW,mCAAmC;IACnD,OAAO,EAAE,CAAC,CAAC;IACX,IAAI,EAAE,qBAAqB,CAAC;IAC5B,UAAU,EAAE,MAAM,CAAC;IACnB,OAAO,EAAE,MAAM,CAAC;IAChB,GAAG,EAAE,GAAG,CAAC;IACT,QAAQ,EAAE,yBAAyB,CAAC;IACpC,QAAQ,EAAE;QACT,UAAU,EAAE,OAAO,CAAC;QACpB,eAAe,EAAE,OAAO,CAAC;KACzB,CAAC;IACF,kBAAkB,EAAE,OAAO,CAAC;CAC5B;AAED,MAAM,WAAW,yBAAyB;IACzC,UAAU,EAAE,mCAAmC,CAAC;IAChD,WAAW,EAAE,MAAM,CAAC;CACpB;AAkBD,wBAAgB,6BAA6B,CAAC,UAAU,EAAE,mCAAmC,GAAG,MAAM,CAIrG;AAED,wBAAgB,+BAA+B,CAC9C,UAAU,EAAE,mCAAmC,GAC7C,yBAAyB,CAK3B","sourcesContent":["import { createHash } from \"node:crypto\";\nimport type { Api } from \"@earendil-works/pi-ai\";\n\nexport type ProviderExecutionMode =\n\t| \"builtin\"\n\t| \"serializable_overlay\"\n\t| \"provider_config_stream_simple\"\n\t| \"native_provider\";\n\nexport type ProviderExecutionKind =\n\t| \"builtin_provider\"\n\t| \"builtin_api\"\n\t| \"provider_config_stream_simple\"\n\t| \"native_provider\";\n\nexport type ProviderExecutionExecutor =\n\t| { kind: \"builtin_provider\"; id: string }\n\t| { kind: \"builtin_api\"; id: Api }\n\t| { kind: \"provider_config_stream_simple\"; id: string }\n\t| { kind: \"native_provider\"; id: string };\n\nexport interface ProviderExecutionContractDescriptor {\n\tversion: 1;\n\tmode: ProviderExecutionMode;\n\tproviderId: string;\n\tmodelId: string;\n\tapi: Api;\n\texecutor: ProviderExecutionExecutor;\n\toverlays: {\n\t\tmodelsJson: boolean;\n\t\textensionConfig: boolean;\n\t};\n\tpiServerCompatible: boolean;\n}\n\nexport interface ProviderExecutionContract {\n\tdescriptor: ProviderExecutionContractDescriptor;\n\tfingerprint: string;\n}\n\nfunction canonicalJson(value: unknown): string | undefined {\n\tif (Array.isArray(value)) {\n\t\treturn `[${value.map((item) => canonicalJson(item) ?? \"null\").join(\",\")}]`;\n\t}\n\tif (value !== null && typeof value === \"object\") {\n\t\tconst record = value as Record<string, unknown>;\n\t\tconst properties: string[] = [];\n\t\tfor (const key of Object.keys(record).sort()) {\n\t\t\tconst serialized = canonicalJson(record[key]);\n\t\t\tif (serialized !== undefined) properties.push(`${JSON.stringify(key)}:${serialized}`);\n\t\t}\n\t\treturn `{${properties.join(\",\")}}`;\n\t}\n\treturn JSON.stringify(value);\n}\n\nexport function hashProviderExecutionContract(descriptor: ProviderExecutionContractDescriptor): string {\n\tconst serialized = canonicalJson(descriptor);\n\tif (serialized === undefined) throw new Error(\"Failed to serialize provider execution contract\");\n\treturn createHash(\"sha256\").update(serialized).digest(\"hex\");\n}\n\nexport function createProviderExecutionContract(\n\tdescriptor: ProviderExecutionContractDescriptor,\n): ProviderExecutionContract {\n\treturn {\n\t\tdescriptor,\n\t\tfingerprint: hashProviderExecutionContract(descriptor),\n\t};\n}\n"]}
@@ -1,30 +0,0 @@
1
- import { createHash } from "node:crypto";
2
- function canonicalJson(value) {
3
- if (Array.isArray(value)) {
4
- return `[${value.map((item) => canonicalJson(item) ?? "null").join(",")}]`;
5
- }
6
- if (value !== null && typeof value === "object") {
7
- const record = value;
8
- const properties = [];
9
- for (const key of Object.keys(record).sort()) {
10
- const serialized = canonicalJson(record[key]);
11
- if (serialized !== undefined)
12
- properties.push(`${JSON.stringify(key)}:${serialized}`);
13
- }
14
- return `{${properties.join(",")}}`;
15
- }
16
- return JSON.stringify(value);
17
- }
18
- export function hashProviderExecutionContract(descriptor) {
19
- const serialized = canonicalJson(descriptor);
20
- if (serialized === undefined)
21
- throw new Error("Failed to serialize provider execution contract");
22
- return createHash("sha256").update(serialized).digest("hex");
23
- }
24
- export function createProviderExecutionContract(descriptor) {
25
- return {
26
- descriptor,
27
- fingerprint: hashProviderExecutionContract(descriptor),
28
- };
29
- }
30
- //# sourceMappingURL=provider-execution-contract.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"provider-execution-contract.js","sourceRoot":"","sources":["../../src/core/provider-execution-contract.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AAwCzC,SAAS,aAAa,CAAC,KAAc,EAAsB;IAC1D,IAAI,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC,EAAE,CAAC;QAC1B,OAAO,IAAI,KAAK,CAAC,GAAG,CAAC,CAAC,IAAI,EAAE,EAAE,CAAC,aAAa,CAAC,IAAI,CAAC,IAAI,MAAM,CAAC,CAAC,IAAI,CAAC,GAAG,CAAC,GAAG,CAAC;IAC5E,CAAC;IACD,IAAI,KAAK,KAAK,IAAI,IAAI,OAAO,KAAK,KAAK,QAAQ,EAAE,CAAC;QACjD,MAAM,MAAM,GAAG,KAAgC,CAAC;QAChD,MAAM,UAAU,GAAa,EAAE,CAAC;QAChC,KAAK,MAAM,GAAG,IAAI,MAAM,CAAC,IAAI,CAAC,MAAM,CAAC,CAAC,IAAI,EAAE,EAAE,CAAC;YAC9C,MAAM,UAAU,GAAG,aAAa,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC,CAAC;YAC9C,IAAI,UAAU,KAAK,SAAS;gBAAE,UAAU,CAAC,IAAI,CAAC,GAAG,IAAI,CAAC,SAAS,CAAC,GAAG,CAAC,IAAI,UAAU,EAAE,CAAC,CAAC;QACvF,CAAC;QACD,OAAO,IAAI,UAAU,CAAC,IAAI,CAAC,GAAG,CAAC,GAAG,CAAC;IACpC,CAAC;IACD,OAAO,IAAI,CAAC,SAAS,CAAC,KAAK,CAAC,CAAC;AAAA,CAC7B;AAED,MAAM,UAAU,6BAA6B,CAAC,UAA+C,EAAU;IACtG,MAAM,UAAU,GAAG,aAAa,CAAC,UAAU,CAAC,CAAC;IAC7C,IAAI,UAAU,KAAK,SAAS;QAAE,MAAM,IAAI,KAAK,CAAC,iDAAiD,CAAC,CAAC;IACjG,OAAO,UAAU,CAAC,QAAQ,CAAC,CAAC,MAAM,CAAC,UAAU,CAAC,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC;AAAA,CAC7D;AAED,MAAM,UAAU,+BAA+B,CAC9C,UAA+C,EACnB;IAC5B,OAAO;QACN,UAAU;QACV,WAAW,EAAE,6BAA6B,CAAC,UAAU,CAAC;KACtD,CAAC;AAAA,CACF","sourcesContent":["import { createHash } from \"node:crypto\";\nimport type { Api } from \"@earendil-works/pi-ai\";\n\nexport type ProviderExecutionMode =\n\t| \"builtin\"\n\t| \"serializable_overlay\"\n\t| \"provider_config_stream_simple\"\n\t| \"native_provider\";\n\nexport type ProviderExecutionKind =\n\t| \"builtin_provider\"\n\t| \"builtin_api\"\n\t| \"provider_config_stream_simple\"\n\t| \"native_provider\";\n\nexport type ProviderExecutionExecutor =\n\t| { kind: \"builtin_provider\"; id: string }\n\t| { kind: \"builtin_api\"; id: Api }\n\t| { kind: \"provider_config_stream_simple\"; id: string }\n\t| { kind: \"native_provider\"; id: string };\n\nexport interface ProviderExecutionContractDescriptor {\n\tversion: 1;\n\tmode: ProviderExecutionMode;\n\tproviderId: string;\n\tmodelId: string;\n\tapi: Api;\n\texecutor: ProviderExecutionExecutor;\n\toverlays: {\n\t\tmodelsJson: boolean;\n\t\textensionConfig: boolean;\n\t};\n\tpiServerCompatible: boolean;\n}\n\nexport interface ProviderExecutionContract {\n\tdescriptor: ProviderExecutionContractDescriptor;\n\tfingerprint: string;\n}\n\nfunction canonicalJson(value: unknown): string | undefined {\n\tif (Array.isArray(value)) {\n\t\treturn `[${value.map((item) => canonicalJson(item) ?? \"null\").join(\",\")}]`;\n\t}\n\tif (value !== null && typeof value === \"object\") {\n\t\tconst record = value as Record<string, unknown>;\n\t\tconst properties: string[] = [];\n\t\tfor (const key of Object.keys(record).sort()) {\n\t\t\tconst serialized = canonicalJson(record[key]);\n\t\t\tif (serialized !== undefined) properties.push(`${JSON.stringify(key)}:${serialized}`);\n\t\t}\n\t\treturn `{${properties.join(\",\")}}`;\n\t}\n\treturn JSON.stringify(value);\n}\n\nexport function hashProviderExecutionContract(descriptor: ProviderExecutionContractDescriptor): string {\n\tconst serialized = canonicalJson(descriptor);\n\tif (serialized === undefined) throw new Error(\"Failed to serialize provider execution contract\");\n\treturn createHash(\"sha256\").update(serialized).digest(\"hex\");\n}\n\nexport function createProviderExecutionContract(\n\tdescriptor: ProviderExecutionContractDescriptor,\n): ProviderExecutionContract {\n\treturn {\n\t\tdescriptor,\n\t\tfingerprint: hashProviderExecutionContract(descriptor),\n\t};\n}\n"]}