@caupulican/pi-adaptative 0.93.9 → 0.93.11
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/CHANGELOG.md +18 -0
- package/dist/core/agent-session-contracts.d.ts +5 -1
- package/dist/core/agent-session-contracts.d.ts.map +1 -1
- package/dist/core/agent-session-contracts.js +4 -0
- package/dist/core/agent-session-contracts.js.map +1 -1
- package/dist/core/agent-session.d.ts.map +1 -1
- package/dist/core/agent-session.js +4 -2
- package/dist/core/agent-session.js.map +1 -1
- package/dist/core/autonomy/envelope-enforcement.d.ts.map +1 -1
- package/dist/core/autonomy/envelope-enforcement.js +2 -0
- package/dist/core/autonomy/envelope-enforcement.js.map +1 -1
- package/dist/core/fast-mode.d.ts +22 -0
- package/dist/core/fast-mode.d.ts.map +1 -0
- package/dist/core/fast-mode.js +37 -0
- package/dist/core/fast-mode.js.map +1 -0
- package/dist/core/goal-loop-controller.d.ts +1 -1
- package/dist/core/goal-loop-controller.d.ts.map +1 -1
- package/dist/core/goal-loop-controller.js +8 -5
- package/dist/core/goal-loop-controller.js.map +1 -1
- package/dist/core/goals/goal-auto-continue-controller.d.ts.map +1 -1
- package/dist/core/goals/goal-auto-continue-controller.js +3 -1
- package/dist/core/goals/goal-auto-continue-controller.js.map +1 -1
- package/dist/core/goals/goal-session-controller.d.ts +3 -2
- package/dist/core/goals/goal-session-controller.d.ts.map +1 -1
- package/dist/core/goals/goal-session-controller.js +22 -1
- package/dist/core/goals/goal-session-controller.js.map +1 -1
- package/dist/core/goals/natural-language-goal.d.ts +1 -1
- package/dist/core/goals/natural-language-goal.d.ts.map +1 -1
- package/dist/core/goals/natural-language-goal.js +1 -1
- package/dist/core/goals/natural-language-goal.js.map +1 -1
- package/dist/core/sdk.d.ts.map +1 -1
- package/dist/core/sdk.js +3 -1
- package/dist/core/sdk.js.map +1 -1
- package/dist/core/secrets/credential-exposure-guard.d.ts +1 -1
- package/dist/core/secrets/credential-exposure-guard.d.ts.map +1 -1
- package/dist/core/secrets/credential-exposure-guard.js +11 -4
- package/dist/core/secrets/credential-exposure-guard.js.map +1 -1
- package/dist/core/secrets/credential-source-discovery.d.ts +23 -0
- package/dist/core/secrets/credential-source-discovery.d.ts.map +1 -0
- package/dist/core/secrets/credential-source-discovery.js +187 -0
- package/dist/core/secrets/credential-source-discovery.js.map +1 -0
- package/dist/core/settings-manager.d.ts +4 -0
- package/dist/core/settings-manager.d.ts.map +1 -1
- package/dist/core/settings-manager.js +12 -0
- package/dist/core/settings-manager.js.map +1 -1
- package/dist/core/slash-commands.d.ts.map +1 -1
- package/dist/core/slash-commands.js +1 -0
- package/dist/core/slash-commands.js.map +1 -1
- package/dist/core/tool-capability-policy.js +1 -1
- package/dist/core/tool-capability-policy.js.map +1 -1
- package/dist/core/tools/goal.js +7 -7
- package/dist/core/tools/goal.js.map +1 -1
- package/dist/core/tools/secret-store.d.ts +8 -3
- package/dist/core/tools/secret-store.d.ts.map +1 -1
- package/dist/core/tools/secret-store.js +37 -6
- package/dist/core/tools/secret-store.js.map +1 -1
- package/dist/modes/interactive/components/footer.d.ts.map +1 -1
- package/dist/modes/interactive/components/footer.js +12 -3
- package/dist/modes/interactive/components/footer.js.map +1 -1
- package/dist/modes/interactive/fast-mode-command.d.ts +7 -0
- package/dist/modes/interactive/fast-mode-command.d.ts.map +1 -0
- package/dist/modes/interactive/fast-mode-command.js +32 -0
- package/dist/modes/interactive/fast-mode-command.js.map +1 -0
- package/dist/modes/interactive/interactive-mode.d.ts.map +1 -1
- package/dist/modes/interactive/interactive-mode.js +7 -0
- package/dist/modes/interactive/interactive-mode.js.map +1 -1
- package/examples/extensions/custom-provider-anthropic/package-lock.json +2 -2
- package/examples/extensions/custom-provider-anthropic/package.json +1 -1
- package/examples/extensions/custom-provider-gitlab-duo/package.json +1 -1
- package/examples/extensions/sandbox/package-lock.json +2 -2
- package/examples/extensions/sandbox/package.json +1 -1
- package/examples/extensions/with-deps/package-lock.json +2 -2
- package/examples/extensions/with-deps/package.json +1 -1
- package/npm-shrinkwrap.json +12 -12
- package/package.json +4 -4
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"goal-session-controller.js","sourceRoot":"","sources":["../../../src/core/goals/goal-session-controller.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AACzC,OAAO,EAAE,eAAe,EAAE,MAAM,uCAAuC,CAAC;AAaxE,OAAO,EAAE,kBAAkB,EAAE,MAAM,4BAA4B,CAAC;AAChE,OAAO,EAAE,cAAc,EAAE,MAAM,wCAAwC,CAAC;AAExE,OAAO,EAAE,wBAAwB,EAAE,MAAM,4BAA4B,CAAC;AACtE,OAAO,EAA0B,oBAAoB,EAAE,kBAAkB,EAAE,MAAM,qBAAqB,CAAC;AACvG,OAAO,EACN,wBAAwB,GAGxB,MAAM,4BAA4B,CAAC;AACpC,OAAO,EAAE,cAAc,EAAkB,qBAAqB,EAAE,sBAAsB,EAAE,MAAM,iBAAiB,CAAC;AAChH,OAAO,EAAE,eAAe,EAAE,MAAM,qBAAqB,CAAC;AACtD,OAAO,EAEN,qBAAqB,EACrB,mBAAmB,GACnB,MAAM,4BAA4B,CAAC;AACpC,OAAO,EACN,yBAAyB,EACzB,uBAAuB,EACvB,0BAA0B,GAC1B,MAAM,yBAAyB,CAAC;AAmBjC;;;;;;;;;;GAUG;AACH,MAAM,kCAAkC,GAAG,KAAK,CAAC;AAEjD,MAAM,wBAAwB,GAAkB,MAAM,CAAC,oBAAoB,CAAC,CAAC;AA2B7E;;;GAGG;AACH,MAAM,OAAO,qBAAqB;IAQjC,YAAY,IAA+B;QAH1B,yBAAoB,GAAG,IAAI,OAAO,EAAqC,CAAC;QAIxF,IAAI,CAAC,IAAI,GAAG,IAAI,CAAC;QACjB,IAAI,CAAC,IAAI,GAAG,IAAI,kBAAkB,CAAC;YAClC,sBAAsB,EAAE,CAAC,QAAQ,EAAE,EAAE,CAAC,IAAI,CAAC,kBAAkB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AAC,CAAC;IAC/C,CAAC;IAEO,cAAc,CAAC,MAAsD,EAAE,MAAc;QAC5F,MAAM,KAAK,GAAG,IAAI,CAAC,QAAQ,EAAE,CAAC;QAC9B,MAAM,OAAO,GAAG,kBAAkB,CAAC,KAAK,EAAE,EAAE,MAAM,EAAE,MAAM,EAAE,EAAE,IAAI,IAAI,EAAE,CAAC,WAAW,EAAE,CAAC,CAAC;QACxF,IAAI,CAAC,OAAO,CAAC,EAAE,IAAI,CAAC,KAAK;YAAE,OAAO,KAAK,CAAC;QACxC,IAAI,CAAC,SAAS,CAAC,OAAO,CAAC,KAAK,EAAE,oBAAoB,CAAC,KAAK,CAAC,CAAC,CAAC;QAC3D,OAAO,IAAI,CAAC;IACb,CAAC;CACD","sourcesContent":["import { createHash } from \"node:crypto\";\nimport { classifyFailure } from \"@caupulican/pi-agent-core/reliability\";\nimport type { SessionManager } from \"@caupulican/pi-agent-core/session\";\nimport type { AgentMessage, AgentRunawayStopInfo } from \"@caupulican/pi-agent-core/types\";\nimport type { AssistantMessage } from \"@caupulican/pi-ai\";\nimport type {\n\tGoalContinuationLoopOptions,\n\tGoalContinuationLoopResult,\n\tGoalContinuationOnceOptions,\n\tGoalContinuationOnceResult,\n\tPromptOptions,\n} from \"../agent-session-contracts.ts\";\nimport type { LaneRecord } from \"../autonomy/lane-tracker.ts\";\nimport type { BackgroundToolTaskRef } from \"../background-tool-task-controller.ts\";\nimport { GoalLoopController } from \"../goal-loop-controller.ts\";\nimport { budgetedTokens } from \"../orchestration/capability-gateway.ts\";\nimport type { TaskRuntimeProjection } from \"../orchestration/task-runtime.ts\";\nimport { GoalBudgetExhaustedError } from \"./goal-execution-errors.ts\";\nimport { type GoalStateRevision, getGoalStateRevision, stopGoalFromSystem } from \"./goal-lifecycle.ts\";\nimport {\n\tbuildGoalRuntimeSnapshot,\n\ttype GoalRuntimeSnapshot,\n\ttype GoalRuntimeSnapshotSettings,\n} from \"./goal-runtime-snapshot.ts\";\nimport { applyGoalEvent, type GoalState, isGoalExecutionActive, isGoalUnfinishedStatus } from \"./goal-state.ts\";\nimport { applyGoalAction } from \"./goal-tool-core.ts\";\nimport {\n\ttype ExplicitGoalStartAuthority,\n\tparseExplicitChatGoal,\n\tpriorUserPromptText,\n} from \"./natural-language-goal.ts\";\nimport {\n\tappendGoalClearedSnapshot,\n\tappendGoalStateSnapshot,\n\tgetLatestGoalStateSnapshot,\n} from \"./session-goal-state.ts\";\n\nexport interface GoalSessionControllerDeps {\n\tgetSessionManager(): SessionManager;\n\tgetModelProvider(): string | undefined;\n\tgetLaneRecords(): readonly LaneRecord[];\n\tgetTaskRuntimeSnapshot(): TaskRuntimeProjection | undefined;\n\tgetBackgroundToolTasks(): readonly BackgroundToolTaskRef[];\n\tsynchronizeGoalState(state: GoalState): void;\n\tscheduleGoalAutoContinueFromIdle(): void;\n\tprompt(text: string, options?: PromptOptions): Promise<void>;\n\temitWarning(message: string): void;\n}\n\nexport type ChatGoalAdmission =\n\t| { status: \"not_explicit\" }\n\t| { status: \"started\"; state: GoalState }\n\t| { status: \"unfinished_goal_exists\"; state: GoalState };\n\n/**\n * Smallest remaining goal budget worth handing to the provider as one more request's OUTPUT cap.\n * `admitProviderRequest` returns the goal's remaining TOTAL budget (input+output, cache-weighted) as\n * that cap — correct only because it also narrows further downstream against the model's real output\n * limit. When remaining drops below this floor (e.g. 200k budget, 199.4k used → 600 remaining), handing\n * 600 to the provider as maxTokens produces a request that pays the FULL input cost of the turn only to\n * get cut off mid-generation (`stopReason: \"length\"`) — a doomed, wasted turn. Below the floor, stop\n * the goal cleanly BEFORE sending instead of gambling on a truncated one. Above it, the remaining-total\n * value is a generous (imprecise but safe) protective ceiling — a modest final-turn overrun is\n * acceptable; a truncated turn is not.\n */\nconst MIN_VIABLE_GOAL_TURN_OUTPUT_TOKENS = 1_000;\n\nconst goalExecutionLeaseMarker: unique symbol = Symbol(\"goalExecutionLease\");\n\n/** Identity-bound attribution for one goal-owned foreground execution. */\nexport interface GoalExecutionLease {\n\treadonly goalId?: string;\n\treadonly [goalExecutionLeaseMarker]: true;\n}\n\ninterface MutableGoalExecutionLease extends GoalExecutionLease {\n\tgoalId?: string;\n\tadoptNewGoal: boolean;\n\tadoptionBaselineGoalId?: string;\n\tprovisionalTokenBudget?: number;\n\tpendingTokens: number;\n\tpendingSpendUsd: number;\n\t/** Set once this lease has admitted a provider request while its goal was still active. Lets a\n\t * later admission on the SAME still-held lease recognize \"the goal ended mid-turn\" (drain the\n\t * in-flight turn's wrap-up response) instead of \"a new turn is starting against a dead goal\"\n\t * (which stays denied). */\n\tadmittedWhileActive: boolean;\n}\n\ninterface QueuedOwnerChatGoal {\n\ttext: string;\n\tauthority: ExplicitGoalStartAuthority;\n}\n\n/**\n * Owns durable goal state, exact continuation accounting, and the raw continuation loop. The\n * AgentSession facade supplies process collaborators but no longer implements goal lifecycle rules.\n */\nexport class GoalSessionController {\n\tprivate readonly deps: GoalSessionControllerDeps;\n\tprivate readonly loop: GoalLoopController;\n\tprivate executionLease: MutableGoalExecutionLease | undefined;\n\tprivate startAuthority: ExplicitGoalStartAuthority | undefined;\n\tprivate readonly queuedOwnerChatGoals = new WeakMap<AgentMessage, QueuedOwnerChatGoal>();\n\tprivate queuedOwnerChatExecutionLease: GoalExecutionLease | undefined;\n\n\tconstructor(deps: GoalSessionControllerDeps) {\n\t\tthis.deps = deps;\n\t\tthis.loop = new GoalLoopController({\n\t\t\tgetGoalRuntimeSnapshot: (settings) => this.getRuntimeSnapshot(settings),\n\t\t\tprompt: (text, options) => this.deps.prompt(text, options),\n\t\t\trecordGoalContinuationPass: (pass) => this.recordContinuationPass(pass),\n\t\t\trecordGoalContinuationFailure: (error) => this.recordContinuationFailure(error),\n\t\t\tmarkGoalBudgetLimited: (reason) => this.markBudgetLimited(reason),\n\t\t});\n\t}\n\n\tsaveState(state: GoalState, expected?: GoalStateRevision): string {\n\t\tconst current = this.getState();\n\t\tif (\n\t\t\texpected &&\n\t\t\t(!current || current.goalId !== expected.goalId || (current.revision ?? 0) !== expected.revision)\n\t\t) {\n\t\t\tthrow new Error(\n\t\t\t\t`Goal state changed concurrently; expected ${expected.goalId}@${expected.revision}, found ${current ? `${current.goalId}@${current.revision ?? 0}` : \"none\"}. Retry against the latest state.`,\n\t\t\t);\n\t\t}\n\t\tconst entryId = appendGoalStateSnapshot(this.deps.getSessionManager(), state, current);\n\t\ttry {\n\t\t\tthis.deps.synchronizeGoalState(state);\n\t\t} catch (error) {\n\t\t\tthis.deps.emitWarning(\n\t\t\t\t`Goal state persisted but durable worker reconciliation failed: ${error instanceof Error ? error.message : String(error)}`,\n\t\t\t);\n\t\t}\n\t\treturn entryId;\n\t}\n\n\tclearState(state: GoalState, now: string): string {\n\t\tconst current = this.getState();\n\t\tconst expected = getGoalStateRevision(state);\n\t\tif (!current || current.goalId !== expected.goalId || (current.revision ?? 0) !== expected.revision) {\n\t\t\tthrow new Error(\"Goal state changed concurrently; retry clear against the latest state.\");\n\t\t}\n\t\tif (state.status !== \"completed\" && state.status !== \"cancelled\") {\n\t\t\tthis.deps.synchronizeGoalState(applyGoalEvent(state, { type: \"cancel_goal\", now }));\n\t\t}\n\t\treturn appendGoalClearedSnapshot(this.deps.getSessionManager(), state, now);\n\t}\n\n\tgetState(): GoalState | undefined {\n\t\treturn getLatestGoalStateSnapshot(this.deps.getSessionManager());\n\t}\n\n\t/**\n\t * Promote high-confidence natural-language persistence into the same durable state written by the\n\t * goal tool. This is intentionally narrower than task detection: ordinary work never starts a\n\t * goal, and an unfinished goal is never replaced implicitly.\n\t */\n\tadmitOwnerChatGoal(text: string, messages: readonly { role: string; content?: unknown }[]): ChatGoalAdmission {\n\t\treturn this.admitExplicitChatGoal(text, undefined, priorUserPromptText(messages, text));\n\t}\n\n\tstartOwnerChatGoal(text: string, messages: readonly { role: string; content?: unknown }[]): string | undefined {\n\t\tconst admission = this.admitOwnerChatGoal(text, messages);\n\t\tif (admission.status === \"started\") return admission.state.goalId;\n\t\tif (admission.status === \"unfinished_goal_exists\") {\n\t\t\tthis.deps.emitWarning(\n\t\t\t\t`Explicit chat goal was not started because unfinished goal '${admission.state.goalId}' is ${admission.state.status}. Complete, clear, or explicitly replace it first.`,\n\t\t\t);\n\t\t}\n\t\treturn undefined;\n\t}\n\n\tqueueOwnerChatGoal(message: AgentMessage, text: string, authority: ExplicitGoalStartAuthority): void {\n\t\tthis.queuedOwnerChatGoals.set(message, { text, authority });\n\t}\n\n\tactivateQueuedOwnerChatGoal(message: AgentMessage, messages: readonly { role: string; content?: unknown }[]): void {\n\t\tconst queued = this.queuedOwnerChatGoals.get(message);\n\t\tif (!queued) return;\n\t\tthis.queuedOwnerChatGoals.delete(message);\n\t\tconst goalId = this.startOwnerChatGoal(queued.text, messages);\n\t\tif (!goalId) return;\n\t\tthis.setStartAuthority(queued.authority);\n\t\tconst lease = this.beginExecution(goalId);\n\t\tif (!lease) {\n\t\t\tthis.setStartAuthority(undefined);\n\t\t\treturn;\n\t\t}\n\t\tthis.queuedOwnerChatExecutionLease = lease;\n\t}\n\n\tendQueuedOwnerChatGoalExecution(): void {\n\t\tconst lease = this.queuedOwnerChatExecutionLease;\n\t\tif (!lease) return;\n\t\tthis.queuedOwnerChatExecutionLease = undefined;\n\t\tthis.setStartAuthority(undefined);\n\t\tthis.endExecution(lease);\n\t}\n\n\tadmitExplicitChatGoal(text: string, now?: string, priorUserText?: string): ChatGoalAdmission {\n\t\tconst admittedAt = now ?? new Date().toISOString();\n\t\tconst parsed = parseExplicitChatGoal(text, priorUserText);\n\t\tif (!parsed) return { status: \"not_explicit\" };\n\t\tconst current = this.getState();\n\t\tif (current && isGoalUnfinishedStatus(current.status)) {\n\t\t\treturn { status: \"unfinished_goal_exists\", state: current };\n\t\t}\n\t\tconst digest = createHash(\"sha256\")\n\t\t\t.update(`${admittedAt}\\0${current?.goalId ?? \"none\"}\\0${parsed.objective}`)\n\t\t\t.digest(\"hex\")\n\t\t\t.slice(0, 20);\n\t\tconst result = applyGoalAction(\n\t\t\tcurrent,\n\t\t\t{\n\t\t\t\taction: \"start\",\n\t\t\t\tgoalId: `chat-${digest}`,\n\t\t\t\tuserGoal: parsed.objective,\n\t\t\t\ttokenBudget: parsed.tokenBudget,\n\t\t\t},\n\t\t\tadmittedAt,\n\t\t);\n\t\tif (!result.ok) throw new Error(result.error);\n\t\tthis.saveState(result.state, current ? getGoalStateRevision(current) : undefined);\n\t\treturn { status: \"started\", state: result.state };\n\t}\n\n\t/** Attribute turn/wall-clock telemetry without inferring progress (public/manual accounting seam). */\n\trecordContinuationTelemetry(pass: { turns: number; wallClockMs: number }): void {\n\t\tthis.persistContinuationPass(pass);\n\t}\n\n\t/** Attribute one host-driven pass and derive stall state from the authoritative revision. */\n\tprivate recordContinuationPass(pass: {\n\t\tturns: number;\n\t\twallClockMs: number;\n\t\tgoalId: string;\n\t\tprogressRevision: number;\n\t\tstallTurns: number;\n\t}): void {\n\t\tthis.persistContinuationPass(pass);\n\t}\n\n\tprivate persistContinuationPass(\n\t\tpass: { turns: number; wallClockMs: number } & Partial<\n\t\t\tPick<GoalState, \"goalId\" | \"progressRevision\" | \"stallTurns\">\n\t\t>,\n\t): void {\n\t\tconst state = this.getState();\n\t\tif (!state) return;\n\t\tif (pass.goalId !== undefined && state.goalId !== pass.goalId) {\n\t\t\tthis.deps.emitWarning(\n\t\t\t\t`Goal continuation accounting skipped because goal '${pass.goalId}' was replaced by '${state.goalId}' during the pass.`,\n\t\t\t);\n\t\t\treturn;\n\t\t}\n\t\tconst now = new Date().toISOString();\n\t\tlet updated = applyGoalEvent(state, {\n\t\t\ttype: \"record_continuation_budget\",\n\t\t\tturns: pass.turns,\n\t\t\twallClockMs: pass.wallClockMs,\n\t\t\ttokens: 0,\n\t\t\tspendUsd: 0,\n\t\t\tnow,\n\t\t});\n\t\tif (\n\t\t\tpass.progressRevision !== undefined &&\n\t\t\tpass.stallTurns !== undefined &&\n\t\t\tisGoalExecutionActive(state.status) &&\n\t\t\t(state.progressRevision ?? 0) <= pass.progressRevision &&\n\t\t\tstate.stallTurns <= pass.stallTurns\n\t\t) {\n\t\t\tupdated = applyGoalEvent(updated, { type: \"no_progress\", now });\n\t\t}\n\t\tthis.saveState(updated, getGoalStateRevision(state));\n\t}\n\n\t/** Begin one foreground execution whose provider usage belongs to the specified active goal. */\n\tbeginExecution(\n\t\tgoalId: string | undefined,\n\t\toptions: { adoptNewGoal?: boolean; provisionalTokenBudget?: number } = {},\n\t): GoalExecutionLease | undefined {\n\t\tif (!goalId && !options.adoptNewGoal) return undefined;\n\t\tif (this.executionLease) throw new Error(\"Goal execution attribution is already active\");\n\t\tconst state = this.getState();\n\t\tif (goalId && (!state || state.goalId !== goalId || !isGoalExecutionActive(state.status))) return undefined;\n\t\tconst lease: MutableGoalExecutionLease = {\n\t\t\t...(goalId ? { goalId } : {}),\n\t\t\t[goalExecutionLeaseMarker]: true,\n\t\t\tadoptNewGoal: options.adoptNewGoal === true,\n\t\t\t...(options.adoptNewGoal && state ? { adoptionBaselineGoalId: state.goalId } : {}),\n\t\t\t...(options.provisionalTokenBudget !== undefined\n\t\t\t\t? { provisionalTokenBudget: options.provisionalTokenBudget }\n\t\t\t\t: {}),\n\t\t\tpendingTokens: 0,\n\t\t\tpendingSpendUsd: 0,\n\t\t\tadmittedWhileActive: false,\n\t\t};\n\t\tthis.executionLease = lease;\n\t\treturn lease;\n\t}\n\n\tendExecution(lease: GoalExecutionLease | undefined): void {\n\t\tif (!lease) return;\n\t\tif (this.executionLease !== lease) throw new Error(\"Cannot end goal execution attribution owned by another run\");\n\t\tthis.flushPendingExecutionUsage(this.executionLease);\n\t\tthis.executionLease = undefined;\n\t}\n\n\t/** Charge one observed assistant response exactly once, including routed responses buffered from persistence. */\n\trecordExecutionUsage(message: AssistantMessage): void {\n\t\tconst lease = this.executionLease;\n\t\tif (!lease) return;\n\t\tconst tokens = budgetedTokens({\n\t\t\tinputTokens: Math.max(0, message.usage.input),\n\t\t\toutputTokens: Math.max(0, message.usage.output),\n\t\t\tcacheReadTokens: Math.max(0, message.usage.cacheRead),\n\t\t\tcacheWriteTokens: Math.max(0, message.usage.cacheWrite),\n\t\t\ttotalTokens: Math.max(0, message.usage.totalTokens),\n\t\t});\n\t\tconst spendUsd = Math.max(0, message.usage.cost.total);\n\t\tif (tokens === 0 && spendUsd === 0) return;\n\t\tconst state = this.resolveExecutionState(lease);\n\t\tif (!state) {\n\t\t\tlease.pendingTokens += tokens;\n\t\t\tlease.pendingSpendUsd += spendUsd;\n\t\t\treturn;\n\t\t}\n\t\tthis.chargeExecutionUsage(lease, state, tokens, spendUsd);\n\t}\n\n\tprivate chargeExecutionUsage(\n\t\tlease: MutableGoalExecutionLease,\n\t\tstate: GoalState,\n\t\ttokens: number,\n\t\tspendUsd: number,\n\t): void {\n\t\tconst updated = applyGoalEvent(state, {\n\t\t\ttype: \"record_continuation_budget\",\n\t\t\tturns: 0,\n\t\t\twallClockMs: 0,\n\t\t\ttokens,\n\t\t\tspendUsd,\n\t\t\tnow: new Date().toISOString(),\n\t\t});\n\t\tthis.saveState(updated, getGoalStateRevision(state));\n\t\tlease.pendingTokens = 0;\n\t\tlease.pendingSpendUsd = 0;\n\t\tif (\n\t\t\tisGoalExecutionActive(updated.status) &&\n\t\t\tupdated.tokenBudget !== undefined &&\n\t\t\t(updated.tokensUsed ?? 0) >= updated.tokenBudget\n\t\t) {\n\t\t\tthis.markBudgetLimited(\n\t\t\t\t`token budget exhausted (${updated.tokensUsed ?? 0}/${updated.tokenBudget}) during goal execution`,\n\t\t\t);\n\t\t}\n\t}\n\n\tmarkProtocolFailureBlocked(errorMessage: string): boolean {\n\t\tconst lease = this.executionLease;\n\t\tif (!lease) return false;\n\t\tconst state = this.resolveExecutionState(lease);\n\t\tif (!state || !isGoalExecutionActive(state.status)) return false;\n\t\tconst stopped = stopGoalFromSystem(\n\t\t\tstate,\n\t\t\t{ status: \"blocked\", reason: errorMessage.slice(0, 500) },\n\t\t\tnew Date().toISOString(),\n\t\t);\n\t\tif (!stopped.ok) return false;\n\t\tthis.saveState(stopped.state, getGoalStateRevision(state));\n\t\treturn true;\n\t}\n\n\tsetStartAuthority(authority: ExplicitGoalStartAuthority | undefined): void {\n\t\tthis.startAuthority = authority;\n\t}\n\n\tauthorizeStartFromTool(input: { tokenBudget?: number }): string | undefined {\n\t\tconst authority = this.startAuthority;\n\t\tif (!authority) return \"goal start requires explicit owner authorization in the current prompt.\";\n\t\tif (authority.tokenBudget === undefined && input.tokenBudget !== undefined) {\n\t\t\treturn \"tokenBudget requires an exact numeric token ceiling in the current owner prompt.\";\n\t\t}\n\t\tif (authority.tokenBudget !== undefined && input.tokenBudget !== authority.tokenBudget) {\n\t\t\treturn `tokenBudget must equal the owner-requested ceiling ${authority.tokenBudget}.`;\n\t\t}\n\t\treturn undefined;\n\t}\n\n\t/**\n\t * True once the currently held execution lease's goal has crossed into `budget_limited` — set\n\t * synchronously by `chargeExecutionUsage` as soon as a just-charged response crosses the ceiling.\n\t * Wired to the agent's `shouldStopAfterTurn` hook so a mid-turn budget stop ends the loop\n\t * gracefully BEFORE the next provider request is even planned, instead of only being caught by\n\t * `admitProviderRequest`'s throw — which still exists as the backstop for a fresh turn or an\n\t * external admission starting against an already budget_limited goal, but would otherwise also\n\t * fire for a request this same lease was already mid-flight for, surfacing a synthetic error\n\t * message where a clean turn end belongs.\n\t */\n\thasExecutionLeaseCrossedBudgetLimit(): boolean {\n\t\tconst lease = this.executionLease;\n\t\tif (!lease) return false;\n\t\treturn this.resolveExecutionState(lease)?.status === \"budget_limited\";\n\t}\n\n\t/** Reserve only remaining output capacity; actual provider usage is charged on response. */\n\tadmitProviderRequest(): number | undefined {\n\t\tconst lease = this.executionLease;\n\t\tif (!lease) return undefined;\n\t\tthis.flushPendingExecutionUsage(lease);\n\t\tconst state = this.resolveExecutionState(lease);\n\t\tif (state?.status === \"budget_limited\") {\n\t\t\tthrow new GoalBudgetExhaustedError(`goal_token_budget_exhausted: ${state.blockedReason ?? lease.goalId}`);\n\t\t}\n\t\tif (state && !isGoalExecutionActive(state.status)) {\n\t\t\tif (!lease.admittedWhileActive) {\n\t\t\t\t// A fresh turn/continuation is being started against a goal that is already done —\n\t\t\t\t// keep this denied so a dead goal cannot restart itself.\n\t\t\t\tthrow new Error(`goal_execution_not_active: ${state.goalId} is ${state.status}`);\n\t\t\t}\n\t\t\t// This lease already admitted at least one request while the goal was active, so the\n\t\t\t// goal ended mid-turn (e.g. the model itself just called `goal complete`/`block`). Let\n\t\t\t// the already-in-flight turn drain to its closing response instead of throwing an error\n\t\t\t// at the user right after a successful stop.\n\t\t\treturn undefined;\n\t\t}\n\t\tif (!state && lease.goalId !== undefined) {\n\t\t\tthrow new Error(`goal_execution_not_active: ${lease.goalId} no longer exists`);\n\t\t}\n\t\tlease.admittedWhileActive = true;\n\t\tconst tokenBudget = state?.tokenBudget ?? lease.provisionalTokenBudget;\n\t\tif (tokenBudget === undefined) return undefined;\n\t\tconst tokensUsed = state?.tokensUsed ?? lease.pendingTokens;\n\t\tconst remaining = Math.max(0, tokenBudget - tokensUsed);\n\t\tif (remaining < MIN_VIABLE_GOAL_TURN_OUTPUT_TOKENS) {\n\t\t\t// Below the floor, remaining is too small to hand to the provider as an output cap without\n\t\t\t// dooming the turn to a mid-generation truncation that still burns the full input cost.\n\t\t\t// Stop cleanly now instead of sending a request that cannot possibly complete.\n\t\t\tif (state) {\n\t\t\t\tthis.markBudgetLimited(\n\t\t\t\t\t`token budget nearly exhausted (${tokensUsed}/${tokenBudget}, ${remaining} remaining is below the ` +\n\t\t\t\t\t\t`${MIN_VIABLE_GOAL_TURN_OUTPUT_TOKENS}-token minimum viable turn) before provider request`,\n\t\t\t\t);\n\t\t\t}\n\t\t\tthrow new GoalBudgetExhaustedError(\n\t\t\t\t`goal_token_budget_exhausted: ${remaining} tokens remain, below the ${MIN_VIABLE_GOAL_TURN_OUTPUT_TOKENS}-token minimum viable turn`,\n\t\t\t);\n\t\t}\n\t\treturn remaining;\n\t}\n\n\tprivate resolveExecutionState(lease: MutableGoalExecutionLease): GoalState | undefined {\n\t\tconst state = this.getState();\n\t\tif (!state) return undefined;\n\t\tif (lease.goalId === state.goalId) return state;\n\t\tif (lease.goalId !== undefined || !lease.adoptNewGoal) return undefined;\n\t\tif (lease.adoptionBaselineGoalId === state.goalId) return undefined;\n\t\tlease.goalId = state.goalId;\n\t\treturn state;\n\t}\n\n\tprivate flushPendingExecutionUsage(lease: MutableGoalExecutionLease): void {\n\t\tif (lease.pendingTokens === 0 && lease.pendingSpendUsd === 0) return;\n\t\tconst state = this.resolveExecutionState(lease);\n\t\tif (!state) {\n\t\t\t// A speculative adopt-new-goal lease (lease.goalId still undefined) that never actually\n\t\t\t// adopted a goal this turn has nowhere to attribute usage — that is normal, not a loss.\n\t\t\t// A lease that WAS bound to a real goal but can no longer resolve it is a genuine loss of\n\t\t\t// buffered spend; fail loudly instead of silently discarding it (matches the cursor-based\n\t\t\t// accounting this replaced, which stopped the goal on `goal_usage_cursor_lost`).\n\t\t\tif (lease.goalId !== undefined) {\n\t\t\t\tthis.deps.emitWarning(\n\t\t\t\t\t`Goal usage cursor is no longer resolvable for '${lease.goalId}'; ${lease.pendingTokens} pending tokens and $${lease.pendingSpendUsd.toFixed(6)} pending spend could not be attributed and were dropped.`,\n\t\t\t\t);\n\t\t\t\tthis.recordContinuationFailure(new Error(\"goal_usage_cursor_lost\"));\n\t\t\t}\n\t\t\tlease.pendingTokens = 0;\n\t\t\tlease.pendingSpendUsd = 0;\n\t\t\treturn;\n\t\t}\n\t\tthis.chargeExecutionUsage(lease, state, lease.pendingTokens, lease.pendingSpendUsd);\n\t}\n\n\tmarkToolUnavailable(): void {\n\t\tthis.stopActiveGoal(\n\t\t\t\"blocked\",\n\t\t\t\"goal_tool_unavailable: the active capability surface cannot update durable goal state\",\n\t\t);\n\t}\n\n\tmarkHarnessGuardBlocked(info: AgentRunawayStopInfo): boolean {\n\t\tconst reason =\n\t\t\tinfo.reason === \"provider_turn_limit\"\n\t\t\t\t? `provider_turn_limit: reached the explicit ${info.repeats}-request provider-turn limit`\n\t\t\t\t: `runaway_tool_loop: repeated tool-call signature ${info.signature} ${info.repeats} times without progress`;\n\t\treturn this.stopActiveGoal(\"blocked\", reason);\n\t}\n\n\tmarkTerminalToolFailureBlocked(toolName: string): boolean {\n\t\treturn this.stopActiveGoal(\n\t\t\t\"blocked\",\n\t\t\t`terminal_tool_failure: ${toolName} reported an unrecoverable error and terminated the run`,\n\t\t);\n\t}\n\n\tgetRuntimeSnapshot(settings: GoalRuntimeSnapshotSettings): GoalRuntimeSnapshot {\n\t\treturn buildGoalRuntimeSnapshot({\n\t\t\tsessionManager: this.deps.getSessionManager(),\n\t\t\tsettings,\n\t\t\tlaneRecords: this.deps.getLaneRecords(),\n\t\t\ttaskRuntime: this.deps.getTaskRuntimeSnapshot(),\n\t\t\tbackgroundToolTasks: this.deps.getBackgroundToolTasks(),\n\t\t});\n\t}\n\n\tcontinueOnce(options: GoalContinuationOnceOptions): Promise<GoalContinuationOnceResult> {\n\t\treturn this.loop.continueGoalOnce(options);\n\t}\n\n\tcontinueLoop(options: GoalContinuationLoopOptions): Promise<GoalContinuationLoopResult> {\n\t\treturn this.loop.continueGoalLoop(options);\n\t}\n\n\trestoreAfterResume(): void {\n\t\tthis.deps.scheduleGoalAutoContinueFromIdle();\n\t}\n\n\tprivate recordContinuationFailure(error: unknown): void {\n\t\tconst state = this.getState();\n\t\tif (!state || !isGoalExecutionActive(state.status)) return;\n\t\tconst message = error instanceof Error ? error.message : String(error);\n\t\tconst classified = classifyFailure({ message, provider: this.deps.getModelProvider() });\n\t\tconst status = classified.reason === \"billing_or_quota\" ? \"usage_limited\" : \"blocked\";\n\t\tthis.stopActiveGoal(status, `${classified.reason}: ${message}`);\n\t}\n\n\tprivate markBudgetLimited(reason: string): void {\n\t\tthis.stopActiveGoal(\"budget_limited\", reason);\n\t}\n\n\tprivate stopActiveGoal(status: \"blocked\" | \"usage_limited\" | \"budget_limited\", reason: string): boolean {\n\t\tconst state = this.getState();\n\t\tconst stopped = stopGoalFromSystem(state, { status, reason }, new Date().toISOString());\n\t\tif (!stopped.ok || !state) return false;\n\t\tthis.saveState(stopped.state, getGoalStateRevision(state));\n\t\treturn true;\n\t}\n}\n"]}
|
|
1
|
+
{"version":3,"file":"goal-session-controller.js","sourceRoot":"","sources":["../../../src/core/goals/goal-session-controller.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AACzC,OAAO,EAAE,eAAe,EAAE,MAAM,uCAAuC,CAAC;AACxE,OAAO,EAAE,6BAA6B,EAAuB,MAAM,mCAAmC,CAAC;AAGvG,OAAO,EAKN,gCAAgC,GAEhC,MAAM,+BAA+B,CAAC;AAGvC,OAAO,EAAE,kBAAkB,EAAE,MAAM,4BAA4B,CAAC;AAChE,OAAO,EAAE,cAAc,EAAE,MAAM,wCAAwC,CAAC;AAExE,OAAO,EAAE,wBAAwB,EAAE,MAAM,4BAA4B,CAAC;AACtE,OAAO,EAA0B,oBAAoB,EAAE,kBAAkB,EAAE,MAAM,qBAAqB,CAAC;AACvG,OAAO,EACN,wBAAwB,GAGxB,MAAM,4BAA4B,CAAC;AACpC,OAAO,EAAE,cAAc,EAAkB,qBAAqB,EAAE,sBAAsB,EAAE,MAAM,iBAAiB,CAAC;AAChH,OAAO,EAAE,eAAe,EAAE,MAAM,qBAAqB,CAAC;AACtD,OAAO,EAEN,qBAAqB,EACrB,mBAAmB,GACnB,MAAM,4BAA4B,CAAC;AACpC,OAAO,EACN,yBAAyB,EACzB,uBAAuB,EACvB,0BAA0B,GAC1B,MAAM,yBAAyB,CAAC;AAmBjC;;;;;;;;;;GAUG;AACH,MAAM,kCAAkC,GAAG,KAAK,CAAC;AAEjD,MAAM,wBAAwB,GAAkB,MAAM,CAAC,oBAAoB,CAAC,CAAC;AA2B7E;;;GAGG;AACH,MAAM,OAAO,qBAAqB;IAQjC,YAAY,IAA+B;QAH1B,yBAAoB,GAAG,IAAI,OAAO,EAAqC,CAAC;QAIxF,IAAI,CAAC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AG,kBAAkB,CAAC,KAAK,EAAE,EAAE,MAAM,EAAE,MAAM,EAAE,EAAE,IAAI,IAAI,EAAE,CAAC,WAAW,EAAE,CAAC,CAAC;QACxF,IAAI,CAAC,OAAO,CAAC,EAAE,IAAI,CAAC,KAAK;YAAE,OAAO,KAAK,CAAC;QACxC,IAAI,CAAC,SAAS,CAAC,OAAO,CAAC,KAAK,EAAE,oBAAoB,CAAC,KAAK,CAAC,CAAC,CAAC;QAC3D,OAAO,IAAI,CAAC;IACb,CAAC;CACD","sourcesContent":["import { createHash } from \"node:crypto\";\nimport { classifyFailure } from \"@caupulican/pi-agent-core/reliability\";\nimport { MAX_SESSION_ENTRY_VISIT_COUNT, type SessionManager } from \"@caupulican/pi-agent-core/session\";\nimport type { AgentMessage, AgentRunawayStopInfo } from \"@caupulican/pi-agent-core/types\";\nimport type { AssistantMessage } from \"@caupulican/pi-ai\";\nimport {\n\ttype GoalContinuationLoopOptions,\n\ttype GoalContinuationLoopResult,\n\ttype GoalContinuationOnceOptions,\n\ttype GoalContinuationOnceResult,\n\tisInterruptedAssistantStopReason,\n\ttype PromptOptions,\n} from \"../agent-session-contracts.ts\";\nimport type { LaneRecord } from \"../autonomy/lane-tracker.ts\";\nimport type { BackgroundToolTaskRef } from \"../background-tool-task-controller.ts\";\nimport { GoalLoopController } from \"../goal-loop-controller.ts\";\nimport { budgetedTokens } from \"../orchestration/capability-gateway.ts\";\nimport type { TaskRuntimeProjection } from \"../orchestration/task-runtime.ts\";\nimport { GoalBudgetExhaustedError } from \"./goal-execution-errors.ts\";\nimport { type GoalStateRevision, getGoalStateRevision, stopGoalFromSystem } from \"./goal-lifecycle.ts\";\nimport {\n\tbuildGoalRuntimeSnapshot,\n\ttype GoalRuntimeSnapshot,\n\ttype GoalRuntimeSnapshotSettings,\n} from \"./goal-runtime-snapshot.ts\";\nimport { applyGoalEvent, type GoalState, isGoalExecutionActive, isGoalUnfinishedStatus } from \"./goal-state.ts\";\nimport { applyGoalAction } from \"./goal-tool-core.ts\";\nimport {\n\ttype ExplicitGoalStartAuthority,\n\tparseExplicitChatGoal,\n\tpriorUserPromptText,\n} from \"./natural-language-goal.ts\";\nimport {\n\tappendGoalClearedSnapshot,\n\tappendGoalStateSnapshot,\n\tgetLatestGoalStateSnapshot,\n} from \"./session-goal-state.ts\";\n\nexport interface GoalSessionControllerDeps {\n\tgetSessionManager(): SessionManager;\n\tgetModelProvider(): string | undefined;\n\tgetLaneRecords(): readonly LaneRecord[];\n\tgetTaskRuntimeSnapshot(): TaskRuntimeProjection | undefined;\n\tgetBackgroundToolTasks(): readonly BackgroundToolTaskRef[];\n\tsynchronizeGoalState(state: GoalState): void;\n\tscheduleGoalAutoContinueFromIdle(): void;\n\tprompt(text: string, options?: PromptOptions): Promise<void>;\n\temitWarning(message: string): void;\n}\n\nexport type ChatGoalAdmission =\n\t| { status: \"not_explicit\" }\n\t| { status: \"started\"; state: GoalState }\n\t| { status: \"unfinished_goal_exists\"; state: GoalState };\n\n/**\n * Smallest remaining goal budget worth handing to the provider as one more request's OUTPUT cap.\n * `admitProviderRequest` returns the goal's remaining TOTAL budget (input+output, cache-weighted) as\n * that cap — correct only because it also narrows further downstream against the model's real output\n * limit. When remaining drops below this floor (e.g. 200k budget, 199.4k used → 600 remaining), handing\n * 600 to the provider as maxTokens produces a request that pays the FULL input cost of the turn only to\n * get cut off mid-generation (`stopReason: \"length\"`) — a doomed, wasted turn. Below the floor, stop\n * the goal cleanly BEFORE sending instead of gambling on a truncated one. Above it, the remaining-total\n * value is a generous (imprecise but safe) protective ceiling — a modest final-turn overrun is\n * acceptable; a truncated turn is not.\n */\nconst MIN_VIABLE_GOAL_TURN_OUTPUT_TOKENS = 1_000;\n\nconst goalExecutionLeaseMarker: unique symbol = Symbol(\"goalExecutionLease\");\n\n/** Identity-bound attribution for one goal-owned foreground execution. */\nexport interface GoalExecutionLease {\n\treadonly goalId?: string;\n\treadonly [goalExecutionLeaseMarker]: true;\n}\n\ninterface MutableGoalExecutionLease extends GoalExecutionLease {\n\tgoalId?: string;\n\tadoptNewGoal: boolean;\n\tadoptionBaselineGoalId?: string;\n\tprovisionalTokenBudget?: number;\n\tpendingTokens: number;\n\tpendingSpendUsd: number;\n\t/** Set once this lease has admitted a provider request while its goal was still active. Lets a\n\t * later admission on the SAME still-held lease recognize \"the goal ended mid-turn\" (drain the\n\t * in-flight turn's wrap-up response) instead of \"a new turn is starting against a dead goal\"\n\t * (which stays denied). */\n\tadmittedWhileActive: boolean;\n}\n\ninterface QueuedOwnerChatGoal {\n\ttext: string;\n\tauthority: ExplicitGoalStartAuthority;\n}\n\n/**\n * Owns durable goal state, exact continuation accounting, and the raw continuation loop. The\n * AgentSession facade supplies process collaborators but no longer implements goal lifecycle rules.\n */\nexport class GoalSessionController {\n\tprivate readonly deps: GoalSessionControllerDeps;\n\tprivate readonly loop: GoalLoopController;\n\tprivate executionLease: MutableGoalExecutionLease | undefined;\n\tprivate startAuthority: ExplicitGoalStartAuthority | undefined;\n\tprivate readonly queuedOwnerChatGoals = new WeakMap<AgentMessage, QueuedOwnerChatGoal>();\n\tprivate queuedOwnerChatExecutionLease: GoalExecutionLease | undefined;\n\n\tconstructor(deps: GoalSessionControllerDeps) {\n\t\tthis.deps = deps;\n\t\tthis.loop = new GoalLoopController({\n\t\t\tgetGoalRuntimeSnapshot: (settings) => this.getRuntimeSnapshot(settings),\n\t\t\tprompt: async (text, options) => {\n\t\t\t\tconst firstTurnEntryIndex = this.deps.getSessionManager().getEntryCount();\n\t\t\t\tawait this.deps.prompt(text, options);\n\t\t\t\treturn this.getContinuationTurnOutcome(firstTurnEntryIndex);\n\t\t\t},\n\t\t\trecordGoalContinuationPass: (pass) => this.recordContinuationPass(pass),\n\t\t\trecordGoalContinuationFailure: (error) => this.recordContinuationFailure(error),\n\t\t\tmarkGoalBudgetLimited: (reason) => this.markBudgetLimited(reason),\n\t\t});\n\t}\n\n\tprivate getContinuationTurnOutcome(firstTurnEntryIndex: number): \"completed\" | \"interrupted\" {\n\t\tconst sessionManager = this.deps.getSessionManager();\n\t\tconst endIndex = sessionManager.getEntryCount();\n\t\tlet nextIndex = firstTurnEntryIndex;\n\t\tlet lastAssistantStopReason: AssistantMessage[\"stopReason\"] | undefined;\n\t\twhile (nextIndex < endIndex) {\n\t\t\tconst visitCount = Math.min(MAX_SESSION_ENTRY_VISIT_COUNT, endIndex - nextIndex);\n\t\t\tnextIndex = sessionManager.visitEntries(nextIndex, visitCount, (entry) => {\n\t\t\t\tif (entry.type === \"message\" && entry.message.role === \"assistant\") {\n\t\t\t\t\tlastAssistantStopReason = entry.message.stopReason;\n\t\t\t\t}\n\t\t\t});\n\t\t}\n\t\treturn isInterruptedAssistantStopReason(lastAssistantStopReason) ? \"interrupted\" : \"completed\";\n\t}\n\n\tsaveState(state: GoalState, expected?: GoalStateRevision): string {\n\t\tconst current = this.getState();\n\t\tif (\n\t\t\texpected &&\n\t\t\t(!current || current.goalId !== expected.goalId || (current.revision ?? 0) !== expected.revision)\n\t\t) {\n\t\t\tthrow new Error(\n\t\t\t\t`Goal state changed concurrently; expected ${expected.goalId}@${expected.revision}, found ${current ? `${current.goalId}@${current.revision ?? 0}` : \"none\"}. Retry against the latest state.`,\n\t\t\t);\n\t\t}\n\t\tconst entryId = appendGoalStateSnapshot(this.deps.getSessionManager(), state, current);\n\t\ttry {\n\t\t\tthis.deps.synchronizeGoalState(state);\n\t\t} catch (error) {\n\t\t\tthis.deps.emitWarning(\n\t\t\t\t`Goal state persisted but durable worker reconciliation failed: ${error instanceof Error ? error.message : String(error)}`,\n\t\t\t);\n\t\t}\n\t\treturn entryId;\n\t}\n\n\tclearState(state: GoalState, now: string): string {\n\t\tconst current = this.getState();\n\t\tconst expected = getGoalStateRevision(state);\n\t\tif (!current || current.goalId !== expected.goalId || (current.revision ?? 0) !== expected.revision) {\n\t\t\tthrow new Error(\"Goal state changed concurrently; retry clear against the latest state.\");\n\t\t}\n\t\tif (state.status !== \"completed\" && state.status !== \"cancelled\") {\n\t\t\tthis.deps.synchronizeGoalState(applyGoalEvent(state, { type: \"cancel_goal\", now }));\n\t\t}\n\t\treturn appendGoalClearedSnapshot(this.deps.getSessionManager(), state, now);\n\t}\n\n\tgetState(): GoalState | undefined {\n\t\treturn getLatestGoalStateSnapshot(this.deps.getSessionManager());\n\t}\n\n\t/**\n\t * Promote high-confidence natural-language persistence into the same durable state written by the\n\t * goal tool. This is intentionally narrower than task detection: ordinary work never starts a\n\t * goal, and an unfinished goal is never replaced implicitly.\n\t */\n\tadmitOwnerChatGoal(text: string, messages: readonly { role: string; content?: unknown }[]): ChatGoalAdmission {\n\t\treturn this.admitExplicitChatGoal(text, undefined, priorUserPromptText(messages, text));\n\t}\n\n\tstartOwnerChatGoal(text: string, messages: readonly { role: string; content?: unknown }[]): string | undefined {\n\t\tconst admission = this.admitOwnerChatGoal(text, messages);\n\t\tif (admission.status === \"started\") return admission.state.goalId;\n\t\tif (admission.status === \"unfinished_goal_exists\") {\n\t\t\tthis.deps.emitWarning(\n\t\t\t\t`Explicit chat goal was not started because unfinished goal '${admission.state.goalId}' is ${admission.state.status}. Complete, clear, or explicitly replace it first.`,\n\t\t\t);\n\t\t}\n\t\treturn undefined;\n\t}\n\n\tqueueOwnerChatGoal(message: AgentMessage, text: string, authority: ExplicitGoalStartAuthority): void {\n\t\tthis.queuedOwnerChatGoals.set(message, { text, authority });\n\t}\n\n\tactivateQueuedOwnerChatGoal(message: AgentMessage, messages: readonly { role: string; content?: unknown }[]): void {\n\t\tconst queued = this.queuedOwnerChatGoals.get(message);\n\t\tif (!queued) return;\n\t\tthis.queuedOwnerChatGoals.delete(message);\n\t\tconst goalId = this.startOwnerChatGoal(queued.text, messages);\n\t\tif (!goalId) return;\n\t\tthis.setStartAuthority(queued.authority);\n\t\tconst lease = this.beginExecution(goalId);\n\t\tif (!lease) {\n\t\t\tthis.setStartAuthority(undefined);\n\t\t\treturn;\n\t\t}\n\t\tthis.queuedOwnerChatExecutionLease = lease;\n\t}\n\n\tendQueuedOwnerChatGoalExecution(): void {\n\t\tconst lease = this.queuedOwnerChatExecutionLease;\n\t\tif (!lease) return;\n\t\tthis.queuedOwnerChatExecutionLease = undefined;\n\t\tthis.setStartAuthority(undefined);\n\t\tthis.endExecution(lease);\n\t}\n\n\tadmitExplicitChatGoal(text: string, now?: string, priorUserText?: string): ChatGoalAdmission {\n\t\tconst admittedAt = now ?? new Date().toISOString();\n\t\tconst parsed = parseExplicitChatGoal(text, priorUserText);\n\t\tif (!parsed) return { status: \"not_explicit\" };\n\t\tconst current = this.getState();\n\t\tif (current && isGoalUnfinishedStatus(current.status)) {\n\t\t\treturn { status: \"unfinished_goal_exists\", state: current };\n\t\t}\n\t\tconst digest = createHash(\"sha256\")\n\t\t\t.update(`${admittedAt}\\0${current?.goalId ?? \"none\"}\\0${parsed.objective}`)\n\t\t\t.digest(\"hex\")\n\t\t\t.slice(0, 20);\n\t\tconst result = applyGoalAction(\n\t\t\tcurrent,\n\t\t\t{\n\t\t\t\taction: \"start\",\n\t\t\t\tgoalId: `chat-${digest}`,\n\t\t\t\tuserGoal: parsed.objective,\n\t\t\t\ttokenBudget: parsed.tokenBudget,\n\t\t\t},\n\t\t\tadmittedAt,\n\t\t);\n\t\tif (!result.ok) throw new Error(result.error);\n\t\tthis.saveState(result.state, current ? getGoalStateRevision(current) : undefined);\n\t\treturn { status: \"started\", state: result.state };\n\t}\n\n\t/** Attribute turn/wall-clock telemetry without inferring progress (public/manual accounting seam). */\n\trecordContinuationTelemetry(pass: { turns: number; wallClockMs: number }): void {\n\t\tthis.persistContinuationPass(pass);\n\t}\n\n\t/** Attribute one host-driven pass and derive stall state from the authoritative revision. */\n\tprivate recordContinuationPass(pass: {\n\t\tturns: number;\n\t\twallClockMs: number;\n\t\tgoalId: string;\n\t\tprogressRevision: number;\n\t\tstallTurns: number;\n\t}): void {\n\t\tthis.persistContinuationPass(pass);\n\t}\n\n\tprivate persistContinuationPass(\n\t\tpass: { turns: number; wallClockMs: number } & Partial<\n\t\t\tPick<GoalState, \"goalId\" | \"progressRevision\" | \"stallTurns\">\n\t\t>,\n\t): void {\n\t\tconst state = this.getState();\n\t\tif (!state) return;\n\t\tif (pass.goalId !== undefined && state.goalId !== pass.goalId) {\n\t\t\tthis.deps.emitWarning(\n\t\t\t\t`Goal continuation accounting skipped because goal '${pass.goalId}' was replaced by '${state.goalId}' during the pass.`,\n\t\t\t);\n\t\t\treturn;\n\t\t}\n\t\tconst now = new Date().toISOString();\n\t\tlet updated = applyGoalEvent(state, {\n\t\t\ttype: \"record_continuation_budget\",\n\t\t\tturns: pass.turns,\n\t\t\twallClockMs: pass.wallClockMs,\n\t\t\ttokens: 0,\n\t\t\tspendUsd: 0,\n\t\t\tnow,\n\t\t});\n\t\tif (\n\t\t\tpass.progressRevision !== undefined &&\n\t\t\tpass.stallTurns !== undefined &&\n\t\t\tisGoalExecutionActive(state.status) &&\n\t\t\t(state.progressRevision ?? 0) <= pass.progressRevision &&\n\t\t\tstate.stallTurns <= pass.stallTurns\n\t\t) {\n\t\t\tupdated = applyGoalEvent(updated, { type: \"no_progress\", now });\n\t\t}\n\t\tthis.saveState(updated, getGoalStateRevision(state));\n\t}\n\n\t/** Begin one foreground execution whose provider usage belongs to the specified active goal. */\n\tbeginExecution(\n\t\tgoalId: string | undefined,\n\t\toptions: { adoptNewGoal?: boolean; provisionalTokenBudget?: number } = {},\n\t): GoalExecutionLease | undefined {\n\t\tif (!goalId && !options.adoptNewGoal) return undefined;\n\t\tif (this.executionLease) throw new Error(\"Goal execution attribution is already active\");\n\t\tconst state = this.getState();\n\t\tif (goalId && (!state || state.goalId !== goalId || !isGoalExecutionActive(state.status))) return undefined;\n\t\tconst lease: MutableGoalExecutionLease = {\n\t\t\t...(goalId ? { goalId } : {}),\n\t\t\t[goalExecutionLeaseMarker]: true,\n\t\t\tadoptNewGoal: options.adoptNewGoal === true,\n\t\t\t...(options.adoptNewGoal && state ? { adoptionBaselineGoalId: state.goalId } : {}),\n\t\t\t...(options.provisionalTokenBudget !== undefined\n\t\t\t\t? { provisionalTokenBudget: options.provisionalTokenBudget }\n\t\t\t\t: {}),\n\t\t\tpendingTokens: 0,\n\t\t\tpendingSpendUsd: 0,\n\t\t\tadmittedWhileActive: false,\n\t\t};\n\t\tthis.executionLease = lease;\n\t\treturn lease;\n\t}\n\n\tendExecution(lease: GoalExecutionLease | undefined): void {\n\t\tif (!lease) return;\n\t\tif (this.executionLease !== lease) throw new Error(\"Cannot end goal execution attribution owned by another run\");\n\t\tthis.flushPendingExecutionUsage(this.executionLease);\n\t\tthis.executionLease = undefined;\n\t}\n\n\t/** Charge one observed assistant response exactly once, including routed responses buffered from persistence. */\n\trecordExecutionUsage(message: AssistantMessage): void {\n\t\tconst lease = this.executionLease;\n\t\tif (!lease) return;\n\t\tconst tokens = budgetedTokens({\n\t\t\tinputTokens: Math.max(0, message.usage.input),\n\t\t\toutputTokens: Math.max(0, message.usage.output),\n\t\t\tcacheReadTokens: Math.max(0, message.usage.cacheRead),\n\t\t\tcacheWriteTokens: Math.max(0, message.usage.cacheWrite),\n\t\t\ttotalTokens: Math.max(0, message.usage.totalTokens),\n\t\t});\n\t\tconst spendUsd = Math.max(0, message.usage.cost.total);\n\t\tif (tokens === 0 && spendUsd === 0) return;\n\t\tconst state = this.resolveExecutionState(lease);\n\t\tif (!state) {\n\t\t\tlease.pendingTokens += tokens;\n\t\t\tlease.pendingSpendUsd += spendUsd;\n\t\t\treturn;\n\t\t}\n\t\tthis.chargeExecutionUsage(lease, state, tokens, spendUsd);\n\t}\n\n\tprivate chargeExecutionUsage(\n\t\tlease: MutableGoalExecutionLease,\n\t\tstate: GoalState,\n\t\ttokens: number,\n\t\tspendUsd: number,\n\t): void {\n\t\tconst updated = applyGoalEvent(state, {\n\t\t\ttype: \"record_continuation_budget\",\n\t\t\tturns: 0,\n\t\t\twallClockMs: 0,\n\t\t\ttokens,\n\t\t\tspendUsd,\n\t\t\tnow: new Date().toISOString(),\n\t\t});\n\t\tthis.saveState(updated, getGoalStateRevision(state));\n\t\tlease.pendingTokens = 0;\n\t\tlease.pendingSpendUsd = 0;\n\t\tif (\n\t\t\tisGoalExecutionActive(updated.status) &&\n\t\t\tupdated.tokenBudget !== undefined &&\n\t\t\t(updated.tokensUsed ?? 0) >= updated.tokenBudget\n\t\t) {\n\t\t\tthis.markBudgetLimited(\n\t\t\t\t`token budget exhausted (${updated.tokensUsed ?? 0}/${updated.tokenBudget}) during goal execution`,\n\t\t\t);\n\t\t}\n\t}\n\n\tmarkProtocolFailureBlocked(errorMessage: string): boolean {\n\t\tconst lease = this.executionLease;\n\t\tif (!lease) return false;\n\t\tconst state = this.resolveExecutionState(lease);\n\t\tif (!state || !isGoalExecutionActive(state.status)) return false;\n\t\tconst stopped = stopGoalFromSystem(\n\t\t\tstate,\n\t\t\t{ status: \"blocked\", reason: errorMessage.slice(0, 500) },\n\t\t\tnew Date().toISOString(),\n\t\t);\n\t\tif (!stopped.ok) return false;\n\t\tthis.saveState(stopped.state, getGoalStateRevision(state));\n\t\treturn true;\n\t}\n\n\tsetStartAuthority(authority: ExplicitGoalStartAuthority | undefined): void {\n\t\tthis.startAuthority = authority;\n\t}\n\n\tauthorizeStartFromTool(input: { tokenBudget?: number }): string | undefined {\n\t\tconst authority = this.startAuthority;\n\t\tif (!authority) return \"goal start requires explicit owner authorization in the current prompt.\";\n\t\tif (authority.tokenBudget === undefined && input.tokenBudget !== undefined) {\n\t\t\treturn \"tokenBudget requires an exact numeric token ceiling in the current owner prompt.\";\n\t\t}\n\t\tif (authority.tokenBudget !== undefined && input.tokenBudget !== authority.tokenBudget) {\n\t\t\treturn `tokenBudget must equal the owner-requested ceiling ${authority.tokenBudget}.`;\n\t\t}\n\t\treturn undefined;\n\t}\n\n\t/**\n\t * True once the currently held execution lease's goal has crossed into `budget_limited` — set\n\t * synchronously by `chargeExecutionUsage` as soon as a just-charged response crosses the ceiling.\n\t * Wired to the agent's `shouldStopAfterTurn` hook so a mid-turn budget stop ends the loop\n\t * gracefully BEFORE the next provider request is even planned, instead of only being caught by\n\t * `admitProviderRequest`'s throw — which still exists as the backstop for a fresh turn or an\n\t * external admission starting against an already budget_limited goal, but would otherwise also\n\t * fire for a request this same lease was already mid-flight for, surfacing a synthetic error\n\t * message where a clean turn end belongs.\n\t */\n\thasExecutionLeaseCrossedBudgetLimit(): boolean {\n\t\tconst lease = this.executionLease;\n\t\tif (!lease) return false;\n\t\treturn this.resolveExecutionState(lease)?.status === \"budget_limited\";\n\t}\n\n\t/** Reserve only remaining output capacity; actual provider usage is charged on response. */\n\tadmitProviderRequest(): number | undefined {\n\t\tconst lease = this.executionLease;\n\t\tif (!lease) return undefined;\n\t\tthis.flushPendingExecutionUsage(lease);\n\t\tconst state = this.resolveExecutionState(lease);\n\t\tif (state?.status === \"budget_limited\") {\n\t\t\tthrow new GoalBudgetExhaustedError(`goal_token_budget_exhausted: ${state.blockedReason ?? lease.goalId}`);\n\t\t}\n\t\tif (state && !isGoalExecutionActive(state.status)) {\n\t\t\tif (!lease.admittedWhileActive) {\n\t\t\t\t// A fresh turn/continuation is being started against a goal that is already done —\n\t\t\t\t// keep this denied so a dead goal cannot restart itself.\n\t\t\t\tthrow new Error(`goal_execution_not_active: ${state.goalId} is ${state.status}`);\n\t\t\t}\n\t\t\t// This lease already admitted at least one request while the goal was active, so the\n\t\t\t// goal ended mid-turn (e.g. the model itself just called `goal complete`/`block`). Let\n\t\t\t// the already-in-flight turn drain to its closing response instead of throwing an error\n\t\t\t// at the user right after a successful stop.\n\t\t\treturn undefined;\n\t\t}\n\t\tif (!state && lease.goalId !== undefined) {\n\t\t\tthrow new Error(`goal_execution_not_active: ${lease.goalId} no longer exists`);\n\t\t}\n\t\tlease.admittedWhileActive = true;\n\t\tconst tokenBudget = state?.tokenBudget ?? lease.provisionalTokenBudget;\n\t\tif (tokenBudget === undefined) return undefined;\n\t\tconst tokensUsed = state?.tokensUsed ?? lease.pendingTokens;\n\t\tconst remaining = Math.max(0, tokenBudget - tokensUsed);\n\t\tif (remaining < MIN_VIABLE_GOAL_TURN_OUTPUT_TOKENS) {\n\t\t\t// Below the floor, remaining is too small to hand to the provider as an output cap without\n\t\t\t// dooming the turn to a mid-generation truncation that still burns the full input cost.\n\t\t\t// Stop cleanly now instead of sending a request that cannot possibly complete.\n\t\t\tif (state) {\n\t\t\t\tthis.markBudgetLimited(\n\t\t\t\t\t`token budget nearly exhausted (${tokensUsed}/${tokenBudget}, ${remaining} remaining is below the ` +\n\t\t\t\t\t\t`${MIN_VIABLE_GOAL_TURN_OUTPUT_TOKENS}-token minimum viable turn) before provider request`,\n\t\t\t\t);\n\t\t\t}\n\t\t\tthrow new GoalBudgetExhaustedError(\n\t\t\t\t`goal_token_budget_exhausted: ${remaining} tokens remain, below the ${MIN_VIABLE_GOAL_TURN_OUTPUT_TOKENS}-token minimum viable turn`,\n\t\t\t);\n\t\t}\n\t\treturn remaining;\n\t}\n\n\tprivate resolveExecutionState(lease: MutableGoalExecutionLease): GoalState | undefined {\n\t\tconst state = this.getState();\n\t\tif (!state) return undefined;\n\t\tif (lease.goalId === state.goalId) return state;\n\t\tif (lease.goalId !== undefined || !lease.adoptNewGoal) return undefined;\n\t\tif (lease.adoptionBaselineGoalId === state.goalId) return undefined;\n\t\tlease.goalId = state.goalId;\n\t\treturn state;\n\t}\n\n\tprivate flushPendingExecutionUsage(lease: MutableGoalExecutionLease): void {\n\t\tif (lease.pendingTokens === 0 && lease.pendingSpendUsd === 0) return;\n\t\tconst state = this.resolveExecutionState(lease);\n\t\tif (!state) {\n\t\t\t// A speculative adopt-new-goal lease (lease.goalId still undefined) that never actually\n\t\t\t// adopted a goal this turn has nowhere to attribute usage — that is normal, not a loss.\n\t\t\t// A lease that WAS bound to a real goal but can no longer resolve it is a genuine loss of\n\t\t\t// buffered spend; fail loudly instead of silently discarding it (matches the cursor-based\n\t\t\t// accounting this replaced, which stopped the goal on `goal_usage_cursor_lost`).\n\t\t\tif (lease.goalId !== undefined) {\n\t\t\t\tthis.deps.emitWarning(\n\t\t\t\t\t`Goal usage cursor is no longer resolvable for '${lease.goalId}'; ${lease.pendingTokens} pending tokens and $${lease.pendingSpendUsd.toFixed(6)} pending spend could not be attributed and were dropped.`,\n\t\t\t\t);\n\t\t\t\tthis.recordContinuationFailure(new Error(\"goal_usage_cursor_lost\"));\n\t\t\t}\n\t\t\tlease.pendingTokens = 0;\n\t\t\tlease.pendingSpendUsd = 0;\n\t\t\treturn;\n\t\t}\n\t\tthis.chargeExecutionUsage(lease, state, lease.pendingTokens, lease.pendingSpendUsd);\n\t}\n\n\tmarkToolUnavailable(): void {\n\t\tthis.stopActiveGoal(\n\t\t\t\"blocked\",\n\t\t\t\"goal_tool_unavailable: the active capability surface cannot update durable goal state\",\n\t\t);\n\t}\n\n\tmarkHarnessGuardBlocked(info: AgentRunawayStopInfo): boolean {\n\t\tconst reason =\n\t\t\tinfo.reason === \"provider_turn_limit\"\n\t\t\t\t? `provider_turn_limit: reached the explicit ${info.repeats}-request provider-turn limit`\n\t\t\t\t: `runaway_tool_loop: repeated tool-call signature ${info.signature} ${info.repeats} times without progress`;\n\t\treturn this.stopActiveGoal(\"blocked\", reason);\n\t}\n\n\tmarkTerminalToolFailureBlocked(toolName: string): boolean {\n\t\treturn this.stopActiveGoal(\n\t\t\t\"blocked\",\n\t\t\t`terminal_tool_failure: ${toolName} reported an unrecoverable error and terminated the run`,\n\t\t);\n\t}\n\n\tgetRuntimeSnapshot(settings: GoalRuntimeSnapshotSettings): GoalRuntimeSnapshot {\n\t\treturn buildGoalRuntimeSnapshot({\n\t\t\tsessionManager: this.deps.getSessionManager(),\n\t\t\tsettings,\n\t\t\tlaneRecords: this.deps.getLaneRecords(),\n\t\t\ttaskRuntime: this.deps.getTaskRuntimeSnapshot(),\n\t\t\tbackgroundToolTasks: this.deps.getBackgroundToolTasks(),\n\t\t});\n\t}\n\n\tcontinueOnce(options: GoalContinuationOnceOptions): Promise<GoalContinuationOnceResult> {\n\t\treturn this.loop.continueGoalOnce(options);\n\t}\n\n\tcontinueLoop(options: GoalContinuationLoopOptions): Promise<GoalContinuationLoopResult> {\n\t\treturn this.loop.continueGoalLoop(options);\n\t}\n\n\trestoreAfterResume(): void {\n\t\tthis.deps.scheduleGoalAutoContinueFromIdle();\n\t}\n\n\tprivate recordContinuationFailure(error: unknown): void {\n\t\tconst state = this.getState();\n\t\tif (!state || !isGoalExecutionActive(state.status)) return;\n\t\tconst message = error instanceof Error ? error.message : String(error);\n\t\tconst classified = classifyFailure({ message, provider: this.deps.getModelProvider() });\n\t\tconst status = classified.reason === \"billing_or_quota\" ? \"usage_limited\" : \"blocked\";\n\t\tthis.stopActiveGoal(status, `${classified.reason}: ${message}`);\n\t}\n\n\tprivate markBudgetLimited(reason: string): void {\n\t\tthis.stopActiveGoal(\"budget_limited\", reason);\n\t}\n\n\tprivate stopActiveGoal(status: \"blocked\" | \"usage_limited\" | \"budget_limited\", reason: string): boolean {\n\t\tconst state = this.getState();\n\t\tconst stopped = stopGoalFromSystem(state, { status, reason }, new Date().toISOString());\n\t\tif (!stopped.ok || !state) return false;\n\t\tthis.saveState(stopped.state, getGoalStateRevision(state));\n\t\treturn true;\n\t}\n}\n"]}
|
|
@@ -29,6 +29,6 @@ export declare function priorUserPromptText(messages: readonly {
|
|
|
29
29
|
content?: unknown;
|
|
30
30
|
}[], currentText: string): string | undefined;
|
|
31
31
|
export declare function parseExplicitChatGoal(text: string, priorUserText?: string): ExplicitChatGoal | undefined;
|
|
32
|
-
/** Exact owner authority for model-
|
|
32
|
+
/** Exact owner authority for model-supplied token budgets; ordinary work carries no budget authority. */
|
|
33
33
|
export declare function parseExplicitGoalStartAuthority(text: string): ExplicitGoalStartAuthority | undefined;
|
|
34
34
|
//# sourceMappingURL=natural-language-goal.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"natural-language-goal.d.ts","sourceRoot":"","sources":["../../../src/core/goals/natural-language-goal.ts"],"names":[],"mappings":"AAEA,MAAM,WAAW,gBAAgB;IAChC,SAAS,EAAE,MAAM,CAAC;IAClB,WAAW,CAAC,EAAE,MAAM,CAAC;CACrB;AAED,MAAM,WAAW,0BAA0B;IAC1C,WAAW,CAAC,EAAE,MAAM,CAAC;CACrB;AAkCD;;2CAE2C;AAC3C,qBAAa,yBAA0B,SAAQ,KAAK;IACnD,YAAY,OAAO,EAAE,MAAM,EAG1B;CACD;AAsED;;;;;;;GAOG;AACH,wBAAgB,yBAAyB,CACxC,IAAI,EAAE,MAAM,EACZ,SAAS,CAAC,EAAE;IAAE,KAAK,EAAE,MAAM,CAAC;IAAC,GAAG,EAAE,MAAM,CAAA;CAAE,GACxC,MAAM,GAAG,SAAS,CAMpB;AAyED,gFAAgF;AAChF,wBAAgB,mBAAmB,CAClC,QAAQ,EAAE,SAAS;IAAE,IAAI,EAAE,MAAM,CAAC;IAAC,OAAO,CAAC,EAAE,OAAO,CAAA;CAAE,EAAE,EACxD,WAAW,EAAE,MAAM,GACjB,MAAM,GAAG,SAAS,CAUpB;AAED,wBAAgB,qBAAqB,CAAC,IAAI,EAAE,MAAM,EAAE,aAAa,CAAC,EAAE,MAAM,GAAG,gBAAgB,GAAG,SAAS,CA4BxG;AAED,
|
|
1
|
+
{"version":3,"file":"natural-language-goal.d.ts","sourceRoot":"","sources":["../../../src/core/goals/natural-language-goal.ts"],"names":[],"mappings":"AAEA,MAAM,WAAW,gBAAgB;IAChC,SAAS,EAAE,MAAM,CAAC;IAClB,WAAW,CAAC,EAAE,MAAM,CAAC;CACrB;AAED,MAAM,WAAW,0BAA0B;IAC1C,WAAW,CAAC,EAAE,MAAM,CAAC;CACrB;AAkCD;;2CAE2C;AAC3C,qBAAa,yBAA0B,SAAQ,KAAK;IACnD,YAAY,OAAO,EAAE,MAAM,EAG1B;CACD;AAsED;;;;;;;GAOG;AACH,wBAAgB,yBAAyB,CACxC,IAAI,EAAE,MAAM,EACZ,SAAS,CAAC,EAAE;IAAE,KAAK,EAAE,MAAM,CAAC;IAAC,GAAG,EAAE,MAAM,CAAA;CAAE,GACxC,MAAM,GAAG,SAAS,CAMpB;AAyED,gFAAgF;AAChF,wBAAgB,mBAAmB,CAClC,QAAQ,EAAE,SAAS;IAAE,IAAI,EAAE,MAAM,CAAC;IAAC,OAAO,CAAC,EAAE,OAAO,CAAA;CAAE,EAAE,EACxD,WAAW,EAAE,MAAM,GACjB,MAAM,GAAG,SAAS,CAUpB;AAED,wBAAgB,qBAAqB,CAAC,IAAI,EAAE,MAAM,EAAE,aAAa,CAAC,EAAE,MAAM,GAAG,gBAAgB,GAAG,SAAS,CA4BxG;AAED,yGAAyG;AACzG,wBAAgB,+BAA+B,CAAC,IAAI,EAAE,MAAM,GAAG,0BAA0B,GAAG,SAAS,CAMpG"}
|
|
@@ -237,7 +237,7 @@ export function parseExplicitChatGoal(text, priorUserText) {
|
|
|
237
237
|
return undefined;
|
|
238
238
|
return { objective, ...(tokenBudget !== undefined ? { tokenBudget } : {}) };
|
|
239
239
|
}
|
|
240
|
-
/** Exact owner authority for model-
|
|
240
|
+
/** Exact owner authority for model-supplied token budgets; ordinary work carries no budget authority. */
|
|
241
241
|
export function parseExplicitGoalStartAuthority(text) {
|
|
242
242
|
const goal = parseExplicitChatGoal(text);
|
|
243
243
|
if (goal)
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"natural-language-goal.js","sourceRoot":"","sources":["../../../src/core/goals/natural-language-goal.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,yBAAyB,EAAE,MAAM,iBAAiB,CAAC;AAW5D,MAAM,sBAAsB,GAAG;IAC9B,+EAA+E;IAC/E,gDAAgD;IAChD,8DAA8D;IAC9D,mEAAmE;IACnE,2EAA2E;IAC3E,0EAA0E;IAC1E,wCAAwC;IACxC,8DAA8D;CACrD,CAAC;AAEX,MAAM,kCAAkC,GAAG;IAC1C,2EAA2E;IAC3E,uFAAuF;IACvF,kFAAkF;IAClF,6FAA6F;IAC7F,+FAA+F;IAC/F,sGAAsG;CAC7F,CAAC;AAEX,MAAM,sBAAsB,GAAG,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AM,KAAK,GAAG,aAAa,EAAE,IAAI,EAAE,CAAC;IACpC,MAAM,SAAS,GACd,MAAM,IAAI,MAAM,CAAC,MAAM,IAAI,yBAAyB;QACnD,CAAC,CAAC,MAAM;QACR,CAAC,CAAC,KAAK,IAAI,KAAK,KAAK,IAAI,CAAC,IAAI,EAAE,IAAI,KAAK,CAAC,MAAM,IAAI,yBAAyB;YAC5E,CAAC,CAAC,KAAK;YACP,CAAC,CAAC,SAAS,CAAC;IACf,IAAI,CAAC,SAAS;QAAE,OAAO,SAAS,CAAC;IACjC,OAAO,EAAE,SAAS,EAAE,GAAG,CAAC,WAAW,KAAK,SAAS,CAAC,CAAC,CAAC,EAAE,WAAW,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC,EAAE,CAAC;AAC7E,CAAC;AAED,2GAA2G;AAC3G,MAAM,UAAU,+BAA+B,CAAC,IAAY;IAC3D,MAAM,IAAI,GAAG,qBAAqB,CAAC,IAAI,CAAC,CAAC;IACzC,IAAI,IAAI;QAAE,OAAO,IAAI,CAAC,WAAW,KAAK,SAAS,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,EAAE,WAAW,EAAE,IAAI,CAAC,WAAW,EAAE,CAAC;IACzF,IAAI,CAAC,kCAAkC,CAAC,IAAI,CAAC,CAAC,OAAO,EAAE,EAAE,CAAC,OAAO,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;QAAE,OAAO,SAAS,CAAC;IAChG,MAAM,WAAW,GAAG,yBAAyB,CAAC,IAAI,CAAC,CAAC;IACpD,OAAO,WAAW,KAAK,SAAS,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,EAAE,WAAW,EAAE,CAAC;AACzD,CAAC","sourcesContent":["import { MAX_GOAL_OBJECTIVE_LENGTH } from \"./goal-state.ts\";\n\nexport interface ExplicitChatGoal {\n\tobjective: string;\n\ttokenBudget?: number;\n}\n\nexport interface ExplicitGoalStartAuthority {\n\ttokenBudget?: number;\n}\n\nconst EXPLICIT_GOAL_PATTERNS = [\n\t/^\\s*set\\s+(?:this\\s+as\\s+)?a\\s+(?:persistent\\s+)?goal\\s*(?::|to\\s+)\\s*(.+)$/is,\n\t/^\\s*my\\s+persistent\\s+goal\\s+is\\s+to\\s+(.+)$/is,\n\t/^\\s*(?:the|our)\\s+(?:persistent\\s+)?goal\\s+is\\s+to\\s+(.+)$/is,\n\t/^\\s*treat\\s+this\\s+as\\s+my\\s+(?:persistent\\s+)?goal\\s*:\\s*(.+)$/is,\n\t/^\\s*i\\s+want\\s+this\\s+as\\s+(?:my\\s+)?(?:persistent\\s+)?goal\\s*:\\s*(.+)$/is,\n\t/^\\s*keep\\s+working\\s+until\\s+this\\s+is\\s+(?:complete|done)\\s*:\\s*(.+)$/is,\n\t/^\\s*instead of .+,\\s*i want to (.+)$/is,\n\t/^\\s*i want to ((?:refactor|rewrite|rebuild|redesign)\\b.+)$/is,\n] as const;\n\nconst STANDALONE_GOAL_AUTHORITY_PATTERNS = [\n\t// After \"goal\" require end, whitespace, or punctuation — not a hyphen — so\n\t// \"this is a goal, use it\" authorizes while \"this is a goal-oriented design\" does not.\n\t/^\\s*(?:this|that)\\s+is\\s+(?:now\\s+)?a\\s+(?:persistent\\s+)?goal(?=[\\s,.:;!?]|$)/is,\n\t/^\\s*(?:this|the|that)\\s+task\\s+is\\s+(?:now\\s+)?a\\s+(?:persistent\\s+)?goal(?=[\\s,.:;!?]|$)/is,\n\t/^\\s*(?:make|treat)\\s+this\\s+(?:as\\s+)?(?:my\\s+|a\\s+)?(?:persistent\\s+)?goal(?=[\\s,.:;!?]|$)/is,\n\t/^\\s*(?:make|treat)\\s+this\\s+task\\s+(?:as\\s+)?(?:my\\s+|a\\s+)?(?:persistent\\s+)?goal(?=[\\s,.:;!?]|$)/is,\n] as const;\n\nconst STANDALONE_GOAL_FILLER = /^(?:use it|please|now|ok|okay|thanks|go|do it)(?:[.!?])?$/i;\n\nconst STANDALONE_GOAL_PROCESS_PHRASES = [\n\t/\\bby the way\\b/gi,\n\t/\\bi(?:'m| am) handing (?:(?:this|it) )?over(?: to you)?\\b/gi,\n\t/\\bhand(?:ing)? (?:(?:this|it) )?over(?: to you)?\\b/gi,\n\t/\\buse max(?:imum)? \\d+ sub[-\\s]?agents?\\b/gi,\n\t/\\byou are (?:the )?(?:orchestrator|reviewer|team lead)(?:(?:\\s+and|\\s*,)\\s*(?:also\\s+)?(?:the\\s+)?(?:orchestrator|reviewer|team lead))*\\b/gi,\n\t/\\bhelp you deliver\\b/gi,\n\t/\\b(?:orchestrator|reviewer|team lead)\\b/gi,\n] as const;\n\n/** Raised when text unambiguously states a token-budget directive but the amount cannot be resolved\n * to an exact positive integer. Callers must let this propagate as a loud, explicit failure instead\n * of falling back to an unbounded goal. */\nexport class GoalTokenBudgetParseError extends Error {\n\tconstructor(message: string) {\n\t\tsuper(message);\n\t\tthis.name = \"GoalTokenBudgetParseError\";\n\t}\n}\n\nconst TOKEN_UNIT_MULTIPLIERS: Record<string, number> = {\n\tk: 1_000,\n\tthousand: 1_000,\n\tm: 1_000_000,\n\tmillion: 1_000_000,\n};\n\n/**\n * Resolve a matched numeral into a plain integer, disambiguating a thousands separator from a\n * decimal point. Comma is never a decimal point in this grammar, so any comma-grouped digits\n * (e.g. \"5,000\") are treated as a separator. A dot is genuinely ambiguous (\"1.5\" vs \"1.000.000\"),\n * so it is only treated as a separator when the exactly-3-digit group repeats (e.g. \"1.000.000\");\n * a single dot group falls back to a literal decimal (e.g. \"1.5\", or \"1.000\" read as 1).\n */\nfunction normalizeTokenNumeral(raw: string): number | undefined {\n\t// The caller's capture regex allows \",\" \"_\" \".\" to continue a numeral (they can be internal\n\t// separators), so it greedily swallows a trailing one that is NOT followed by more digits — e.g.\n\t// the sentence-ending \".\" after a dot-grouped \"1.000.000.\" A separator is only ever meaningful\n\t// between digits, so a trailing one is always incidental punctuation; drop it before classifying.\n\tconst compact = raw.replace(/_/g, \"\").replace(/[,.]+$/, \"\");\n\tif (/^[0-9]+$/.test(compact)) return Number(compact);\n\tif (/^[0-9]{1,3}(,[0-9]{3})+\\.[0-9]+$/.test(compact)) return Number(compact.replace(/,/g, \"\"));\n\tif (/^[0-9]{1,3}(,[0-9]{3})+$/.test(compact)) return Number(compact.replace(/,/g, \"\"));\n\tif (/^[0-9]{1,3}(\\.[0-9]{3}){2,}$/.test(compact)) return Number(compact.replace(/\\./g, \"\"));\n\tif (/^[0-9]+\\.[0-9]+$/.test(compact)) return Number(compact);\n\treturn undefined;\n}\n\nfunction parsePositiveTokenCount(raw: string, unit: string | undefined): number | undefined {\n\tconst value = normalizeTokenNumeral(raw);\n\tif (value === undefined) return undefined;\n\tconst multiplier = unit ? (TOKEN_UNIT_MULTIPLIERS[unit.toLowerCase()] ?? 1) : 1;\n\tconst tokens = value * multiplier;\n\treturn Number.isSafeInteger(tokens) && tokens > 0 ? tokens : undefined;\n}\n\nconst TOKEN_BUDGET_PATTERNS = [\n\t/\\btoken\\s+budget\\s*(?:of|is|:|=)?\\s*([0-9][0-9,_.]*)(?:\\s*(thousand|million|k|m)\\b)?/i,\n\t/\\b([0-9][0-9,_.]*)(?:\\s*(thousand|million|k|m)\\b)?\\s*(?:token|tokens)\\s+budget\\b/i,\n\t/\\bbudget\\s*(?:of|is|:|=)?\\s*([0-9][0-9,_.]*)(?:\\s*(thousand|million|k|m)\\b)?\\s*(?:token|tokens)\\b/i,\n] as const;\n\n/**\n * Scan `text` for one explicit token-budget directive. When `trailingOnly` is set, a match only\n * counts if it runs to the end of `text` (ignoring closing punctuation/whitespace) — used to scan\n * inside a captured goal objective, where a budget-shaped phrase embedded mid-sentence usually\n * describes the task's subject matter (e.g. a constant being edited in code), not the agent's own\n * execution ceiling, whereas a trailing clause (\"... with a 40k token budget.\") is a real directive.\n */\nfunction scanTokenBudget(text: string, options: { trailingOnly: boolean }): number | undefined {\n\tfor (const pattern of TOKEN_BUDGET_PATTERNS) {\n\t\tconst match = pattern.exec(text);\n\t\tif (!match) continue;\n\t\tif (options.trailingOnly) {\n\t\t\tconst tail = text.slice(match.index + match[0].length);\n\t\t\tif (!/^[.!?]?\\s*$/.test(tail)) continue;\n\t\t}\n\t\tconst tokens = parsePositiveTokenCount(match[1], match[2]);\n\t\tif (tokens === undefined) {\n\t\t\tthrow new GoalTokenBudgetParseError(\n\t\t\t\t`Token budget phrase \"${match[0].trim()}\" could not be parsed into an exact token ceiling.`,\n\t\t\t);\n\t\t}\n\t\treturn tokens;\n\t}\n\treturn undefined;\n}\n\n/**\n * Parse an explicit token-budget directive from `text`. When `objective` locates a captured goal\n * objective within `text`, a budget-shaped phrase found INSIDE it only counts when it is the\n * trailing clause of the objective; text outside the objective (the prefix/suffix around it) is\n * scanned without that restriction. This keeps a genuine directive (\"... with a 40k token budget.\")\n * working while refusing to adopt a number that is merely part of the task's own subject matter\n * (\"raise the model token budget of 4096 ... to 8192\").\n */\nexport function parseRequestedTokenBudget(\n\ttext: string,\n\tobjective?: { start: number; end: number },\n): number | undefined {\n\tif (!objective) return scanTokenBudget(text, { trailingOnly: false });\n\tconst outside = `${text.slice(0, objective.start)} ${text.slice(objective.end)}`;\n\tconst outsideBudget = scanTokenBudget(outside, { trailingOnly: false });\n\tif (outsideBudget !== undefined) return outsideBudget;\n\treturn scanTokenBudget(text.slice(objective.start, objective.end), { trailingOnly: true });\n}\n\n/**\n * Recognize only explicit persistence language. Ordinary multi-step work and discussion ABOUT goal\n * mechanics deliberately return undefined; those must not silently expand into autonomous work.\n */\nfunction standaloneGoalRemainder(text: string): string | undefined {\n\tfor (const pattern of STANDALONE_GOAL_AUTHORITY_PATTERNS) {\n\t\tconst match = pattern.exec(text);\n\t\tif (!match) continue;\n\t\treturn text\n\t\t\t.slice(match.index + match[0].length)\n\t\t\t.replace(/^[\\s,.:;!?-]+/, \"\")\n\t\t\t.replace(/^(?:and|then|so)\\s+/i, \"\")\n\t\t\t.trim();\n\t}\n\treturn undefined;\n}\n\nfunction remainderWithoutBudgetPhrase(remainder: string): string {\n\tlet next = remainder;\n\tfor (const pattern of TOKEN_BUDGET_PATTERNS) {\n\t\tnext = next.replace(pattern, \" \");\n\t}\n\treturn next\n\t\t.replace(/\\b(?:with|of|is|a|the|:|=)\\b/gi, \" \")\n\t\t.replace(/\\s+/g, \" \")\n\t\t.trim();\n}\n\nfunction remainderWithoutProcessPhrases(remainder: string): string {\n\tlet next = remainder;\n\tfor (const pattern of STANDALONE_GOAL_PROCESS_PHRASES) {\n\t\tnext = next.replace(pattern, \" \");\n\t}\n\treturn next\n\t\t.replace(/\\b(?:with|of|is|a|the|to|and|also|you|i|i'm|:|=)\\b/gi, \" \")\n\t\t.replace(/[.,:;!?]/g, \" \")\n\t\t.replace(/\\s+/g, \" \")\n\t\t.trim();\n}\n\nfunction isClassificationRemainder(remainder: string): boolean {\n\tif (!remainder || STANDALONE_GOAL_FILLER.test(remainder)) return true;\n\tconst leftover = remainderWithoutProcessPhrases(remainder);\n\tif (!leftover || STANDALONE_GOAL_FILLER.test(leftover)) return true;\n\ttry {\n\t\tif (parseRequestedTokenBudget(remainder) === undefined) return false;\n\t} catch {\n\t\treturn false;\n\t}\n\tconst afterBudget = remainderWithoutBudgetPhrase(leftover);\n\treturn afterBudget.length === 0 || STANDALONE_GOAL_FILLER.test(afterBudget);\n}\n\nfunction userMessageText(content: unknown): string {\n\tif (typeof content === \"string\") return content.trim();\n\tif (!Array.isArray(content)) return \"\";\n\treturn content\n\t\t.filter(\n\t\t\t(block): block is { type: \"text\"; text: string } =>\n\t\t\t\ttypeof block === \"object\" &&\n\t\t\t\tblock !== null &&\n\t\t\t\t\"type\" in block &&\n\t\t\t\tblock.type === \"text\" &&\n\t\t\t\t\"text\" in block &&\n\t\t\t\ttypeof block.text === \"string\",\n\t\t)\n\t\t.map((block) => block.text)\n\t\t.join(\"\")\n\t\t.trim();\n}\n\n/** Latest owner prompt that is not the current classification phrase itself. */\nexport function priorUserPromptText(\n\tmessages: readonly { role: string; content?: unknown }[],\n\tcurrentText: string,\n): string | undefined {\n\tconst current = currentText.trim();\n\tfor (let index = messages.length - 1; index >= 0; index--) {\n\t\tconst message = messages[index];\n\t\tif (message.role !== \"user\") continue;\n\t\tconst text = userMessageText(message.content);\n\t\tif (!text || text === current) continue;\n\t\treturn text;\n\t}\n\treturn undefined;\n}\n\nexport function parseExplicitChatGoal(text: string, priorUserText?: string): ExplicitChatGoal | undefined {\n\tfor (const pattern of EXPLICIT_GOAL_PATTERNS) {\n\t\tconst match = pattern.exec(text);\n\t\tconst rawObjective = match?.[1];\n\t\tconst objective = rawObjective?.trim();\n\t\tif (!match || !objective || objective.length > MAX_GOAL_OBJECTIVE_LENGTH) continue;\n\t\t// rawObjective is always a suffix of match[0] (every pattern ends in `(.+)$`), so its start\n\t\t// offset in `text` is match[0]'s length minus its own length.\n\t\tconst objectiveSpan = {\n\t\t\tstart: match.index + (match[0].length - (rawObjective?.length ?? 0)),\n\t\t\tend: match.index + match[0].length,\n\t\t};\n\t\tconst tokenBudget = parseRequestedTokenBudget(text, objectiveSpan);\n\t\treturn { objective, ...(tokenBudget !== undefined ? { tokenBudget } : {}) };\n\t}\n\tconst remainder = standaloneGoalRemainder(text);\n\tif (remainder === undefined) return undefined;\n\tconst tokenBudget = parseRequestedTokenBudget(text);\n\tconst inline = remainder && !isClassificationRemainder(remainder) ? remainder : undefined;\n\tconst prior = priorUserText?.trim();\n\tconst objective =\n\t\tinline && inline.length <= MAX_GOAL_OBJECTIVE_LENGTH\n\t\t\t? inline\n\t\t\t: prior && prior !== text.trim() && prior.length <= MAX_GOAL_OBJECTIVE_LENGTH\n\t\t\t\t? prior\n\t\t\t\t: undefined;\n\tif (!objective) return undefined;\n\treturn { objective, ...(tokenBudget !== undefined ? { tokenBudget } : {}) };\n}\n\n/** Exact owner authority for model-facing goal creation; ordinary work and meta-discussion fail closed. */\nexport function parseExplicitGoalStartAuthority(text: string): ExplicitGoalStartAuthority | undefined {\n\tconst goal = parseExplicitChatGoal(text);\n\tif (goal) return goal.tokenBudget === undefined ? {} : { tokenBudget: goal.tokenBudget };\n\tif (!STANDALONE_GOAL_AUTHORITY_PATTERNS.some((pattern) => pattern.test(text))) return undefined;\n\tconst tokenBudget = parseRequestedTokenBudget(text);\n\treturn tokenBudget === undefined ? {} : { tokenBudget };\n}\n"]}
|
|
1
|
+
{"version":3,"file":"natural-language-goal.js","sourceRoot":"","sources":["../../../src/core/goals/natural-language-goal.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,yBAAyB,EAAE,MAAM,iBAAiB,CAAC;AAW5D,MAAM,sBAAsB,GAAG;IAC9B,+EAA+E;IAC/E,gDAAgD;IAChD,8DAA8D;IAC9D,mEAAmE;IACnE,2EAA2E;IAC3E,0EAA0E;IAC1E,wCAAwC;IACxC,8DAA8D;CACrD,CAAC;AAEX,MAAM,kCAAkC,GAAG;IAC1C,2EAA2E;IAC3E,uFAAuF;IACvF,kFAAkF;IAClF,6FAA6F;IAC7F,+FAA+F;IAC/F,sGAAsG;CAC7F,CAAC;AAEX,MAAM,sBAAsB,GAAG,4DAA4D,CAAC;AAE5F,MAAM,+BAA+B,GAAG;IACvC,kBAAkB;IAClB,6DAA6D;IAC7D,sDAAsD;IACtD,6CAA6C;IAC7C,6IAA6I;IAC7I,wBAAwB;IACxB,2CAA2C;CAClC,CAAC;AAEX;;2CAE2C;AAC3C,MAAM,OAAO,yBAA0B,SAAQ,KAAK;IACnD,YAAY,OAAe;QAC1B,KAAK,CAAC,OAAO,CAAC,CAAC;QACf,IAAI,CAAC,IAAI,GAAG,2BAA2B,CAAC;IACzC,CAAC;CACD;AAED,MAAM,sBAAsB,GAA2B;IACtD,CAAC,EAAE,KAAK;IACR,QAAQ,EAAE,KAAK;IACf,CAAC,EAAE,SAAS;IACZ,OAAO,EAAE,SAAS;CAClB,CAAC;AAEF;;;;;;GAMG;AACH,SAAS,qBAAqB,CAAC,GAAW;IACzC,4FAA4F;IAC5F,iGAAiG;IACjG,+FAA+F;IAC/F,kGAAkG;IAClG,MAAM,OAAO,GAAG,GAAG,CAAC,OAAO,CAAC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QAAE,OAAO,IAAI,CAAC,WAAW,KAAK,SAAS,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,EAAE,WAAW,EAAE,IAAI,CAAC,WAAW,EAAE,CAAC;IACzF,IAAI,CAAC,kCAAkC,CAAC,IAAI,CAAC,CAAC,OAAO,EAAE,EAAE,CAAC,OAAO,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;QAAE,OAAO,SAAS,CAAC;IAChG,MAAM,WAAW,GAAG,yBAAyB,CAAC,IAAI,CAAC,CAAC;IACpD,OAAO,WAAW,KAAK,SAAS,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,EAAE,WAAW,EAAE,CAAC;AACzD,CAAC","sourcesContent":["import { MAX_GOAL_OBJECTIVE_LENGTH } from \"./goal-state.ts\";\n\nexport interface ExplicitChatGoal {\n\tobjective: string;\n\ttokenBudget?: number;\n}\n\nexport interface ExplicitGoalStartAuthority {\n\ttokenBudget?: number;\n}\n\nconst EXPLICIT_GOAL_PATTERNS = [\n\t/^\\s*set\\s+(?:this\\s+as\\s+)?a\\s+(?:persistent\\s+)?goal\\s*(?::|to\\s+)\\s*(.+)$/is,\n\t/^\\s*my\\s+persistent\\s+goal\\s+is\\s+to\\s+(.+)$/is,\n\t/^\\s*(?:the|our)\\s+(?:persistent\\s+)?goal\\s+is\\s+to\\s+(.+)$/is,\n\t/^\\s*treat\\s+this\\s+as\\s+my\\s+(?:persistent\\s+)?goal\\s*:\\s*(.+)$/is,\n\t/^\\s*i\\s+want\\s+this\\s+as\\s+(?:my\\s+)?(?:persistent\\s+)?goal\\s*:\\s*(.+)$/is,\n\t/^\\s*keep\\s+working\\s+until\\s+this\\s+is\\s+(?:complete|done)\\s*:\\s*(.+)$/is,\n\t/^\\s*instead of .+,\\s*i want to (.+)$/is,\n\t/^\\s*i want to ((?:refactor|rewrite|rebuild|redesign)\\b.+)$/is,\n] as const;\n\nconst STANDALONE_GOAL_AUTHORITY_PATTERNS = [\n\t// After \"goal\" require end, whitespace, or punctuation — not a hyphen — so\n\t// \"this is a goal, use it\" authorizes while \"this is a goal-oriented design\" does not.\n\t/^\\s*(?:this|that)\\s+is\\s+(?:now\\s+)?a\\s+(?:persistent\\s+)?goal(?=[\\s,.:;!?]|$)/is,\n\t/^\\s*(?:this|the|that)\\s+task\\s+is\\s+(?:now\\s+)?a\\s+(?:persistent\\s+)?goal(?=[\\s,.:;!?]|$)/is,\n\t/^\\s*(?:make|treat)\\s+this\\s+(?:as\\s+)?(?:my\\s+|a\\s+)?(?:persistent\\s+)?goal(?=[\\s,.:;!?]|$)/is,\n\t/^\\s*(?:make|treat)\\s+this\\s+task\\s+(?:as\\s+)?(?:my\\s+|a\\s+)?(?:persistent\\s+)?goal(?=[\\s,.:;!?]|$)/is,\n] as const;\n\nconst STANDALONE_GOAL_FILLER = /^(?:use it|please|now|ok|okay|thanks|go|do it)(?:[.!?])?$/i;\n\nconst STANDALONE_GOAL_PROCESS_PHRASES = [\n\t/\\bby the way\\b/gi,\n\t/\\bi(?:'m| am) handing (?:(?:this|it) )?over(?: to you)?\\b/gi,\n\t/\\bhand(?:ing)? (?:(?:this|it) )?over(?: to you)?\\b/gi,\n\t/\\buse max(?:imum)? \\d+ sub[-\\s]?agents?\\b/gi,\n\t/\\byou are (?:the )?(?:orchestrator|reviewer|team lead)(?:(?:\\s+and|\\s*,)\\s*(?:also\\s+)?(?:the\\s+)?(?:orchestrator|reviewer|team lead))*\\b/gi,\n\t/\\bhelp you deliver\\b/gi,\n\t/\\b(?:orchestrator|reviewer|team lead)\\b/gi,\n] as const;\n\n/** Raised when text unambiguously states a token-budget directive but the amount cannot be resolved\n * to an exact positive integer. Callers must let this propagate as a loud, explicit failure instead\n * of falling back to an unbounded goal. */\nexport class GoalTokenBudgetParseError extends Error {\n\tconstructor(message: string) {\n\t\tsuper(message);\n\t\tthis.name = \"GoalTokenBudgetParseError\";\n\t}\n}\n\nconst TOKEN_UNIT_MULTIPLIERS: Record<string, number> = {\n\tk: 1_000,\n\tthousand: 1_000,\n\tm: 1_000_000,\n\tmillion: 1_000_000,\n};\n\n/**\n * Resolve a matched numeral into a plain integer, disambiguating a thousands separator from a\n * decimal point. Comma is never a decimal point in this grammar, so any comma-grouped digits\n * (e.g. \"5,000\") are treated as a separator. A dot is genuinely ambiguous (\"1.5\" vs \"1.000.000\"),\n * so it is only treated as a separator when the exactly-3-digit group repeats (e.g. \"1.000.000\");\n * a single dot group falls back to a literal decimal (e.g. \"1.5\", or \"1.000\" read as 1).\n */\nfunction normalizeTokenNumeral(raw: string): number | undefined {\n\t// The caller's capture regex allows \",\" \"_\" \".\" to continue a numeral (they can be internal\n\t// separators), so it greedily swallows a trailing one that is NOT followed by more digits — e.g.\n\t// the sentence-ending \".\" after a dot-grouped \"1.000.000.\" A separator is only ever meaningful\n\t// between digits, so a trailing one is always incidental punctuation; drop it before classifying.\n\tconst compact = raw.replace(/_/g, \"\").replace(/[,.]+$/, \"\");\n\tif (/^[0-9]+$/.test(compact)) return Number(compact);\n\tif (/^[0-9]{1,3}(,[0-9]{3})+\\.[0-9]+$/.test(compact)) return Number(compact.replace(/,/g, \"\"));\n\tif (/^[0-9]{1,3}(,[0-9]{3})+$/.test(compact)) return Number(compact.replace(/,/g, \"\"));\n\tif (/^[0-9]{1,3}(\\.[0-9]{3}){2,}$/.test(compact)) return Number(compact.replace(/\\./g, \"\"));\n\tif (/^[0-9]+\\.[0-9]+$/.test(compact)) return Number(compact);\n\treturn undefined;\n}\n\nfunction parsePositiveTokenCount(raw: string, unit: string | undefined): number | undefined {\n\tconst value = normalizeTokenNumeral(raw);\n\tif (value === undefined) return undefined;\n\tconst multiplier = unit ? (TOKEN_UNIT_MULTIPLIERS[unit.toLowerCase()] ?? 1) : 1;\n\tconst tokens = value * multiplier;\n\treturn Number.isSafeInteger(tokens) && tokens > 0 ? tokens : undefined;\n}\n\nconst TOKEN_BUDGET_PATTERNS = [\n\t/\\btoken\\s+budget\\s*(?:of|is|:|=)?\\s*([0-9][0-9,_.]*)(?:\\s*(thousand|million|k|m)\\b)?/i,\n\t/\\b([0-9][0-9,_.]*)(?:\\s*(thousand|million|k|m)\\b)?\\s*(?:token|tokens)\\s+budget\\b/i,\n\t/\\bbudget\\s*(?:of|is|:|=)?\\s*([0-9][0-9,_.]*)(?:\\s*(thousand|million|k|m)\\b)?\\s*(?:token|tokens)\\b/i,\n] as const;\n\n/**\n * Scan `text` for one explicit token-budget directive. When `trailingOnly` is set, a match only\n * counts if it runs to the end of `text` (ignoring closing punctuation/whitespace) — used to scan\n * inside a captured goal objective, where a budget-shaped phrase embedded mid-sentence usually\n * describes the task's subject matter (e.g. a constant being edited in code), not the agent's own\n * execution ceiling, whereas a trailing clause (\"... with a 40k token budget.\") is a real directive.\n */\nfunction scanTokenBudget(text: string, options: { trailingOnly: boolean }): number | undefined {\n\tfor (const pattern of TOKEN_BUDGET_PATTERNS) {\n\t\tconst match = pattern.exec(text);\n\t\tif (!match) continue;\n\t\tif (options.trailingOnly) {\n\t\t\tconst tail = text.slice(match.index + match[0].length);\n\t\t\tif (!/^[.!?]?\\s*$/.test(tail)) continue;\n\t\t}\n\t\tconst tokens = parsePositiveTokenCount(match[1], match[2]);\n\t\tif (tokens === undefined) {\n\t\t\tthrow new GoalTokenBudgetParseError(\n\t\t\t\t`Token budget phrase \"${match[0].trim()}\" could not be parsed into an exact token ceiling.`,\n\t\t\t);\n\t\t}\n\t\treturn tokens;\n\t}\n\treturn undefined;\n}\n\n/**\n * Parse an explicit token-budget directive from `text`. When `objective` locates a captured goal\n * objective within `text`, a budget-shaped phrase found INSIDE it only counts when it is the\n * trailing clause of the objective; text outside the objective (the prefix/suffix around it) is\n * scanned without that restriction. This keeps a genuine directive (\"... with a 40k token budget.\")\n * working while refusing to adopt a number that is merely part of the task's own subject matter\n * (\"raise the model token budget of 4096 ... to 8192\").\n */\nexport function parseRequestedTokenBudget(\n\ttext: string,\n\tobjective?: { start: number; end: number },\n): number | undefined {\n\tif (!objective) return scanTokenBudget(text, { trailingOnly: false });\n\tconst outside = `${text.slice(0, objective.start)} ${text.slice(objective.end)}`;\n\tconst outsideBudget = scanTokenBudget(outside, { trailingOnly: false });\n\tif (outsideBudget !== undefined) return outsideBudget;\n\treturn scanTokenBudget(text.slice(objective.start, objective.end), { trailingOnly: true });\n}\n\n/**\n * Recognize only explicit persistence language. Ordinary multi-step work and discussion ABOUT goal\n * mechanics deliberately return undefined; those must not silently expand into autonomous work.\n */\nfunction standaloneGoalRemainder(text: string): string | undefined {\n\tfor (const pattern of STANDALONE_GOAL_AUTHORITY_PATTERNS) {\n\t\tconst match = pattern.exec(text);\n\t\tif (!match) continue;\n\t\treturn text\n\t\t\t.slice(match.index + match[0].length)\n\t\t\t.replace(/^[\\s,.:;!?-]+/, \"\")\n\t\t\t.replace(/^(?:and|then|so)\\s+/i, \"\")\n\t\t\t.trim();\n\t}\n\treturn undefined;\n}\n\nfunction remainderWithoutBudgetPhrase(remainder: string): string {\n\tlet next = remainder;\n\tfor (const pattern of TOKEN_BUDGET_PATTERNS) {\n\t\tnext = next.replace(pattern, \" \");\n\t}\n\treturn next\n\t\t.replace(/\\b(?:with|of|is|a|the|:|=)\\b/gi, \" \")\n\t\t.replace(/\\s+/g, \" \")\n\t\t.trim();\n}\n\nfunction remainderWithoutProcessPhrases(remainder: string): string {\n\tlet next = remainder;\n\tfor (const pattern of STANDALONE_GOAL_PROCESS_PHRASES) {\n\t\tnext = next.replace(pattern, \" \");\n\t}\n\treturn next\n\t\t.replace(/\\b(?:with|of|is|a|the|to|and|also|you|i|i'm|:|=)\\b/gi, \" \")\n\t\t.replace(/[.,:;!?]/g, \" \")\n\t\t.replace(/\\s+/g, \" \")\n\t\t.trim();\n}\n\nfunction isClassificationRemainder(remainder: string): boolean {\n\tif (!remainder || STANDALONE_GOAL_FILLER.test(remainder)) return true;\n\tconst leftover = remainderWithoutProcessPhrases(remainder);\n\tif (!leftover || STANDALONE_GOAL_FILLER.test(leftover)) return true;\n\ttry {\n\t\tif (parseRequestedTokenBudget(remainder) === undefined) return false;\n\t} catch {\n\t\treturn false;\n\t}\n\tconst afterBudget = remainderWithoutBudgetPhrase(leftover);\n\treturn afterBudget.length === 0 || STANDALONE_GOAL_FILLER.test(afterBudget);\n}\n\nfunction userMessageText(content: unknown): string {\n\tif (typeof content === \"string\") return content.trim();\n\tif (!Array.isArray(content)) return \"\";\n\treturn content\n\t\t.filter(\n\t\t\t(block): block is { type: \"text\"; text: string } =>\n\t\t\t\ttypeof block === \"object\" &&\n\t\t\t\tblock !== null &&\n\t\t\t\t\"type\" in block &&\n\t\t\t\tblock.type === \"text\" &&\n\t\t\t\t\"text\" in block &&\n\t\t\t\ttypeof block.text === \"string\",\n\t\t)\n\t\t.map((block) => block.text)\n\t\t.join(\"\")\n\t\t.trim();\n}\n\n/** Latest owner prompt that is not the current classification phrase itself. */\nexport function priorUserPromptText(\n\tmessages: readonly { role: string; content?: unknown }[],\n\tcurrentText: string,\n): string | undefined {\n\tconst current = currentText.trim();\n\tfor (let index = messages.length - 1; index >= 0; index--) {\n\t\tconst message = messages[index];\n\t\tif (message.role !== \"user\") continue;\n\t\tconst text = userMessageText(message.content);\n\t\tif (!text || text === current) continue;\n\t\treturn text;\n\t}\n\treturn undefined;\n}\n\nexport function parseExplicitChatGoal(text: string, priorUserText?: string): ExplicitChatGoal | undefined {\n\tfor (const pattern of EXPLICIT_GOAL_PATTERNS) {\n\t\tconst match = pattern.exec(text);\n\t\tconst rawObjective = match?.[1];\n\t\tconst objective = rawObjective?.trim();\n\t\tif (!match || !objective || objective.length > MAX_GOAL_OBJECTIVE_LENGTH) continue;\n\t\t// rawObjective is always a suffix of match[0] (every pattern ends in `(.+)$`), so its start\n\t\t// offset in `text` is match[0]'s length minus its own length.\n\t\tconst objectiveSpan = {\n\t\t\tstart: match.index + (match[0].length - (rawObjective?.length ?? 0)),\n\t\t\tend: match.index + match[0].length,\n\t\t};\n\t\tconst tokenBudget = parseRequestedTokenBudget(text, objectiveSpan);\n\t\treturn { objective, ...(tokenBudget !== undefined ? { tokenBudget } : {}) };\n\t}\n\tconst remainder = standaloneGoalRemainder(text);\n\tif (remainder === undefined) return undefined;\n\tconst tokenBudget = parseRequestedTokenBudget(text);\n\tconst inline = remainder && !isClassificationRemainder(remainder) ? remainder : undefined;\n\tconst prior = priorUserText?.trim();\n\tconst objective =\n\t\tinline && inline.length <= MAX_GOAL_OBJECTIVE_LENGTH\n\t\t\t? inline\n\t\t\t: prior && prior !== text.trim() && prior.length <= MAX_GOAL_OBJECTIVE_LENGTH\n\t\t\t\t? prior\n\t\t\t\t: undefined;\n\tif (!objective) return undefined;\n\treturn { objective, ...(tokenBudget !== undefined ? { tokenBudget } : {}) };\n}\n\n/** Exact owner authority for model-supplied token budgets; ordinary work carries no budget authority. */\nexport function parseExplicitGoalStartAuthority(text: string): ExplicitGoalStartAuthority | undefined {\n\tconst goal = parseExplicitChatGoal(text);\n\tif (goal) return goal.tokenBudget === undefined ? {} : { tokenBudget: goal.tokenBudget };\n\tif (!STANDALONE_GOAL_AUTHORITY_PATTERNS.some((pattern) => pattern.test(text))) return undefined;\n\tconst tokenBudget = parseRequestedTokenBudget(text);\n\treturn tokenBudget === undefined ? {} : { tokenBudget };\n}\n"]}
|
package/dist/core/sdk.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"sdk.d.ts","sourceRoot":"","sources":["../../src/core/sdk.ts"],"names":[],"mappings":"AAEA,OAAO,EAAwB,cAAc,EAAE,MAAM,mCAAmC,CAAC;AACzF,OAAO,KAAK,EAAgB,aAAa,EAAE,MAAM,iCAAiC,CAAC;AACnF,OAAO,EACN,KAAK,GAAG,EAER,KAAK,KAAK,EAEV,KAAK,WAAW,EAEhB,MAAM,mBAAmB,CAAC;AAI3B,OAAO,EAAE,YAAY,EAAE,MAAM,oBAAoB,CAAC;AAElD,OAAO,EAAE,WAAW,EAAE,MAAM,mBAAmB,CAAC;AAShD,OAAO,KAAK,EAAmB,oBAAoB,EAAE,iBA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AAiB,CAAC,EAAE,iBAAiB,CAAC;CACtC;AAED,qCAAqC;AACrC,MAAM,WAAW,wBAAwB;IACxC,0BAA0B;IAC1B,OAAO,EAAE,YAAY,CAAC;IACtB,mEAAmE;IACnE,gBAAgB,EAAE,oBAAoB,CAAC;IACvC,wEAAwE;IACxE,oBAAoB,CAAC,EAAE,MAAM,CAAC;CAC9B;AAID,cAAc,4BAA4B,CAAC;AAC3C,YAAY,EACX,YAAY,EACZ,uBAAuB,EACvB,gBAAgB,EAChB,gBAAgB,EAChB,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;AA8CF;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAkCG;AACH,wBAAsB,kBAAkB,CAAC,OAAO,GAAE,yBAA8B,GAAG,OAAO,CAAC,wBAAwB,CAAC,CA0WnH"}
|
package/dist/core/sdk.js
CHANGED
|
@@ -11,6 +11,7 @@ import { AuthStorage } from "./auth-storage.js";
|
|
|
11
11
|
import { BEDROCK_PROVIDER_ID, bindSavedBedrockScope, getActiveBedrockScope, isUnscopedBedrockProxy, } from "./bedrock-scope.js";
|
|
12
12
|
import { recoverBedrockSsoAuthentication } from "./bedrock-sso-login.js";
|
|
13
13
|
import { DEFAULT_ACTIVE_TOOL_NAMES } from "./default-tool-surface.js";
|
|
14
|
+
import { resolveFastModeServiceTier } from "./fast-mode.js";
|
|
14
15
|
import { isInstallTelemetryEnabled } from "./install-telemetry.js";
|
|
15
16
|
import { ModelRegistry } from "./model-registry.js";
|
|
16
17
|
import { findInitialModel, resolveProfileModelSettings } from "./model-resolver.js";
|
|
@@ -303,9 +304,10 @@ export async function createAgentSession(options = {}) {
|
|
|
303
304
|
const timeoutMs = options?.timeoutMs ?? providerRetrySettings.timeoutMs ?? effectiveTimeoutMs;
|
|
304
305
|
const websocketConnectTimeoutMs = options?.websocketConnectTimeoutMs ?? settingsManager.getWebSocketConnectTimeoutMs();
|
|
305
306
|
const attributionHeaders = getAttributionHeaders(model, settingsManager, options?.sessionId);
|
|
307
|
+
const fastModeServiceTier = resolveFastModeServiceTier(model, settingsManager.getFastModeEnabled(model.provider));
|
|
306
308
|
const providerOptions = {
|
|
307
309
|
...options,
|
|
308
|
-
serviceTier: options?.serviceTier === undefined ? defaultServiceTier : options.serviceTier,
|
|
310
|
+
serviceTier: options?.serviceTier === undefined ? (fastModeServiceTier ?? defaultServiceTier) : options.serviceTier,
|
|
309
311
|
...(bedrockScope ? { region: bedrockScope.region, profile: bedrockScope.profile } : {}),
|
|
310
312
|
interactionMode: forceBackgroundRequests ? "background" : (options?.interactionMode ?? "user"),
|
|
311
313
|
onInteractiveAuthRecovery: options?.onInteractiveAuthRecovery ?? recoverBedrockSsoAuthentication,
|
package/dist/core/sdk.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"sdk.js","sourceRoot":"","sources":["../../src/core/sdk.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,KAAK,EAAE,MAAM,iCAAiC,CAAC;AACxD,OAAO,EAAE,YAAY,EAAE,MAAM,oCAAoC,CAAC;AAClE,OAAO,EAAE,oBAAoB,EAAE,cAAc,EAAE,MAAM,mCAAmC,CAAC;AAEzF,OAAO,EAIN,yBAAyB,EAEzB,YAAY,GACZ,MAAM,mBAAmB,CAAC;AAC3B,OAAO,EAAE,WAAW,EAAE,MAAM,cAAc,CAAC;AAC3C,OAAO,EAAE,WAAW,EAAE,MAAM,mBAAmB,CAAC;AAChD,OAAO,EAA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\";\nimport { convertToLlm } from \"@caupulican/pi-agent-core/messages\";\nimport { getDefaultSessionDir, SessionManager } from \"@caupulican/pi-agent-core/session\";\nimport type { AgentMessage, ThinkingLevel } from \"@caupulican/pi-agent-core/types\";\nimport {\n\ttype Api,\n\ttype Message,\n\ttype Model,\n\tresolveModelThinkingLevel,\n\ttype ServiceTier,\n\tstreamSimple,\n} from \"@caupulican/pi-ai\";\nimport { getAgentDir } from \"../config.ts\";\nimport { resolvePath } from \"../utils/paths.ts\";\nimport { configFile } from \"./agent-paths.ts\";\nimport { AgentSession } from \"./agent-session.ts\";\nimport { formatNoModelsAvailableMessage } from \"./auth-guidance.ts\";\nimport { AuthStorage } from \"./auth-storage.ts\";\nimport {\n\tBEDROCK_PROVIDER_ID,\n\tbindSavedBedrockScope,\n\tgetActiveBedrockScope,\n\tisUnscopedBedrockProxy,\n} from \"./bedrock-scope.ts\";\nimport { recoverBedrockSsoAuthentication } from \"./bedrock-sso-login.ts\";\nimport { DEFAULT_ACTIVE_TOOL_NAMES } from \"./default-tool-surface.ts\";\nimport type { ExtensionRunner, LoadExtensionsResult, SessionStartEvent, ToolDefinition } from \"./extensions/index.ts\";\nimport { isInstallTelemetryEnabled } from \"./install-telemetry.ts\";\nimport { ModelRegistry } from \"./model-registry.ts\";\nimport { findInitialModel, resolveProfileModelSettings } from \"./model-resolver.ts\";\nimport type { OrchestrationProfile } from \"./orchestration/contracts.ts\";\nimport { resolveConfiguredOrchestrationModel } from \"./orchestration/model-binding.ts\";\nimport { validateOrchestrationProfile } from \"./orchestration/profile-registry.ts\";\nimport type { ResourceLoader } from \"./resource-loader.ts\";\nimport { DefaultResourceLoader } from \"./resource-loader.ts\";\nimport { parseResourceProfileInput } from \"./resource-profile-blocks.ts\";\nimport { isWorkerSession } from \"./session-role.ts\";\nimport type {\n\tProfileDefinitionInput,\n\tResourceProfileFilterSettings,\n\tResourceProfileSettings,\n} from \"./settings-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\twithFileMutationQueue,\n} from \"./tools/index.ts\";\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: ModelRegistry.create(authStorage, agentDir/models.json) */\n\tmodelRegistry?: ModelRegistry;\n\n\t/** Model to use. Default: from settings, else first available */\n\tmodel?: Model<Api>;\n\t/** Thinking level. Default: from settings, then the model's declared default, else 'medium'. */\n\tthinkingLevel?: ThinkingLevel;\n\t/** Default provider processing tier for this session. Per-request options take precedence. */\n\tserviceTier?: ServiceTier;\n\t/**\n\t * Whether `model` came from an explicit CLI/SDK flag (vs. profile/settings resolution).\n\t * When false (default), the active profile's model is re-applied on reload so live profile\n\t * edits take effect; when true, the explicit launch-time model is preserved across reloads.\n\t */\n\tisExplicitModel?: boolean;\n\t/** Whether `thinkingLevel` came from an explicit flag (see isExplicitModel). */\n\tisExplicitThinking?: boolean;\n\t/** True when this session is a spawned subagent/child — gates durable memory writes. */\n\tisChildSession?: boolean;\n\t/** Models available for cycling (Ctrl+P in interactive mode) */\n\tscopedModels?: Array<{ model: Model<Api>; 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, python, edit, write,\n\t * goal, delegate, and run_toolkit_script)\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 shared default built-in tool surface and leaves extension/custom\n\t * 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/** Optional resource-profile allow/block filters for tool names. */\n\ttoolProfileFilter?: ResourceProfileFilterSettings;\n\t/** Optional one-shot resource filters or complete situation profiles. Never persisted to disk. */\n\tresourceProfileDefinitions?: Record<string, ResourceProfileSettings | ProfileDefinitionInput>;\n\t/** Optional one-shot profile definitions as JSON or <resource-profile> tag text. Never persisted to disk. */\n\tresourceProfileJson?: string | string[];\n\t/** Optional runtime profile selection. Never persisted to disk. */\n\tresourceProfiles?: string[];\n\t/** Immutable owner-authored orchestration policy for this session. */\n\torchestrationProfile?: OrchestrationProfile;\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, agentDir, getDefaultSessionDir(cwd, agentDir)) */\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}\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\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 getAttributionHeaders(\n\tmodel: Model<Api>,\n\tsettingsManager: SettingsManager,\n\tsessionId?: string,\n): Record<string, string> | undefined {\n\tif (\n\t\tsessionId &&\n\t\t(model.provider === \"opencode\" || model.provider === \"opencode-go\" || model.baseUrl.includes(\"opencode.ai\"))\n\t) {\n\t\treturn { \"x-opencode-session\": sessionId, \"x-opencode-client\": \"pi\" };\n\t}\n\n\tif (!isInstallTelemetryEnabled(settingsManager)) {\n\t\treturn undefined;\n\t}\n\n\tif (model.provider === \"openrouter\" || model.baseUrl.includes(\"openrouter.ai\")) {\n\t\treturn {\n\t\t\t\"HTTP-Referer\": \"https://pi.dev\",\n\t\t\t\"X-OpenRouter-Title\": \"pi\",\n\t\t\t\"X-OpenRouter-Categories\": \"cli-agent\",\n\t\t};\n\t}\n\n\tif (\n\t\tmodel.provider === \"cloudflare-workers-ai\" ||\n\t\tmodel.provider === \"cloudflare-ai-gateway\" ||\n\t\tmodel.baseUrl.includes(\"api.cloudflare.com\") ||\n\t\tmodel.baseUrl.includes(\"gateway.ai.cloudflare.com\")\n\t) {\n\t\treturn {\n\t\t\t\"User-Agent\": \"pi-coding-agent\",\n\t\t};\n\t}\n\n\treturn undefined;\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 '@caupulican/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\t// Use provided or create AuthStorage and ModelRegistry\n\tconst authPath = options.agentDir ? configFile(agentDir, \"auth.json\") : undefined;\n\tconst modelsPath = options.agentDir ? configFile(agentDir, \"models.json\") : undefined;\n\tconst authStorage = options.authStorage ?? AuthStorage.create(authPath);\n\tconst modelRegistry = options.modelRegistry ?? ModelRegistry.create(authStorage, modelsPath);\n\n\tconst settingsManager = options.settingsManager ?? SettingsManager.create(cwd, agentDir);\n\tbindSavedBedrockScope(settingsManager, modelRegistry);\n\tconst isChildSession = options.isChildSession ?? process.env.PI_CHILD_SESSION === \"1\";\n\tconst forceBackgroundRequests = isChildSession || isWorkerSession();\n\tconst defaultServiceTier = options.serviceTier;\n\tconst orchestrationProfile = options.orchestrationProfile;\n\tif (orchestrationProfile) {\n\t\tvalidateOrchestrationProfile(orchestrationProfile);\n\t\tconst conflictingOptions = [\n\t\t\t...(options.model ? [\"model\"] : []),\n\t\t\t...(options.thinkingLevel !== undefined ? [\"thinkingLevel\"] : []),\n\t\t\t...(options.scopedModels !== undefined ? [\"scopedModels\"] : []),\n\t\t\t...(options.tools !== undefined ? [\"tools\"] : []),\n\t\t\t...(options.noTools !== undefined ? [\"noTools\"] : []),\n\t\t\t...(options.excludeTools !== undefined ? [\"excludeTools\"] : []),\n\t\t\t...(options.toolProfileFilter !== undefined ? [\"toolProfileFilter\"] : []),\n\t\t\t...(options.resourceProfiles !== undefined ? [\"resourceProfiles\"] : []),\n\t\t];\n\t\tif (conflictingOptions.length > 0) {\n\t\t\tthrow new TypeError(\n\t\t\t\t`Orchestration profile '${orchestrationProfile.profileId}' owns model, thinking, tools, and resources; remove conflicting SDK options: ${conflictingOptions.join(\", \")}.`,\n\t\t\t);\n\t\t}\n\t\tsettingsManager.setRuntimeResourceProfiles([...orchestrationProfile.resourceProfileNames]);\n\t}\n\tconst needsProfileReload =\n\t\toptions.resourceProfileDefinitions !== undefined ||\n\t\toptions.resourceProfileJson !== undefined ||\n\t\toptions.resourceProfiles !== undefined ||\n\t\torchestrationProfile !== undefined;\n\tif (options.resourceProfileDefinitions) {\n\t\tsettingsManager.addInlineResourceProfileDefinitions(options.resourceProfileDefinitions);\n\t}\n\tif (options.resourceProfileJson) {\n\t\tconst inputs = Array.isArray(options.resourceProfileJson)\n\t\t\t? options.resourceProfileJson\n\t\t\t: [options.resourceProfileJson];\n\t\tfor (const input of inputs) {\n\t\t\tsettingsManager.addInlineResourceProfileDefinitions(parseResourceProfileInput(input).profiles);\n\t\t}\n\t}\n\tif (!orchestrationProfile && options.resourceProfiles !== undefined) {\n\t\tsettingsManager.setRuntimeResourceProfiles(options.resourceProfiles);\n\t}\n\tconst sessionManager =\n\t\toptions.sessionManager ?? SessionManager.create(cwd, agentDir, 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} else if (needsProfileReload) {\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\tconst orchestrationModel = orchestrationProfile\n\t\t? resolveConfiguredOrchestrationModel(orchestrationProfile, modelRegistry)\n\t\t: undefined;\n\tif (orchestrationProfile && !orchestrationModel) {\n\t\tthrow new TypeError(\n\t\t\t`Orchestration profile '${orchestrationProfile.profileId}' has no configured, authenticated model that supports its exact thinking level.`,\n\t\t);\n\t}\n\tlet model = orchestrationModel?.model ?? options.model;\n\tlet modelFallbackMessage: string | undefined;\n\n\tlet thinkingLevel = orchestrationModel?.binding.thinkingLevel ?? options.thinkingLevel;\n\n\tconst activeProfileNames = settingsManager.getActiveResourceProfileNames();\n\tif (!orchestrationProfile && activeProfileNames.length > 0) {\n\t\tconst profileSettings = resolveProfileModelSettings({\n\t\t\tactiveProfileNames,\n\t\t\tregistry: settingsManager.getProfileRegistry(),\n\t\t\tmodelRegistry,\n\t\t\tcwd,\n\t\t});\n\t\tif (profileSettings.error) {\n\t\t\tmodelFallbackMessage = `Profile model resolution error: ${profileSettings.error}`;\n\t\t}\n\t\tif (!model && profileSettings.model) {\n\t\t\tmodel = profileSettings.model;\n\t\t}\n\t\tif (thinkingLevel === undefined && profileSettings.thinkingLevel) {\n\t\t\tthinkingLevel = profileSettings.thinkingLevel;\n\t\t}\n\t}\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\tif (restoredModel && modelRegistry.hasConfiguredAuth(restoredModel)) {\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\tmodelRegistry,\n\t\t});\n\t\tmodel = result.model;\n\t\tif (thinkingLevel === undefined && !(hasExistingSession && hasThinkingEntry)) {\n\t\t\tthinkingLevel = result.thinkingLevel;\n\t\t}\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\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();\n\t}\n\n\t// Resolve preference, model metadata, harness fallback, and capability clamping through the\n\t// same contract used by CLI startup and isolated lanes.\n\tif (!model) {\n\t\tthinkingLevel = \"off\";\n\t} else {\n\t\tthinkingLevel = resolveModelThinkingLevel(\n\t\t\tmodel,\n\t\t\tthinkingLevel ?? settingsManager.getDefaultThinkingLevel(),\n\t\t) as ThinkingLevel;\n\t}\n\n\tconst defaultActiveToolNames = [\n\t\t...DEFAULT_ACTIVE_TOOL_NAMES,\n\t\t...(settingsManager.getScoutSettings().enabled ? [\"context_scout\"] : []),\n\t];\n\tconst toolProfileFilter = orchestrationProfile\n\t\t? settingsManager.getResourceProfileFilter(\"tools\")\n\t\t: (options.toolProfileFilter ?? settingsManager.getResourceProfileFilter(\"tools\"));\n\tconst allowedToolNames = orchestrationProfile\n\t\t? [...orchestrationProfile.toolNames]\n\t\t: (options.tools ?? (options.noTools === \"all\" ? [] : undefined));\n\tconst excludedToolNames = orchestrationProfile ? undefined : options.excludeTools;\n\tconst excludedToolNameSet = excludedToolNames ? new Set(excludedToolNames) : undefined;\n\tconst initialActiveToolNames: string[] = (\n\t\torchestrationProfile\n\t\t\t? [...orchestrationProfile.toolNames]\n\t\t\t: options.tools\n\t\t\t\t? [...options.tools]\n\t\t\t\t: options.noTools\n\t\t\t\t\t? []\n\t\t\t\t\t: defaultActiveToolNames\n\t).filter((name) => !excludedToolNameSet?.has(name));\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\tstreamFn: async (model, context, options) => {\n\t\t\tconst bedrockScope =\n\t\t\t\tmodel.provider === BEDROCK_PROVIDER_ID ? getActiveBedrockScope(settingsManager) : undefined;\n\t\t\tif (model.provider === BEDROCK_PROVIDER_ID && !bedrockScope && !isUnscopedBedrockProxy()) {\n\t\t\t\tthrow new Error(\n\t\t\t\t\t\"Amazon Bedrock requires a verified profile/region scope. Run /login amazon-bedrock before using this model.\",\n\t\t\t\t);\n\t\t\t}\n\t\t\tconst auth = await modelRegistry.getApiKeyAndHeaders(model);\n\t\t\tif (!auth.ok) {\n\t\t\t\tthrow new Error(auth.error);\n\t\t\t}\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 attributionHeaders = getAttributionHeaders(model, settingsManager, options?.sessionId);\n\t\t\tconst providerOptions = {\n\t\t\t\t...options,\n\t\t\t\tserviceTier: options?.serviceTier === undefined ? defaultServiceTier : options.serviceTier,\n\t\t\t\t...(bedrockScope ? { region: bedrockScope.region, profile: bedrockScope.profile } : {}),\n\t\t\t\tinteractionMode: forceBackgroundRequests ? \"background\" : (options?.interactionMode ?? \"user\"),\n\t\t\t\tonInteractiveAuthRecovery: options?.onInteractiveAuthRecovery ?? recoverBedrockSsoAuthentication,\n\t\t\t\tapiKey: auth.apiKey,\n\t\t\t\tonAuthRejection:\n\t\t\t\t\tauth.apiKey && model.provider === \"openai-codex\"\n\t\t\t\t\t\t? async () => modelRegistry.recoverRejectedOAuthApiKey(model.provider, auth.apiKey as string)\n\t\t\t\t\t\t: options?.onAuthRejection,\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\theaders:\n\t\t\t\t\tattributionHeaders || auth.headers || options?.headers\n\t\t\t\t\t\t? { ...attributionHeaders, ...auth.headers, ...options?.headers }\n\t\t\t\t\t\t: undefined,\n\t\t\t};\n\t\t\treturn streamSimple(model, context, providerOptions);\n\t\t},\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\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\tagentDir,\n\t\tscopedModels: orchestrationModel\n\t\t\t? [{ model: orchestrationModel.model, thinkingLevel: orchestrationModel.binding.thinkingLevel }]\n\t\t\t: options.scopedModels,\n\t\tresourceLoader,\n\t\tcustomTools: options.customTools,\n\t\tmodelRegistry,\n\t\tinitialActiveToolNames,\n\t\tallowedToolNames,\n\t\texcludedToolNames,\n\t\textensionRunnerRef,\n\t\ttoolProfileFilter,\n\t\tisExplicitModel: orchestrationProfile ? true : (options.isExplicitModel ?? options.model != null),\n\t\tisExplicitThinking: orchestrationProfile\n\t\t\t? true\n\t\t\t: (options.isExplicitThinking ?? options.thinkingLevel !== undefined),\n\t\tisChildSession,\n\t\torchestrationProfile,\n\t\tsessionStartEvent: options.sessionStartEvent,\n\t});\n\ttry {\n\t\t// The initial runtime has now bound providers from profile-granted extensions. Re-resolve the\n\t\t// profile model against that authoritative registry generation, then resync model capability.\n\t\tawait session.reapplyActiveProfileModelSettings();\n\t\tif (modelFallbackMessage?.startsWith(\"Profile model resolution error:\")) {\n\t\t\tmodelFallbackMessage = undefined;\n\t\t}\n\t} catch (error) {\n\t\t// Preserve the established non-fatal fallback for a genuinely unresolved profile model.\n\t\tif (!modelFallbackMessage?.startsWith(\"Profile model resolution error:\")) {\n\t\t\tawait session.disposeAndWait();\n\t\t\tthrow error;\n\t\t}\n\t}\n\t// File-store memory tools exist only after providers initialize. Do this here so an SDK session\n\t// that never calls bindExtensions still has the requested `memory` tool when the grant allows it.\n\tawait session.initializeMemory();\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,KAAK,EAAE,MAAM,iCAAiC,CAAC;AACxD,OAAO,EAAE,YAAY,EAAE,MAAM,oCAAoC,CAAC;AAClE,OAAO,EAAE,oBAAoB,EAAE,cAAc,EAAE,MAAM,mCAAmC,CAAC;AAEzF,OAAO,EAIN,yBAAyB,EAEzB,YAAY,GACZ,MAAM,mBAAmB,CAAC;AAC3B,OAAO,EAAE,WAAW,EAAE,MAAM,cAAc,CAAC;AAC3C,OAAO,EAAE,WAAW,EAAE,MAAM,mBAAmB,CAAC;AAChD,OAAO,EAAE,UAAU,EAAE,MAAM,kBAAkB,CAAC;AAC9C,OAAO,EAAE,YAAY,EAAE,MAAM,oBAAoB,CAAC;AAClD,OAAO,EAAE,8BAA8B,EAAE,MAAM,oBAAoB,CAAC;AACpE,OAAO,EAAE,WAAW,EAAE,MAAM,mBAAmB,CAAC;AAChD,OAAO,EACN,mBAAmB,EACnB,qBAAqB,EACrB,qBAAqB,EACrB,sBAAsB,GACtB,MAAM,oBAAoB,CAAC;AAC5B,OAAO,EAAE,+BAA+B,EAAE,MAAM,wBAAwB,CAAC;AACzE,OAAO,EAAE,yBAAyB,EAAE,MAAM,2BAA2B,CAAC;AAEtE,OAAO,EAAE,0BAA0B,EAAE,MAAM,gBAAgB,CAAC;AAC5D,OAAO,EAAE,yBAAyB,EAAE,MAAM,wBAAwB,CAAC;AACnE,OAAO,EAAE,aAAa,EAAE,MA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,CAAC;QACjG,kBAAkB,EAAE,oBAAoB;YACvC,CAAC,CAAC,IAAI;YACN,CAAC,CAAC,CAAC,OAAO,CAAC,kBAAkB,IAAI,OAAO,CAAC,aAAa,KAAK,SAAS,CAAC;QACtE,cAAc;QACd,oBAAoB;QACpB,iBAAiB,EAAE,OAAO,CAAC,iBAAiB;KAC5C,CAAC,CAAC;IACH,IAAI,CAAC;QACJ,8FAA8F;QAC9F,8FAA8F;QAC9F,MAAM,OAAO,CAAC,iCAAiC,EAAE,CAAC;QAClD,IAAI,oBAAoB,EAAE,UAAU,CAAC,iCAAiC,CAAC,EAAE,CAAC;YACzE,oBAAoB,GAAG,SAAS,CAAC;QAClC,CAAC;IACF,CAAC;IAAC,OAAO,KAAK,EAAE,CAAC;QAChB,wFAAwF;QACxF,IAAI,CAAC,oBAAoB,EAAE,UAAU,CAAC,iCAAiC,CAAC,EAAE,CAAC;YAC1E,MAAM,OAAO,CAAC,cAAc,EAAE,CAAC;YAC/B,MAAM,KAAK,CAAC;QACb,CAAC;IACF,CAAC;IACD,gGAAgG;IAChG,kGAAkG;IAClG,MAAM,OAAO,CAAC,gBAAgB,EAAE,CAAC;IACjC,MAAM,gBAAgB,GAAG,cAAc,CAAC,aAAa,EAAE,CAAC;IAExD,OAAO;QACN,OAAO;QACP,gBAAgB;QAChB,oBAAoB;KACpB,CAAC;AACH,CAAC","sourcesContent":["import { Agent } from \"@caupulican/pi-agent-core/agent\";\nimport { convertToLlm } from \"@caupulican/pi-agent-core/messages\";\nimport { getDefaultSessionDir, SessionManager } from \"@caupulican/pi-agent-core/session\";\nimport type { AgentMessage, ThinkingLevel } from \"@caupulican/pi-agent-core/types\";\nimport {\n\ttype Api,\n\ttype Message,\n\ttype Model,\n\tresolveModelThinkingLevel,\n\ttype ServiceTier,\n\tstreamSimple,\n} from \"@caupulican/pi-ai\";\nimport { getAgentDir } from \"../config.ts\";\nimport { resolvePath } from \"../utils/paths.ts\";\nimport { configFile } from \"./agent-paths.ts\";\nimport { AgentSession } from \"./agent-session.ts\";\nimport { formatNoModelsAvailableMessage } from \"./auth-guidance.ts\";\nimport { AuthStorage } from \"./auth-storage.ts\";\nimport {\n\tBEDROCK_PROVIDER_ID,\n\tbindSavedBedrockScope,\n\tgetActiveBedrockScope,\n\tisUnscopedBedrockProxy,\n} from \"./bedrock-scope.ts\";\nimport { recoverBedrockSsoAuthentication } from \"./bedrock-sso-login.ts\";\nimport { DEFAULT_ACTIVE_TOOL_NAMES } from \"./default-tool-surface.ts\";\nimport type { ExtensionRunner, LoadExtensionsResult, SessionStartEvent, ToolDefinition } from \"./extensions/index.ts\";\nimport { resolveFastModeServiceTier } from \"./fast-mode.ts\";\nimport { isInstallTelemetryEnabled } from \"./install-telemetry.ts\";\nimport { ModelRegistry } from \"./model-registry.ts\";\nimport { findInitialModel, resolveProfileModelSettings } from \"./model-resolver.ts\";\nimport type { OrchestrationProfile } from \"./orchestration/contracts.ts\";\nimport { resolveConfiguredOrchestrationModel } from \"./orchestration/model-binding.ts\";\nimport { validateOrchestrationProfile } from \"./orchestration/profile-registry.ts\";\nimport type { ResourceLoader } from \"./resource-loader.ts\";\nimport { DefaultResourceLoader } from \"./resource-loader.ts\";\nimport { parseResourceProfileInput } from \"./resource-profile-blocks.ts\";\nimport { isWorkerSession } from \"./session-role.ts\";\nimport type {\n\tProfileDefinitionInput,\n\tResourceProfileFilterSettings,\n\tResourceProfileSettings,\n} from \"./settings-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\twithFileMutationQueue,\n} from \"./tools/index.ts\";\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: ModelRegistry.create(authStorage, agentDir/models.json) */\n\tmodelRegistry?: ModelRegistry;\n\n\t/** Model to use. Default: from settings, else first available */\n\tmodel?: Model<Api>;\n\t/** Thinking level. Default: from settings, then the model's declared default, else 'medium'. */\n\tthinkingLevel?: ThinkingLevel;\n\t/** Default provider processing tier for this session. Per-request options take precedence. */\n\tserviceTier?: ServiceTier;\n\t/**\n\t * Whether `model` came from an explicit CLI/SDK flag (vs. profile/settings resolution).\n\t * When false (default), the active profile's model is re-applied on reload so live profile\n\t * edits take effect; when true, the explicit launch-time model is preserved across reloads.\n\t */\n\tisExplicitModel?: boolean;\n\t/** Whether `thinkingLevel` came from an explicit flag (see isExplicitModel). */\n\tisExplicitThinking?: boolean;\n\t/** True when this session is a spawned subagent/child — gates durable memory writes. */\n\tisChildSession?: boolean;\n\t/** Models available for cycling (Ctrl+P in interactive mode) */\n\tscopedModels?: Array<{ model: Model<Api>; 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, python, edit, write,\n\t * goal, delegate, and run_toolkit_script)\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 shared default built-in tool surface and leaves extension/custom\n\t * 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/** Optional resource-profile allow/block filters for tool names. */\n\ttoolProfileFilter?: ResourceProfileFilterSettings;\n\t/** Optional one-shot resource filters or complete situation profiles. Never persisted to disk. */\n\tresourceProfileDefinitions?: Record<string, ResourceProfileSettings | ProfileDefinitionInput>;\n\t/** Optional one-shot profile definitions as JSON or <resource-profile> tag text. Never persisted to disk. */\n\tresourceProfileJson?: string | string[];\n\t/** Optional runtime profile selection. Never persisted to disk. */\n\tresourceProfiles?: string[];\n\t/** Immutable owner-authored orchestration policy for this session. */\n\torchestrationProfile?: OrchestrationProfile;\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, agentDir, getDefaultSessionDir(cwd, agentDir)) */\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}\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\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 getAttributionHeaders(\n\tmodel: Model<Api>,\n\tsettingsManager: SettingsManager,\n\tsessionId?: string,\n): Record<string, string> | undefined {\n\tif (\n\t\tsessionId &&\n\t\t(model.provider === \"opencode\" || model.provider === \"opencode-go\" || model.baseUrl.includes(\"opencode.ai\"))\n\t) {\n\t\treturn { \"x-opencode-session\": sessionId, \"x-opencode-client\": \"pi\" };\n\t}\n\n\tif (!isInstallTelemetryEnabled(settingsManager)) {\n\t\treturn undefined;\n\t}\n\n\tif (model.provider === \"openrouter\" || model.baseUrl.includes(\"openrouter.ai\")) {\n\t\treturn {\n\t\t\t\"HTTP-Referer\": \"https://pi.dev\",\n\t\t\t\"X-OpenRouter-Title\": \"pi\",\n\t\t\t\"X-OpenRouter-Categories\": \"cli-agent\",\n\t\t};\n\t}\n\n\tif (\n\t\tmodel.provider === \"cloudflare-workers-ai\" ||\n\t\tmodel.provider === \"cloudflare-ai-gateway\" ||\n\t\tmodel.baseUrl.includes(\"api.cloudflare.com\") ||\n\t\tmodel.baseUrl.includes(\"gateway.ai.cloudflare.com\")\n\t) {\n\t\treturn {\n\t\t\t\"User-Agent\": \"pi-coding-agent\",\n\t\t};\n\t}\n\n\treturn undefined;\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 '@caupulican/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\t// Use provided or create AuthStorage and ModelRegistry\n\tconst authPath = options.agentDir ? configFile(agentDir, \"auth.json\") : undefined;\n\tconst modelsPath = options.agentDir ? configFile(agentDir, \"models.json\") : undefined;\n\tconst authStorage = options.authStorage ?? AuthStorage.create(authPath);\n\tconst modelRegistry = options.modelRegistry ?? ModelRegistry.create(authStorage, modelsPath);\n\n\tconst settingsManager = options.settingsManager ?? SettingsManager.create(cwd, agentDir);\n\tbindSavedBedrockScope(settingsManager, modelRegistry);\n\tconst isChildSession = options.isChildSession ?? process.env.PI_CHILD_SESSION === \"1\";\n\tconst forceBackgroundRequests = isChildSession || isWorkerSession();\n\tconst defaultServiceTier = options.serviceTier;\n\tconst orchestrationProfile = options.orchestrationProfile;\n\tif (orchestrationProfile) {\n\t\tvalidateOrchestrationProfile(orchestrationProfile);\n\t\tconst conflictingOptions = [\n\t\t\t...(options.model ? [\"model\"] : []),\n\t\t\t...(options.thinkingLevel !== undefined ? [\"thinkingLevel\"] : []),\n\t\t\t...(options.scopedModels !== undefined ? [\"scopedModels\"] : []),\n\t\t\t...(options.tools !== undefined ? [\"tools\"] : []),\n\t\t\t...(options.noTools !== undefined ? [\"noTools\"] : []),\n\t\t\t...(options.excludeTools !== undefined ? [\"excludeTools\"] : []),\n\t\t\t...(options.toolProfileFilter !== undefined ? [\"toolProfileFilter\"] : []),\n\t\t\t...(options.resourceProfiles !== undefined ? [\"resourceProfiles\"] : []),\n\t\t];\n\t\tif (conflictingOptions.length > 0) {\n\t\t\tthrow new TypeError(\n\t\t\t\t`Orchestration profile '${orchestrationProfile.profileId}' owns model, thinking, tools, and resources; remove conflicting SDK options: ${conflictingOptions.join(\", \")}.`,\n\t\t\t);\n\t\t}\n\t\tsettingsManager.setRuntimeResourceProfiles([...orchestrationProfile.resourceProfileNames]);\n\t}\n\tconst needsProfileReload =\n\t\toptions.resourceProfileDefinitions !== undefined ||\n\t\toptions.resourceProfileJson !== undefined ||\n\t\toptions.resourceProfiles !== undefined ||\n\t\torchestrationProfile !== undefined;\n\tif (options.resourceProfileDefinitions) {\n\t\tsettingsManager.addInlineResourceProfileDefinitions(options.resourceProfileDefinitions);\n\t}\n\tif (options.resourceProfileJson) {\n\t\tconst inputs = Array.isArray(options.resourceProfileJson)\n\t\t\t? options.resourceProfileJson\n\t\t\t: [options.resourceProfileJson];\n\t\tfor (const input of inputs) {\n\t\t\tsettingsManager.addInlineResourceProfileDefinitions(parseResourceProfileInput(input).profiles);\n\t\t}\n\t}\n\tif (!orchestrationProfile && options.resourceProfiles !== undefined) {\n\t\tsettingsManager.setRuntimeResourceProfiles(options.resourceProfiles);\n\t}\n\tconst sessionManager =\n\t\toptions.sessionManager ?? SessionManager.create(cwd, agentDir, 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} else if (needsProfileReload) {\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\tconst orchestrationModel = orchestrationProfile\n\t\t? resolveConfiguredOrchestrationModel(orchestrationProfile, modelRegistry)\n\t\t: undefined;\n\tif (orchestrationProfile && !orchestrationModel) {\n\t\tthrow new TypeError(\n\t\t\t`Orchestration profile '${orchestrationProfile.profileId}' has no configured, authenticated model that supports its exact thinking level.`,\n\t\t);\n\t}\n\tlet model = orchestrationModel?.model ?? options.model;\n\tlet modelFallbackMessage: string | undefined;\n\n\tlet thinkingLevel = orchestrationModel?.binding.thinkingLevel ?? options.thinkingLevel;\n\n\tconst activeProfileNames = settingsManager.getActiveResourceProfileNames();\n\tif (!orchestrationProfile && activeProfileNames.length > 0) {\n\t\tconst profileSettings = resolveProfileModelSettings({\n\t\t\tactiveProfileNames,\n\t\t\tregistry: settingsManager.getProfileRegistry(),\n\t\t\tmodelRegistry,\n\t\t\tcwd,\n\t\t});\n\t\tif (profileSettings.error) {\n\t\t\tmodelFallbackMessage = `Profile model resolution error: ${profileSettings.error}`;\n\t\t}\n\t\tif (!model && profileSettings.model) {\n\t\t\tmodel = profileSettings.model;\n\t\t}\n\t\tif (thinkingLevel === undefined && profileSettings.thinkingLevel) {\n\t\t\tthinkingLevel = profileSettings.thinkingLevel;\n\t\t}\n\t}\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\tif (restoredModel && modelRegistry.hasConfiguredAuth(restoredModel)) {\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\tmodelRegistry,\n\t\t});\n\t\tmodel = result.model;\n\t\tif (thinkingLevel === undefined && !(hasExistingSession && hasThinkingEntry)) {\n\t\t\tthinkingLevel = result.thinkingLevel;\n\t\t}\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\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();\n\t}\n\n\t// Resolve preference, model metadata, harness fallback, and capability clamping through the\n\t// same contract used by CLI startup and isolated lanes.\n\tif (!model) {\n\t\tthinkingLevel = \"off\";\n\t} else {\n\t\tthinkingLevel = resolveModelThinkingLevel(\n\t\t\tmodel,\n\t\t\tthinkingLevel ?? settingsManager.getDefaultThinkingLevel(),\n\t\t) as ThinkingLevel;\n\t}\n\n\tconst defaultActiveToolNames = [\n\t\t...DEFAULT_ACTIVE_TOOL_NAMES,\n\t\t...(settingsManager.getScoutSettings().enabled ? [\"context_scout\"] : []),\n\t];\n\tconst toolProfileFilter = orchestrationProfile\n\t\t? settingsManager.getResourceProfileFilter(\"tools\")\n\t\t: (options.toolProfileFilter ?? settingsManager.getResourceProfileFilter(\"tools\"));\n\tconst allowedToolNames = orchestrationProfile\n\t\t? [...orchestrationProfile.toolNames]\n\t\t: (options.tools ?? (options.noTools === \"all\" ? [] : undefined));\n\tconst excludedToolNames = orchestrationProfile ? undefined : options.excludeTools;\n\tconst excludedToolNameSet = excludedToolNames ? new Set(excludedToolNames) : undefined;\n\tconst initialActiveToolNames: string[] = (\n\t\torchestrationProfile\n\t\t\t? [...orchestrationProfile.toolNames]\n\t\t\t: options.tools\n\t\t\t\t? [...options.tools]\n\t\t\t\t: options.noTools\n\t\t\t\t\t? []\n\t\t\t\t\t: defaultActiveToolNames\n\t).filter((name) => !excludedToolNameSet?.has(name));\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\tstreamFn: async (model, context, options) => {\n\t\t\tconst bedrockScope =\n\t\t\t\tmodel.provider === BEDROCK_PROVIDER_ID ? getActiveBedrockScope(settingsManager) : undefined;\n\t\t\tif (model.provider === BEDROCK_PROVIDER_ID && !bedrockScope && !isUnscopedBedrockProxy()) {\n\t\t\t\tthrow new Error(\n\t\t\t\t\t\"Amazon Bedrock requires a verified profile/region scope. Run /login amazon-bedrock before using this model.\",\n\t\t\t\t);\n\t\t\t}\n\t\t\tconst auth = await modelRegistry.getApiKeyAndHeaders(model);\n\t\t\tif (!auth.ok) {\n\t\t\t\tthrow new Error(auth.error);\n\t\t\t}\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 attributionHeaders = getAttributionHeaders(model, settingsManager, options?.sessionId);\n\t\t\tconst fastModeServiceTier = resolveFastModeServiceTier(\n\t\t\t\tmodel,\n\t\t\t\tsettingsManager.getFastModeEnabled(model.provider),\n\t\t\t);\n\t\t\tconst providerOptions = {\n\t\t\t\t...options,\n\t\t\t\tserviceTier:\n\t\t\t\t\toptions?.serviceTier === undefined ? (fastModeServiceTier ?? defaultServiceTier) : options.serviceTier,\n\t\t\t\t...(bedrockScope ? { region: bedrockScope.region, profile: bedrockScope.profile } : {}),\n\t\t\t\tinteractionMode: forceBackgroundRequests ? \"background\" : (options?.interactionMode ?? \"user\"),\n\t\t\t\tonInteractiveAuthRecovery: options?.onInteractiveAuthRecovery ?? recoverBedrockSsoAuthentication,\n\t\t\t\tapiKey: auth.apiKey,\n\t\t\t\tonAuthRejection:\n\t\t\t\t\tauth.apiKey && model.provider === \"openai-codex\"\n\t\t\t\t\t\t? async () => modelRegistry.recoverRejectedOAuthApiKey(model.provider, auth.apiKey as string)\n\t\t\t\t\t\t: options?.onAuthRejection,\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\theaders:\n\t\t\t\t\tattributionHeaders || auth.headers || options?.headers\n\t\t\t\t\t\t? { ...attributionHeaders, ...auth.headers, ...options?.headers }\n\t\t\t\t\t\t: undefined,\n\t\t\t};\n\t\t\treturn streamSimple(model, context, providerOptions);\n\t\t},\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\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\tagentDir,\n\t\tscopedModels: orchestrationModel\n\t\t\t? [{ model: orchestrationModel.model, thinkingLevel: orchestrationModel.binding.thinkingLevel }]\n\t\t\t: options.scopedModels,\n\t\tresourceLoader,\n\t\tcustomTools: options.customTools,\n\t\tmodelRegistry,\n\t\tinitialActiveToolNames,\n\t\tallowedToolNames,\n\t\texcludedToolNames,\n\t\textensionRunnerRef,\n\t\ttoolProfileFilter,\n\t\tisExplicitModel: orchestrationProfile ? true : (options.isExplicitModel ?? options.model != null),\n\t\tisExplicitThinking: orchestrationProfile\n\t\t\t? true\n\t\t\t: (options.isExplicitThinking ?? options.thinkingLevel !== undefined),\n\t\tisChildSession,\n\t\torchestrationProfile,\n\t\tsessionStartEvent: options.sessionStartEvent,\n\t});\n\ttry {\n\t\t// The initial runtime has now bound providers from profile-granted extensions. Re-resolve the\n\t\t// profile model against that authoritative registry generation, then resync model capability.\n\t\tawait session.reapplyActiveProfileModelSettings();\n\t\tif (modelFallbackMessage?.startsWith(\"Profile model resolution error:\")) {\n\t\t\tmodelFallbackMessage = undefined;\n\t\t}\n\t} catch (error) {\n\t\t// Preserve the established non-fatal fallback for a genuinely unresolved profile model.\n\t\tif (!modelFallbackMessage?.startsWith(\"Profile model resolution error:\")) {\n\t\t\tawait session.disposeAndWait();\n\t\t\tthrow error;\n\t\t}\n\t}\n\t// File-store memory tools exist only after providers initialize. Do this here so an SDK session\n\t// that never calls bindExtensions still has the requested `memory` tool when the grant allows it.\n\tawait session.initializeMemory();\n\tconst extensionsResult = resourceLoader.getExtensions();\n\n\treturn {\n\t\tsession,\n\t\textensionsResult,\n\t\tmodelFallbackMessage,\n\t};\n}\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"credential-exposure-guard.d.ts","sourceRoot":"","sources":["../../../src/core/secrets/credential-exposure-guard.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,
|
|
1
|
+
{"version":3,"file":"credential-exposure-guard.d.ts","sourceRoot":"","sources":["../../../src/core/secrets/credential-exposure-guard.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,KAAK,SAAS,EAAiD,MAAM,2BAA2B,CAAC;AAC1G,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,SAAS,CAAC;AAgCvC,MAAM,WAAW,0BAA0B;IAC1C,mBAAmB,CAAC,IAAI,EAAE,MAAM,GAAG,MAAM,CAAC;IAC1C,cAAc,CAAC,EAAE,SAAS,MAAM,EAAE,CAAC;IACnC,oBAAoB,CAAC,EAAE,SAAS,MAAM,EAAE,CAAC;CACzC;AAWD,wBAAgB,yBAAyB,CACxC,OAAO,EAAE,MAAM,EACf,GAAG,EAAE,MAAM,EACX,QAAQ,CAAC,EAAE,0BAA0B,GACnC,OAAO,CAgCT;AAyHD,yFAAyF;AACzF,wBAAgB,yBAAyB,CACxC,QAAQ,EAAE,MAAM,EAChB,IAAI,EAAE,OAAO,EACb,GAAG,EAAE,MAAM,EACX,QAAQ,CAAC,EAAE,0BAA0B,GACnC,MAAM,GAAG,SAAS,CAwDpB;AAuCD,wGAAwG;AACxG,wBAAgB,mCAAmC,CAAC,WAAW,SAAS,OAAO,EAAE,QAAQ,EACxF,IAAI,EAAE,SAAS,CAAC,WAAW,EAAE,QAAQ,CAAC,EACtC,IAAI,EAAE,MAAM,EACZ,QAAQ,CAAC,EAAE,0BAA0B,GACnC,SAAS,CAAC,WAAW,EAAE,QAAQ,CAAC,CAyBlC"}
|