gsd-pi 2.80.0-dev.488219eb6 → 2.80.0-dev.4edec4620
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/resources/.managed-resources-content-hash +1 -1
- package/dist/resources/extensions/claude-code-cli/stream-adapter.js +11 -3
- package/dist/resources/extensions/gsd/auto-dashboard.js +18 -0
- package/dist/resources/extensions/gsd/bootstrap/register-hooks.js +21 -10
- package/dist/resources/extensions/gsd/bootstrap/write-gate.js +19 -2
- package/dist/resources/extensions/gsd/guided-flow.js +6 -0
- package/dist/resources/extensions/gsd/health-widget.js +3 -0
- package/dist/tsconfig.extensions.tsbuildinfo +1 -1
- package/dist/web/standalone/.next/BUILD_ID +1 -1
- package/dist/web/standalone/.next/app-path-routes-manifest.json +10 -10
- package/dist/web/standalone/.next/build-manifest.json +2 -2
- package/dist/web/standalone/.next/prerender-manifest.json +3 -3
- package/dist/web/standalone/.next/server/app/_global-error.html +1 -1
- package/dist/web/standalone/.next/server/app/_global-error.rsc +1 -1
- package/dist/web/standalone/.next/server/app/_global-error.segments/_full.segment.rsc +1 -1
- package/dist/web/standalone/.next/server/app/_global-error.segments/_global-error/__PAGE__.segment.rsc +1 -1
- package/dist/web/standalone/.next/server/app/_global-error.segments/_global-error.segment.rsc +1 -1
- package/dist/web/standalone/.next/server/app/_global-error.segments/_head.segment.rsc +1 -1
- package/dist/web/standalone/.next/server/app/_global-error.segments/_index.segment.rsc +1 -1
- package/dist/web/standalone/.next/server/app/_global-error.segments/_tree.segment.rsc +1 -1
- package/dist/web/standalone/.next/server/app/_not-found.html +1 -1
- package/dist/web/standalone/.next/server/app/_not-found.rsc +1 -1
- package/dist/web/standalone/.next/server/app/_not-found.segments/_full.segment.rsc +1 -1
- package/dist/web/standalone/.next/server/app/_not-found.segments/_head.segment.rsc +1 -1
- package/dist/web/standalone/.next/server/app/_not-found.segments/_index.segment.rsc +1 -1
- package/dist/web/standalone/.next/server/app/_not-found.segments/_not-found/__PAGE__.segment.rsc +1 -1
- package/dist/web/standalone/.next/server/app/_not-found.segments/_not-found.segment.rsc +1 -1
- package/dist/web/standalone/.next/server/app/_not-found.segments/_tree.segment.rsc +1 -1
- package/dist/web/standalone/.next/server/app/index.html +1 -1
- package/dist/web/standalone/.next/server/app/index.rsc +1 -1
- package/dist/web/standalone/.next/server/app/index.segments/__PAGE__.segment.rsc +1 -1
- package/dist/web/standalone/.next/server/app/index.segments/_full.segment.rsc +1 -1
- package/dist/web/standalone/.next/server/app/index.segments/_head.segment.rsc +1 -1
- package/dist/web/standalone/.next/server/app/index.segments/_index.segment.rsc +1 -1
- package/dist/web/standalone/.next/server/app/index.segments/_tree.segment.rsc +1 -1
- package/dist/web/standalone/.next/server/app-paths-manifest.json +10 -10
- package/dist/web/standalone/.next/server/middleware-build-manifest.js +1 -1
- package/dist/web/standalone/.next/server/pages/404.html +1 -1
- package/dist/web/standalone/.next/server/pages/500.html +1 -1
- package/dist/web/standalone/.next/server/server-reference-manifest.json +1 -1
- package/package.json +1 -1
- package/packages/pi-agent-core/tsconfig.tsbuildinfo +1 -1
- package/packages/pi-ai/dist/types.d.ts +2 -0
- package/packages/pi-ai/dist/types.d.ts.map +1 -1
- package/packages/pi-ai/dist/types.js.map +1 -1
- package/packages/pi-ai/src/types.ts +3 -0
- package/packages/pi-ai/tsconfig.tsbuildinfo +1 -1
- package/packages/pi-coding-agent/dist/core/agent-session-tool-refresh.test.js +12 -1
- package/packages/pi-coding-agent/dist/core/agent-session-tool-refresh.test.js.map +1 -1
- package/packages/pi-coding-agent/dist/core/agent-session.d.ts +5 -0
- package/packages/pi-coding-agent/dist/core/agent-session.d.ts.map +1 -1
- package/packages/pi-coding-agent/dist/core/agent-session.js +8 -0
- package/packages/pi-coding-agent/dist/core/agent-session.js.map +1 -1
- package/packages/pi-coding-agent/dist/core/sdk.d.ts.map +1 -1
- package/packages/pi-coding-agent/dist/core/sdk.js +7 -2
- package/packages/pi-coding-agent/dist/core/sdk.js.map +1 -1
- package/packages/pi-coding-agent/src/core/agent-session-tool-refresh.test.ts +15 -1
- package/packages/pi-coding-agent/src/core/agent-session.ts +11 -0
- package/packages/pi-coding-agent/src/core/sdk.ts +7 -1
- package/packages/pi-coding-agent/tsconfig.tsbuildinfo +1 -1
- package/src/resources/extensions/claude-code-cli/stream-adapter.ts +12 -3
- package/src/resources/extensions/claude-code-cli/tests/stream-adapter.test.ts +41 -0
- package/src/resources/extensions/gsd/auto-dashboard.ts +20 -0
- package/src/resources/extensions/gsd/bootstrap/register-hooks.ts +20 -10
- package/src/resources/extensions/gsd/bootstrap/write-gate.ts +19 -2
- package/src/resources/extensions/gsd/guided-flow.ts +6 -0
- package/src/resources/extensions/gsd/health-widget.ts +3 -0
- package/src/resources/extensions/gsd/tests/tui-header-lifecycle.test.ts +210 -0
- package/src/resources/extensions/gsd/tests/write-gate.test.ts +40 -1
- /package/dist/web/standalone/.next/static/{G68KoLv5claox_Dyd4pZn → eeMbUJZnoHp7l3SZHeXY9}/_buildManifest.js +0 -0
- /package/dist/web/standalone/.next/static/{G68KoLv5claox_Dyd4pZn → eeMbUJZnoHp7l3SZHeXY9}/_ssgManifest.js +0 -0
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"sdk.d.ts","sourceRoot":"","sources":["../../src/core/sdk.ts"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"sdk.d.ts","sourceRoot":"","sources":["../../src/core/sdk.ts"],"names":[],"mappings":"AAeA;;;;GAIG;AACH,qBAAa,uBAAwB,SAAQ,KAAK;IACjD,QAAQ,CAAC,IAAI,EAAG,eAAe,CAAU;IACzC,6FAA6F;IAC7F,QAAQ,CAAC,YAAY,EAAE,MAAM,GAAG,SAAS,CAAC;gBAE9B,QAAQ,EAAE,MAAM,EAAE,YAAY,CAAC,EAAE,MAAM;CAQnD;AAED,wBAAgB,sBAAsB,CACrC,aAAa,EAAE,IAAI,CAAC,aAAa,EAAE,wBAAwB,CAAC,EAC5D,K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EACX,YAAY,EACZ,uBAAuB,EACvB,gBAAgB,EAChB,gBAAgB,EAChB,gBAAgB,EAChB,oBAAoB,EACpB,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,EAEN,QAAQ,EACR,QAAQ,EACR,QAAQ,EACR,SAAS,EACT,QAAQ,EACR,QAAQ,EACR,MAAM,EACN,WAAW,EACX,aAAa,EACb,QAAQ,IAAI,eAAe,EAE3B,iBAAiB,EACjB,mBAAmB,EACnB,cAAc,EACd,cAAc,EACd,cAAc,EACd,eAAe,EACf,cAAc,EACd,cAAc,EACd,YAAY,EAEZ,mBAAmB,EACnB,gBAAgB,EAChB,gBAAgB,EAChB,yBAAyB,EACzB,sBAAsB,EACtB,sBAAsB,GACtB,CAAC;AAQF;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAkCG;AACH,wBAAsB,kBAAkB,CAAC,OAAO,GAAE,yBAA8B,GAAG,OAAO,CAAC,wBAAwB,CAAC,CAyWnH"}
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
// GSD2 - Coding agent session factory and runtime wiring
|
|
1
2
|
import { existsSync } from "node:fs";
|
|
2
3
|
import { join } from "node:path";
|
|
3
4
|
/**
|
|
@@ -262,6 +263,7 @@ export async function createAgentSession(options = {}) {
|
|
|
262
263
|
});
|
|
263
264
|
};
|
|
264
265
|
const extensionRunnerRef = {};
|
|
266
|
+
const workspaceRootRef = { current: cwd };
|
|
265
267
|
agent = new Agent({
|
|
266
268
|
initialState: {
|
|
267
269
|
systemPrompt: "",
|
|
@@ -318,9 +320,11 @@ export async function createAgentSession(options = {}) {
|
|
|
318
320
|
if (currentModel.provider !== "claude-code")
|
|
319
321
|
return undefined;
|
|
320
322
|
const runner = extensionRunnerRef.current;
|
|
321
|
-
if (!runner?.hasUI())
|
|
322
|
-
return
|
|
323
|
+
if (!runner?.hasUI()) {
|
|
324
|
+
return { cwd: workspaceRootRef.current };
|
|
325
|
+
}
|
|
323
326
|
return {
|
|
327
|
+
cwd: workspaceRootRef.current,
|
|
324
328
|
extensionUIContext: runner.getUIContext(),
|
|
325
329
|
};
|
|
326
330
|
},
|
|
@@ -448,6 +452,7 @@ export async function createAgentSession(options = {}) {
|
|
|
448
452
|
modelRegistry,
|
|
449
453
|
initialActiveToolNames,
|
|
450
454
|
extensionRunnerRef,
|
|
455
|
+
workspaceRootRef,
|
|
451
456
|
isClaudeCodeReady: options.isClaudeCodeReady,
|
|
452
457
|
});
|
|
453
458
|
const extensionsResult = resourceLoader.getExtensions();
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"sdk.js","sourceRoot":"","sources":["../../src/core/sdk.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,MAAM,SAAS,CAAC;AACrC,OAAO,EAAE,IAAI,EAAE,MAAM,WAAW,CAAC;AAEjC;;;;;GAKG;AACH,SAAS,wBAAwB;IAChC,MAAM,QAAQ,GAAG,CAAC,OAAO,CAAC,GAAG,CAAC,IAAI,IAAI,EAAE,CAAC,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC;IACrD,OAAO,QAAQ,CAAC,IAAI,CAAC,CAAC,GAAG,EAAE,EAAE,CAAC,GAAG,IAAI,UAAU,CAAC,IAAI,CAAC,GAAG,EAAE,QAAQ,CAAC,CAAC,CAAC,CAAC;AACvE,CAAC;AAED;;;;GAIG;AACH,MAAM,OAAO,uBAAwB,SAAQ,KAAK;IAKjD,YAAY,QAAgB,EAAE,YAAqB;QAClD,KAAK,CACJ,wBAAwB,QAAQ,8BAA8B;YAC7D,wEAAwE,CACzE,CAAC;QARM,SAAI,GAAG,eAAwB,CAAC;QASxC,IAAI,CAAC,IAAI,GAAG,yBAAyB,CAAC;QACt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O,CAAC,WAAW;QAChC,aAAa;QACb,sBAAsB;QACtB,kBAAkB;QAClB,iBAAiB,EAAE,OAAO,CAAC,iBAAiB;KAC5C,CAAC,CAAC;IACH,MAAM,gBAAgB,GAAG,cAAc,CAAC,aAAa,EAAE,CAAC;IAExD,OAAO;QACN,OAAO;QACP,gBAAgB;QAChB,oBAAoB;KACpB,CAAC;AACH,CAAC","sourcesContent":["import { existsSync } from \"node:fs\";\nimport { join } from \"node:path\";\n\n/**\n * Lightweight PATH scan for the `claude` binary — no subprocess, no network.\n * Mirrors the check in src/resources/extensions/gsd/doctor-providers.ts so the\n * legacy Anthropic OAuth self-heal path can only trigger when the user has a\n * working Claude Code CLI to fall back to.\n */\nfunction isClaudeCodeBinaryInPath(): boolean {\n\tconst pathDirs = (process.env.PATH ?? \"\").split(\":\");\n\treturn pathDirs.some((dir) => dir && existsSync(join(dir, \"claude\")));\n}\n\n/**\n * Structured error thrown when all credentials for a provider are in a\n * backoff window. Carries typed metadata so callers (e.g. the auto-loop)\n * can make informed retry decisions instead of string-matching the message.\n */\nexport class CredentialCooldownError extends Error {\n\treadonly code = \"AUTH_COOLDOWN\" as const;\n\t/** Milliseconds until the earliest credential becomes available, or undefined if unknown. */\n\treadonly retryAfterMs: number | undefined;\n\n\tconstructor(provider: string, retryAfterMs?: number) {\n\t\tsuper(\n\t\t\t`All credentials for \"${provider}\" are in a cooldown window. ` +\n\t\t\t\t`Please wait a moment and try again, or switch to a different provider.`,\n\t\t);\n\t\tthis.name = \"CredentialCooldownError\";\n\t\tthis.retryAfterMs = retryAfterMs;\n\t}\n}\n\nexport function canRestoreSessionModel(\n\tmodelRegistry: Pick<ModelRegistry, \"isProviderRequestReady\">,\n\tmodel: Model<any>,\n): boolean {\n\treturn modelRegistry.isProviderRequestReady(model.provider);\n}\n\nconst PROVIDER_TOOL_LIMITS: Record<string, number> = {\n\tgroq: 128,\n};\n\nfunction resolveProviderToolLimit(\n\tproviderCaps: ReturnType<typeof getProviderCapabilities>,\n\tprovider: string | undefined,\n): number {\n\tif (provider && PROVIDER_TOOL_LIMITS[provider]) {\n\t\treturn PROVIDER_TOOL_LIMITS[provider];\n\t}\n\treturn providerCaps.maxTools > 0 ? providerCaps.maxTools : 0;\n}\n\nexport function filterToolsForProviderRequest(\n\ttools: AgentTool[],\n\tmodel: Pick<Model<any>, \"api\" | \"provider\">,\n): { compatible: AgentTool[]; filtered: AgentTool[] } {\n\tconst providerCaps = getProviderCapabilities(model.api);\n\tif (!providerCaps.toolCalling) {\n\t\treturn { compatible: [], filtered: tools };\n\t}\n\n\tconst compatible: AgentTool[] = [];\n\tconst filtered: AgentTool[] = [];\n\tfor (const tool of tools) {\n\t\tconst compat = getToolCompatibility(tool.name);\n\t\tif (\n\t\t\t(compat?.producesImages && !providerCaps.imageToolResults) ||\n\t\t\tcompat?.schemaFeatures?.some((feature) => providerCaps.unsupportedSchemaFeatures.includes(feature))\n\t\t) {\n\t\t\tfiltered.push(tool);\n\t\t} else {\n\t\t\tcompatible.push(tool);\n\t\t}\n\t}\n\n\tconst toolLimit = resolveProviderToolLimit(providerCaps, model.provider);\n\tif (toolLimit > 0 && compatible.length > toolLimit) {\n\t\tfiltered.push(...compatible.splice(toolLimit));\n\t}\n\n\treturn { compatible, filtered };\n}\nimport { Agent, maybeLogProviderPayloadAudit, type AgentMessage, type AgentTool, type ThinkingLevel } from \"@gsd/pi-agent-core\";\nimport { getProviderCapabilities, type Message, type Model } from \"@gsd/pi-ai\";\nimport { getAgentDir, getDocsPath } from \"../config.js\";\nimport { AgentSession } from \"./agent-session.js\";\nimport { AuthStorage } from \"./auth-storage.js\";\nimport { DEFAULT_THINKING_LEVEL } from \"./defaults.js\";\nimport type { ExtensionRunner, LoadExtensionsResult, ToolDefinition } from \"./extensions/index.js\";\nimport { convertToLlm } from \"./messages.js\";\nimport { ModelRegistry } from \"./model-registry.js\";\nimport { findInitialModel } from \"./model-resolver.js\";\nimport type { ResourceLoader } from \"./resource-loader.js\";\nimport { DefaultResourceLoader } from \"./resource-loader.js\";\nimport { SessionManager } from \"./session-manager.js\";\nimport { SettingsManager } from \"./settings-manager.js\";\nimport { time } from \"./timings.js\";\nimport {\n\tallTools,\n\tbashTool,\n\tcodingTools,\n\tcreateBashTool,\n\tcreateCodingTools,\n\tcreateEditTool,\n\tcreateFindTool,\n\tcreateGrepTool,\n\tcreateLsTool,\n\tcreateReadOnlyTools,\n\tcreateReadTool,\n\tcreateWriteTool,\n\teditTool,\n\tfindTool,\n\tgrepTool,\n\thashlineCodingTools,\n\thashlineEditTool,\n\thashlineReadTool,\n\tcreateHashlineCodingTools,\n\tcreateHashlineEditTool,\n\tcreateHashlineReadTool,\n\tlsTool,\n\treadOnlyTools,\n\treadTool,\n\ttype Tool,\n\ttype ToolName,\n\twriteTool,\n} from \"./tools/index.js\";\nimport { getToolCompatibility } from \"./tools/tool-compatibility-registry.js\";\n\nexport function getAdjustToolSetRequestCustomMessages(\n\tmessages: readonly AgentMessage[] | undefined,\n): Array<{ index: number; customType: string }> {\n\tif (!messages) return [];\n\tconst requestMessages: Array<{ index: number; customType: string }> = [];\n\tfor (let index = messages.length - 1; index >= 0; index--) {\n\t\tconst message = messages[index] as { role?: unknown; customType?: unknown };\n\t\tif (message?.role === \"assistant\") break;\n\t\tif (message?.role === \"custom\" && typeof message.customType === \"string\") {\n\t\t\trequestMessages.push({ index, customType: message.customType });\n\t\t}\n\t}\n\treturn requestMessages.reverse();\n}\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/** Auth storage for credentials. Default: AuthStorage.create(agentDir/auth.json) */\n\tauthStorage?: AuthStorage;\n\t/** Model registry. Default: new ModelRegistry(authStorage, agentDir/models.json) */\n\tmodelRegistry?: ModelRegistry;\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/** Built-in tools to use. Default: codingTools [read, bash, edit, write] */\n\ttools?: Tool[];\n\t/** Custom tools to register (in addition to built-in tools). */\n\tcustomTools?: ToolDefinition[];\n\t/**\n\t * Additional tool names to activate after extensions/MCP servers register.\n\t * Names that are not registered by any extension are silently ignored\n\t * by AgentSession.setActiveToolsByName.\n\t *\n\t * Used by --tools to forward names that don't match a built-in (likely\n\t * extension- or MCP-provided), so subagents whose frontmatter declares\n\t * extension tools don't end up with an empty tool list.\n\t */\n\textraActiveToolNames?: string[];\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\n\t/** Optional: check if the claude-code CLI provider is ready (installed + authed).\n\t * Passed to RetryHandler for third-party block recovery (#3772). */\n\tisClaudeCodeReady?: () => 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 type {\n\tExtensionAPI,\n\tExtensionCommandContext,\n\tExtensionContext,\n\tExtensionFactory,\n\tSlashCommandInfo,\n\tSlashCommandLocation,\n\tSlashCommandSource,\n\tToolDefinition,\n} from \"./extensions/index.js\";\nexport type { PromptTemplate } from \"./prompt-templates.js\";\nexport type { Skill } from \"./skills.js\";\nexport type { Tool } from \"./tools/index.js\";\n\nexport {\n\t// Pre-built tools (use process.cwd())\n\treadTool,\n\tbashTool,\n\teditTool,\n\twriteTool,\n\tgrepTool,\n\tfindTool,\n\tlsTool,\n\tcodingTools,\n\treadOnlyTools,\n\tallTools as allBuiltInTools,\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\t// Hashline edit mode\n\thashlineCodingTools,\n\thashlineEditTool,\n\thashlineReadTool,\n\tcreateHashlineCodingTools,\n\tcreateHashlineEditTool,\n\tcreateHashlineReadTool,\n};\n\n// Helper Functions\n\nfunction getDefaultAgentDir(): string {\n\treturn getAgentDir();\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 '@gsd/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: [readTool, bashTool],\n * resourceLoader: loader,\n * sessionManager: SessionManager.inMemory(),\n * });\n * ```\n */\nexport async function createAgentSession(options: CreateAgentSessionOptions = {}): Promise<CreateAgentSessionResult> {\n\tconst cwd = options.cwd ?? process.cwd();\n\tconst agentDir = options.agentDir ?? getDefaultAgentDir();\n\tlet resourceLoader = options.resourceLoader;\n\n\t// Use provided or create AuthStorage and ModelRegistry\n\tconst authPath = options.agentDir ? join(agentDir, \"auth.json\") : undefined;\n\tconst modelsPath = options.agentDir ? join(agentDir, \"models.json\") : undefined;\n\tconst authStorage = options.authStorage ?? AuthStorage.create(authPath);\n\tconst modelRegistry = options.modelRegistry ?? new ModelRegistry(authStorage, modelsPath);\n\n\tconst settingsManager = options.settingsManager ?? SettingsManager.create(cwd, agentDir);\n\tconst sessionManager = options.sessionManager ?? SessionManager.create(cwd);\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// Flush provider registrations queued during extension loading so that\n\t// extension models (e.g. pi-claude-cli) are visible in the registry before\n\t// findInitialModel() runs. bindCore() repeats this flush as a safety net\n\t// for any late-arriving registrations.\n\tconst { runtime: extensionRuntime } = resourceLoader.getExtensions();\n\tfor (const { name, config } of extensionRuntime.pendingProviderRegistrations) {\n\t\tmodelRegistry.registerProvider(name, config);\n\t}\n\textensionRuntime.pendingProviderRegistrations = [];\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 = modelRegistry.find(existingSession.model.provider, existingSession.model.modelId);\n\t\t\tif (restoredModel && canRestoreSessionModel(modelRegistry, restoredModel)) {\n\t\t\t\tmodel = restoredModel;\n\t\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// Flush extension provider registrations so extension-provided models (e.g. claude-code/*)\n\t// are available in the registry before model resolution. Without this, findInitialModel()\n\t// cannot find extension models and falls back to built-in providers (#3534).\n\tconst extensionsForModelResolution = resourceLoader.getExtensions();\n\tfor (const { name, config } of extensionsForModelResolution.runtime.pendingProviderRegistrations) {\n\t\tmodelRegistry.registerProvider(name, config);\n\t}\n\t// Clear the queue so bindCore() doesn't re-register the same providers.\n\textensionsForModelResolution.runtime.pendingProviderRegistrations = [];\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\tmodelRegistry,\n\t\t});\n\t\tmodel = result.model;\n\t\tif (!model) {\n\t\t\tmodelFallbackMessage = `No models available. Use /login or set an API key environment variable. See ${join(getDocsPath(), \"providers.md\")}. Then use /model to select a model.`;\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 || !model.reasoning) {\n\t\tthinkingLevel = \"off\";\n\t}\n\n\tconst editMode = settingsManager.getEditMode();\n\tconst defaultActiveToolNames: ToolName[] = editMode === \"hashline\"\n\t\t? [\"hashline_read\", \"bash\", \"hashline_edit\", \"write\", \"lsp\"]\n\t\t: [\"read\", \"bash\", \"edit\", \"write\", \"lsp\"];\n\tconst builtinActiveToolNames: ToolName[] = options.tools\n\t\t? options.tools.map((t) => t.name).filter((n): n is ToolName => n in allTools)\n\t\t: defaultActiveToolNames;\n\t// Merge in extension/MCP tool names from --tools that didn't match a built-in.\n\t// AgentSession.setActiveToolsByName silently drops names that aren't in the\n\t// registry, so unknown names are harmless here.\n\tconst initialActiveToolNames: string[] = options.extraActiveToolNames\n\t\t? [...builtinActiveToolNames, ...options.extraActiveToolNames]\n\t\t: builtinActiveToolNames;\n\n\tlet agent: Agent;\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\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\tonPayload: async (payload, currentModel) => {\n\t\t\tconst runner = extensionRunnerRef.current;\n\t\t\tif (!runner?.hasHandlers(\"before_provider_request\")) {\n\t\t\t\tmaybeLogProviderPayloadAudit(payload, \"before_provider_request:unchanged\");\n\t\t\t\treturn payload;\n\t\t\t}\n\t\t\tconst nextPayload = await runner.emitBeforeProviderRequest(payload, currentModel);\n\t\t\tmaybeLogProviderPayloadAudit(nextPayload, \"before_provider_request:after\");\n\t\t\treturn nextPayload;\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\tfilterTools: async (tools, _signal, messages) => {\n\t\t\tconst currentModel = agent.state.activeInferenceModel ?? agent.state.model ?? model;\n\t\t\tif (!currentModel) return tools;\n\t\t\tconst providerFiltered = filterToolsForProviderRequest(tools, currentModel);\n\t\t\tconst runner = extensionRunnerRef.current;\n\t\t\tif (!runner?.hasHandlers(\"adjust_tool_set\")) return providerFiltered.compatible;\n\t\t\tconst result = await runner.emitAdjustToolSet({\n\t\t\t\tselectedModelApi: currentModel.api,\n\t\t\t\tselectedModelProvider: currentModel.provider,\n\t\t\t\tselectedModelId: currentModel.id,\n\t\t\t\tactiveToolNames: providerFiltered.compatible.map((tool) => tool.name),\n\t\t\t\tfilteredTools: providerFiltered.filtered.map((tool) => tool.name),\n\t\t\t\trequestCustomMessages: getAdjustToolSetRequestCustomMessages(messages),\n\t\t\t});\n\t\t\tif (!result?.toolNames) return providerFiltered.compatible;\n\t\t\tconst allowedNames = new Set(result.toolNames);\n\t\t\treturn providerFiltered.compatible.filter((tool) => allowedNames.has(tool.name));\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.getRetrySettings().maxDelayMs,\n\t\texternalToolExecution: (m) => modelRegistry.getProviderAuthMode(m.provider) === \"externalCli\",\n\t\tgetProviderOptions: async (currentModel) => {\n\t\t\tif (currentModel.provider !== \"claude-code\") return undefined;\n\t\t\tconst runner = extensionRunnerRef.current;\n\t\t\tif (!runner?.hasUI()) return undefined;\n\t\t\treturn {\n\t\t\t\textensionUIContext: runner.getUIContext(),\n\t\t\t};\n\t\t},\n\t\tgetApiKey: async (provider) => {\n\t\t\t// Use the provider argument from the in-flight request;\n\t\t\t// agent.state.model may already be switched mid-turn.\n\t\t\tconst resolvedProvider = provider || agent.state.model?.provider;\n\t\t\tif (!resolvedProvider) {\n\t\t\t\tthrow new Error(\"No model selected\");\n\t\t\t}\n\t\t\tconst authMode = modelRegistry.getProviderAuthMode(resolvedProvider);\n\t\t\tif (authMode === \"externalCli\" || authMode === \"none\") {\n\t\t\t\treturn undefined;\n\t\t\t}\n\n\t\t\t// Retry key resolution with backoff to handle transient network failures\n\t\t\t// (e.g., OAuth token refresh failing due to brief connectivity loss).\n\t\t\t// When credentials are in a cooldown window (e.g., after a 429), wait\n\t\t\t// for the backoff to expire instead of using fixed delays that are\n\t\t\t// shorter than the cooldown duration.\n\t\t\tconst maxAttempts = 3;\n\t\t\tconst baseDelayMs = 2000;\n\t\t\tconst maxCooldownWaitMs = 60_000; // Don't wait longer than 60s (skip quota-exhausted 30min backoffs)\n\t\t\tfor (let attempt = 1; attempt <= maxAttempts; attempt++) {\n\t\t\t\tconst key = await modelRegistry.getApiKeyForProvider(resolvedProvider);\n\t\t\t\tif (key) return key;\n\n\t\t\t\t// On the last attempt, fall through to error handling below\n\t\t\t\tif (attempt >= maxAttempts) break;\n\n\t\t\t\t// Only retry if credentials exist (network issue) — no point retrying\n\t\t\t\t// when there are genuinely no credentials configured.\n\t\t\t\tconst hasAuth = modelRegistry.authStorage.hasAuth(resolvedProvider);\n\t\t\t\tconst model = agent.state.model;\n\t\t\t\tconst isOAuth = model && modelRegistry.isUsingOAuth(model);\n\t\t\t\tif (!hasAuth && !isOAuth) break;\n\n\t\t\t\t// If credentials are in a cooldown window, wait for the earliest\n\t\t\t\t// one to expire rather than using a fixed delay that's too short.\n\t\t\t\tconst backoffExpiry = modelRegistry.authStorage.getEarliestBackoffExpiry(resolvedProvider);\n\t\t\t\tif (backoffExpiry !== undefined) {\n\t\t\t\t\tconst waitMs = backoffExpiry - Date.now() + 500; // 500ms buffer\n\t\t\t\t\tif (waitMs > 0 && waitMs <= maxCooldownWaitMs) {\n\t\t\t\t\t\tawait new Promise(resolve => setTimeout(resolve, waitMs));\n\t\t\t\t\t\tcontinue; // Retry immediately after cooldown clears\n\t\t\t\t\t}\n\t\t\t\t\tif (waitMs > maxCooldownWaitMs) {\n\t\t\t\t\t\tbreak; // Quota-exhausted or very long backoff — don't block\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\t// Standard exponential backoff for non-cooldown transient failures\n\t\t\t\tawait new Promise(resolve => setTimeout(resolve, baseDelayMs * attempt));\n\t\t\t}\n\n\t\t\t// All retries exhausted — throw descriptive error.\n\t\t\t// Check if credentials exist but are temporarily in a backoff window\n\t\t\t// (e.g., after a 429). This message intentionally avoids phrases like\n\t\t\t// \"rate limit\" / \"429\" to prevent isRetryableError() from re-entering\n\t\t\t// the retry handler and creating cascading error entries (#3429).\n\t\t\tconst hasAuth = modelRegistry.authStorage.hasAuth(resolvedProvider);\n\t\t\tif (hasAuth) {\n\t\t\t\t// Anthropic OAuth was removed in v2.74.0 for TOS compliance (#3952).\n\t\t\t\t// Users who upgraded from an older version may still have OAuth\n\t\t\t\t// credentials in auth.json that will never resolve to a valid API key.\n\t\t\t\tif (\n\t\t\t\t\tresolvedProvider === \"anthropic\" &&\n\t\t\t\t\tmodelRegistry.authStorage.hasLegacyOAuthCredential(resolvedProvider)\n\t\t\t\t) {\n\t\t\t\t\t// Self-heal: strip the stale oauth entry so hasAuth() stops lying\n\t\t\t\t\t// about anthropic being configured. This preserves any api_key\n\t\t\t\t\t// credentials alongside it.\n\t\t\t\t\tconst removed = modelRegistry.authStorage.removeLegacyOAuthCredential(resolvedProvider);\n\t\t\t\t\tif (removed) {\n\t\t\t\t\t\tconsole.warn(\n\t\t\t\t\t\t\t`[auth] Removed unsupported Anthropic OAuth credential from auth.json (#3952).`,\n\t\t\t\t\t\t);\n\t\t\t\t\t}\n\t\t\t\t\tif (isClaudeCodeBinaryInPath()) {\n\t\t\t\t\t\tthrow new Error(\n\t\t\t\t\t\t\t`Removed stale Anthropic OAuth credential (OAuth support removed in v2.74.0). ` +\n\t\t\t\t\t\t\t\t`Your current model's provider is set to \"anthropic\" but the local Claude Code CLI ` +\n\t\t\t\t\t\t\t\t`is available — switch the model's provider to \"claude-code\" in your preferences ` +\n\t\t\t\t\t\t\t\t`to use it, or set ANTHROPIC_API_KEY to continue with the Anthropic API directly.`,\n\t\t\t\t\t\t);\n\t\t\t\t\t}\n\t\t\t\t\tthrow new Error(\n\t\t\t\t\t\t`Removed stale Anthropic OAuth credential (OAuth support removed in v2.74.0). ` +\n\t\t\t\t\t\t\t`Set ANTHROPIC_API_KEY, run '/login' and paste an API key, or switch to a different provider.`,\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t\tconst expiry = modelRegistry.authStorage.getEarliestBackoffExpiry(resolvedProvider);\n\t\t\t\tconst retryAfterMs = expiry !== undefined ? Math.max(0, expiry - Date.now()) : undefined;\n\t\t\t\tthrow new CredentialCooldownError(resolvedProvider, retryAfterMs);\n\t\t\t}\n\t\t\tconst model = agent.state.model;\n\t\t\tconst isOAuth = model && modelRegistry.isUsingOAuth(model);\n\t\t\tif (isOAuth) {\n\t\t\t\t// If credentials exist but are all in a backoff window (quota / rate-limit),\n\t\t\t\t// surface a specific message instead of the misleading \"Authentication failed\".\n\t\t\t\tif (modelRegistry.authStorage.areAllCredentialsBackedOff(resolvedProvider)) {\n\t\t\t\t\tconst expiry = modelRegistry.authStorage.getEarliestBackoffExpiry(resolvedProvider);\n\t\t\t\t\tconst retryAfterMs = expiry !== undefined ? Math.max(0, expiry - Date.now()) : undefined;\n\t\t\t\t\tthrow new CredentialCooldownError(resolvedProvider, retryAfterMs);\n\t\t\t\t}\n\t\t\t\tthrow new Error(\n\t\t\t\t\t`Authentication failed for \"${resolvedProvider}\". ` +\n\t\t\t\t\t\t`Credentials may have expired or network is unavailable. ` +\n\t\t\t\t\t\t`Run '/login ${resolvedProvider}' to re-authenticate.`,\n\t\t\t\t);\n\t\t\t}\n\t\t\tthrow new Error(\n\t\t\t\t`No API key found for \"${resolvedProvider}\". ` +\n\t\t\t\t\t`Set an API key environment variable or run '/login ${resolvedProvider}'.`,\n\t\t\t);\n\t\t},\n\t});\n\n\t// Restore messages if session has existing data\n\tif (hasExistingSession) {\n\t\tagent.replaceMessages(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\tmodelRegistry,\n\t\tinitialActiveToolNames,\n\t\textensionRunnerRef,\n\t\tisClaudeCodeReady: options.isClaudeCodeReady,\n\t});\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,yDAAyD;AACzD,OAAO,EAAE,UAAU,EAAE,MAAM,SAAS,CAAC;AACrC,OAAO,EAAE,IAAI,EAAE,MAAM,WAAW,CAAC;AAEjC;;;;;GAKG;AACH,SAAS,wBAAwB;IAChC,MAAM,QAAQ,GAAG,CAAC,OAAO,CAAC,GAAG,CAAC,IAAI,IAAI,EAAE,CAAC,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC;IACrD,OAAO,QAAQ,CAAC,IAAI,CAAC,CAAC,GAAG,EAAE,EAAE,CAAC,GAAG,IAAI,UAAU,CAAC,IAAI,CAAC,GAAG,EAAE,QAAQ,CAAC,CAAC,CAAC,CAAC;AACvE,CAAC;AAED;;;;GAIG;AACH,MAAM,OAAO,uBAAwB,SAAQ,KAAK;IAKjD,YAAY,QAAgB,EAAE,YAAqB;QAClD,KAAK,CACJ,wBAAwB,QAAQ,8BAA8B;YAC7D,wEAAwE,CACzE,CAAC;QARM,SAAI,GAAG,eAAwB,CAAC;QASxC,IAAI,CAAC,IAAI,GAAG,yBAAyB,CAAC;QACtC,IAAI,CAAC,YAAY,GAAG,YAAY,CAAC;IAClC,CAAC;CACD;AAED,MAAM,UAAU,sBAAsB,CACrC,aAA4D,EAC5D,KAAiB;IAEjB,OAAO,aAAa,CAAC,sBAAsB,CAAC,KAAK,CAAC,QAAQ,CAAC,CAAC;AAC7D,CAAC;AAED,MAAM,oBAAoB,GAA2B;IACpD,IAAI,EAAE,GAAG;CACT,CAAC;AAEF,SAAS,wBAAwB,CAChC,YAAwD,EACxD,QAA4B;IAE5B,IAAI,QAAQ,IAAI,oBAAoB,CAAC,QAAQ,CAAC,EAAE,CAAC;QAChD,OAAO,oBAAoB,CA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AChB,oBAAoB;KACpB,CAAC;AACH,CAAC","sourcesContent":["// GSD2 - Coding agent session factory and runtime wiring\nimport { existsSync } from \"node:fs\";\nimport { join } from \"node:path\";\n\n/**\n * Lightweight PATH scan for the `claude` binary — no subprocess, no network.\n * Mirrors the check in src/resources/extensions/gsd/doctor-providers.ts so the\n * legacy Anthropic OAuth self-heal path can only trigger when the user has a\n * working Claude Code CLI to fall back to.\n */\nfunction isClaudeCodeBinaryInPath(): boolean {\n\tconst pathDirs = (process.env.PATH ?? \"\").split(\":\");\n\treturn pathDirs.some((dir) => dir && existsSync(join(dir, \"claude\")));\n}\n\n/**\n * Structured error thrown when all credentials for a provider are in a\n * backoff window. Carries typed metadata so callers (e.g. the auto-loop)\n * can make informed retry decisions instead of string-matching the message.\n */\nexport class CredentialCooldownError extends Error {\n\treadonly code = \"AUTH_COOLDOWN\" as const;\n\t/** Milliseconds until the earliest credential becomes available, or undefined if unknown. */\n\treadonly retryAfterMs: number | undefined;\n\n\tconstructor(provider: string, retryAfterMs?: number) {\n\t\tsuper(\n\t\t\t`All credentials for \"${provider}\" are in a cooldown window. ` +\n\t\t\t\t`Please wait a moment and try again, or switch to a different provider.`,\n\t\t);\n\t\tthis.name = \"CredentialCooldownError\";\n\t\tthis.retryAfterMs = retryAfterMs;\n\t}\n}\n\nexport function canRestoreSessionModel(\n\tmodelRegistry: Pick<ModelRegistry, \"isProviderRequestReady\">,\n\tmodel: Model<any>,\n): boolean {\n\treturn modelRegistry.isProviderRequestReady(model.provider);\n}\n\nconst PROVIDER_TOOL_LIMITS: Record<string, number> = {\n\tgroq: 128,\n};\n\nfunction resolveProviderToolLimit(\n\tproviderCaps: ReturnType<typeof getProviderCapabilities>,\n\tprovider: string | undefined,\n): number {\n\tif (provider && PROVIDER_TOOL_LIMITS[provider]) {\n\t\treturn PROVIDER_TOOL_LIMITS[provider];\n\t}\n\treturn providerCaps.maxTools > 0 ? providerCaps.maxTools : 0;\n}\n\nexport function filterToolsForProviderRequest(\n\ttools: AgentTool[],\n\tmodel: Pick<Model<any>, \"api\" | \"provider\">,\n): { compatible: AgentTool[]; filtered: AgentTool[] } {\n\tconst providerCaps = getProviderCapabilities(model.api);\n\tif (!providerCaps.toolCalling) {\n\t\treturn { compatible: [], filtered: tools };\n\t}\n\n\tconst compatible: AgentTool[] = [];\n\tconst filtered: AgentTool[] = [];\n\tfor (const tool of tools) {\n\t\tconst compat = getToolCompatibility(tool.name);\n\t\tif (\n\t\t\t(compat?.producesImages && !providerCaps.imageToolResults) ||\n\t\t\tcompat?.schemaFeatures?.some((feature) => providerCaps.unsupportedSchemaFeatures.includes(feature))\n\t\t) {\n\t\t\tfiltered.push(tool);\n\t\t} else {\n\t\t\tcompatible.push(tool);\n\t\t}\n\t}\n\n\tconst toolLimit = resolveProviderToolLimit(providerCaps, model.provider);\n\tif (toolLimit > 0 && compatible.length > toolLimit) {\n\t\tfiltered.push(...compatible.splice(toolLimit));\n\t}\n\n\treturn { compatible, filtered };\n}\nimport { Agent, maybeLogProviderPayloadAudit, type AgentMessage, type AgentTool, type ThinkingLevel } from \"@gsd/pi-agent-core\";\nimport { getProviderCapabilities, type Message, type Model } from \"@gsd/pi-ai\";\nimport { getAgentDir, getDocsPath } from \"../config.js\";\nimport { AgentSession } from \"./agent-session.js\";\nimport { AuthStorage } from \"./auth-storage.js\";\nimport { DEFAULT_THINKING_LEVEL } from \"./defaults.js\";\nimport type { ExtensionRunner, LoadExtensionsResult, ToolDefinition } from \"./extensions/index.js\";\nimport { convertToLlm } from \"./messages.js\";\nimport { ModelRegistry } from \"./model-registry.js\";\nimport { findInitialModel } from \"./model-resolver.js\";\nimport type { ResourceLoader } from \"./resource-loader.js\";\nimport { DefaultResourceLoader } from \"./resource-loader.js\";\nimport { SessionManager } from \"./session-manager.js\";\nimport { SettingsManager } from \"./settings-manager.js\";\nimport { time } from \"./timings.js\";\nimport {\n\tallTools,\n\tbashTool,\n\tcodingTools,\n\tcreateBashTool,\n\tcreateCodingTools,\n\tcreateEditTool,\n\tcreateFindTool,\n\tcreateGrepTool,\n\tcreateLsTool,\n\tcreateReadOnlyTools,\n\tcreateReadTool,\n\tcreateWriteTool,\n\teditTool,\n\tfindTool,\n\tgrepTool,\n\thashlineCodingTools,\n\thashlineEditTool,\n\thashlineReadTool,\n\tcreateHashlineCodingTools,\n\tcreateHashlineEditTool,\n\tcreateHashlineReadTool,\n\tlsTool,\n\treadOnlyTools,\n\treadTool,\n\ttype Tool,\n\ttype ToolName,\n\twriteTool,\n} from \"./tools/index.js\";\nimport { getToolCompatibility } from \"./tools/tool-compatibility-registry.js\";\n\nexport function getAdjustToolSetRequestCustomMessages(\n\tmessages: readonly AgentMessage[] | undefined,\n): Array<{ index: number; customType: string }> {\n\tif (!messages) return [];\n\tconst requestMessages: Array<{ index: number; customType: string }> = [];\n\tfor (let index = messages.length - 1; index >= 0; index--) {\n\t\tconst message = messages[index] as { role?: unknown; customType?: unknown };\n\t\tif (message?.role === \"assistant\") break;\n\t\tif (message?.role === \"custom\" && typeof message.customType === \"string\") {\n\t\t\trequestMessages.push({ index, customType: message.customType });\n\t\t}\n\t}\n\treturn requestMessages.reverse();\n}\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/** Auth storage for credentials. Default: AuthStorage.create(agentDir/auth.json) */\n\tauthStorage?: AuthStorage;\n\t/** Model registry. Default: new ModelRegistry(authStorage, agentDir/models.json) */\n\tmodelRegistry?: ModelRegistry;\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/** Built-in tools to use. Default: codingTools [read, bash, edit, write] */\n\ttools?: Tool[];\n\t/** Custom tools to register (in addition to built-in tools). */\n\tcustomTools?: ToolDefinition[];\n\t/**\n\t * Additional tool names to activate after extensions/MCP servers register.\n\t * Names that are not registered by any extension are silently ignored\n\t * by AgentSession.setActiveToolsByName.\n\t *\n\t * Used by --tools to forward names that don't match a built-in (likely\n\t * extension- or MCP-provided), so subagents whose frontmatter declares\n\t * extension tools don't end up with an empty tool list.\n\t */\n\textraActiveToolNames?: string[];\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\n\t/** Optional: check if the claude-code CLI provider is ready (installed + authed).\n\t * Passed to RetryHandler for third-party block recovery (#3772). */\n\tisClaudeCodeReady?: () => 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 type {\n\tExtensionAPI,\n\tExtensionCommandContext,\n\tExtensionContext,\n\tExtensionFactory,\n\tSlashCommandInfo,\n\tSlashCommandLocation,\n\tSlashCommandSource,\n\tToolDefinition,\n} from \"./extensions/index.js\";\nexport type { PromptTemplate } from \"./prompt-templates.js\";\nexport type { Skill } from \"./skills.js\";\nexport type { Tool } from \"./tools/index.js\";\n\nexport {\n\t// Pre-built tools (use process.cwd())\n\treadTool,\n\tbashTool,\n\teditTool,\n\twriteTool,\n\tgrepTool,\n\tfindTool,\n\tlsTool,\n\tcodingTools,\n\treadOnlyTools,\n\tallTools as allBuiltInTools,\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\t// Hashline edit mode\n\thashlineCodingTools,\n\thashlineEditTool,\n\thashlineReadTool,\n\tcreateHashlineCodingTools,\n\tcreateHashlineEditTool,\n\tcreateHashlineReadTool,\n};\n\n// Helper Functions\n\nfunction getDefaultAgentDir(): string {\n\treturn getAgentDir();\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 '@gsd/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: [readTool, bashTool],\n * resourceLoader: loader,\n * sessionManager: SessionManager.inMemory(),\n * });\n * ```\n */\nexport async function createAgentSession(options: CreateAgentSessionOptions = {}): Promise<CreateAgentSessionResult> {\n\tconst cwd = options.cwd ?? process.cwd();\n\tconst agentDir = options.agentDir ?? getDefaultAgentDir();\n\tlet resourceLoader = options.resourceLoader;\n\n\t// Use provided or create AuthStorage and ModelRegistry\n\tconst authPath = options.agentDir ? join(agentDir, \"auth.json\") : undefined;\n\tconst modelsPath = options.agentDir ? join(agentDir, \"models.json\") : undefined;\n\tconst authStorage = options.authStorage ?? AuthStorage.create(authPath);\n\tconst modelRegistry = options.modelRegistry ?? new ModelRegistry(authStorage, modelsPath);\n\n\tconst settingsManager = options.settingsManager ?? SettingsManager.create(cwd, agentDir);\n\tconst sessionManager = options.sessionManager ?? SessionManager.create(cwd);\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// Flush provider registrations queued during extension loading so that\n\t// extension models (e.g. pi-claude-cli) are visible in the registry before\n\t// findInitialModel() runs. bindCore() repeats this flush as a safety net\n\t// for any late-arriving registrations.\n\tconst { runtime: extensionRuntime } = resourceLoader.getExtensions();\n\tfor (const { name, config } of extensionRuntime.pendingProviderRegistrations) {\n\t\tmodelRegistry.registerProvider(name, config);\n\t}\n\textensionRuntime.pendingProviderRegistrations = [];\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 = modelRegistry.find(existingSession.model.provider, existingSession.model.modelId);\n\t\t\tif (restoredModel && canRestoreSessionModel(modelRegistry, restoredModel)) {\n\t\t\t\tmodel = restoredModel;\n\t\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// Flush extension provider registrations so extension-provided models (e.g. claude-code/*)\n\t// are available in the registry before model resolution. Without this, findInitialModel()\n\t// cannot find extension models and falls back to built-in providers (#3534).\n\tconst extensionsForModelResolution = resourceLoader.getExtensions();\n\tfor (const { name, config } of extensionsForModelResolution.runtime.pendingProviderRegistrations) {\n\t\tmodelRegistry.registerProvider(name, config);\n\t}\n\t// Clear the queue so bindCore() doesn't re-register the same providers.\n\textensionsForModelResolution.runtime.pendingProviderRegistrations = [];\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\tmodelRegistry,\n\t\t});\n\t\tmodel = result.model;\n\t\tif (!model) {\n\t\t\tmodelFallbackMessage = `No models available. Use /login or set an API key environment variable. See ${join(getDocsPath(), \"providers.md\")}. Then use /model to select a model.`;\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 || !model.reasoning) {\n\t\tthinkingLevel = \"off\";\n\t}\n\n\tconst editMode = settingsManager.getEditMode();\n\tconst defaultActiveToolNames: ToolName[] = editMode === \"hashline\"\n\t\t? [\"hashline_read\", \"bash\", \"hashline_edit\", \"write\", \"lsp\"]\n\t\t: [\"read\", \"bash\", \"edit\", \"write\", \"lsp\"];\n\tconst builtinActiveToolNames: ToolName[] = options.tools\n\t\t? options.tools.map((t) => t.name).filter((n): n is ToolName => n in allTools)\n\t\t: defaultActiveToolNames;\n\t// Merge in extension/MCP tool names from --tools that didn't match a built-in.\n\t// AgentSession.setActiveToolsByName silently drops names that aren't in the\n\t// registry, so unknown names are harmless here.\n\tconst initialActiveToolNames: string[] = options.extraActiveToolNames\n\t\t? [...builtinActiveToolNames, ...options.extraActiveToolNames]\n\t\t: builtinActiveToolNames;\n\n\tlet agent: Agent;\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\tconst workspaceRootRef: { current: string } = { current: cwd };\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\tonPayload: async (payload, currentModel) => {\n\t\t\tconst runner = extensionRunnerRef.current;\n\t\t\tif (!runner?.hasHandlers(\"before_provider_request\")) {\n\t\t\t\tmaybeLogProviderPayloadAudit(payload, \"before_provider_request:unchanged\");\n\t\t\t\treturn payload;\n\t\t\t}\n\t\t\tconst nextPayload = await runner.emitBeforeProviderRequest(payload, currentModel);\n\t\t\tmaybeLogProviderPayloadAudit(nextPayload, \"before_provider_request:after\");\n\t\t\treturn nextPayload;\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\tfilterTools: async (tools, _signal, messages) => {\n\t\t\tconst currentModel = agent.state.activeInferenceModel ?? agent.state.model ?? model;\n\t\t\tif (!currentModel) return tools;\n\t\t\tconst providerFiltered = filterToolsForProviderRequest(tools, currentModel);\n\t\t\tconst runner = extensionRunnerRef.current;\n\t\t\tif (!runner?.hasHandlers(\"adjust_tool_set\")) return providerFiltered.compatible;\n\t\t\tconst result = await runner.emitAdjustToolSet({\n\t\t\t\tselectedModelApi: currentModel.api,\n\t\t\t\tselectedModelProvider: currentModel.provider,\n\t\t\t\tselectedModelId: currentModel.id,\n\t\t\t\tactiveToolNames: providerFiltered.compatible.map((tool) => tool.name),\n\t\t\t\tfilteredTools: providerFiltered.filtered.map((tool) => tool.name),\n\t\t\t\trequestCustomMessages: getAdjustToolSetRequestCustomMessages(messages),\n\t\t\t});\n\t\t\tif (!result?.toolNames) return providerFiltered.compatible;\n\t\t\tconst allowedNames = new Set(result.toolNames);\n\t\t\treturn providerFiltered.compatible.filter((tool) => allowedNames.has(tool.name));\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.getRetrySettings().maxDelayMs,\n\t\texternalToolExecution: (m) => modelRegistry.getProviderAuthMode(m.provider) === \"externalCli\",\n\t\tgetProviderOptions: async (currentModel) => {\n\t\t\tif (currentModel.provider !== \"claude-code\") return undefined;\n\t\t\tconst runner = extensionRunnerRef.current;\n\t\t\tif (!runner?.hasUI()) {\n\t\t\t\treturn { cwd: workspaceRootRef.current };\n\t\t\t}\n\t\t\treturn {\n\t\t\t\tcwd: workspaceRootRef.current,\n\t\t\t\textensionUIContext: runner.getUIContext(),\n\t\t\t};\n\t\t},\n\t\tgetApiKey: async (provider) => {\n\t\t\t// Use the provider argument from the in-flight request;\n\t\t\t// agent.state.model may already be switched mid-turn.\n\t\t\tconst resolvedProvider = provider || agent.state.model?.provider;\n\t\t\tif (!resolvedProvider) {\n\t\t\t\tthrow new Error(\"No model selected\");\n\t\t\t}\n\t\t\tconst authMode = modelRegistry.getProviderAuthMode(resolvedProvider);\n\t\t\tif (authMode === \"externalCli\" || authMode === \"none\") {\n\t\t\t\treturn undefined;\n\t\t\t}\n\n\t\t\t// Retry key resolution with backoff to handle transient network failures\n\t\t\t// (e.g., OAuth token refresh failing due to brief connectivity loss).\n\t\t\t// When credentials are in a cooldown window (e.g., after a 429), wait\n\t\t\t// for the backoff to expire instead of using fixed delays that are\n\t\t\t// shorter than the cooldown duration.\n\t\t\tconst maxAttempts = 3;\n\t\t\tconst baseDelayMs = 2000;\n\t\t\tconst maxCooldownWaitMs = 60_000; // Don't wait longer than 60s (skip quota-exhausted 30min backoffs)\n\t\t\tfor (let attempt = 1; attempt <= maxAttempts; attempt++) {\n\t\t\t\tconst key = await modelRegistry.getApiKeyForProvider(resolvedProvider);\n\t\t\t\tif (key) return key;\n\n\t\t\t\t// On the last attempt, fall through to error handling below\n\t\t\t\tif (attempt >= maxAttempts) break;\n\n\t\t\t\t// Only retry if credentials exist (network issue) — no point retrying\n\t\t\t\t// when there are genuinely no credentials configured.\n\t\t\t\tconst hasAuth = modelRegistry.authStorage.hasAuth(resolvedProvider);\n\t\t\t\tconst model = agent.state.model;\n\t\t\t\tconst isOAuth = model && modelRegistry.isUsingOAuth(model);\n\t\t\t\tif (!hasAuth && !isOAuth) break;\n\n\t\t\t\t// If credentials are in a cooldown window, wait for the earliest\n\t\t\t\t// one to expire rather than using a fixed delay that's too short.\n\t\t\t\tconst backoffExpiry = modelRegistry.authStorage.getEarliestBackoffExpiry(resolvedProvider);\n\t\t\t\tif (backoffExpiry !== undefined) {\n\t\t\t\t\tconst waitMs = backoffExpiry - Date.now() + 500; // 500ms buffer\n\t\t\t\t\tif (waitMs > 0 && waitMs <= maxCooldownWaitMs) {\n\t\t\t\t\t\tawait new Promise(resolve => setTimeout(resolve, waitMs));\n\t\t\t\t\t\tcontinue; // Retry immediately after cooldown clears\n\t\t\t\t\t}\n\t\t\t\t\tif (waitMs > maxCooldownWaitMs) {\n\t\t\t\t\t\tbreak; // Quota-exhausted or very long backoff — don't block\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\t// Standard exponential backoff for non-cooldown transient failures\n\t\t\t\tawait new Promise(resolve => setTimeout(resolve, baseDelayMs * attempt));\n\t\t\t}\n\n\t\t\t// All retries exhausted — throw descriptive error.\n\t\t\t// Check if credentials exist but are temporarily in a backoff window\n\t\t\t// (e.g., after a 429). This message intentionally avoids phrases like\n\t\t\t// \"rate limit\" / \"429\" to prevent isRetryableError() from re-entering\n\t\t\t// the retry handler and creating cascading error entries (#3429).\n\t\t\tconst hasAuth = modelRegistry.authStorage.hasAuth(resolvedProvider);\n\t\t\tif (hasAuth) {\n\t\t\t\t// Anthropic OAuth was removed in v2.74.0 for TOS compliance (#3952).\n\t\t\t\t// Users who upgraded from an older version may still have OAuth\n\t\t\t\t// credentials in auth.json that will never resolve to a valid API key.\n\t\t\t\tif (\n\t\t\t\t\tresolvedProvider === \"anthropic\" &&\n\t\t\t\t\tmodelRegistry.authStorage.hasLegacyOAuthCredential(resolvedProvider)\n\t\t\t\t) {\n\t\t\t\t\t// Self-heal: strip the stale oauth entry so hasAuth() stops lying\n\t\t\t\t\t// about anthropic being configured. This preserves any api_key\n\t\t\t\t\t// credentials alongside it.\n\t\t\t\t\tconst removed = modelRegistry.authStorage.removeLegacyOAuthCredential(resolvedProvider);\n\t\t\t\t\tif (removed) {\n\t\t\t\t\t\tconsole.warn(\n\t\t\t\t\t\t\t`[auth] Removed unsupported Anthropic OAuth credential from auth.json (#3952).`,\n\t\t\t\t\t\t);\n\t\t\t\t\t}\n\t\t\t\t\tif (isClaudeCodeBinaryInPath()) {\n\t\t\t\t\t\tthrow new Error(\n\t\t\t\t\t\t\t`Removed stale Anthropic OAuth credential (OAuth support removed in v2.74.0). ` +\n\t\t\t\t\t\t\t\t`Your current model's provider is set to \"anthropic\" but the local Claude Code CLI ` +\n\t\t\t\t\t\t\t\t`is available — switch the model's provider to \"claude-code\" in your preferences ` +\n\t\t\t\t\t\t\t\t`to use it, or set ANTHROPIC_API_KEY to continue with the Anthropic API directly.`,\n\t\t\t\t\t\t);\n\t\t\t\t\t}\n\t\t\t\t\tthrow new Error(\n\t\t\t\t\t\t`Removed stale Anthropic OAuth credential (OAuth support removed in v2.74.0). ` +\n\t\t\t\t\t\t\t`Set ANTHROPIC_API_KEY, run '/login' and paste an API key, or switch to a different provider.`,\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t\tconst expiry = modelRegistry.authStorage.getEarliestBackoffExpiry(resolvedProvider);\n\t\t\t\tconst retryAfterMs = expiry !== undefined ? Math.max(0, expiry - Date.now()) : undefined;\n\t\t\t\tthrow new CredentialCooldownError(resolvedProvider, retryAfterMs);\n\t\t\t}\n\t\t\tconst model = agent.state.model;\n\t\t\tconst isOAuth = model && modelRegistry.isUsingOAuth(model);\n\t\t\tif (isOAuth) {\n\t\t\t\t// If credentials exist but are all in a backoff window (quota / rate-limit),\n\t\t\t\t// surface a specific message instead of the misleading \"Authentication failed\".\n\t\t\t\tif (modelRegistry.authStorage.areAllCredentialsBackedOff(resolvedProvider)) {\n\t\t\t\t\tconst expiry = modelRegistry.authStorage.getEarliestBackoffExpiry(resolvedProvider);\n\t\t\t\t\tconst retryAfterMs = expiry !== undefined ? Math.max(0, expiry - Date.now()) : undefined;\n\t\t\t\t\tthrow new CredentialCooldownError(resolvedProvider, retryAfterMs);\n\t\t\t\t}\n\t\t\t\tthrow new Error(\n\t\t\t\t\t`Authentication failed for \"${resolvedProvider}\". ` +\n\t\t\t\t\t\t`Credentials may have expired or network is unavailable. ` +\n\t\t\t\t\t\t`Run '/login ${resolvedProvider}' to re-authenticate.`,\n\t\t\t\t);\n\t\t\t}\n\t\t\tthrow new Error(\n\t\t\t\t`No API key found for \"${resolvedProvider}\". ` +\n\t\t\t\t\t`Set an API key environment variable or run '/login ${resolvedProvider}'.`,\n\t\t\t);\n\t\t},\n\t});\n\n\t// Restore messages if session has existing data\n\tif (hasExistingSession) {\n\t\tagent.replaceMessages(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\tmodelRegistry,\n\t\tinitialActiveToolNames,\n\t\textensionRunnerRef,\n\t\tworkspaceRootRef,\n\t\tisClaudeCodeReady: options.isClaudeCodeReady,\n\t});\n\tconst extensionsResult = resourceLoader.getExtensions();\n\n\treturn {\n\t\tsession,\n\t\textensionsResult,\n\t\tmodelFallbackMessage,\n\t};\n}\n"]}
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
// GSD2 - Agent session workspace-root refresh regression tests
|
|
1
2
|
// Regression test for #3616: newSession() must restore the full tool set
|
|
2
3
|
// when cwd is unchanged.
|
|
3
4
|
//
|
|
@@ -26,7 +27,7 @@ import { SettingsManager } from "./settings-manager.js";
|
|
|
26
27
|
|
|
27
28
|
let testDir: string;
|
|
28
29
|
|
|
29
|
-
async function createSession(): Promise<AgentSession> {
|
|
30
|
+
async function createSession(options: { workspaceRootRef?: { current: string } } = {}): Promise<AgentSession> {
|
|
30
31
|
const agentDir = join(testDir, "agent-home");
|
|
31
32
|
const authStorage = AuthStorage.inMemory({});
|
|
32
33
|
const modelRegistry = new ModelRegistry(authStorage, join(agentDir, "models.json"));
|
|
@@ -48,6 +49,7 @@ async function createSession(): Promise<AgentSession> {
|
|
|
48
49
|
cwd: testDir,
|
|
49
50
|
resourceLoader,
|
|
50
51
|
modelRegistry,
|
|
52
|
+
workspaceRootRef: options.workspaceRootRef,
|
|
51
53
|
});
|
|
52
54
|
}
|
|
53
55
|
|
|
@@ -155,4 +157,16 @@ describe("#3616 — newSession() restores narrowed tool set when cwd unchanged",
|
|
|
155
157
|
"explicit workspaceRoot rebuild must pass includeAllExtensionTools: true",
|
|
156
158
|
);
|
|
157
159
|
});
|
|
160
|
+
|
|
161
|
+
it("updates provider workspace root ref when newSession uses explicit workspaceRoot", async () => {
|
|
162
|
+
const workspaceRootRef = { current: "" };
|
|
163
|
+
const session = await createSession({ workspaceRootRef });
|
|
164
|
+
const explicitWorkspaceRoot = mkdtempSync(join(testDir, "provider-workspace-"));
|
|
165
|
+
|
|
166
|
+
assert.equal(workspaceRootRef.current, testDir);
|
|
167
|
+
|
|
168
|
+
const ok = await session.newSession({ workspaceRoot: explicitWorkspaceRoot });
|
|
169
|
+
assert.equal(ok, true);
|
|
170
|
+
assert.equal(workspaceRootRef.current, explicitWorkspaceRoot);
|
|
171
|
+
});
|
|
158
172
|
});
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
// GSD2 - Agent session lifecycle and workspace runtime coordination
|
|
1
2
|
/**
|
|
2
3
|
* AgentSession - Core abstraction for agent lifecycle and session management.
|
|
3
4
|
*
|
|
@@ -167,6 +168,8 @@ export interface AgentSessionConfig {
|
|
|
167
168
|
baseToolsOverride?: Record<string, AgentTool>;
|
|
168
169
|
/** Mutable ref used by Agent to access the current ExtensionRunner */
|
|
169
170
|
extensionRunnerRef?: { current?: ExtensionRunner };
|
|
171
|
+
/** Mutable ref used by providers to access the current workspace root. */
|
|
172
|
+
workspaceRootRef?: { current: string };
|
|
170
173
|
/** Optional: check if the claude-code CLI provider is ready (installed + authed).
|
|
171
174
|
* Passed through to RetryHandler for third-party block recovery (#3772). */
|
|
172
175
|
isClaudeCodeReady?: () => boolean;
|
|
@@ -284,6 +287,7 @@ export class AgentSession {
|
|
|
284
287
|
private _baseToolRegistry: Map<string, AgentTool> = new Map();
|
|
285
288
|
private _cwd: string;
|
|
286
289
|
private _extensionRunnerRef?: { current?: ExtensionRunner };
|
|
290
|
+
private _workspaceRootRef?: { current: string };
|
|
287
291
|
private _initialActiveToolNames?: string[];
|
|
288
292
|
private _baseToolsOverride?: Record<string, AgentTool>;
|
|
289
293
|
private _extensionUIContext?: ExtensionUIContext;
|
|
@@ -323,6 +327,10 @@ export class AgentSession {
|
|
|
323
327
|
this._modelRegistry,
|
|
324
328
|
);
|
|
325
329
|
this._extensionRunnerRef = config.extensionRunnerRef;
|
|
330
|
+
this._workspaceRootRef = config.workspaceRootRef;
|
|
331
|
+
if (this._workspaceRootRef) {
|
|
332
|
+
this._workspaceRootRef.current = this._cwd;
|
|
333
|
+
}
|
|
326
334
|
this._initialActiveToolNames = config.initialActiveToolNames;
|
|
327
335
|
this._baseToolsOverride = config.baseToolsOverride;
|
|
328
336
|
|
|
@@ -1711,6 +1719,9 @@ export class AgentSession {
|
|
|
1711
1719
|
// historical default.
|
|
1712
1720
|
const previousCwd = this._cwd;
|
|
1713
1721
|
this._cwd = options?.workspaceRoot ?? process.cwd();
|
|
1722
|
+
if (this._workspaceRootRef) {
|
|
1723
|
+
this._workspaceRootRef.current = this._cwd;
|
|
1724
|
+
}
|
|
1714
1725
|
this.sessionManager.newSession({ parentSession: options?.parentSession });
|
|
1715
1726
|
this.agent.sessionId = this.sessionManager.getSessionId();
|
|
1716
1727
|
this._steeringMessages = [];
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
// GSD2 - Coding agent session factory and runtime wiring
|
|
1
2
|
import { existsSync } from "node:fs";
|
|
2
3
|
import { join } from "node:path";
|
|
3
4
|
|
|
@@ -439,6 +440,7 @@ export async function createAgentSession(options: CreateAgentSessionOptions = {}
|
|
|
439
440
|
};
|
|
440
441
|
|
|
441
442
|
const extensionRunnerRef: { current?: ExtensionRunner } = {};
|
|
443
|
+
const workspaceRootRef: { current: string } = { current: cwd };
|
|
442
444
|
|
|
443
445
|
agent = new Agent({
|
|
444
446
|
initialState: {
|
|
@@ -491,8 +493,11 @@ export async function createAgentSession(options: CreateAgentSessionOptions = {}
|
|
|
491
493
|
getProviderOptions: async (currentModel) => {
|
|
492
494
|
if (currentModel.provider !== "claude-code") return undefined;
|
|
493
495
|
const runner = extensionRunnerRef.current;
|
|
494
|
-
if (!runner?.hasUI())
|
|
496
|
+
if (!runner?.hasUI()) {
|
|
497
|
+
return { cwd: workspaceRootRef.current };
|
|
498
|
+
}
|
|
495
499
|
return {
|
|
500
|
+
cwd: workspaceRootRef.current,
|
|
496
501
|
extensionUIContext: runner.getUIContext(),
|
|
497
502
|
};
|
|
498
503
|
},
|
|
@@ -636,6 +641,7 @@ export async function createAgentSession(options: CreateAgentSessionOptions = {}
|
|
|
636
641
|
modelRegistry,
|
|
637
642
|
initialActiveToolNames,
|
|
638
643
|
extensionRunnerRef,
|
|
644
|
+
workspaceRootRef,
|
|
639
645
|
isClaudeCodeReady: options.isClaudeCodeReady,
|
|
640
646
|
});
|
|
641
647
|
const extensionsResult = resourceLoader.getExtensions();
|