@ponythewhite/base-context 1.0.5 → 1.0.7
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 +12 -0
- package/dist/base-context-runtime/pyproject.toml +1 -1
- package/dist/base-context-runtime/uv.lock +1 -1
- package/dist/build-info.json +1 -1
- package/dist/bundle/{bundled-modules-UVCJPNFC.js → bundled-modules-PS66L3IT.js} +2 -2
- package/dist/bundle/{chunk-WFJRFQGG.js → chunk-PFROC4EV.js} +4 -3
- package/dist/bundle/{chunk-6FZM46AU.js → chunk-VCW3YDFF.js} +90 -47
- package/dist/bundle/{cli-main-OYVMMJUO.js → cli-main-MMHTK7EB.js} +2 -2
- package/dist/bundle/cli.js +1 -1
- package/dist/bundle/{main-AVMYOTHF.js → main-XAIVH4Y7.js} +2 -2
- package/dist/cli/product-doctor.d.ts.map +1 -1
- package/dist/cli/product-doctor.js +2 -2
- package/dist/cli/product-doctor.js.map +1 -1
- package/dist/core/agent-session.d.ts.map +1 -1
- package/dist/core/agent-session.js +23 -12
- package/dist/core/agent-session.js.map +1 -1
- package/dist/core/canonical-context.d.ts +3 -1
- package/dist/core/canonical-context.d.ts.map +1 -1
- package/dist/core/canonical-context.js +46 -16
- package/dist/core/canonical-context.js.map +1 -1
- package/dist/core/context-epoch-copy.d.ts.map +1 -1
- package/dist/core/context-epoch-copy.js +1 -1
- package/dist/core/context-epoch-copy.js.map +1 -1
- package/dist/core/context-epoch.d.ts +13 -3
- package/dist/core/context-epoch.d.ts.map +1 -1
- package/dist/core/context-epoch.js +47 -24
- package/dist/core/context-epoch.js.map +1 -1
- package/dist/core/inference-coordinator.d.ts.map +1 -1
- package/dist/core/inference-coordinator.js +3 -1
- package/dist/core/inference-coordinator.js.map +1 -1
- package/dist/core/request-view-selection.d.ts +3 -3
- package/dist/core/request-view-selection.d.ts.map +1 -1
- package/dist/core/request-view-selection.js +14 -7
- package/dist/core/request-view-selection.js.map +1 -1
- package/dist/core/sdk.d.ts.map +1 -1
- package/dist/core/sdk.js +1 -1
- package/dist/core/sdk.js.map +1 -1
- package/dist/core/session-bootstrap.d.ts +1 -0
- package/dist/core/session-bootstrap.d.ts.map +1 -1
- package/dist/core/session-bootstrap.js +1 -1
- package/dist/core/session-bootstrap.js.map +1 -1
- package/package.json +4 -4
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"request-view-selection.js","sourceRoot":"","sources":["../../src/core/request-view-selection.ts"],"names":[],"mappings":"AACA,OAAO,EAMN,uBAAuB,GAEvB,MAAM,+BAA+B,CAAC;AACvC,OAAO,EAEN,+BAA+B,EAC/B,+BAA+B,EAC/B,0BAA0B,EAC1B,6BAA6B,GAC7B,MAAM,wBAAwB,CAAC;AAChC,OAAO,EAAE,YAAY,EAAE,MAAM,eAAe,CAAC;AAE7C,OAAO,EAAE,sBAAsB,EAAE,kBAAkB,EAAE,MAAM,iBAAiB,CAAC;AAE7E,wFAAwF;AACxF,MAAM,OAAO,wBAAyB,SAAQ,uBAAuB;IAM1D,kBAAkB;IALnB,MAAM,CAAoB;IAEnC,YACC,MAAyB,EACzB,UAAkC,EACzB,kBAA0C,EAClD;QACD,KAAK,CAAC,UAAU,CAAC,CAAC;kCAFT,kBAAkB;QAG3B,IAAI,CAAC,IAAI,GAAG,0BAA0B,CAAC;QACvC,IAAI,CAAC,MAAM,GAAG,MAAM,CAAC,MAAM,CAAC,EAAE,GAAG,MAAM,EAAE,CAAC,CAAC;IAAA,CAC3C;CACD;AAsCD,MAAM,UAAU,0BAA0B,CACzC,QAAiC,EACjC,MAAyB,EACzB,QAA8B,EAC9B,YAAsC,EACR;IAC9B,MAAM,MAAM,GAAG,+BAA+B,CAAC,QAAQ,CAAC,CAAC;IACzD,IAAI,CAAC,MAAM;QAAE,MAAM,IAAI,KAAK,CAAC,4DAA4D,CAAC,CAAC;IAC3F,MAAM,sBAAsB,GAAG,QAAQ,CAAC,OAAO,CAAC,CAAC,OAAO,EAAE,KAAK,E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AAC;IACD,OAAO,iBAAiB,EAAE,CAAC;AAAA,CAC3B","sourcesContent":["import type { AgentMessage } from \"@ponythewhite/base-context-agent\";\nimport {\n\ttype Context,\n\ttype ProviderRequestProjection,\n\ttype ProviderRequestPublicMessage,\n\ttype ProviderRequestRepresentation,\n\ttype RequestTokenAssessment,\n\tRequestTokenBudgetError,\n\ttype RequestTokenBudgetEvaluator,\n} from \"@ponythewhite/base-context-ai\";\nimport {\n\ttype CanonicalViewSelectionSource,\n\tcaptureCanonicalRequestMessages,\n\tgetCanonicalViewSelectionSource,\n\tpreparePublicContextWindow,\n\tprepareToolContinuationWindow,\n} from \"./canonical-context.js\";\nimport { convertToLlm } from \"./messages.js\";\nimport type { ContextEpochEntryRef, SourceSnapshotRef } from \"./request-events.js\";\nimport { bindMessageReplayUnits, closeViewSelection } from \"./view-units.js\";\n\n/** Actual adapter-public measurement, not a verdict about the opaque native request. */\nexport class PublicContextBudgetError extends RequestTokenBudgetError {\n\treadonly source: SourceSnapshotRef;\n\n\tconstructor(\n\t\tsource: SourceSnapshotRef,\n\t\tassessment: RequestTokenAssessment,\n\t\treadonly originalAssessment: RequestTokenAssessment,\n\t) {\n\t\tsuper(assessment);\n\t\tthis.name = \"PublicContextBudgetError\";\n\t\tthis.source = Object.freeze({ ...source });\n\t}\n}\n\nexport interface RequestViewCandidate {\n\treadonly source: SourceSnapshotRef;\n\treadonly selectedUnitIds: readonly string[];\n\treadonly request: ProviderRequestRepresentation;\n\treadonly projection: ProviderRequestProjection;\n\treadonly assessment: RequestTokenAssessment;\n\treadonly originalAssessment: RequestTokenAssessment;\n\t/** Exact public messages represented by the accepted candidate, with captured source recipes. */\n\treadonly publicMessages?: readonly AgentMessage[];\n}\n\n/** Root resolves only after its canonical epoch checkpoint ACK. This module owns no epoch state. */\nexport type RequestViewCommit = (\n\tcandidate: RequestViewCandidate,\n) => Promise<ContextEpochEntryRef | undefined> | Promise<void>;\nexport type RequestViewValidate = (\n\trequest: ProviderRequestRepresentation,\n\tassessment: RequestTokenAssessment | undefined,\n) => void;\n\nexport type RequestViewFixedPrepare = (\n\trequest: ProviderRequestRepresentation,\n\tprojection: ProviderRequestProjection,\n\tassessment: RequestTokenAssessment | undefined,\n) => ContextEpochEntryRef | void | Promise<ContextEpochEntryRef | undefined> | Promise<void>;\n\nexport interface CapturedRequestViewBoundary extends CanonicalViewSelectionSource {\n\treadonly messages: readonly AgentMessage[];\n\t/** Provider logical positions mapped to the unchanged canonical messages/units. */\n\treadonly providerMessageIndices: readonly number[];\n\treadonly providerPendingPublicMessageGroups?: readonly (readonly number[])[];\n\treadonly commit: RequestViewCommit;\n\treadonly validate?: RequestViewValidate;\n\treadonly fixedPrepare?: RequestViewFixedPrepare;\n}\n\nexport function captureRequestViewBoundary(\n\tmessages: readonly AgentMessage[],\n\tcommit: RequestViewCommit,\n\tvalidate?: RequestViewValidate,\n\tfixedPrepare?: RequestViewFixedPrepare,\n): CapturedRequestViewBoundary {\n\tconst source = getCanonicalViewSelectionSource(messages);\n\tif (!source) throw new Error(\"Request view boundary requires compiled canonical messages\");\n\tconst providerMessageIndices = messages.flatMap((message, index) => convertToLlm([message]).map(() => index));\n\treturn {\n\t\t...source,\n\t\tmessages: captureCanonicalRequestMessages(messages),\n\t\tproviderMessageIndices,\n\t\t...(source.pendingPublicMessageGroups\n\t\t\t? {\n\t\t\t\t\tproviderPendingPublicMessageGroups: source.pendingPublicMessageGroups.map((group) =>\n\t\t\t\t\t\tgroup.map((index) => providerMessageIndex(providerMessageIndices, index)),\n\t\t\t\t\t),\n\t\t\t\t}\n\t\t\t: {}),\n\t\tcommit,\n\t\tvalidate,\n\t\tfixedPrepare,\n\t};\n}\n\nfunction providerMessageIndex(indices: readonly number[], canonicalIndex: number): number {\n\tconst index = indices.indexOf(canonicalIndex);\n\tif (index < 0) throw new Error(\"Provider projection cannot address a filtered canonical message\");\n\treturn index;\n}\n\n/** Keep canonical UI barriers while translating the native serializer's provider-only positions. */\nfunction canonicalRequestProjection(\n\tboundary: CapturedRequestViewBoundary,\n\tprojection: ProviderRequestProjection,\n): ProviderRequestProjection {\n\tconst indices = boundary.providerMessageIndices;\n\tif (indices.length === boundary.messages.length) return projection;\n\tconst canonicalIndex = (index: number): number => {\n\t\tconst canonical = indices[index];\n\t\tif (canonical === undefined) throw new Error(\"Provider projection message index is outside its captured view\");\n\t\treturn canonical;\n\t};\n\treturn {\n\t\t...projection,\n\t\tmessageIndices: projection.messageIndices.map((index) => (index === null ? null : canonicalIndex(index))),\n\t\t...(projection.optionalMessageIndices\n\t\t\t? { optionalMessageIndices: projection.optionalMessageIndices.map(canonicalIndex) }\n\t\t\t: {}),\n\t\t...(projection.generatedMessageIndices\n\t\t\t? { generatedMessageIndices: projection.generatedMessageIndices.map(canonicalIndex) }\n\t\t\t: {}),\n\t\t...(projection.publicMessageGroups\n\t\t\t? { publicMessageGroups: projection.publicMessageGroups.map((group) => group.map(canonicalIndex)) }\n\t\t\t: {}),\n\t\t...(projection.pendingPublicMessageGroups\n\t\t\t? {\n\t\t\t\t\tpendingPublicMessageGroups: projection.pendingPublicMessageGroups.map((group) =>\n\t\t\t\t\t\tgroup.map(canonicalIndex),\n\t\t\t\t\t),\n\t\t\t\t}\n\t\t\t: {}),\n\t\t...(projection.encodePublicWindow\n\t\t\t? {\n\t\t\t\t\tencodePublicWindow: (replacements: readonly ProviderRequestPublicMessage[]) => {\n\t\t\t\t\t\tconst encoded = projection.encodePublicWindow!(\n\t\t\t\t\t\t\treplacements.map((replacement) => ({\n\t\t\t\t\t\t\t\t...replacement,\n\t\t\t\t\t\t\t\tmessageIndex: providerMessageIndex(indices, replacement.messageIndex),\n\t\t\t\t\t\t\t})),\n\t\t\t\t\t\t);\n\t\t\t\t\t\treturn (\n\t\t\t\t\t\t\tencoded && { ...encoded, projection: canonicalRequestProjection(boundary, encoded.projection) }\n\t\t\t\t\t\t);\n\t\t\t\t\t},\n\t\t\t\t}\n\t\t\t: {}),\n\t};\n}\n\nexport function matchesRequestView(\n\tboundary: CapturedRequestViewBoundary,\n\tsource: SourceSnapshotRef,\n\tcontext: Context,\n): boolean {\n\tconst expected = boundary.source;\n\tif (\n\t\texpected.sessionId !== source.sessionId ||\n\t\texpected.sessionFile !== source.sessionFile ||\n\t\texpected.leafId !== source.leafId ||\n\t\texpected.sourceSequence !== source.sourceSequence\n\t)\n\t\treturn false;\n\tconst rendered = convertToLlm([...boundary.messages]);\n\treturn (\n\t\tboundary.messages.length === boundary.units.length &&\n\t\trendered.length === boundary.providerMessageIndices.length &&\n\t\tJSON.stringify(rendered) === JSON.stringify(context.messages)\n\t);\n}\n\n/** Projection kinds describe their actual provider body, never an OpenAI-format route alias. */\nfunction requestInputKey(\n\trequest: ProviderRequestRepresentation,\n\tprojection: ProviderRequestProjection,\n): \"input\" | \"messages\" | undefined {\n\tif (\n\t\t(request.api === \"openai-responses\" || request.api === \"openai-codex-responses\") &&\n\t\t(projection.kind === \"openai-responses-text-v1\" || projection.kind === \"openai-responses-replay-v1\")\n\t)\n\t\treturn \"input\";\n\tif (\n\t\trequest.api === \"openai-completions\" &&\n\t\trequest.provider === \"deepseek\" &&\n\t\trequest.url === \"https://api.deepseek.com/chat/completions\" &&\n\t\tprojection.kind === \"deepseek-completions-text-tools-v1\" &&\n\t\trequest.body !== undefined &&\n\t\tJSON.parse(request.body).model === \"deepseek-flash\"\n\t)\n\t\treturn \"messages\";\n\treturn undefined;\n}\n\n/** Check the actual final mapping without selecting, converting, or committing another view. */\nexport async function prepareFixedRequestView(\n\tboundary: CapturedRequestViewBoundary,\n\trequest: ProviderRequestRepresentation,\n\tprojection: ProviderRequestProjection,\n\tassessment: RequestTokenAssessment | undefined,\n) {\n\tprojection = canonicalRequestProjection(boundary, projection);\n\tconst inputKey = requestInputKey(request, projection);\n\tconst payload = JSON.parse(request.body!) as Record<string, unknown> | null;\n\tconst input = inputKey && payload ? payload[inputKey] : undefined;\n\tif (!Array.isArray(input) || input.length !== projection.messageIndices.length)\n\t\tthrow new Error(\"Fixed context requires its final provider projection\");\n\tif (\n\t\tprojection.kind === \"openai-responses-text-v1\" &&\n\t\tboundary.messages.some(\n\t\t\t(message) =>\n\t\t\t\tmessage.role === \"toolResult\" ||\n\t\t\t\t(message.role === \"assistant\" && (message.content.length !== 1 || message.content[0].type !== \"text\")),\n\t\t)\n\t)\n\t\tthrow new Error(\"Fixed context requires its native replay adapter\");\n\tconst units = bindMessageReplayUnits(\n\t\tboundary.messages,\n\t\tboundary.units,\n\t\tboundary.limits,\n\t\tprojection.replayContract ?? \"complete-context\",\n\t);\n\tcloseViewSelection(\n\t\tunits,\n\t\tunits.map((unit) => unit.id),\n\t\tboundary.limits,\n\t);\n\treturn await boundary.fixedPrepare!(request, projection, assessment);\n}\n\n/** Only the actual serializer's established replay contract authorizes historical-literal omission. */\nexport async function selectRequestView(\n\tboundary: CapturedRequestViewBoundary,\n\trequest: ProviderRequestRepresentation,\n\tprojection: ProviderRequestProjection,\n\tbudget: RequestTokenBudgetEvaluator,\n\tallowShrink: boolean,\n): Promise<string | undefined> {\n\tprojection = canonicalRequestProjection(boundary, projection);\n\tconst full = budget.measure(request);\n\tconst inputKey = requestInputKey(request, projection);\n\tif (full.limitSource !== \"explicit-profile\" || !inputKey) return;\n\tconst payload = JSON.parse(request.body!) as Record<string, unknown>;\n\tconst input = payload[inputKey];\n\tif (!Array.isArray(input) || input.length !== projection.messageIndices.length) return;\n\n\t// Absence is complete-context; a profile or tool-shaped message is never group authority.\n\tconst replayContract = projection.replayContract ?? \"complete-context\";\n\tif (\n\t\tprojection.kind === \"openai-responses-text-v1\" &&\n\t\tboundary.messages.some(\n\t\t\t(message) =>\n\t\t\t\tmessage.role === \"toolResult\" ||\n\t\t\t\t(message.role === \"assistant\" && (message.content.length !== 1 || message.content[0].type !== \"text\")),\n\t\t)\n\t)\n\t\treturn;\n\tconst units = bindMessageReplayUnits(\n\t\tboundary.messages,\n\t\tboundary.units,\n\t\tboundary.limits,\n\t\treplayContract,\n\t\tboundary.pendingPublicMessageGroups,\n\t);\n\tconst offer = async (\n\t\tselectedUnitIds: readonly string[],\n\t\tcandidateRequest: ProviderRequestRepresentation,\n\t\tcandidateProjection: ProviderRequestProjection,\n\t\tassessment: RequestTokenAssessment,\n\t\tpublicMessages?: readonly AgentMessage[],\n\t) =>\n\t\tboundary.commit(\n\t\t\tObject.freeze({\n\t\t\t\tsource: Object.freeze({ ...boundary.source }),\n\t\t\t\tselectedUnitIds: Object.freeze([...selectedUnitIds]),\n\t\t\t\trequest: Object.freeze({ ...candidateRequest }),\n\t\t\t\tprojection: Object.freeze({\n\t\t\t\t\t...candidateProjection,\n\t\t\t\t\treplayContract,\n\t\t\t\t\tmessageIndices: Object.freeze([...candidateProjection.messageIndices]),\n\t\t\t\t\t...(candidateProjection.optionalMessageIndices\n\t\t\t\t\t\t? {\n\t\t\t\t\t\t\t\toptionalMessageIndices: Object.freeze([...candidateProjection.optionalMessageIndices]),\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t: {}),\n\t\t\t\t\t...(candidateProjection.generatedMessageIndices\n\t\t\t\t\t\t? {\n\t\t\t\t\t\t\t\tgeneratedMessageIndices: Object.freeze([...candidateProjection.generatedMessageIndices]),\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t: {}),\n\t\t\t\t}),\n\t\t\t\tassessment,\n\t\t\t\toriginalAssessment: full,\n\t\t\t\t...(publicMessages ? { publicMessages } : {}),\n\t\t\t}),\n\t\t);\n\tif (boundary.pendingPublicMessageGroups?.length) {\n\t\tif (\n\t\t\treplayContract !== \"message-groups\" ||\n\t\t\t!projection.publicWindow ||\n\t\t\t!projection.encodePublicWindow ||\n\t\t\tJSON.stringify(projection.pendingPublicMessageGroups) !== JSON.stringify(boundary.pendingPublicMessageGroups)\n\t\t)\n\t\t\tthrow new Error(\"Original tool group requires current native adapter public conversion\");\n\t\tconst publicView = prepareToolContinuationWindow(boundary.messages);\n\t\tconst encoded = projection.encodePublicWindow(publicView.replacements);\n\t\tif (!encoded || encoded.projection.pendingPublicMessageGroups?.length)\n\t\t\tthrow new Error(\"Native adapter did not convert the whole required tool group\");\n\t\tconst publicSource = getCanonicalViewSelectionSource(publicView.messages)!;\n\t\tconst publicUnits = bindMessageReplayUnits(\n\t\t\tpublicView.messages,\n\t\t\tpublicSource.units,\n\t\t\tboundary.limits,\n\t\t\treplayContract,\n\t\t);\n\t\tconst closed = closeViewSelection(\n\t\t\tpublicUnits,\n\t\t\tpublicUnits.map((unit) => unit.id),\n\t\t\tboundary.limits,\n\t\t);\n\t\tconst assessment = budget.measure(encoded.request);\n\t\tif (assessment.status === \"over-budget\") throw new PublicContextBudgetError(boundary.source, assessment, full);\n\t\tif (assessment.status !== \"within-estimate\")\n\t\t\tthrow new Error(\"Tool continuation public request exceeds its token budget\");\n\t\tawait offer(\n\t\t\tclosed.map((unit) => unit.id),\n\t\t\tencoded.request,\n\t\t\tencoded.projection,\n\t\t\tassessment,\n\t\t\tpublicView.messages,\n\t\t);\n\t\treturn encoded.request.body;\n\t}\n\tif (projection.pendingPublicMessageGroups?.length)\n\t\tthrow new Error(\"Adapter pending group has no original owned source plan\");\n\tconst offerPublicWindow = async (): Promise<string | undefined> => {\n\t\tif (\n\t\t\t!allowShrink ||\n\t\t\treplayContract !== \"message-groups\" ||\n\t\t\t!projection.publicWindow ||\n\t\t\t!projection.encodePublicWindow\n\t\t)\n\t\t\treturn;\n\t\tconst closed = closeViewSelection(\n\t\t\tunits,\n\t\t\tunits.map((unit) => unit.id),\n\t\t\tboundary.limits,\n\t\t);\n\t\tlet firstMessageIndex = 0;\n\t\tif (\n\t\t\tfull.status === \"unknown\" &&\n\t\t\tfull.unknown.length === 1 &&\n\t\t\tfull.unknown[0] === \"media, opaque or unsupported replay token coverage unknown\"\n\t\t) {\n\t\t\t// Credited items are not part of the unknown input. Keep original projection indices.\n\t\t\tconst firstUnmeteredItem = request.retainedPrefix?.inputItems ?? 0;\n\t\t\tconst reasoningItemIndex = input.findIndex(\n\t\t\t\t(item, index) => index >= firstUnmeteredItem && item?.type === \"reasoning\",\n\t\t\t);\n\t\t\tconst messageIndex = projection.messageIndices[reasoningItemIndex];\n\t\t\tconst group =\n\t\t\t\tmessageIndex == null\n\t\t\t\t\t? undefined\n\t\t\t\t\t: projection.publicMessageGroups?.find((members) => members.includes(messageIndex));\n\t\t\t// The adapter still accepts only complete groups; earlier meterable groups stay native.\n\t\t\tfirstMessageIndex = group ? Math.min(...group) : 0;\n\t\t}\n\t\tconst publicView = preparePublicContextWindow(boundary.messages, firstMessageIndex);\n\t\tif (!publicView) {\n\t\t\t// Keep the original measured refusal when no public conversion can be offered.\n\t\t\t// This is not a new recovery signal or permission to reprepare again.\n\t\t\tif (full.status === \"over-budget\") throw new RequestTokenBudgetError(full);\n\t\t\treturn;\n\t\t}\n\t\tconst encoded = projection.encodePublicWindow(publicView.replacements);\n\t\tif (!encoded) return;\n\t\tconst assessment = budget.measure(encoded.request);\n\t\tif (assessment.status === \"over-budget\") throw new PublicContextBudgetError(boundary.source, assessment, full);\n\t\tif (assessment.status !== \"within-estimate\") return;\n\t\tawait offer(\n\t\t\tclosed.map((unit) => unit.id),\n\t\t\tencoded.request,\n\t\t\tencoded.projection,\n\t\t\tassessment,\n\t\t\tpublicView.messages,\n\t\t);\n\t\treturn encoded.request.body;\n\t};\n\tif (full.status === \"within-estimate\") {\n\t\tconst closed = closeViewSelection(\n\t\t\tunits,\n\t\t\tunits.map((unit) => unit.id),\n\t\t\tboundary.limits,\n\t\t);\n\t\tawait offer(\n\t\t\tclosed.map((unit) => unit.id),\n\t\t\trequest,\n\t\t\tprojection,\n\t\t\tfull,\n\t\t);\n\t\treturn request.body;\n\t}\n\tif (!allowShrink || replayContract !== \"message-groups\") return;\n\tif (full.status !== \"over-budget\") return offerPublicWindow();\n\tlet latestAssistant = -1;\n\tfor (const [index, message] of boundary.messages.entries())\n\t\tif (message.role === \"assistant\") latestAssistant = index;\n\tconst retained = new Set(projection.messageIndices.slice(0, request.retainedPrefix?.inputItems ?? 0));\n\tconst projectedOptional =\n\t\tprojection.kind !== \"openai-responses-text-v1\" ? new Set(projection.optionalMessageIndices ?? []) : undefined;\n\tconst optional = units.filter((unit, index) => {\n\t\tconst message = boundary.messages[index];\n\t\treturn (\n\t\t\tindex !== latestAssistant &&\n\t\t\t!retained.has(index) &&\n\t\t\t(!projectedOptional || projectedOptional.has(index)) &&\n\t\t\tunit.kind === \"literal\" &&\n\t\t\tunit.authority === \"assistant-public\" &&\n\t\t\tmessage.role === \"assistant\" &&\n\t\t\tmessage.stopReason === \"stop\" &&\n\t\t\tmessage.content.length === 1 &&\n\t\t\tmessage.content[0].type === \"text\"\n\t\t);\n\t});\n\tconst generatedPositions = new Map<string, number>();\n\tconst generated =\n\t\tprojection.generatedMessageIndices ??\n\t\tboundary.messages.flatMap((message, index) =>\n\t\t\tmessage.role === \"assistant\" &&\n\t\t\tmessage.content.some((block) => block.type === \"text\" && block.textSignature === undefined)\n\t\t\t\t? [index]\n\t\t\t\t: [],\n\t\t);\n\tfor (const index of generated) generatedPositions.set(units[index].id, index);\n\t// All user inputs, the latest assistant, fixed/TaskFrame/recovery units and errors stay selected.\n\tconst selected = new Set(units.map((unit) => unit.id));\n\tfor (const unit of optional) {\n\t\tselected.delete(unit.id);\n\t\tconst closed = closeViewSelection(units, [...selected], boundary.limits);\n\t\t// Normal Responses rendering uses msg_<message index> for unsigned assistants.\n\t\t// Reject any subset that would change a retained generated item ID on reconstruction.\n\t\tif (closed.some((item, index) => generatedPositions.has(item.id) && generatedPositions.get(item.id) !== index))\n\t\t\tcontinue;\n\t\tconst closedIds = new Set(closed.map((item) => item.id));\n\t\tconst keepItem = (index: number) => {\n\t\t\tconst messageIndex = projection.messageIndices[index];\n\t\t\treturn messageIndex === null || closedIds.has(units[messageIndex].id);\n\t\t};\n\t\tconst body = JSON.stringify({ ...payload, [inputKey]: input.filter((_, index) => keepItem(index)) });\n\t\tconst candidateRequest = { ...request, body };\n\t\tconst assessment = budget.measure(candidateRequest);\n\t\tif (assessment.status !== \"within-estimate\") continue;\n\t\tawait offer(\n\t\t\tclosed.map((item) => item.id),\n\t\t\tcandidateRequest,\n\t\t\t{\n\t\t\t\t...projection,\n\t\t\t\tmessageIndices: projection.messageIndices.filter((_, index) => keepItem(index)),\n\t\t\t\t...(projection.optionalMessageIndices\n\t\t\t\t\t? {\n\t\t\t\t\t\t\toptionalMessageIndices: projection.optionalMessageIndices.filter((index) =>\n\t\t\t\t\t\t\t\tclosedIds.has(units[index].id),\n\t\t\t\t\t\t\t),\n\t\t\t\t\t\t}\n\t\t\t\t\t: {}),\n\t\t\t\t...(projection.generatedMessageIndices\n\t\t\t\t\t? {\n\t\t\t\t\t\t\tgeneratedMessageIndices: projection.generatedMessageIndices.filter((index) =>\n\t\t\t\t\t\t\t\tclosedIds.has(units[index].id),\n\t\t\t\t\t\t\t),\n\t\t\t\t\t\t}\n\t\t\t\t\t: {}),\n\t\t\t},\n\t\t\tassessment,\n\t\t);\n\t\treturn body;\n\t}\n\treturn offerPublicWindow();\n}\n"]}
|
|
1
|
+
{"version":3,"file":"request-view-selection.js","sourceRoot":"","sources":["../../src/core/request-view-selection.ts"],"names":[],"mappings":"AACA,OAAO,EAMN,uBAAuB,GAEvB,MAAM,+BAA+B,CAAC;AACvC,OAAO,EAEN,+BAA+B,EAC/B,+BAA+B,EAC/B,0BAA0B,EAC1B,6BAA6B,GAC7B,MAAM,wBAAwB,CAAC;AAChC,OAAO,EAAE,YAAY,EAAE,MAAM,eAAe,CAAC;AAE7C,OAAO,EAAE,sBAAsB,EAAE,kBAAkB,EAAE,MAAM,iBAAiB,CAAC;AAE7E,wFAAwF;AACxF,MAAM,OAAO,wBAAyB,SAAQ,uBAAuB;IAM1D,kBAAkB;IALnB,MAAM,CAAoB;IAEnC,YACC,MAAyB,EACzB,UAAkC,EACzB,kBAA0C,EAClD;QACD,KAAK,CAAC,UAAU,CAAC,CAAC;kCAFT,kBAAkB;QAG3B,IAAI,CAAC,IAAI,GAAG,0BAA0B,CAAC;QACvC,IAAI,CA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,KAAK,EAAE,EAAE,CAAC,QAAQ,CAAC,KAAK,CAAC,CAAC;YAC/E,GAAG,CAAC,UAAU,CAAC,sBAAsB;gBACpC,CAAC,CAAC;oBACA,sBAAsB,EAAE,UAAU,CAAC,sBAAsB,CAAC,MAAM,CAAC,CAAC,KAAK,EAAE,EAAE,CAC1E,SAAS,CAAC,GAAG,CAAC,KAAK,CAAC,KAAK,CAAC,CAAC,EAAE,CAAC,CAC9B;iBACD;gBACF,CAAC,CAAC,EAAE,CAAC;YACN,GAAG,CAAC,UAAU,CAAC,uBAAuB;gBACrC,CAAC,CAAC;oBACA,uBAAuB,EAAE,UAAU,CAAC,uBAAuB,CAAC,MAAM,CAAC,CAAC,KAAK,EAAE,EAAE,CAC5E,SAAS,CAAC,GAAG,CAAC,KAAK,CAAC,KAAK,CAAC,CAAC,EAAE,CAAC,CAC9B;iBACD;gBACF,CAAC,CAAC,EAAE,CAAC;SACN,EACD,UAAU,CACV,CAAC;QACF,OAAO,IAAI,CAAC;IACb,CAAC;IACD,OAAO,iBAAiB,EAAE,CAAC;AAAA,CAC3B","sourcesContent":["import type { AgentMessage } from \"@ponythewhite/base-context-agent\";\nimport {\n\ttype Context,\n\ttype ProviderRequestProjection,\n\ttype ProviderRequestPublicMessage,\n\ttype ProviderRequestRepresentation,\n\ttype RequestTokenAssessment,\n\tRequestTokenBudgetError,\n\ttype RequestTokenBudgetEvaluator,\n} from \"@ponythewhite/base-context-ai\";\nimport {\n\ttype CanonicalViewSelectionSource,\n\tcaptureCanonicalRequestMessages,\n\tgetCanonicalViewSelectionSource,\n\tpreparePublicContextWindow,\n\tprepareToolContinuationWindow,\n} from \"./canonical-context.js\";\nimport { convertToLlm } from \"./messages.js\";\nimport type { ContextEpochEntryRef, SourceSnapshotRef } from \"./request-events.js\";\nimport { bindMessageReplayUnits, closeViewSelection } from \"./view-units.js\";\n\n/** Actual adapter-public measurement, not a verdict about the opaque native request. */\nexport class PublicContextBudgetError extends RequestTokenBudgetError {\n\treadonly source: SourceSnapshotRef;\n\n\tconstructor(\n\t\tsource: SourceSnapshotRef,\n\t\tassessment: RequestTokenAssessment,\n\t\treadonly originalAssessment: RequestTokenAssessment,\n\t) {\n\t\tsuper(assessment);\n\t\tthis.name = \"PublicContextBudgetError\";\n\t\tthis.source = Object.freeze({ ...source });\n\t}\n}\n\nexport interface RequestViewCandidate {\n\treadonly source: SourceSnapshotRef;\n\treadonly selectedUnitIds: readonly string[];\n\treadonly request: ProviderRequestRepresentation;\n\treadonly projection: ProviderRequestProjection;\n\t// Absent only for mandatory full-view admission without a configured token budget.\n\treadonly assessment: RequestTokenAssessment | undefined;\n\treadonly originalAssessment: RequestTokenAssessment | undefined;\n\t/** Exact public messages represented by the accepted candidate, with captured source recipes. */\n\treadonly publicMessages?: readonly AgentMessage[];\n}\n\n/** Root resolves only after its canonical epoch checkpoint ACK. This module owns no epoch state. */\nexport type RequestViewCommit = (\n\tcandidate: RequestViewCandidate,\n) => Promise<ContextEpochEntryRef | undefined> | Promise<void>;\nexport type RequestViewValidate = (\n\trequest: ProviderRequestRepresentation,\n\tassessment: RequestTokenAssessment | undefined,\n) => void;\n\nexport type RequestViewFixedPrepare = (\n\trequest: ProviderRequestRepresentation,\n\tprojection: ProviderRequestProjection,\n\tassessment: RequestTokenAssessment | undefined,\n) => ContextEpochEntryRef | void | Promise<ContextEpochEntryRef | undefined> | Promise<void>;\n\nexport interface CapturedRequestViewBoundary extends CanonicalViewSelectionSource {\n\treadonly messages: readonly AgentMessage[];\n\t/** Provider logical positions mapped to the unchanged canonical messages/units. */\n\treadonly providerMessageIndices: readonly number[];\n\treadonly providerPendingPublicMessageGroups?: readonly (readonly number[])[];\n\treadonly commit: RequestViewCommit;\n\treadonly validate?: RequestViewValidate;\n\treadonly fixedPrepare?: RequestViewFixedPrepare;\n}\n\nexport function captureRequestViewBoundary(\n\tmessages: readonly AgentMessage[],\n\tcommit: RequestViewCommit,\n\tvalidate?: RequestViewValidate,\n\tfixedPrepare?: RequestViewFixedPrepare,\n): CapturedRequestViewBoundary {\n\tconst source = getCanonicalViewSelectionSource(messages);\n\tif (!source) throw new Error(\"Request view boundary requires compiled canonical messages\");\n\tconst providerMessageIndices = messages.flatMap((message, index) => convertToLlm([message]).map(() => index));\n\treturn {\n\t\t...source,\n\t\tmessages: captureCanonicalRequestMessages(messages),\n\t\tproviderMessageIndices,\n\t\t...(source.pendingPublicMessageGroups\n\t\t\t? {\n\t\t\t\t\tproviderPendingPublicMessageGroups: source.pendingPublicMessageGroups.map((group) =>\n\t\t\t\t\t\tgroup.map((index) => providerMessageIndex(providerMessageIndices, index)),\n\t\t\t\t\t),\n\t\t\t\t}\n\t\t\t: {}),\n\t\tcommit,\n\t\tvalidate,\n\t\tfixedPrepare,\n\t};\n}\n\nfunction providerMessageIndex(indices: readonly number[], canonicalIndex: number): number {\n\tconst index = indices.indexOf(canonicalIndex);\n\tif (index < 0) throw new Error(\"Provider projection cannot address a filtered canonical message\");\n\treturn index;\n}\n\n/** Keep canonical UI barriers while translating the native serializer's provider-only positions. */\nfunction canonicalRequestProjection(\n\tboundary: CapturedRequestViewBoundary,\n\tprojection: ProviderRequestProjection,\n): ProviderRequestProjection {\n\tconst indices = boundary.providerMessageIndices;\n\tif (indices.length === boundary.messages.length) return projection;\n\tconst canonicalIndex = (index: number): number => {\n\t\tconst canonical = indices[index];\n\t\tif (canonical === undefined) throw new Error(\"Provider projection message index is outside its captured view\");\n\t\treturn canonical;\n\t};\n\treturn {\n\t\t...projection,\n\t\tmessageIndices: projection.messageIndices.map((index) => (index === null ? null : canonicalIndex(index))),\n\t\t...(projection.optionalMessageIndices\n\t\t\t? { optionalMessageIndices: projection.optionalMessageIndices.map(canonicalIndex) }\n\t\t\t: {}),\n\t\t...(projection.generatedMessageIndices\n\t\t\t? { generatedMessageIndices: projection.generatedMessageIndices.map(canonicalIndex) }\n\t\t\t: {}),\n\t\t...(projection.publicMessageGroups\n\t\t\t? { publicMessageGroups: projection.publicMessageGroups.map((group) => group.map(canonicalIndex)) }\n\t\t\t: {}),\n\t\t...(projection.pendingPublicMessageGroups\n\t\t\t? {\n\t\t\t\t\tpendingPublicMessageGroups: projection.pendingPublicMessageGroups.map((group) =>\n\t\t\t\t\t\tgroup.map(canonicalIndex),\n\t\t\t\t\t),\n\t\t\t\t}\n\t\t\t: {}),\n\t\t...(projection.encodePublicWindow\n\t\t\t? {\n\t\t\t\t\tencodePublicWindow: (replacements: readonly ProviderRequestPublicMessage[]) => {\n\t\t\t\t\t\tconst encoded = projection.encodePublicWindow!(\n\t\t\t\t\t\t\treplacements.map((replacement) => ({\n\t\t\t\t\t\t\t\t...replacement,\n\t\t\t\t\t\t\t\tmessageIndex: providerMessageIndex(indices, replacement.messageIndex),\n\t\t\t\t\t\t\t})),\n\t\t\t\t\t\t);\n\t\t\t\t\t\treturn (\n\t\t\t\t\t\t\tencoded && { ...encoded, projection: canonicalRequestProjection(boundary, encoded.projection) }\n\t\t\t\t\t\t);\n\t\t\t\t\t},\n\t\t\t\t}\n\t\t\t: {}),\n\t};\n}\n\nexport function matchesRequestView(\n\tboundary: CapturedRequestViewBoundary,\n\tsource: SourceSnapshotRef,\n\tcontext: Context,\n): boolean {\n\tconst expected = boundary.source;\n\tif (\n\t\texpected.sessionId !== source.sessionId ||\n\t\texpected.sessionFile !== source.sessionFile ||\n\t\texpected.leafId !== source.leafId ||\n\t\texpected.sourceSequence !== source.sourceSequence\n\t)\n\t\treturn false;\n\tconst rendered = convertToLlm([...boundary.messages]);\n\treturn (\n\t\tboundary.messages.length === boundary.units.length &&\n\t\trendered.length === boundary.providerMessageIndices.length &&\n\t\tJSON.stringify(rendered) === JSON.stringify(context.messages)\n\t);\n}\n\n/** Projection kinds describe their actual provider body, never an OpenAI-format route alias. */\nfunction requestInputKey(\n\trequest: ProviderRequestRepresentation,\n\tprojection: ProviderRequestProjection,\n): \"input\" | \"messages\" | undefined {\n\tif (\n\t\t(request.api === \"openai-responses\" || request.api === \"openai-codex-responses\") &&\n\t\t(projection.kind === \"openai-responses-text-v1\" || projection.kind === \"openai-responses-replay-v1\")\n\t)\n\t\treturn \"input\";\n\tif (\n\t\trequest.api === \"openai-completions\" &&\n\t\trequest.provider === \"deepseek\" &&\n\t\trequest.url === \"https://api.deepseek.com/chat/completions\" &&\n\t\tprojection.kind === \"deepseek-completions-text-tools-v1\" &&\n\t\trequest.body !== undefined &&\n\t\tJSON.parse(request.body).model === \"deepseek-flash\"\n\t)\n\t\treturn \"messages\";\n\treturn undefined;\n}\n\n/** Check the actual final mapping without selecting, converting, or committing another view. */\nexport async function prepareFixedRequestView(\n\tboundary: CapturedRequestViewBoundary,\n\trequest: ProviderRequestRepresentation,\n\tprojection: ProviderRequestProjection,\n\tassessment: RequestTokenAssessment | undefined,\n) {\n\tprojection = canonicalRequestProjection(boundary, projection);\n\tconst inputKey = requestInputKey(request, projection);\n\tconst payload = JSON.parse(request.body!) as Record<string, unknown> | null;\n\tconst input = inputKey && payload ? payload[inputKey] : undefined;\n\tif (!Array.isArray(input) || input.length !== projection.messageIndices.length)\n\t\tthrow new Error(\"Fixed context requires its final provider projection\");\n\tif (\n\t\tprojection.kind === \"openai-responses-text-v1\" &&\n\t\tboundary.messages.some(\n\t\t\t(message) =>\n\t\t\t\tmessage.role === \"toolResult\" ||\n\t\t\t\t(message.role === \"assistant\" && (message.content.length !== 1 || message.content[0].type !== \"text\")),\n\t\t)\n\t)\n\t\tthrow new Error(\"Fixed context requires its native replay adapter\");\n\tconst units = bindMessageReplayUnits(\n\t\tboundary.messages,\n\t\tboundary.units,\n\t\tboundary.limits,\n\t\tprojection.replayContract ?? \"complete-context\",\n\t);\n\tcloseViewSelection(\n\t\tunits,\n\t\tunits.map((unit) => unit.id),\n\t\tboundary.limits,\n\t);\n\treturn await boundary.fixedPrepare!(request, projection, assessment);\n}\n\n/** Only the actual serializer's established replay contract authorizes historical-literal omission. */\nexport async function selectRequestView(\n\tboundary: CapturedRequestViewBoundary,\n\trequest: ProviderRequestRepresentation,\n\tprojection: ProviderRequestProjection,\n\tbudget: RequestTokenBudgetEvaluator | undefined,\n\tallowShrink: boolean,\n): Promise<string | undefined> {\n\tprojection = canonicalRequestProjection(boundary, projection);\n\tconst full = budget?.measure(request);\n\tconst inputKey = requestInputKey(request, projection);\n\tif ((budget && full?.limitSource !== \"explicit-profile\") || !inputKey) return;\n\tif (!budget && !boundary.pendingPublicMessageGroups?.length) return;\n\tconst payload = JSON.parse(request.body!) as Record<string, unknown>;\n\tconst input = payload[inputKey];\n\tif (!Array.isArray(input) || input.length !== projection.messageIndices.length) return;\n\n\t// Absence is complete-context; a profile or tool-shaped message is never group authority.\n\tconst replayContract = projection.replayContract ?? \"complete-context\";\n\tif (\n\t\tprojection.kind === \"openai-responses-text-v1\" &&\n\t\tboundary.messages.some(\n\t\t\t(message) =>\n\t\t\t\tmessage.role === \"toolResult\" ||\n\t\t\t\t(message.role === \"assistant\" && (message.content.length !== 1 || message.content[0].type !== \"text\")),\n\t\t)\n\t)\n\t\treturn;\n\tconst units = bindMessageReplayUnits(\n\t\tboundary.messages,\n\t\tboundary.units,\n\t\tboundary.limits,\n\t\treplayContract,\n\t\tboundary.pendingPublicMessageGroups,\n\t);\n\tconst offer = async (\n\t\tselectedUnitIds: readonly string[],\n\t\tcandidateRequest: ProviderRequestRepresentation,\n\t\tcandidateProjection: ProviderRequestProjection,\n\t\tassessment: RequestTokenAssessment | undefined,\n\t\tpublicMessages?: readonly AgentMessage[],\n\t) =>\n\t\tboundary.commit(\n\t\t\tObject.freeze({\n\t\t\t\tsource: Object.freeze({ ...boundary.source }),\n\t\t\t\tselectedUnitIds: Object.freeze([...selectedUnitIds]),\n\t\t\t\trequest: Object.freeze({ ...candidateRequest }),\n\t\t\t\tprojection: Object.freeze({\n\t\t\t\t\t...candidateProjection,\n\t\t\t\t\treplayContract,\n\t\t\t\t\tmessageIndices: Object.freeze([...candidateProjection.messageIndices]),\n\t\t\t\t\t...(candidateProjection.optionalMessageIndices\n\t\t\t\t\t\t? {\n\t\t\t\t\t\t\t\toptionalMessageIndices: Object.freeze([...candidateProjection.optionalMessageIndices]),\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t: {}),\n\t\t\t\t\t...(candidateProjection.generatedMessageIndices\n\t\t\t\t\t\t? {\n\t\t\t\t\t\t\t\tgeneratedMessageIndices: Object.freeze([...candidateProjection.generatedMessageIndices]),\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t: {}),\n\t\t\t\t}),\n\t\t\t\tassessment,\n\t\t\t\toriginalAssessment: full,\n\t\t\t\t...(publicMessages ? { publicMessages } : {}),\n\t\t\t}),\n\t\t);\n\tif (boundary.pendingPublicMessageGroups?.length) {\n\t\tif (\n\t\t\treplayContract !== \"message-groups\" ||\n\t\t\t!projection.publicWindow ||\n\t\t\t!projection.encodePublicWindow ||\n\t\t\tJSON.stringify(projection.pendingPublicMessageGroups) !== JSON.stringify(boundary.pendingPublicMessageGroups)\n\t\t)\n\t\t\tthrow new Error(\"Original tool group requires current native adapter public conversion\");\n\t\tconst publicView = prepareToolContinuationWindow(boundary.messages);\n\t\tconst encoded = projection.encodePublicWindow(publicView.replacements);\n\t\tif (!encoded || encoded.projection.pendingPublicMessageGroups?.length)\n\t\t\tthrow new Error(\"Native adapter did not convert the whole required tool group\");\n\t\tconst publicSource = getCanonicalViewSelectionSource(publicView.messages)!;\n\t\tconst publicUnits = bindMessageReplayUnits(\n\t\t\tpublicView.messages,\n\t\t\tpublicSource.units,\n\t\t\tboundary.limits,\n\t\t\treplayContract,\n\t\t);\n\t\tconst closed = closeViewSelection(\n\t\t\tpublicUnits,\n\t\t\tpublicUnits.map((unit) => unit.id),\n\t\t\tboundary.limits,\n\t\t);\n\t\tconst assessment = budget?.measure(encoded.request);\n\t\tif (assessment && full) {\n\t\t\tif (assessment.status === \"over-budget\") throw new PublicContextBudgetError(boundary.source, assessment, full);\n\t\t\tif (assessment.status !== \"within-estimate\")\n\t\t\t\tthrow new Error(\"Tool continuation public request exceeds its token budget\");\n\t\t}\n\t\tawait offer(\n\t\t\tclosed.map((unit) => unit.id),\n\t\t\tencoded.request,\n\t\t\tencoded.projection,\n\t\t\tassessment,\n\t\t\tpublicView.messages,\n\t\t);\n\t\treturn encoded.request.body;\n\t}\n\tif (projection.pendingPublicMessageGroups?.length)\n\t\tthrow new Error(\"Adapter pending group has no original owned source plan\");\n\t// Unbudgeted admission above retains every source unit; it never selects a smaller view.\n\tif (!budget || !full) return;\n\tconst offerPublicWindow = async (): Promise<string | undefined> => {\n\t\tif (\n\t\t\t!allowShrink ||\n\t\t\treplayContract !== \"message-groups\" ||\n\t\t\t!projection.publicWindow ||\n\t\t\t!projection.encodePublicWindow\n\t\t)\n\t\t\treturn;\n\t\tconst closed = closeViewSelection(\n\t\t\tunits,\n\t\t\tunits.map((unit) => unit.id),\n\t\t\tboundary.limits,\n\t\t);\n\t\tlet firstMessageIndex = 0;\n\t\tif (\n\t\t\tfull.status === \"unknown\" &&\n\t\t\tfull.unknown.length === 1 &&\n\t\t\tfull.unknown[0] === \"media, opaque or unsupported replay token coverage unknown\"\n\t\t) {\n\t\t\t// Credited items are not part of the unknown input. Keep original projection indices.\n\t\t\tconst firstUnmeteredItem = request.retainedPrefix?.inputItems ?? 0;\n\t\t\tconst reasoningItemIndex = input.findIndex(\n\t\t\t\t(item, index) => index >= firstUnmeteredItem && item?.type === \"reasoning\",\n\t\t\t);\n\t\t\tconst messageIndex = projection.messageIndices[reasoningItemIndex];\n\t\t\tconst group =\n\t\t\t\tmessageIndex == null\n\t\t\t\t\t? undefined\n\t\t\t\t\t: projection.publicMessageGroups?.find((members) => members.includes(messageIndex));\n\t\t\t// The adapter still accepts only complete groups; earlier meterable groups stay native.\n\t\t\tfirstMessageIndex = group ? Math.min(...group) : 0;\n\t\t}\n\t\tconst publicView = preparePublicContextWindow(boundary.messages, firstMessageIndex);\n\t\tif (!publicView) {\n\t\t\t// Keep the original measured refusal when no public conversion can be offered.\n\t\t\t// This is not a new recovery signal or permission to reprepare again.\n\t\t\tif (full.status === \"over-budget\") throw new RequestTokenBudgetError(full);\n\t\t\treturn;\n\t\t}\n\t\tconst encoded = projection.encodePublicWindow(publicView.replacements);\n\t\tif (!encoded) return;\n\t\tconst assessment = budget.measure(encoded.request);\n\t\tif (assessment.status === \"over-budget\") throw new PublicContextBudgetError(boundary.source, assessment, full);\n\t\tif (assessment.status !== \"within-estimate\") return;\n\t\tawait offer(\n\t\t\tclosed.map((unit) => unit.id),\n\t\t\tencoded.request,\n\t\t\tencoded.projection,\n\t\t\tassessment,\n\t\t\tpublicView.messages,\n\t\t);\n\t\treturn encoded.request.body;\n\t};\n\tif (full.status === \"within-estimate\") {\n\t\tconst closed = closeViewSelection(\n\t\t\tunits,\n\t\t\tunits.map((unit) => unit.id),\n\t\t\tboundary.limits,\n\t\t);\n\t\tawait offer(\n\t\t\tclosed.map((unit) => unit.id),\n\t\t\trequest,\n\t\t\tprojection,\n\t\t\tfull,\n\t\t);\n\t\treturn request.body;\n\t}\n\tif (!allowShrink || replayContract !== \"message-groups\") return;\n\tif (full.status !== \"over-budget\") return offerPublicWindow();\n\tlet latestAssistant = -1;\n\tfor (const [index, message] of boundary.messages.entries())\n\t\tif (message.role === \"assistant\") latestAssistant = index;\n\tconst retained = new Set(projection.messageIndices.slice(0, request.retainedPrefix?.inputItems ?? 0));\n\tconst projectedOptional =\n\t\tprojection.kind !== \"openai-responses-text-v1\" ? new Set(projection.optionalMessageIndices ?? []) : undefined;\n\tconst optional = units.filter((unit, index) => {\n\t\tconst message = boundary.messages[index];\n\t\treturn (\n\t\t\tindex !== latestAssistant &&\n\t\t\t!retained.has(index) &&\n\t\t\t(!projectedOptional || projectedOptional.has(index)) &&\n\t\t\tunit.kind === \"literal\" &&\n\t\t\tunit.authority === \"assistant-public\" &&\n\t\t\tmessage.role === \"assistant\" &&\n\t\t\tmessage.stopReason === \"stop\" &&\n\t\t\tmessage.content.length === 1 &&\n\t\t\tmessage.content[0].type === \"text\"\n\t\t);\n\t});\n\tconst generatedPositions = new Map<string, number>();\n\tconst generated =\n\t\tprojection.generatedMessageIndices ??\n\t\tboundary.messages.flatMap((message, index) =>\n\t\t\tmessage.role === \"assistant\" &&\n\t\t\tmessage.content.some((block) => block.type === \"text\" && block.textSignature === undefined)\n\t\t\t\t? [index]\n\t\t\t\t: [],\n\t\t);\n\tfor (const index of generated) generatedPositions.set(units[index].id, index);\n\t// All user inputs, the latest assistant, fixed/TaskFrame/recovery units and errors stay selected.\n\tconst selected = new Set(units.map((unit) => unit.id));\n\tfor (const unit of optional) {\n\t\tselected.delete(unit.id);\n\t\tconst closed = closeViewSelection(units, [...selected], boundary.limits);\n\t\t// Normal Responses rendering uses msg_<message index> for unsigned assistants.\n\t\t// Reject any subset that would change a retained generated item ID on reconstruction.\n\t\tif (closed.some((item, index) => generatedPositions.has(item.id) && generatedPositions.get(item.id) !== index))\n\t\t\tcontinue;\n\t\tconst closedIds = new Set(closed.map((item) => item.id));\n\t\tconst keepItem = (index: number) => {\n\t\t\tconst messageIndex = projection.messageIndices[index];\n\t\t\treturn messageIndex === null || closedIds.has(units[messageIndex].id);\n\t\t};\n\t\tconst body = JSON.stringify({ ...payload, [inputKey]: input.filter((_, index) => keepItem(index)) });\n\t\tconst candidateRequest = { ...request, body };\n\t\tconst assessment = budget.measure(candidateRequest);\n\t\tif (assessment.status !== \"within-estimate\") continue;\n\t\tawait offer(\n\t\t\tclosed.map((item) => item.id),\n\t\t\tcandidateRequest,\n\t\t\t{\n\t\t\t\t...projection,\n\t\t\t\tmessageIndices: projection.messageIndices.filter((_, index) => keepItem(index)),\n\t\t\t\t...(projection.optionalMessageIndices\n\t\t\t\t\t? {\n\t\t\t\t\t\t\toptionalMessageIndices: projection.optionalMessageIndices.filter((index) =>\n\t\t\t\t\t\t\t\tclosedIds.has(units[index].id),\n\t\t\t\t\t\t\t),\n\t\t\t\t\t\t}\n\t\t\t\t\t: {}),\n\t\t\t\t...(projection.generatedMessageIndices\n\t\t\t\t\t? {\n\t\t\t\t\t\t\tgeneratedMessageIndices: projection.generatedMessageIndices.filter((index) =>\n\t\t\t\t\t\t\t\tclosedIds.has(units[index].id),\n\t\t\t\t\t\t\t),\n\t\t\t\t\t\t}\n\t\t\t\t\t: {}),\n\t\t\t},\n\t\t\tassessment,\n\t\t);\n\t\treturn body;\n\t}\n\treturn offerPublicWindow();\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":"AACA,OAAO,EAA4B,KAAK,iBAAiB,EAAE,KAAK,aAAa,EAAE,MAAM,kCAAkC,CAAC;AACxH,OAAO,EAAoC,KAAK,KAAK,EAAoB,MAAM,+BAA+B,CAAC;AAE/G,OAAO,EAAE,YAAY,EAAE,MAAM,oBAAoB,CAAC;AAClD,OAAO,KAAK,EAAE,2BAA2B,EAAE,MAAM,6BAA6B,CAAC;AAE/E,OAAO,EAAE,WAAW,EAAE,MAAM,mBAAmB,CAAC;AAChD,OAAO,KAAK,EAAE,qBAAqB,EAAE,MAAM,iBAAiB,CAAC;AAE7D,OAAO,KAAK,EAAmB,oBAAoB,EAAE,iBAAiB,EAAE,cAAc,EAAE,MAAM,uBAAuB,CAAC;AAEtH,OAAO,EAAE,UAAU,EAAE,MAAM,sBAAsB,CAAC;AAElD,OAAO,EAAE,aAAa,EAAE,MAAM,qBAAqB,CAAC;AAEpD,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,sBAAsB,CAAC;AAG3D,OAAO,EAAwB,cAAc,EAAE,MAAM,sBAAsB,CAAC;AAC5E,OAAO,EAAE,eAAe,EAAE,MAAM,uBAAuB,CAAC;AAExD,OAAO,EACN,cAAc,EACd,cAAc,EACd,iBAAiB,EACjB,sBAAsB,EACtB,qBAAqB,EACrB,MAAM,kBAAkB,CAAC;AAE1B,MAAM,WAAW,yBAA0B,SAAQ,2BAA2B;IAC7E,4EAA4E;IAC5E,GAAG,CAAC,EAAE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AAyB,EAAE,MAAM,2BAA2B,CAAC;AAC3E,cAAc,4BAA4B,CAAC;AAC3C,YAAY,EAAE,2BAA2B,EAAE,MAAM,6BAA6B,CAAC;AAC/E,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,EACX,qBAAqB,EACrB,gBAAgB,EAChB,mBAAmB,EACnB,8BAA8B,GAC9B,MAAM,wBAAwB,CAAC;AAChC,YAAY,EACX,+BAA+B,EAC/B,iBAAiB,EACjB,kBAAkB,EAClB,mBAAmB,GACnB,MAAM,kBAAkB,CAAC;AAC1B,YAAY,EAAE,KAAK,EAAE,MAAM,aAAa,CAAC;AACzC,YAAY,EAAE,IAAI,EAAE,MAAM,kBAAkB,CAAC;AAE7C,OAAO,EAAE,cAAc,EAAE,cAAc,EAAE,iBAAiB,EAAE,sBAAsB,EAAE,qBAAqB,EAAE,CAAC;AAM5G;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAkCG;AACH,wBAAsB,kBAAkB,CAAC,OAAO,GAAE,yBAA8B,GAAG,OAAO,CAAC,wBAAwB,CAAC,CAoSnH","sourcesContent":["import { join } from \"node:path\";\nimport { Agent, type AgentMessage, type AgentOutputLimits, type ThinkingLevel } from \"@ponythewhite/base-context-agent\";\nimport { clampThinkingLevel, type Message, type Model, supportsFastMode } from \"@ponythewhite/base-context-ai\";\nimport { getAgentDir } from \"../config.js\";\nimport { AgentSession } from \"./agent-session.js\";\nimport type { AgentSessionCreationOptions } from \"./agent-session-services.js\";\nimport { formatNoModelsAvailableMessage } from \"./auth-guidance.js\";\nimport { AuthStorage } from \"./auth-storage.js\";\nimport type { AgentAutonomousConfig } from \"./autonomous.js\";\nimport { DEFAULT_THINKING_LEVEL } from \"./defaults.js\";\nimport type { ExtensionRunner, LoadExtensionsResult, SessionStartEvent, ToolDefinition } from \"./extensions/index.js\";\nimport { createNativeInferenceStream } from \"./inference-coordinator.js\";\nimport { McpManager } from \"./mcp/mcp-manager.js\";\nimport { convertToLlm } from \"./messages.js\";\nimport { ModelRegistry } from \"./model-registry.js\";\nimport { findInitialModel } from \"./model-resolver.js\";\nimport type { ResourceLoader } from \"./resource-loader.js\";\nimport { DefaultResourceLoader } from \"./resource-loader.js\";\nimport { readSessionBootstrap } from \"./session-bootstrap.js\";\nimport { getDefaultSessionDir, SessionManager } from \"./session-manager.js\";\nimport { SettingsManager } from \"./settings-manager.js\";\nimport { time } from \"./timings.js\";\nimport {\n\tcreateBashTool,\n\tcreateEditTool,\n\tcreateIpythonTool,\n\tcreatePrimeContextTool,\n\twithFileMutationQueue,\n} from \"./tools/index.js\";\n\nexport interface CreateAgentSessionOptions extends AgentSessionCreationOptions {\n\t/** Working directory for project-local discovery. Default: process.cwd() */\n\tcwd?: string;\n\t/** Global config directory. Default: ~/.base-context */\n\tagentDir?: string;\n\n\t/** Auth storage for credentials. Default: AuthStorage.create(agentDir/auth.json).\n\t * Existing host Codex subscriptions can be injected with\n\t * AuthStorage.fromStorage(readOnlyBackend, { existingOpenAICodexSubscription: true }).\n\t * This retains the built-in owned dispatcher; it does not enable OAuth login/refresh.\n\t */\n\tauthStorage?: AuthStorage;\n\t/** Model registry. Default: ModelRegistry.create(authStorage, agentDir/models.json) */\n\tmodelRegistry?: ModelRegistry;\n\n\t/** Model to use. Undefined restores a saved explicit choice; null leaves the session unselected. */\n\tmodel?: Model<any> | null;\n\t/** Thinking level. Default: from settings, else 'medium' (clamped to model capabilities) */\n\tthinkingLevel?: ThinkingLevel;\n\t/** Models available for cycling (Ctrl+P in interactive mode) */\n\tscopedModels?: Array<{ model: Model<any>; thinkingLevel?: ThinkingLevel }>;\n\n\t/**\n\t * Optional default tool suppression mode when no explicit allowlist is provided.\n\t *\n\t * - \"all\": start with no tools enabled\n\t * - \"builtin\": disable the default built-in tools (ipython and prime_context)\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, Base Context enables the default built-in tools (ipython and prime_context)\n\t * and leaves extension/custom tools enabled unless `noTools` changes that default.\n\t * When provided, only the listed tool names are enabled.\n\t */\n\ttools?: string[];\n\t/** 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/** MCP integration manager. When omitted, MCP host handlers are not wired. */\n\tmcpManager?: McpManager;\n\n\t/** Session manager. Default: SessionManager.create(cwd) */\n\tsessionManager?: SessionManager;\n\n\t/** Override complete native invocation output limits from settings. */\n\tinvocationOutputLimits?: AgentOutputLimits;\n\t/** Settings manager. Default: SettingsManager.create(cwd, agentDir) */\n\tsettingsManager?: SettingsManager;\n\t/** Session start event metadata for extension runtime startup. */\n\tsessionStartEvent?: SessionStartEvent;\n\t/** Host-side autonomous continuation policy. */\n\tautonomous?: AgentAutonomousConfig;\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/** Diagnostic when the selected session or saved model cannot be used. */\n\tmodelFallbackMessage?: string;\n}\n\nexport type { AgentSessionRuntimeConfig } from \"./agent-session-config.js\";\nexport * from \"./agent-session-runtime.js\";\nexport type { AgentSessionCreationOptions } from \"./agent-session-services.js\";\nexport type {\n\tExtensionAPI,\n\tExtensionCommandContext,\n\tExtensionContext,\n\tExtensionFactory,\n\tSlashCommandInfo,\n\tSlashCommandSource,\n\tToolDefinition,\n} from \"./extensions/index.js\";\nexport type { PromptTemplate } from \"./prompt-templates.js\";\nexport type {\n\tRlmMaxSubagentsStatus,\n\tRlmRootAdmission,\n\tRlmSubagentCapacity,\n\tRlmSubagentCapacityReservation,\n} from \"./rlm-max-subagents.js\";\nexport type {\n\tCreateRlmSubagentRuntimeOptions,\n\tRlmChildAdmission,\n\tRlmSubagentRuntime,\n\tSubagentRuntimeHost,\n} from \"./rlm-runtime.js\";\nexport type { Skill } from \"./skills.js\";\nexport type { Tool } from \"./tools/index.js\";\n\nexport { createBashTool, createEditTool, createIpythonTool, createPrimeContextTool, withFileMutationQueue };\n\nfunction getDefaultAgentDir(): string {\n\treturn getAgentDir();\n}\n\n/**\n * Create an AgentSession with the specified options.\n *\n * @example\n * ```typescript\n * // Minimal - uses defaults\n * const { session } = await createAgentSession();\n *\n * // With explicit model\n * import { getModel } from '@ponythewhite/base-context-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: [\"ipython\"],\n * resourceLoader: loader,\n * sessionManager: SessionManager.inMemory(),\n * });\n * ```\n */\nexport async function createAgentSession(options: CreateAgentSessionOptions = {}): Promise<CreateAgentSessionResult> {\n\tconst contextMode = options.contextMode;\n\tif (options.requestTokenBudget)\n\t\toptions = { ...options, requestTokenBudget: structuredClone(options.requestTokenBudget) };\n\tconst cwd = options.cwd ?? options.sessionManager?.getCwd() ?? process.cwd();\n\tconst agentDir = options.agentDir ?? getDefaultAgentDir();\n\tlet resourceLoader = options.resourceLoader;\n\n\tconst authPath = options.agentDir ? join(agentDir, \"auth.json\") : undefined;\n\tconst modelsPath = options.agentDir ? join(agentDir, \"models.json\") : undefined;\n\tconst 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\tconst sessionManager =\n\t\toptions.sessionManager ?? (await SessionManager.create(cwd, getDefaultSessionDir(cwd, agentDir)));\n\n\tlet session: AgentSession | undefined;\n\ttry {\n\t\t// Ensure MCP providers are registered and built-in MCP skills are gated by\n\t\t// auth even on the bare SDK path (not just the CLI's createAgentSessionServices).\n\t\tconst mcpManager =\n\t\t\toptions.mcpManager ??\n\t\t\tnew McpManager({ authStorage, getUserServers: () => settingsManager.getGlobalMcpServers() });\n\t\tmodelRegistry.setOnOAuthProvidersReset(() => mcpManager.registerUserProviders());\n\n\t\tif (!resourceLoader) {\n\t\t\tresourceLoader = new DefaultResourceLoader({\n\t\t\t\tcwd,\n\t\t\t\tagentDir,\n\t\t\t\tsettingsManager,\n\t\t\t\textraBuiltinSkillOverrides: () => mcpManager.getDisabledBuiltinSkillOverrides(),\n\t\t\t});\n\t\t\tawait resourceLoader.reload();\n\t\t\ttime(\"resourceLoader.reload\");\n\t\t}\n\n\t\tconst {\n\t\t\tcontext: existingSession,\n\t\t\thasExistingSession,\n\t\t\thasThinkingEntry,\n\t\t\thasServiceTierEntry,\n\t\t} = await readSessionBootstrap(sessionManager, settingsManager.getCanonicalContextLimits(), {\n\t\t\tallowPendingToolPublic: options.requestTokenBudget !== undefined,\n\t\t\tinitialContextMode: contextMode ?? settingsManager.getContextMode(),\n\t\t});\n\n\t\tlet model = options.model ?? undefined;\n\t\tlet modelFallbackMessage: string | undefined;\n\n\t\tif (options.model === undefined && hasExistingSession && existingSession.model) {\n\t\t\tconst saved = existingSession.model;\n\t\t\tconst restoredModel = modelRegistry.find(saved.provider, saved.modelId);\n\t\t\tmodel = restoredModel;\n\t\t\tif (!restoredModel) {\n\t\t\t\tmodelFallbackMessage = `Could not restore model ${saved.provider}/${saved.modelId}. Use /model to select a supported model.`;\n\t\t\t} else if (!modelRegistry.hasConfiguredAuth(restoredModel)) {\n\t\t\t\tmodelFallbackMessage = `Selected model ${saved.provider}/${saved.modelId} needs authentication. Use /login to configure this provider.`;\n\t\t\t}\n\t\t} else if (options.model === undefined) {\n\t\t\tconst result = await findInitialModel({\n\t\t\t\tscopedModels: [],\n\t\t\t\tisContinuing: hasExistingSession,\n\t\t\t\tdefaultProvider: settingsManager.getDefaultProvider(),\n\t\t\t\tdefaultModelId: settingsManager.getDefaultModel(),\n\t\t\t\tdefaultThinkingLevel: settingsManager.getDefaultThinkingLevel(),\n\t\t\t\tmodelRegistry,\n\t\t\t});\n\t\t\tmodel = result.model;\n\t\t\tif (model && !modelRegistry.hasConfiguredAuth(model)) {\n\t\t\t\tmodelFallbackMessage = `Selected model ${model.provider}/${model.id} needs authentication. Use /login to configure this provider.`;\n\t\t\t} else if (!model) {\n\t\t\t\tconst provider = settingsManager.getDefaultProvider();\n\t\t\t\tconst modelId = settingsManager.getDefaultModel();\n\t\t\t\tmodelFallbackMessage =\n\t\t\t\t\tprovider && modelId\n\t\t\t\t\t\t? `Selected model ${provider}/${modelId} is unavailable. Use /model to select a supported model.`\n\t\t\t\t\t\t: formatNoModelsAvailableMessage();\n\t\t\t}\n\t\t}\n\n\t\tlet thinkingLevel = options.thinkingLevel;\n\n\t\tif (thinkingLevel === undefined && hasExistingSession) {\n\t\t\tthinkingLevel = hasThinkingEntry\n\t\t\t\t? (existingSession.thinkingLevel as ThinkingLevel)\n\t\t\t\t: (settingsManager.getDefaultThinkingLevel() ?? DEFAULT_THINKING_LEVEL);\n\t\t}\n\n\t\tif (thinkingLevel === undefined) {\n\t\t\tthinkingLevel = settingsManager.getDefaultThinkingLevel() ?? DEFAULT_THINKING_LEVEL;\n\t\t}\n\n\t\tif (!model) {\n\t\t\tthinkingLevel = \"off\";\n\t\t} else {\n\t\t\tthinkingLevel = clampThinkingLevel(model, thinkingLevel) as ThinkingLevel;\n\t\t}\n\n\t\tconst serviceTierPreference =\n\t\t\toptions.serviceTier ??\n\t\t\t(hasServiceTierEntry ? existingSession.serviceTier : settingsManager.getDefaultServiceTier());\n\t\tconst serviceTier =\n\t\t\tserviceTierPreference === \"priority\" && (!model || !supportsFastMode(model))\n\t\t\t\t? \"default\"\n\t\t\t\t: serviceTierPreference;\n\n\t\tconst allowedToolNames =\n\t\t\toptions.allowedToolNames ?? options.tools ?? (options.noTools === \"all\" ? [] : undefined);\n\t\tconst includeGoals = options.includeGoals ?? (options.tools !== undefined || options.noTools !== \"all\");\n\t\tconst initialActiveToolNames: string[] =\n\t\t\toptions.initialActiveToolNames ??\n\t\t\t(options.tools ? [...options.tools] : options.noTools ? [] : [\"ipython\", \"prime_context\"]);\n\n\t\tlet agent: Agent;\n\n\t\tconst convertToLlmWithBlockImages = (messages: AgentMessage[]): Message[] => {\n\t\t\tconst converted = convertToLlm(messages);\n\t\t\tif (!settingsManager.getBlockImages()) {\n\t\t\t\treturn converted;\n\t\t\t}\n\t\t\treturn converted.map((msg) => {\n\t\t\t\tif (msg.role === \"user\" || msg.role === \"toolResult\") {\n\t\t\t\t\tconst content = msg.content;\n\t\t\t\t\tif (Array.isArray(content)) {\n\t\t\t\t\t\tconst hasImages = content.some((c) => c.type === \"image\");\n\t\t\t\t\t\tif (hasImages) {\n\t\t\t\t\t\t\tconst filteredContent = content\n\t\t\t\t\t\t\t\t.map((c) =>\n\t\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\t)\n\t\t\t\t\t\t\t\t.filter(\n\t\t\t\t\t\t\t\t\t(c, i, arr) =>\n\t\t\t\t\t\t\t\t\t\t!(\n\t\t\t\t\t\t\t\t\t\t\tc.type === \"text\" &&\n\t\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\t\ti > 0 &&\n\t\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\t(arr[i - 1] as { type: \"text\"; text: string }).text === \"Image reading is disabled.\"\n\t\t\t\t\t\t\t\t\t\t),\n\t\t\t\t\t\t\t\t);\n\t\t\t\t\t\t\treturn { ...msg, content: filteredContent };\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\treturn msg;\n\t\t\t});\n\t\t};\n\n\t\tconst extensionRunnerRef: { current?: ExtensionRunner } = {};\n\n\t\tagent = new Agent({\n\t\t\tinitialState: {\n\t\t\t\tsystemPrompt: \"\",\n\t\t\t\tmodel,\n\t\t\t\tthinkingLevel,\n\t\t\t\tserviceTier,\n\t\t\t\ttools: [],\n\t\t\t},\n\t\t\tconvertToLlm: convertToLlmWithBlockImages,\n\t\t\tstreamFn: createNativeInferenceStream(async (model, _context, options) => {\n\t\t\t\tif (!modelRegistry.hasConfiguredAuth(model)) {\n\t\t\t\t\tthrow new Error(\n\t\t\t\t\t\t`Selected model ${model.provider}/${model.id} needs authentication. Use /login to configure this provider.`,\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t\tconst auth = await modelRegistry.getApiKeyAndHeaders(model);\n\t\t\t\tif (!auth.ok) {\n\t\t\t\t\tthrow new Error(auth.error);\n\t\t\t\t}\n\t\t\t\tconst providerRetrySettings = settingsManager.getProviderRetrySettings();\n\t\t\t\treturn {\n\t\t\t\t\t...options,\n\t\t\t\t\tapiKey: auth.apiKey,\n\t\t\t\t\tauthSourceToken: auth.sourceToken,\n\t\t\t\t\ttimeoutMs: options?.timeoutMs ?? providerRetrySettings.timeoutMs,\n\t\t\t\t\tmaxRetries: options?.maxRetries ?? providerRetrySettings.maxRetries,\n\t\t\t\t\tmaxRetryDelayMs: options?.maxRetryDelayMs ?? providerRetrySettings.maxRetryDelayMs,\n\t\t\t\t\theaders: auth.headers || options?.headers ? { ...auth.headers, ...options?.headers } : undefined,\n\t\t\t\t};\n\t\t\t}),\n\t\t\tonPayload: async (payload, _model) => {\n\t\t\t\tconst runner = extensionRunnerRef.current;\n\t\t\t\tif (!runner?.hasHandlers(\"before_provider_request\")) {\n\t\t\t\t\treturn payload;\n\t\t\t\t}\n\t\t\t\treturn runner.emitBeforeProviderRequest(payload);\n\t\t\t},\n\t\t\tonResponse: async (response, _model) => {\n\t\t\t\tconst runner = extensionRunnerRef.current;\n\t\t\t\tif (!runner?.hasHandlers(\"after_provider_response\")) {\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tawait runner.emit({\n\t\t\t\t\ttype: \"after_provider_response\",\n\t\t\t\t\tstatus: response.status,\n\t\t\t\t\theaders: response.headers,\n\t\t\t\t});\n\t\t\t},\n\t\t\tsessionId: sessionManager.getSessionId(),\n\t\t\ttransformContext: async (messages) => {\n\t\t\t\tconst runner = extensionRunnerRef.current;\n\t\t\t\tif (!runner) return messages;\n\t\t\t\treturn runner.emitContext(messages);\n\t\t\t},\n\t\t\tsteeringMode: settingsManager.getSteeringMode(),\n\t\t\tfollowUpMode: settingsManager.getFollowUpMode(),\n\t\t\ttransport: settingsManager.getTransport(),\n\t\t\tthinkingBudgets: settingsManager.getThinkingBudgets(),\n\t\t\tmaxRetryDelayMs: settingsManager.getProviderRetrySettings().maxRetryDelayMs,\n\t\t});\n\n\t\tif (hasExistingSession) {\n\t\t\tagent.state.messages = existingSession.messages;\n\t\t\tif (!hasThinkingEntry) {\n\t\t\t\tawait sessionManager.appendThinkingLevelChange(thinkingLevel);\n\t\t\t}\n\t\t} else {\n\t\t\tif (model) {\n\t\t\t\tawait sessionManager.appendModelChange(model.provider, model.id);\n\t\t\t}\n\t\t\tawait sessionManager.appendThinkingLevelChange(thinkingLevel);\n\t\t}\n\t\tif (!hasServiceTierEntry) {\n\t\t\tawait sessionManager.appendServiceTierChange(serviceTierPreference);\n\t\t}\n\n\t\tsession = new AgentSession({\n\t\t\tinvocationOutputLimits: options.invocationOutputLimits,\n\t\t\trequestTokenBudget: options.requestTokenBudget,\n\t\t\tcontextMode,\n\t\t\tagent,\n\t\t\tsessionManager,\n\t\t\tsettingsManager,\n\t\t\tserviceTierPreference,\n\t\t\tcwd,\n\t\t\t// Only the explicit dir — the default may not match injected custom storage.\n\t\t\tagentDir: options.agentDir,\n\t\t\tscopedModels: options.scopedModels,\n\t\t\tresourceLoader,\n\t\t\tcustomTools: options.customTools,\n\t\t\tmodelRegistry,\n\t\t\tmcpManager,\n\t\t\tinitialActiveToolNames,\n\t\t\tallowedToolNames,\n\t\t\tincludeGoals,\n\t\t\tincludeCompactSkill: options.includeCompactSkill,\n\t\t\trlmHeartbeatController: options.rlmHeartbeatController,\n\t\t\tagentMessageController: options.agentMessageController,\n\t\t\tagentObserveController: options.agentObserveController,\n\t\t\textensionRunnerRef,\n\t\t\trlmDepth: options.rlmDepth,\n\t\t\trlmMaxDepth: options.rlmMaxDepth,\n\t\t\trlmSessionDir: options.rlmSessionDir,\n\t\t\trlmParentNodeId: options.rlmParentNodeId,\n\t\t\trlmParentAgent: options.rlmParentAgent,\n\t\t\trlmChildAdmission: options.rlmChildAdmission,\n\t\t\trlmSubagentCapacity: options.rlmSubagentCapacity,\n\t\t\trlmRootAdmission: options.rlmRootAdmission,\n\t\t\tsemanticParentSessionId: options.semanticParentSessionId,\n\t\t\tsemanticSpawnedByRequestId: options.semanticSpawnedByRequestId,\n\t\t\tsubagentRuntimeHost: options.subagentRuntimeHost,\n\t\t\tsessionStartEvent: options.sessionStartEvent,\n\t\t\tprewarmIpythonKernel: options.prewarmIpythonKernel,\n\t\t\tautonomous: options.autonomous,\n\t\t\tserializedRefine: options.serializedRefine,\n\t\t\tinitialGoal: options.initialGoal,\n\t\t});\n\t\tawait session.initialize();\n\t\tconst extensionsResult = resourceLoader.getExtensions();\n\n\t\treturn {\n\t\t\tsession,\n\t\t\textensionsResult,\n\t\t\tmodelFallbackMessage,\n\t\t};\n\t} catch (error) {\n\t\ttry {\n\t\t\tconst admitted = options.rlmChildAdmission?.session ?? options.rlmRootAdmission?.session;\n\t\t\tconst failedSession = session ?? (admitted?.sessionManager === sessionManager ? admitted : undefined);\n\t\t\tif (failedSession) await failedSession.disposeAsync();\n\t\t\telse {\n\t\t\t\tawait sessionManager.close();\n\t\t\t\tawait options.rlmChildAdmission?.confirmUnboundCleanup();\n\t\t\t}\n\t\t} catch (cleanupError) {\n\t\t\tif (cleanupError === error || (error instanceof AggregateError && error.errors.includes(cleanupError)))\n\t\t\t\tthrow error;\n\t\t\tthrow new AggregateError([error, cleanupError], \"Session creation and cleanup failed\");\n\t\t}\n\t\tthrow error;\n\t}\n}\n"]}
|
|
1
|
+
{"version":3,"file":"sdk.d.ts","sourceRoot":"","sources":["../../src/core/sdk.ts"],"names":[],"mappings":"AACA,OAAO,EAA4B,KAAK,iBAAiB,EAAE,KAAK,aAAa,EAAE,MAAM,kCAAkC,CAAC;AACxH,OAAO,EAAoC,KAAK,KAAK,EAAoB,MAAM,+BAA+B,CAAC;AAE/G,OAAO,EAAE,YAAY,EAAE,MAAM,oBAAoB,CAAC;AAClD,OAAO,KAAK,EAAE,2BAA2B,EAAE,MAAM,6BAA6B,CAAC;AAE/E,OAAO,EAAE,WAAW,EAAE,MAAM,mBAAmB,CAAC;AAChD,OAAO,KAAK,EAAE,qBAAqB,EAAE,MAAM,iBAAiB,CAAC;AAE7D,OAAO,KAAK,EAAmB,oBAAoB,EAAE,iBAAiB,EAAE,cAAc,EAAE,MAAM,uBAAuB,CAAC;AAEtH,OAAO,EAAE,UAAU,EAAE,MAAM,sBAAsB,CAAC;AAElD,OAAO,EAAE,aAAa,EAAE,MAAM,qBAAqB,CAAC;AAEpD,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,sBAAsB,CAAC;AAG3D,OAAO,EAAwB,cAAc,EAAE,MAAM,sBAAsB,CAAC;AAC5E,OAAO,EAAE,eAAe,EAAE,MAAM,uBAAuB,CAAC;AAExD,OAAO,EACN,cAAc,EACd,cAAc,EACd,iBAAiB,EACjB,sBAAsB,EACtB,qBAAqB,EACrB,MAAM,kBAAkB,CAAC;AAE1B,MAAM,WAAW,yBAA0B,SAAQ,2BAA2B;IAC7E,4EAA4E;IAC5E,GAAG,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Y,EAAE,yBAAyB,EAAE,MAAM,2BAA2B,CAAC;AAC3E,cAAc,4BAA4B,CAAC;AAC3C,YAAY,EAAE,2BAA2B,EAAE,MAAM,6BAA6B,CAAC;AAC/E,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,EACX,qBAAqB,EACrB,gBAAgB,EAChB,mBAAmB,EACnB,8BAA8B,GAC9B,MAAM,wBAAwB,CAAC;AAChC,YAAY,EACX,+BAA+B,EAC/B,iBAAiB,EACjB,kBAAkB,EAClB,mBAAmB,GACnB,MAAM,kBAAkB,CAAC;AAC1B,YAAY,EAAE,KAAK,EAAE,MAAM,aAAa,CAAC;AACzC,YAAY,EAAE,IAAI,EAAE,MAAM,kBAAkB,CAAC;AAE7C,OAAO,EAAE,cAAc,EAAE,cAAc,EAAE,iBAAiB,EAAE,sBAAsB,EAAE,qBAAqB,EAAE,CAAC;AAM5G;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAkCG;AACH,wBAAsB,kBAAkB,CAAC,OAAO,GAAE,yBAA8B,GAAG,OAAO,CAAC,wBAAwB,CAAC,CAoSnH","sourcesContent":["import { join } from \"node:path\";\nimport { Agent, type AgentMessage, type AgentOutputLimits, type ThinkingLevel } from \"@ponythewhite/base-context-agent\";\nimport { clampThinkingLevel, type Message, type Model, supportsFastMode } from \"@ponythewhite/base-context-ai\";\nimport { getAgentDir } from \"../config.js\";\nimport { AgentSession } from \"./agent-session.js\";\nimport type { AgentSessionCreationOptions } from \"./agent-session-services.js\";\nimport { formatNoModelsAvailableMessage } from \"./auth-guidance.js\";\nimport { AuthStorage } from \"./auth-storage.js\";\nimport type { AgentAutonomousConfig } from \"./autonomous.js\";\nimport { DEFAULT_THINKING_LEVEL } from \"./defaults.js\";\nimport type { ExtensionRunner, LoadExtensionsResult, SessionStartEvent, ToolDefinition } from \"./extensions/index.js\";\nimport { createNativeInferenceStream } from \"./inference-coordinator.js\";\nimport { McpManager } from \"./mcp/mcp-manager.js\";\nimport { convertToLlm } from \"./messages.js\";\nimport { ModelRegistry } from \"./model-registry.js\";\nimport { findInitialModel } from \"./model-resolver.js\";\nimport type { ResourceLoader } from \"./resource-loader.js\";\nimport { DefaultResourceLoader } from \"./resource-loader.js\";\nimport { readSessionBootstrap } from \"./session-bootstrap.js\";\nimport { getDefaultSessionDir, SessionManager } from \"./session-manager.js\";\nimport { SettingsManager } from \"./settings-manager.js\";\nimport { time } from \"./timings.js\";\nimport {\n\tcreateBashTool,\n\tcreateEditTool,\n\tcreateIpythonTool,\n\tcreatePrimeContextTool,\n\twithFileMutationQueue,\n} from \"./tools/index.js\";\n\nexport interface CreateAgentSessionOptions extends AgentSessionCreationOptions {\n\t/** Working directory for project-local discovery. Default: process.cwd() */\n\tcwd?: string;\n\t/** Global config directory. Default: ~/.base-context */\n\tagentDir?: string;\n\n\t/** Auth storage for credentials. Default: AuthStorage.create(agentDir/auth.json).\n\t * Existing host Codex subscriptions can be injected with\n\t * AuthStorage.fromStorage(readOnlyBackend, { existingOpenAICodexSubscription: true }).\n\t * This retains the built-in owned dispatcher; it does not enable OAuth login/refresh.\n\t */\n\tauthStorage?: AuthStorage;\n\t/** Model registry. Default: ModelRegistry.create(authStorage, agentDir/models.json) */\n\tmodelRegistry?: ModelRegistry;\n\n\t/** Model to use. Undefined restores a saved explicit choice; null leaves the session unselected. */\n\tmodel?: Model<any> | null;\n\t/** Thinking level. Default: from settings, else 'medium' (clamped to model capabilities) */\n\tthinkingLevel?: ThinkingLevel;\n\t/** Models available for cycling (Ctrl+P in interactive mode) */\n\tscopedModels?: Array<{ model: Model<any>; thinkingLevel?: ThinkingLevel }>;\n\n\t/**\n\t * Optional default tool suppression mode when no explicit allowlist is provided.\n\t *\n\t * - \"all\": start with no tools enabled\n\t * - \"builtin\": disable the default built-in tools (ipython and prime_context)\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, Base Context enables the default built-in tools (ipython and prime_context)\n\t * and leaves extension/custom tools enabled unless `noTools` changes that default.\n\t * When provided, only the listed tool names are enabled.\n\t */\n\ttools?: string[];\n\t/** 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/** MCP integration manager. When omitted, MCP host handlers are not wired. */\n\tmcpManager?: McpManager;\n\n\t/** Session manager. Default: SessionManager.create(cwd) */\n\tsessionManager?: SessionManager;\n\n\t/** Override complete native invocation output limits from settings. */\n\tinvocationOutputLimits?: AgentOutputLimits;\n\t/** Settings manager. Default: SettingsManager.create(cwd, agentDir) */\n\tsettingsManager?: SettingsManager;\n\t/** Session start event metadata for extension runtime startup. */\n\tsessionStartEvent?: SessionStartEvent;\n\t/** Host-side autonomous continuation policy. */\n\tautonomous?: AgentAutonomousConfig;\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/** Diagnostic when the selected session or saved model cannot be used. */\n\tmodelFallbackMessage?: string;\n}\n\nexport type { AgentSessionRuntimeConfig } from \"./agent-session-config.js\";\nexport * from \"./agent-session-runtime.js\";\nexport type { AgentSessionCreationOptions } from \"./agent-session-services.js\";\nexport type {\n\tExtensionAPI,\n\tExtensionCommandContext,\n\tExtensionContext,\n\tExtensionFactory,\n\tSlashCommandInfo,\n\tSlashCommandSource,\n\tToolDefinition,\n} from \"./extensions/index.js\";\nexport type { PromptTemplate } from \"./prompt-templates.js\";\nexport type {\n\tRlmMaxSubagentsStatus,\n\tRlmRootAdmission,\n\tRlmSubagentCapacity,\n\tRlmSubagentCapacityReservation,\n} from \"./rlm-max-subagents.js\";\nexport type {\n\tCreateRlmSubagentRuntimeOptions,\n\tRlmChildAdmission,\n\tRlmSubagentRuntime,\n\tSubagentRuntimeHost,\n} from \"./rlm-runtime.js\";\nexport type { Skill } from \"./skills.js\";\nexport type { Tool } from \"./tools/index.js\";\n\nexport { createBashTool, createEditTool, createIpythonTool, createPrimeContextTool, withFileMutationQueue };\n\nfunction getDefaultAgentDir(): string {\n\treturn getAgentDir();\n}\n\n/**\n * Create an AgentSession with the specified options.\n *\n * @example\n * ```typescript\n * // Minimal - uses defaults\n * const { session } = await createAgentSession();\n *\n * // With explicit model\n * import { getModel } from '@ponythewhite/base-context-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: [\"ipython\"],\n * resourceLoader: loader,\n * sessionManager: SessionManager.inMemory(),\n * });\n * ```\n */\nexport async function createAgentSession(options: CreateAgentSessionOptions = {}): Promise<CreateAgentSessionResult> {\n\tconst contextMode = options.contextMode;\n\tif (options.requestTokenBudget)\n\t\toptions = { ...options, requestTokenBudget: structuredClone(options.requestTokenBudget) };\n\tconst cwd = options.cwd ?? options.sessionManager?.getCwd() ?? process.cwd();\n\tconst agentDir = options.agentDir ?? getDefaultAgentDir();\n\tlet resourceLoader = options.resourceLoader;\n\n\tconst authPath = options.agentDir ? join(agentDir, \"auth.json\") : undefined;\n\tconst modelsPath = options.agentDir ? join(agentDir, \"models.json\") : undefined;\n\tconst 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\tconst sessionManager =\n\t\toptions.sessionManager ?? (await SessionManager.create(cwd, getDefaultSessionDir(cwd, agentDir)));\n\n\tlet session: AgentSession | undefined;\n\ttry {\n\t\t// Ensure MCP providers are registered and built-in MCP skills are gated by\n\t\t// auth even on the bare SDK path (not just the CLI's createAgentSessionServices).\n\t\tconst mcpManager =\n\t\t\toptions.mcpManager ??\n\t\t\tnew McpManager({ authStorage, getUserServers: () => settingsManager.getGlobalMcpServers() });\n\t\tmodelRegistry.setOnOAuthProvidersReset(() => mcpManager.registerUserProviders());\n\n\t\tif (!resourceLoader) {\n\t\t\tresourceLoader = new DefaultResourceLoader({\n\t\t\t\tcwd,\n\t\t\t\tagentDir,\n\t\t\t\tsettingsManager,\n\t\t\t\textraBuiltinSkillOverrides: () => mcpManager.getDisabledBuiltinSkillOverrides(),\n\t\t\t});\n\t\t\tawait resourceLoader.reload();\n\t\t\ttime(\"resourceLoader.reload\");\n\t\t}\n\n\t\tconst {\n\t\t\tcontext: existingSession,\n\t\t\thasExistingSession,\n\t\t\thasThinkingEntry,\n\t\t\thasServiceTierEntry,\n\t\t} = await readSessionBootstrap(sessionManager, settingsManager.getCanonicalContextLimits(), {\n\t\t\tpurpose: \"read\",\n\t\t\tinitialContextMode: contextMode ?? settingsManager.getContextMode(),\n\t\t});\n\n\t\tlet model = options.model ?? undefined;\n\t\tlet modelFallbackMessage: string | undefined;\n\n\t\tif (options.model === undefined && hasExistingSession && existingSession.model) {\n\t\t\tconst saved = existingSession.model;\n\t\t\tconst restoredModel = modelRegistry.find(saved.provider, saved.modelId);\n\t\t\tmodel = restoredModel;\n\t\t\tif (!restoredModel) {\n\t\t\t\tmodelFallbackMessage = `Could not restore model ${saved.provider}/${saved.modelId}. Use /model to select a supported model.`;\n\t\t\t} else if (!modelRegistry.hasConfiguredAuth(restoredModel)) {\n\t\t\t\tmodelFallbackMessage = `Selected model ${saved.provider}/${saved.modelId} needs authentication. Use /login to configure this provider.`;\n\t\t\t}\n\t\t} else if (options.model === undefined) {\n\t\t\tconst result = await findInitialModel({\n\t\t\t\tscopedModels: [],\n\t\t\t\tisContinuing: hasExistingSession,\n\t\t\t\tdefaultProvider: settingsManager.getDefaultProvider(),\n\t\t\t\tdefaultModelId: settingsManager.getDefaultModel(),\n\t\t\t\tdefaultThinkingLevel: settingsManager.getDefaultThinkingLevel(),\n\t\t\t\tmodelRegistry,\n\t\t\t});\n\t\t\tmodel = result.model;\n\t\t\tif (model && !modelRegistry.hasConfiguredAuth(model)) {\n\t\t\t\tmodelFallbackMessage = `Selected model ${model.provider}/${model.id} needs authentication. Use /login to configure this provider.`;\n\t\t\t} else if (!model) {\n\t\t\t\tconst provider = settingsManager.getDefaultProvider();\n\t\t\t\tconst modelId = settingsManager.getDefaultModel();\n\t\t\t\tmodelFallbackMessage =\n\t\t\t\t\tprovider && modelId\n\t\t\t\t\t\t? `Selected model ${provider}/${modelId} is unavailable. Use /model to select a supported model.`\n\t\t\t\t\t\t: formatNoModelsAvailableMessage();\n\t\t\t}\n\t\t}\n\n\t\tlet thinkingLevel = options.thinkingLevel;\n\n\t\tif (thinkingLevel === undefined && hasExistingSession) {\n\t\t\tthinkingLevel = hasThinkingEntry\n\t\t\t\t? (existingSession.thinkingLevel as ThinkingLevel)\n\t\t\t\t: (settingsManager.getDefaultThinkingLevel() ?? DEFAULT_THINKING_LEVEL);\n\t\t}\n\n\t\tif (thinkingLevel === undefined) {\n\t\t\tthinkingLevel = settingsManager.getDefaultThinkingLevel() ?? DEFAULT_THINKING_LEVEL;\n\t\t}\n\n\t\tif (!model) {\n\t\t\tthinkingLevel = \"off\";\n\t\t} else {\n\t\t\tthinkingLevel = clampThinkingLevel(model, thinkingLevel) as ThinkingLevel;\n\t\t}\n\n\t\tconst serviceTierPreference =\n\t\t\toptions.serviceTier ??\n\t\t\t(hasServiceTierEntry ? existingSession.serviceTier : settingsManager.getDefaultServiceTier());\n\t\tconst serviceTier =\n\t\t\tserviceTierPreference === \"priority\" && (!model || !supportsFastMode(model))\n\t\t\t\t? \"default\"\n\t\t\t\t: serviceTierPreference;\n\n\t\tconst allowedToolNames =\n\t\t\toptions.allowedToolNames ?? options.tools ?? (options.noTools === \"all\" ? [] : undefined);\n\t\tconst includeGoals = options.includeGoals ?? (options.tools !== undefined || options.noTools !== \"all\");\n\t\tconst initialActiveToolNames: string[] =\n\t\t\toptions.initialActiveToolNames ??\n\t\t\t(options.tools ? [...options.tools] : options.noTools ? [] : [\"ipython\", \"prime_context\"]);\n\n\t\tlet agent: Agent;\n\n\t\tconst convertToLlmWithBlockImages = (messages: AgentMessage[]): Message[] => {\n\t\t\tconst converted = convertToLlm(messages);\n\t\t\tif (!settingsManager.getBlockImages()) {\n\t\t\t\treturn converted;\n\t\t\t}\n\t\t\treturn converted.map((msg) => {\n\t\t\t\tif (msg.role === \"user\" || msg.role === \"toolResult\") {\n\t\t\t\t\tconst content = msg.content;\n\t\t\t\t\tif (Array.isArray(content)) {\n\t\t\t\t\t\tconst hasImages = content.some((c) => c.type === \"image\");\n\t\t\t\t\t\tif (hasImages) {\n\t\t\t\t\t\t\tconst filteredContent = content\n\t\t\t\t\t\t\t\t.map((c) =>\n\t\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\t)\n\t\t\t\t\t\t\t\t.filter(\n\t\t\t\t\t\t\t\t\t(c, i, arr) =>\n\t\t\t\t\t\t\t\t\t\t!(\n\t\t\t\t\t\t\t\t\t\t\tc.type === \"text\" &&\n\t\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\t\ti > 0 &&\n\t\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\t(arr[i - 1] as { type: \"text\"; text: string }).text === \"Image reading is disabled.\"\n\t\t\t\t\t\t\t\t\t\t),\n\t\t\t\t\t\t\t\t);\n\t\t\t\t\t\t\treturn { ...msg, content: filteredContent };\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\treturn msg;\n\t\t\t});\n\t\t};\n\n\t\tconst extensionRunnerRef: { current?: ExtensionRunner } = {};\n\n\t\tagent = new Agent({\n\t\t\tinitialState: {\n\t\t\t\tsystemPrompt: \"\",\n\t\t\t\tmodel,\n\t\t\t\tthinkingLevel,\n\t\t\t\tserviceTier,\n\t\t\t\ttools: [],\n\t\t\t},\n\t\t\tconvertToLlm: convertToLlmWithBlockImages,\n\t\t\tstreamFn: createNativeInferenceStream(async (model, _context, options) => {\n\t\t\t\tif (!modelRegistry.hasConfiguredAuth(model)) {\n\t\t\t\t\tthrow new Error(\n\t\t\t\t\t\t`Selected model ${model.provider}/${model.id} needs authentication. Use /login to configure this provider.`,\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t\tconst auth = await modelRegistry.getApiKeyAndHeaders(model);\n\t\t\t\tif (!auth.ok) {\n\t\t\t\t\tthrow new Error(auth.error);\n\t\t\t\t}\n\t\t\t\tconst providerRetrySettings = settingsManager.getProviderRetrySettings();\n\t\t\t\treturn {\n\t\t\t\t\t...options,\n\t\t\t\t\tapiKey: auth.apiKey,\n\t\t\t\t\tauthSourceToken: auth.sourceToken,\n\t\t\t\t\ttimeoutMs: options?.timeoutMs ?? providerRetrySettings.timeoutMs,\n\t\t\t\t\tmaxRetries: options?.maxRetries ?? providerRetrySettings.maxRetries,\n\t\t\t\t\tmaxRetryDelayMs: options?.maxRetryDelayMs ?? providerRetrySettings.maxRetryDelayMs,\n\t\t\t\t\theaders: auth.headers || options?.headers ? { ...auth.headers, ...options?.headers } : undefined,\n\t\t\t\t};\n\t\t\t}),\n\t\t\tonPayload: async (payload, _model) => {\n\t\t\t\tconst runner = extensionRunnerRef.current;\n\t\t\t\tif (!runner?.hasHandlers(\"before_provider_request\")) {\n\t\t\t\t\treturn payload;\n\t\t\t\t}\n\t\t\t\treturn runner.emitBeforeProviderRequest(payload);\n\t\t\t},\n\t\t\tonResponse: async (response, _model) => {\n\t\t\t\tconst runner = extensionRunnerRef.current;\n\t\t\t\tif (!runner?.hasHandlers(\"after_provider_response\")) {\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tawait runner.emit({\n\t\t\t\t\ttype: \"after_provider_response\",\n\t\t\t\t\tstatus: response.status,\n\t\t\t\t\theaders: response.headers,\n\t\t\t\t});\n\t\t\t},\n\t\t\tsessionId: sessionManager.getSessionId(),\n\t\t\ttransformContext: async (messages) => {\n\t\t\t\tconst runner = extensionRunnerRef.current;\n\t\t\t\tif (!runner) return messages;\n\t\t\t\treturn runner.emitContext(messages);\n\t\t\t},\n\t\t\tsteeringMode: settingsManager.getSteeringMode(),\n\t\t\tfollowUpMode: settingsManager.getFollowUpMode(),\n\t\t\ttransport: settingsManager.getTransport(),\n\t\t\tthinkingBudgets: settingsManager.getThinkingBudgets(),\n\t\t\tmaxRetryDelayMs: settingsManager.getProviderRetrySettings().maxRetryDelayMs,\n\t\t});\n\n\t\tif (hasExistingSession) {\n\t\t\tagent.state.messages = existingSession.messages;\n\t\t\tif (!hasThinkingEntry) {\n\t\t\t\tawait sessionManager.appendThinkingLevelChange(thinkingLevel);\n\t\t\t}\n\t\t} else {\n\t\t\tif (model) {\n\t\t\t\tawait sessionManager.appendModelChange(model.provider, model.id);\n\t\t\t}\n\t\t\tawait sessionManager.appendThinkingLevelChange(thinkingLevel);\n\t\t}\n\t\tif (!hasServiceTierEntry) {\n\t\t\tawait sessionManager.appendServiceTierChange(serviceTierPreference);\n\t\t}\n\n\t\tsession = new AgentSession({\n\t\t\tinvocationOutputLimits: options.invocationOutputLimits,\n\t\t\trequestTokenBudget: options.requestTokenBudget,\n\t\t\tcontextMode,\n\t\t\tagent,\n\t\t\tsessionManager,\n\t\t\tsettingsManager,\n\t\t\tserviceTierPreference,\n\t\t\tcwd,\n\t\t\t// Only the explicit dir — the default may not match injected custom storage.\n\t\t\tagentDir: options.agentDir,\n\t\t\tscopedModels: options.scopedModels,\n\t\t\tresourceLoader,\n\t\t\tcustomTools: options.customTools,\n\t\t\tmodelRegistry,\n\t\t\tmcpManager,\n\t\t\tinitialActiveToolNames,\n\t\t\tallowedToolNames,\n\t\t\tincludeGoals,\n\t\t\tincludeCompactSkill: options.includeCompactSkill,\n\t\t\trlmHeartbeatController: options.rlmHeartbeatController,\n\t\t\tagentMessageController: options.agentMessageController,\n\t\t\tagentObserveController: options.agentObserveController,\n\t\t\textensionRunnerRef,\n\t\t\trlmDepth: options.rlmDepth,\n\t\t\trlmMaxDepth: options.rlmMaxDepth,\n\t\t\trlmSessionDir: options.rlmSessionDir,\n\t\t\trlmParentNodeId: options.rlmParentNodeId,\n\t\t\trlmParentAgent: options.rlmParentAgent,\n\t\t\trlmChildAdmission: options.rlmChildAdmission,\n\t\t\trlmSubagentCapacity: options.rlmSubagentCapacity,\n\t\t\trlmRootAdmission: options.rlmRootAdmission,\n\t\t\tsemanticParentSessionId: options.semanticParentSessionId,\n\t\t\tsemanticSpawnedByRequestId: options.semanticSpawnedByRequestId,\n\t\t\tsubagentRuntimeHost: options.subagentRuntimeHost,\n\t\t\tsessionStartEvent: options.sessionStartEvent,\n\t\t\tprewarmIpythonKernel: options.prewarmIpythonKernel,\n\t\t\tautonomous: options.autonomous,\n\t\t\tserializedRefine: options.serializedRefine,\n\t\t\tinitialGoal: options.initialGoal,\n\t\t});\n\t\tawait session.initialize();\n\t\tconst extensionsResult = resourceLoader.getExtensions();\n\n\t\treturn {\n\t\t\tsession,\n\t\t\textensionsResult,\n\t\t\tmodelFallbackMessage,\n\t\t};\n\t} catch (error) {\n\t\ttry {\n\t\t\tconst admitted = options.rlmChildAdmission?.session ?? options.rlmRootAdmission?.session;\n\t\t\tconst failedSession = session ?? (admitted?.sessionManager === sessionManager ? admitted : undefined);\n\t\t\tif (failedSession) await failedSession.disposeAsync();\n\t\t\telse {\n\t\t\t\tawait sessionManager.close();\n\t\t\t\tawait options.rlmChildAdmission?.confirmUnboundCleanup();\n\t\t\t}\n\t\t} catch (cleanupError) {\n\t\t\tif (cleanupError === error || (error instanceof AggregateError && error.errors.includes(cleanupError)))\n\t\t\t\tthrow error;\n\t\t\tthrow new AggregateError([error, cleanupError], \"Session creation and cleanup failed\");\n\t\t}\n\t\tthrow error;\n\t}\n}\n"]}
|
package/dist/core/sdk.js
CHANGED
|
@@ -88,7 +88,7 @@ export async function createAgentSession(options = {}) {
|
|
|
88
88
|
time("resourceLoader.reload");
|
|
89
89
|
}
|
|
90
90
|
const { context: existingSession, hasExistingSession, hasThinkingEntry, hasServiceTierEntry, } = await readSessionBootstrap(sessionManager, settingsManager.getCanonicalContextLimits(), {
|
|
91
|
-
|
|
91
|
+
purpose: "read",
|
|
92
92
|
initialContextMode: contextMode ?? settingsManager.getContextMode(),
|
|
93
93
|
});
|
|
94
94
|
let model = options.model ?? undefined;
|
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,IAAI,EAAE,MAAM,WAAW,CAAC;AACjC,OAAO,EAAE,KAAK,EAAiE,MAAM,kCAAkC,CAAC;AACxH,OAAO,EAAE,kBAAkB,EAA4B,gBAAgB,EAAE,MAAM,+BAA+B,CAAC;AAC/G,OAAO,EAAE,WAAW,EAAE,MAAM,cAAc,CAAC;AAC3C,OAAO,EAAE,YAAY,EAAE,MAAM,oBAAoB,CAAC;AAElD,OAAO,EAAE,8BAA8B,EAAE,MAAM,oBAAoB,CAAC;AACpE,OAAO,EAAE,WAAW,EAAE,MAAM,mBAAmB,CAAC;AAEhD,OAAO,EAAE,sBAAsB,EAAE,MAAM,eAAe,CAAC;AAEvD,OAAO,EAAE,2BAA2B,EAAE,MAAM,4BAA4B,CAAC;AACzE,OAAO,EAAE,UAAU,EAAE,M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,CAAC,KAAK,EAAE,YAAY,CAAC,EAAE,qCAAqC,CAAC,CAAC;QACxF,CAAC;QACD,MAAM,KAAK,CAAC;IACb,CAAC;AAAA,CACD","sourcesContent":["import { join } from \"node:path\";\nimport { Agent, type AgentMessage, type AgentOutputLimits, type ThinkingLevel } from \"@ponythewhite/base-context-agent\";\nimport { clampThinkingLevel, type Message, type Model, supportsFastMode } from \"@ponythewhite/base-context-ai\";\nimport { getAgentDir } from \"../config.js\";\nimport { AgentSession } from \"./agent-session.js\";\nimport type { AgentSessionCreationOptions } from \"./agent-session-services.js\";\nimport { formatNoModelsAvailableMessage } from \"./auth-guidance.js\";\nimport { AuthStorage } from \"./auth-storage.js\";\nimport type { AgentAutonomousConfig } from \"./autonomous.js\";\nimport { DEFAULT_THINKING_LEVEL } from \"./defaults.js\";\nimport type { ExtensionRunner, LoadExtensionsResult, SessionStartEvent, ToolDefinition } from \"./extensions/index.js\";\nimport { createNativeInferenceStream } from \"./inference-coordinator.js\";\nimport { McpManager } from \"./mcp/mcp-manager.js\";\nimport { convertToLlm } from \"./messages.js\";\nimport { ModelRegistry } from \"./model-registry.js\";\nimport { findInitialModel } from \"./model-resolver.js\";\nimport type { ResourceLoader } from \"./resource-loader.js\";\nimport { DefaultResourceLoader } from \"./resource-loader.js\";\nimport { readSessionBootstrap } from \"./session-bootstrap.js\";\nimport { getDefaultSessionDir, SessionManager } from \"./session-manager.js\";\nimport { SettingsManager } from \"./settings-manager.js\";\nimport { time } from \"./timings.js\";\nimport {\n\tcreateBashTool,\n\tcreateEditTool,\n\tcreateIpythonTool,\n\tcreatePrimeContextTool,\n\twithFileMutationQueue,\n} from \"./tools/index.js\";\n\nexport interface CreateAgentSessionOptions extends AgentSessionCreationOptions {\n\t/** Working directory for project-local discovery. Default: process.cwd() */\n\tcwd?: string;\n\t/** Global config directory. Default: ~/.base-context */\n\tagentDir?: string;\n\n\t/** Auth storage for credentials. Default: AuthStorage.create(agentDir/auth.json).\n\t * Existing host Codex subscriptions can be injected with\n\t * AuthStorage.fromStorage(readOnlyBackend, { existingOpenAICodexSubscription: true }).\n\t * This retains the built-in owned dispatcher; it does not enable OAuth login/refresh.\n\t */\n\tauthStorage?: AuthStorage;\n\t/** Model registry. Default: ModelRegistry.create(authStorage, agentDir/models.json) */\n\tmodelRegistry?: ModelRegistry;\n\n\t/** Model to use. Undefined restores a saved explicit choice; null leaves the session unselected. */\n\tmodel?: Model<any> | null;\n\t/** Thinking level. Default: from settings, else 'medium' (clamped to model capabilities) */\n\tthinkingLevel?: ThinkingLevel;\n\t/** Models available for cycling (Ctrl+P in interactive mode) */\n\tscopedModels?: Array<{ model: Model<any>; thinkingLevel?: ThinkingLevel }>;\n\n\t/**\n\t * Optional default tool suppression mode when no explicit allowlist is provided.\n\t *\n\t * - \"all\": start with no tools enabled\n\t * - \"builtin\": disable the default built-in tools (ipython and prime_context)\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, Base Context enables the default built-in tools (ipython and prime_context)\n\t * and leaves extension/custom tools enabled unless `noTools` changes that default.\n\t * When provided, only the listed tool names are enabled.\n\t */\n\ttools?: string[];\n\t/** 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/** MCP integration manager. When omitted, MCP host handlers are not wired. */\n\tmcpManager?: McpManager;\n\n\t/** Session manager. Default: SessionManager.create(cwd) */\n\tsessionManager?: SessionManager;\n\n\t/** Override complete native invocation output limits from settings. */\n\tinvocationOutputLimits?: AgentOutputLimits;\n\t/** Settings manager. Default: SettingsManager.create(cwd, agentDir) */\n\tsettingsManager?: SettingsManager;\n\t/** Session start event metadata for extension runtime startup. */\n\tsessionStartEvent?: SessionStartEvent;\n\t/** Host-side autonomous continuation policy. */\n\tautonomous?: AgentAutonomousConfig;\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/** Diagnostic when the selected session or saved model cannot be used. */\n\tmodelFallbackMessage?: string;\n}\n\nexport type { AgentSessionRuntimeConfig } from \"./agent-session-config.js\";\nexport * from \"./agent-session-runtime.js\";\nexport type { AgentSessionCreationOptions } from \"./agent-session-services.js\";\nexport type {\n\tExtensionAPI,\n\tExtensionCommandContext,\n\tExtensionContext,\n\tExtensionFactory,\n\tSlashCommandInfo,\n\tSlashCommandSource,\n\tToolDefinition,\n} from \"./extensions/index.js\";\nexport type { PromptTemplate } from \"./prompt-templates.js\";\nexport type {\n\tRlmMaxSubagentsStatus,\n\tRlmRootAdmission,\n\tRlmSubagentCapacity,\n\tRlmSubagentCapacityReservation,\n} from \"./rlm-max-subagents.js\";\nexport type {\n\tCreateRlmSubagentRuntimeOptions,\n\tRlmChildAdmission,\n\tRlmSubagentRuntime,\n\tSubagentRuntimeHost,\n} from \"./rlm-runtime.js\";\nexport type { Skill } from \"./skills.js\";\nexport type { Tool } from \"./tools/index.js\";\n\nexport { createBashTool, createEditTool, createIpythonTool, createPrimeContextTool, withFileMutationQueue };\n\nfunction getDefaultAgentDir(): string {\n\treturn getAgentDir();\n}\n\n/**\n * Create an AgentSession with the specified options.\n *\n * @example\n * ```typescript\n * // Minimal - uses defaults\n * const { session } = await createAgentSession();\n *\n * // With explicit model\n * import { getModel } from '@ponythewhite/base-context-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: [\"ipython\"],\n * resourceLoader: loader,\n * sessionManager: SessionManager.inMemory(),\n * });\n * ```\n */\nexport async function createAgentSession(options: CreateAgentSessionOptions = {}): Promise<CreateAgentSessionResult> {\n\tconst contextMode = options.contextMode;\n\tif (options.requestTokenBudget)\n\t\toptions = { ...options, requestTokenBudget: structuredClone(options.requestTokenBudget) };\n\tconst cwd = options.cwd ?? options.sessionManager?.getCwd() ?? process.cwd();\n\tconst agentDir = options.agentDir ?? getDefaultAgentDir();\n\tlet resourceLoader = options.resourceLoader;\n\n\tconst authPath = options.agentDir ? join(agentDir, \"auth.json\") : undefined;\n\tconst modelsPath = options.agentDir ? join(agentDir, \"models.json\") : undefined;\n\tconst 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\tconst sessionManager =\n\t\toptions.sessionManager ?? (await SessionManager.create(cwd, getDefaultSessionDir(cwd, agentDir)));\n\n\tlet session: AgentSession | undefined;\n\ttry {\n\t\t// Ensure MCP providers are registered and built-in MCP skills are gated by\n\t\t// auth even on the bare SDK path (not just the CLI's createAgentSessionServices).\n\t\tconst mcpManager =\n\t\t\toptions.mcpManager ??\n\t\t\tnew McpManager({ authStorage, getUserServers: () => settingsManager.getGlobalMcpServers() });\n\t\tmodelRegistry.setOnOAuthProvidersReset(() => mcpManager.registerUserProviders());\n\n\t\tif (!resourceLoader) {\n\t\t\tresourceLoader = new DefaultResourceLoader({\n\t\t\t\tcwd,\n\t\t\t\tagentDir,\n\t\t\t\tsettingsManager,\n\t\t\t\textraBuiltinSkillOverrides: () => mcpManager.getDisabledBuiltinSkillOverrides(),\n\t\t\t});\n\t\t\tawait resourceLoader.reload();\n\t\t\ttime(\"resourceLoader.reload\");\n\t\t}\n\n\t\tconst {\n\t\t\tcontext: existingSession,\n\t\t\thasExistingSession,\n\t\t\thasThinkingEntry,\n\t\t\thasServiceTierEntry,\n\t\t} = await readSessionBootstrap(sessionManager, settingsManager.getCanonicalContextLimits(), {\n\t\t\tallowPendingToolPublic: options.requestTokenBudget !== undefined,\n\t\t\tinitialContextMode: contextMode ?? settingsManager.getContextMode(),\n\t\t});\n\n\t\tlet model = options.model ?? undefined;\n\t\tlet modelFallbackMessage: string | undefined;\n\n\t\tif (options.model === undefined && hasExistingSession && existingSession.model) {\n\t\t\tconst saved = existingSession.model;\n\t\t\tconst restoredModel = modelRegistry.find(saved.provider, saved.modelId);\n\t\t\tmodel = restoredModel;\n\t\t\tif (!restoredModel) {\n\t\t\t\tmodelFallbackMessage = `Could not restore model ${saved.provider}/${saved.modelId}. Use /model to select a supported model.`;\n\t\t\t} else if (!modelRegistry.hasConfiguredAuth(restoredModel)) {\n\t\t\t\tmodelFallbackMessage = `Selected model ${saved.provider}/${saved.modelId} needs authentication. Use /login to configure this provider.`;\n\t\t\t}\n\t\t} else if (options.model === undefined) {\n\t\t\tconst result = await findInitialModel({\n\t\t\t\tscopedModels: [],\n\t\t\t\tisContinuing: hasExistingSession,\n\t\t\t\tdefaultProvider: settingsManager.getDefaultProvider(),\n\t\t\t\tdefaultModelId: settingsManager.getDefaultModel(),\n\t\t\t\tdefaultThinkingLevel: settingsManager.getDefaultThinkingLevel(),\n\t\t\t\tmodelRegistry,\n\t\t\t});\n\t\t\tmodel = result.model;\n\t\t\tif (model && !modelRegistry.hasConfiguredAuth(model)) {\n\t\t\t\tmodelFallbackMessage = `Selected model ${model.provider}/${model.id} needs authentication. Use /login to configure this provider.`;\n\t\t\t} else if (!model) {\n\t\t\t\tconst provider = settingsManager.getDefaultProvider();\n\t\t\t\tconst modelId = settingsManager.getDefaultModel();\n\t\t\t\tmodelFallbackMessage =\n\t\t\t\t\tprovider && modelId\n\t\t\t\t\t\t? `Selected model ${provider}/${modelId} is unavailable. Use /model to select a supported model.`\n\t\t\t\t\t\t: formatNoModelsAvailableMessage();\n\t\t\t}\n\t\t}\n\n\t\tlet thinkingLevel = options.thinkingLevel;\n\n\t\tif (thinkingLevel === undefined && hasExistingSession) {\n\t\t\tthinkingLevel = hasThinkingEntry\n\t\t\t\t? (existingSession.thinkingLevel as ThinkingLevel)\n\t\t\t\t: (settingsManager.getDefaultThinkingLevel() ?? DEFAULT_THINKING_LEVEL);\n\t\t}\n\n\t\tif (thinkingLevel === undefined) {\n\t\t\tthinkingLevel = settingsManager.getDefaultThinkingLevel() ?? DEFAULT_THINKING_LEVEL;\n\t\t}\n\n\t\tif (!model) {\n\t\t\tthinkingLevel = \"off\";\n\t\t} else {\n\t\t\tthinkingLevel = clampThinkingLevel(model, thinkingLevel) as ThinkingLevel;\n\t\t}\n\n\t\tconst serviceTierPreference =\n\t\t\toptions.serviceTier ??\n\t\t\t(hasServiceTierEntry ? existingSession.serviceTier : settingsManager.getDefaultServiceTier());\n\t\tconst serviceTier =\n\t\t\tserviceTierPreference === \"priority\" && (!model || !supportsFastMode(model))\n\t\t\t\t? \"default\"\n\t\t\t\t: serviceTierPreference;\n\n\t\tconst allowedToolNames =\n\t\t\toptions.allowedToolNames ?? options.tools ?? (options.noTools === \"all\" ? [] : undefined);\n\t\tconst includeGoals = options.includeGoals ?? (options.tools !== undefined || options.noTools !== \"all\");\n\t\tconst initialActiveToolNames: string[] =\n\t\t\toptions.initialActiveToolNames ??\n\t\t\t(options.tools ? [...options.tools] : options.noTools ? [] : [\"ipython\", \"prime_context\"]);\n\n\t\tlet agent: Agent;\n\n\t\tconst convertToLlmWithBlockImages = (messages: AgentMessage[]): Message[] => {\n\t\t\tconst converted = convertToLlm(messages);\n\t\t\tif (!settingsManager.getBlockImages()) {\n\t\t\t\treturn converted;\n\t\t\t}\n\t\t\treturn converted.map((msg) => {\n\t\t\t\tif (msg.role === \"user\" || msg.role === \"toolResult\") {\n\t\t\t\t\tconst content = msg.content;\n\t\t\t\t\tif (Array.isArray(content)) {\n\t\t\t\t\t\tconst hasImages = content.some((c) => c.type === \"image\");\n\t\t\t\t\t\tif (hasImages) {\n\t\t\t\t\t\t\tconst filteredContent = content\n\t\t\t\t\t\t\t\t.map((c) =>\n\t\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\t)\n\t\t\t\t\t\t\t\t.filter(\n\t\t\t\t\t\t\t\t\t(c, i, arr) =>\n\t\t\t\t\t\t\t\t\t\t!(\n\t\t\t\t\t\t\t\t\t\t\tc.type === \"text\" &&\n\t\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\t\ti > 0 &&\n\t\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\t(arr[i - 1] as { type: \"text\"; text: string }).text === \"Image reading is disabled.\"\n\t\t\t\t\t\t\t\t\t\t),\n\t\t\t\t\t\t\t\t);\n\t\t\t\t\t\t\treturn { ...msg, content: filteredContent };\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\treturn msg;\n\t\t\t});\n\t\t};\n\n\t\tconst extensionRunnerRef: { current?: ExtensionRunner } = {};\n\n\t\tagent = new Agent({\n\t\t\tinitialState: {\n\t\t\t\tsystemPrompt: \"\",\n\t\t\t\tmodel,\n\t\t\t\tthinkingLevel,\n\t\t\t\tserviceTier,\n\t\t\t\ttools: [],\n\t\t\t},\n\t\t\tconvertToLlm: convertToLlmWithBlockImages,\n\t\t\tstreamFn: createNativeInferenceStream(async (model, _context, options) => {\n\t\t\t\tif (!modelRegistry.hasConfiguredAuth(model)) {\n\t\t\t\t\tthrow new Error(\n\t\t\t\t\t\t`Selected model ${model.provider}/${model.id} needs authentication. Use /login to configure this provider.`,\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t\tconst auth = await modelRegistry.getApiKeyAndHeaders(model);\n\t\t\t\tif (!auth.ok) {\n\t\t\t\t\tthrow new Error(auth.error);\n\t\t\t\t}\n\t\t\t\tconst providerRetrySettings = settingsManager.getProviderRetrySettings();\n\t\t\t\treturn {\n\t\t\t\t\t...options,\n\t\t\t\t\tapiKey: auth.apiKey,\n\t\t\t\t\tauthSourceToken: auth.sourceToken,\n\t\t\t\t\ttimeoutMs: options?.timeoutMs ?? providerRetrySettings.timeoutMs,\n\t\t\t\t\tmaxRetries: options?.maxRetries ?? providerRetrySettings.maxRetries,\n\t\t\t\t\tmaxRetryDelayMs: options?.maxRetryDelayMs ?? providerRetrySettings.maxRetryDelayMs,\n\t\t\t\t\theaders: auth.headers || options?.headers ? { ...auth.headers, ...options?.headers } : undefined,\n\t\t\t\t};\n\t\t\t}),\n\t\t\tonPayload: async (payload, _model) => {\n\t\t\t\tconst runner = extensionRunnerRef.current;\n\t\t\t\tif (!runner?.hasHandlers(\"before_provider_request\")) {\n\t\t\t\t\treturn payload;\n\t\t\t\t}\n\t\t\t\treturn runner.emitBeforeProviderRequest(payload);\n\t\t\t},\n\t\t\tonResponse: async (response, _model) => {\n\t\t\t\tconst runner = extensionRunnerRef.current;\n\t\t\t\tif (!runner?.hasHandlers(\"after_provider_response\")) {\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tawait runner.emit({\n\t\t\t\t\ttype: \"after_provider_response\",\n\t\t\t\t\tstatus: response.status,\n\t\t\t\t\theaders: response.headers,\n\t\t\t\t});\n\t\t\t},\n\t\t\tsessionId: sessionManager.getSessionId(),\n\t\t\ttransformContext: async (messages) => {\n\t\t\t\tconst runner = extensionRunnerRef.current;\n\t\t\t\tif (!runner) return messages;\n\t\t\t\treturn runner.emitContext(messages);\n\t\t\t},\n\t\t\tsteeringMode: settingsManager.getSteeringMode(),\n\t\t\tfollowUpMode: settingsManager.getFollowUpMode(),\n\t\t\ttransport: settingsManager.getTransport(),\n\t\t\tthinkingBudgets: settingsManager.getThinkingBudgets(),\n\t\t\tmaxRetryDelayMs: settingsManager.getProviderRetrySettings().maxRetryDelayMs,\n\t\t});\n\n\t\tif (hasExistingSession) {\n\t\t\tagent.state.messages = existingSession.messages;\n\t\t\tif (!hasThinkingEntry) {\n\t\t\t\tawait sessionManager.appendThinkingLevelChange(thinkingLevel);\n\t\t\t}\n\t\t} else {\n\t\t\tif (model) {\n\t\t\t\tawait sessionManager.appendModelChange(model.provider, model.id);\n\t\t\t}\n\t\t\tawait sessionManager.appendThinkingLevelChange(thinkingLevel);\n\t\t}\n\t\tif (!hasServiceTierEntry) {\n\t\t\tawait sessionManager.appendServiceTierChange(serviceTierPreference);\n\t\t}\n\n\t\tsession = new AgentSession({\n\t\t\tinvocationOutputLimits: options.invocationOutputLimits,\n\t\t\trequestTokenBudget: options.requestTokenBudget,\n\t\t\tcontextMode,\n\t\t\tagent,\n\t\t\tsessionManager,\n\t\t\tsettingsManager,\n\t\t\tserviceTierPreference,\n\t\t\tcwd,\n\t\t\t// Only the explicit dir — the default may not match injected custom storage.\n\t\t\tagentDir: options.agentDir,\n\t\t\tscopedModels: options.scopedModels,\n\t\t\tresourceLoader,\n\t\t\tcustomTools: options.customTools,\n\t\t\tmodelRegistry,\n\t\t\tmcpManager,\n\t\t\tinitialActiveToolNames,\n\t\t\tallowedToolNames,\n\t\t\tincludeGoals,\n\t\t\tincludeCompactSkill: options.includeCompactSkill,\n\t\t\trlmHeartbeatController: options.rlmHeartbeatController,\n\t\t\tagentMessageController: options.agentMessageController,\n\t\t\tagentObserveController: options.agentObserveController,\n\t\t\textensionRunnerRef,\n\t\t\trlmDepth: options.rlmDepth,\n\t\t\trlmMaxDepth: options.rlmMaxDepth,\n\t\t\trlmSessionDir: options.rlmSessionDir,\n\t\t\trlmParentNodeId: options.rlmParentNodeId,\n\t\t\trlmParentAgent: options.rlmParentAgent,\n\t\t\trlmChildAdmission: options.rlmChildAdmission,\n\t\t\trlmSubagentCapacity: options.rlmSubagentCapacity,\n\t\t\trlmRootAdmission: options.rlmRootAdmission,\n\t\t\tsemanticParentSessionId: options.semanticParentSessionId,\n\t\t\tsemanticSpawnedByRequestId: options.semanticSpawnedByRequestId,\n\t\t\tsubagentRuntimeHost: options.subagentRuntimeHost,\n\t\t\tsessionStartEvent: options.sessionStartEvent,\n\t\t\tprewarmIpythonKernel: options.prewarmIpythonKernel,\n\t\t\tautonomous: options.autonomous,\n\t\t\tserializedRefine: options.serializedRefine,\n\t\t\tinitialGoal: options.initialGoal,\n\t\t});\n\t\tawait session.initialize();\n\t\tconst extensionsResult = resourceLoader.getExtensions();\n\n\t\treturn {\n\t\t\tsession,\n\t\t\textensionsResult,\n\t\t\tmodelFallbackMessage,\n\t\t};\n\t} catch (error) {\n\t\ttry {\n\t\t\tconst admitted = options.rlmChildAdmission?.session ?? options.rlmRootAdmission?.session;\n\t\t\tconst failedSession = session ?? (admitted?.sessionManager === sessionManager ? admitted : undefined);\n\t\t\tif (failedSession) await failedSession.disposeAsync();\n\t\t\telse {\n\t\t\t\tawait sessionManager.close();\n\t\t\t\tawait options.rlmChildAdmission?.confirmUnboundCleanup();\n\t\t\t}\n\t\t} catch (cleanupError) {\n\t\t\tif (cleanupError === error || (error instanceof AggregateError && error.errors.includes(cleanupError)))\n\t\t\t\tthrow error;\n\t\t\tthrow new AggregateError([error, cleanupError], \"Session creation and cleanup failed\");\n\t\t}\n\t\tthrow error;\n\t}\n}\n"]}
|
|
1
|
+
{"version":3,"file":"sdk.js","sourceRoot":"","sources":["../../src/core/sdk.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,IAAI,EAAE,MAAM,WAAW,CAAC;AACjC,OAAO,EAAE,KAAK,EAAiE,MAAM,kCAAkC,CAAC;AACxH,OAAO,EAAE,kBAAkB,EAA4B,gBAAgB,EAAE,MAAM,+BAA+B,CAAC;AAC/G,OAAO,EAAE,WAAW,EAAE,MAAM,cAAc,CAAC;AAC3C,OAAO,EAAE,YAAY,EAAE,MAAM,oBAAoB,CAAC;AAElD,OAAO,EAAE,8BAA8B,EAAE,MAAM,oBAAoB,CAAC;AACpE,OAAO,EAAE,WAAW,EAAE,MAAM,mBAAmB,CAA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,KAAK,CAAC,MAAM,CAAC,QAAQ,CAAC,YAAY,CAAC,CAAC;gBACrG,MAAM,KAAK,CAAC;YACb,MAAM,IAAI,cAAc,CAAC,CAAC,KAAK,EAAE,YAAY,CAAC,EAAE,qCAAqC,CAAC,CAAC;QACxF,CAAC;QACD,MAAM,KAAK,CAAC;IACb,CAAC;AAAA,CACD","sourcesContent":["import { join } from \"node:path\";\nimport { Agent, type AgentMessage, type AgentOutputLimits, type ThinkingLevel } from \"@ponythewhite/base-context-agent\";\nimport { clampThinkingLevel, type Message, type Model, supportsFastMode } from \"@ponythewhite/base-context-ai\";\nimport { getAgentDir } from \"../config.js\";\nimport { AgentSession } from \"./agent-session.js\";\nimport type { AgentSessionCreationOptions } from \"./agent-session-services.js\";\nimport { formatNoModelsAvailableMessage } from \"./auth-guidance.js\";\nimport { AuthStorage } from \"./auth-storage.js\";\nimport type { AgentAutonomousConfig } from \"./autonomous.js\";\nimport { DEFAULT_THINKING_LEVEL } from \"./defaults.js\";\nimport type { ExtensionRunner, LoadExtensionsResult, SessionStartEvent, ToolDefinition } from \"./extensions/index.js\";\nimport { createNativeInferenceStream } from \"./inference-coordinator.js\";\nimport { McpManager } from \"./mcp/mcp-manager.js\";\nimport { convertToLlm } from \"./messages.js\";\nimport { ModelRegistry } from \"./model-registry.js\";\nimport { findInitialModel } from \"./model-resolver.js\";\nimport type { ResourceLoader } from \"./resource-loader.js\";\nimport { DefaultResourceLoader } from \"./resource-loader.js\";\nimport { readSessionBootstrap } from \"./session-bootstrap.js\";\nimport { getDefaultSessionDir, SessionManager } from \"./session-manager.js\";\nimport { SettingsManager } from \"./settings-manager.js\";\nimport { time } from \"./timings.js\";\nimport {\n\tcreateBashTool,\n\tcreateEditTool,\n\tcreateIpythonTool,\n\tcreatePrimeContextTool,\n\twithFileMutationQueue,\n} from \"./tools/index.js\";\n\nexport interface CreateAgentSessionOptions extends AgentSessionCreationOptions {\n\t/** Working directory for project-local discovery. Default: process.cwd() */\n\tcwd?: string;\n\t/** Global config directory. Default: ~/.base-context */\n\tagentDir?: string;\n\n\t/** Auth storage for credentials. Default: AuthStorage.create(agentDir/auth.json).\n\t * Existing host Codex subscriptions can be injected with\n\t * AuthStorage.fromStorage(readOnlyBackend, { existingOpenAICodexSubscription: true }).\n\t * This retains the built-in owned dispatcher; it does not enable OAuth login/refresh.\n\t */\n\tauthStorage?: AuthStorage;\n\t/** Model registry. Default: ModelRegistry.create(authStorage, agentDir/models.json) */\n\tmodelRegistry?: ModelRegistry;\n\n\t/** Model to use. Undefined restores a saved explicit choice; null leaves the session unselected. */\n\tmodel?: Model<any> | null;\n\t/** Thinking level. Default: from settings, else 'medium' (clamped to model capabilities) */\n\tthinkingLevel?: ThinkingLevel;\n\t/** Models available for cycling (Ctrl+P in interactive mode) */\n\tscopedModels?: Array<{ model: Model<any>; thinkingLevel?: ThinkingLevel }>;\n\n\t/**\n\t * Optional default tool suppression mode when no explicit allowlist is provided.\n\t *\n\t * - \"all\": start with no tools enabled\n\t * - \"builtin\": disable the default built-in tools (ipython and prime_context)\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, Base Context enables the default built-in tools (ipython and prime_context)\n\t * and leaves extension/custom tools enabled unless `noTools` changes that default.\n\t * When provided, only the listed tool names are enabled.\n\t */\n\ttools?: string[];\n\t/** 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/** MCP integration manager. When omitted, MCP host handlers are not wired. */\n\tmcpManager?: McpManager;\n\n\t/** Session manager. Default: SessionManager.create(cwd) */\n\tsessionManager?: SessionManager;\n\n\t/** Override complete native invocation output limits from settings. */\n\tinvocationOutputLimits?: AgentOutputLimits;\n\t/** Settings manager. Default: SettingsManager.create(cwd, agentDir) */\n\tsettingsManager?: SettingsManager;\n\t/** Session start event metadata for extension runtime startup. */\n\tsessionStartEvent?: SessionStartEvent;\n\t/** Host-side autonomous continuation policy. */\n\tautonomous?: AgentAutonomousConfig;\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/** Diagnostic when the selected session or saved model cannot be used. */\n\tmodelFallbackMessage?: string;\n}\n\nexport type { AgentSessionRuntimeConfig } from \"./agent-session-config.js\";\nexport * from \"./agent-session-runtime.js\";\nexport type { AgentSessionCreationOptions } from \"./agent-session-services.js\";\nexport type {\n\tExtensionAPI,\n\tExtensionCommandContext,\n\tExtensionContext,\n\tExtensionFactory,\n\tSlashCommandInfo,\n\tSlashCommandSource,\n\tToolDefinition,\n} from \"./extensions/index.js\";\nexport type { PromptTemplate } from \"./prompt-templates.js\";\nexport type {\n\tRlmMaxSubagentsStatus,\n\tRlmRootAdmission,\n\tRlmSubagentCapacity,\n\tRlmSubagentCapacityReservation,\n} from \"./rlm-max-subagents.js\";\nexport type {\n\tCreateRlmSubagentRuntimeOptions,\n\tRlmChildAdmission,\n\tRlmSubagentRuntime,\n\tSubagentRuntimeHost,\n} from \"./rlm-runtime.js\";\nexport type { Skill } from \"./skills.js\";\nexport type { Tool } from \"./tools/index.js\";\n\nexport { createBashTool, createEditTool, createIpythonTool, createPrimeContextTool, withFileMutationQueue };\n\nfunction getDefaultAgentDir(): string {\n\treturn getAgentDir();\n}\n\n/**\n * Create an AgentSession with the specified options.\n *\n * @example\n * ```typescript\n * // Minimal - uses defaults\n * const { session } = await createAgentSession();\n *\n * // With explicit model\n * import { getModel } from '@ponythewhite/base-context-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: [\"ipython\"],\n * resourceLoader: loader,\n * sessionManager: SessionManager.inMemory(),\n * });\n * ```\n */\nexport async function createAgentSession(options: CreateAgentSessionOptions = {}): Promise<CreateAgentSessionResult> {\n\tconst contextMode = options.contextMode;\n\tif (options.requestTokenBudget)\n\t\toptions = { ...options, requestTokenBudget: structuredClone(options.requestTokenBudget) };\n\tconst cwd = options.cwd ?? options.sessionManager?.getCwd() ?? process.cwd();\n\tconst agentDir = options.agentDir ?? getDefaultAgentDir();\n\tlet resourceLoader = options.resourceLoader;\n\n\tconst authPath = options.agentDir ? join(agentDir, \"auth.json\") : undefined;\n\tconst modelsPath = options.agentDir ? join(agentDir, \"models.json\") : undefined;\n\tconst 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\tconst sessionManager =\n\t\toptions.sessionManager ?? (await SessionManager.create(cwd, getDefaultSessionDir(cwd, agentDir)));\n\n\tlet session: AgentSession | undefined;\n\ttry {\n\t\t// Ensure MCP providers are registered and built-in MCP skills are gated by\n\t\t// auth even on the bare SDK path (not just the CLI's createAgentSessionServices).\n\t\tconst mcpManager =\n\t\t\toptions.mcpManager ??\n\t\t\tnew McpManager({ authStorage, getUserServers: () => settingsManager.getGlobalMcpServers() });\n\t\tmodelRegistry.setOnOAuthProvidersReset(() => mcpManager.registerUserProviders());\n\n\t\tif (!resourceLoader) {\n\t\t\tresourceLoader = new DefaultResourceLoader({\n\t\t\t\tcwd,\n\t\t\t\tagentDir,\n\t\t\t\tsettingsManager,\n\t\t\t\textraBuiltinSkillOverrides: () => mcpManager.getDisabledBuiltinSkillOverrides(),\n\t\t\t});\n\t\t\tawait resourceLoader.reload();\n\t\t\ttime(\"resourceLoader.reload\");\n\t\t}\n\n\t\tconst {\n\t\t\tcontext: existingSession,\n\t\t\thasExistingSession,\n\t\t\thasThinkingEntry,\n\t\t\thasServiceTierEntry,\n\t\t} = await readSessionBootstrap(sessionManager, settingsManager.getCanonicalContextLimits(), {\n\t\t\tpurpose: \"read\",\n\t\t\tinitialContextMode: contextMode ?? settingsManager.getContextMode(),\n\t\t});\n\n\t\tlet model = options.model ?? undefined;\n\t\tlet modelFallbackMessage: string | undefined;\n\n\t\tif (options.model === undefined && hasExistingSession && existingSession.model) {\n\t\t\tconst saved = existingSession.model;\n\t\t\tconst restoredModel = modelRegistry.find(saved.provider, saved.modelId);\n\t\t\tmodel = restoredModel;\n\t\t\tif (!restoredModel) {\n\t\t\t\tmodelFallbackMessage = `Could not restore model ${saved.provider}/${saved.modelId}. Use /model to select a supported model.`;\n\t\t\t} else if (!modelRegistry.hasConfiguredAuth(restoredModel)) {\n\t\t\t\tmodelFallbackMessage = `Selected model ${saved.provider}/${saved.modelId} needs authentication. Use /login to configure this provider.`;\n\t\t\t}\n\t\t} else if (options.model === undefined) {\n\t\t\tconst result = await findInitialModel({\n\t\t\t\tscopedModels: [],\n\t\t\t\tisContinuing: hasExistingSession,\n\t\t\t\tdefaultProvider: settingsManager.getDefaultProvider(),\n\t\t\t\tdefaultModelId: settingsManager.getDefaultModel(),\n\t\t\t\tdefaultThinkingLevel: settingsManager.getDefaultThinkingLevel(),\n\t\t\t\tmodelRegistry,\n\t\t\t});\n\t\t\tmodel = result.model;\n\t\t\tif (model && !modelRegistry.hasConfiguredAuth(model)) {\n\t\t\t\tmodelFallbackMessage = `Selected model ${model.provider}/${model.id} needs authentication. Use /login to configure this provider.`;\n\t\t\t} else if (!model) {\n\t\t\t\tconst provider = settingsManager.getDefaultProvider();\n\t\t\t\tconst modelId = settingsManager.getDefaultModel();\n\t\t\t\tmodelFallbackMessage =\n\t\t\t\t\tprovider && modelId\n\t\t\t\t\t\t? `Selected model ${provider}/${modelId} is unavailable. Use /model to select a supported model.`\n\t\t\t\t\t\t: formatNoModelsAvailableMessage();\n\t\t\t}\n\t\t}\n\n\t\tlet thinkingLevel = options.thinkingLevel;\n\n\t\tif (thinkingLevel === undefined && hasExistingSession) {\n\t\t\tthinkingLevel = hasThinkingEntry\n\t\t\t\t? (existingSession.thinkingLevel as ThinkingLevel)\n\t\t\t\t: (settingsManager.getDefaultThinkingLevel() ?? DEFAULT_THINKING_LEVEL);\n\t\t}\n\n\t\tif (thinkingLevel === undefined) {\n\t\t\tthinkingLevel = settingsManager.getDefaultThinkingLevel() ?? DEFAULT_THINKING_LEVEL;\n\t\t}\n\n\t\tif (!model) {\n\t\t\tthinkingLevel = \"off\";\n\t\t} else {\n\t\t\tthinkingLevel = clampThinkingLevel(model, thinkingLevel) as ThinkingLevel;\n\t\t}\n\n\t\tconst serviceTierPreference =\n\t\t\toptions.serviceTier ??\n\t\t\t(hasServiceTierEntry ? existingSession.serviceTier : settingsManager.getDefaultServiceTier());\n\t\tconst serviceTier =\n\t\t\tserviceTierPreference === \"priority\" && (!model || !supportsFastMode(model))\n\t\t\t\t? \"default\"\n\t\t\t\t: serviceTierPreference;\n\n\t\tconst allowedToolNames =\n\t\t\toptions.allowedToolNames ?? options.tools ?? (options.noTools === \"all\" ? [] : undefined);\n\t\tconst includeGoals = options.includeGoals ?? (options.tools !== undefined || options.noTools !== \"all\");\n\t\tconst initialActiveToolNames: string[] =\n\t\t\toptions.initialActiveToolNames ??\n\t\t\t(options.tools ? [...options.tools] : options.noTools ? [] : [\"ipython\", \"prime_context\"]);\n\n\t\tlet agent: Agent;\n\n\t\tconst convertToLlmWithBlockImages = (messages: AgentMessage[]): Message[] => {\n\t\t\tconst converted = convertToLlm(messages);\n\t\t\tif (!settingsManager.getBlockImages()) {\n\t\t\t\treturn converted;\n\t\t\t}\n\t\t\treturn converted.map((msg) => {\n\t\t\t\tif (msg.role === \"user\" || msg.role === \"toolResult\") {\n\t\t\t\t\tconst content = msg.content;\n\t\t\t\t\tif (Array.isArray(content)) {\n\t\t\t\t\t\tconst hasImages = content.some((c) => c.type === \"image\");\n\t\t\t\t\t\tif (hasImages) {\n\t\t\t\t\t\t\tconst filteredContent = content\n\t\t\t\t\t\t\t\t.map((c) =>\n\t\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\t)\n\t\t\t\t\t\t\t\t.filter(\n\t\t\t\t\t\t\t\t\t(c, i, arr) =>\n\t\t\t\t\t\t\t\t\t\t!(\n\t\t\t\t\t\t\t\t\t\t\tc.type === \"text\" &&\n\t\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\t\ti > 0 &&\n\t\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\t(arr[i - 1] as { type: \"text\"; text: string }).text === \"Image reading is disabled.\"\n\t\t\t\t\t\t\t\t\t\t),\n\t\t\t\t\t\t\t\t);\n\t\t\t\t\t\t\treturn { ...msg, content: filteredContent };\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\treturn msg;\n\t\t\t});\n\t\t};\n\n\t\tconst extensionRunnerRef: { current?: ExtensionRunner } = {};\n\n\t\tagent = new Agent({\n\t\t\tinitialState: {\n\t\t\t\tsystemPrompt: \"\",\n\t\t\t\tmodel,\n\t\t\t\tthinkingLevel,\n\t\t\t\tserviceTier,\n\t\t\t\ttools: [],\n\t\t\t},\n\t\t\tconvertToLlm: convertToLlmWithBlockImages,\n\t\t\tstreamFn: createNativeInferenceStream(async (model, _context, options) => {\n\t\t\t\tif (!modelRegistry.hasConfiguredAuth(model)) {\n\t\t\t\t\tthrow new Error(\n\t\t\t\t\t\t`Selected model ${model.provider}/${model.id} needs authentication. Use /login to configure this provider.`,\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t\tconst auth = await modelRegistry.getApiKeyAndHeaders(model);\n\t\t\t\tif (!auth.ok) {\n\t\t\t\t\tthrow new Error(auth.error);\n\t\t\t\t}\n\t\t\t\tconst providerRetrySettings = settingsManager.getProviderRetrySettings();\n\t\t\t\treturn {\n\t\t\t\t\t...options,\n\t\t\t\t\tapiKey: auth.apiKey,\n\t\t\t\t\tauthSourceToken: auth.sourceToken,\n\t\t\t\t\ttimeoutMs: options?.timeoutMs ?? providerRetrySettings.timeoutMs,\n\t\t\t\t\tmaxRetries: options?.maxRetries ?? providerRetrySettings.maxRetries,\n\t\t\t\t\tmaxRetryDelayMs: options?.maxRetryDelayMs ?? providerRetrySettings.maxRetryDelayMs,\n\t\t\t\t\theaders: auth.headers || options?.headers ? { ...auth.headers, ...options?.headers } : undefined,\n\t\t\t\t};\n\t\t\t}),\n\t\t\tonPayload: async (payload, _model) => {\n\t\t\t\tconst runner = extensionRunnerRef.current;\n\t\t\t\tif (!runner?.hasHandlers(\"before_provider_request\")) {\n\t\t\t\t\treturn payload;\n\t\t\t\t}\n\t\t\t\treturn runner.emitBeforeProviderRequest(payload);\n\t\t\t},\n\t\t\tonResponse: async (response, _model) => {\n\t\t\t\tconst runner = extensionRunnerRef.current;\n\t\t\t\tif (!runner?.hasHandlers(\"after_provider_response\")) {\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tawait runner.emit({\n\t\t\t\t\ttype: \"after_provider_response\",\n\t\t\t\t\tstatus: response.status,\n\t\t\t\t\theaders: response.headers,\n\t\t\t\t});\n\t\t\t},\n\t\t\tsessionId: sessionManager.getSessionId(),\n\t\t\ttransformContext: async (messages) => {\n\t\t\t\tconst runner = extensionRunnerRef.current;\n\t\t\t\tif (!runner) return messages;\n\t\t\t\treturn runner.emitContext(messages);\n\t\t\t},\n\t\t\tsteeringMode: settingsManager.getSteeringMode(),\n\t\t\tfollowUpMode: settingsManager.getFollowUpMode(),\n\t\t\ttransport: settingsManager.getTransport(),\n\t\t\tthinkingBudgets: settingsManager.getThinkingBudgets(),\n\t\t\tmaxRetryDelayMs: settingsManager.getProviderRetrySettings().maxRetryDelayMs,\n\t\t});\n\n\t\tif (hasExistingSession) {\n\t\t\tagent.state.messages = existingSession.messages;\n\t\t\tif (!hasThinkingEntry) {\n\t\t\t\tawait sessionManager.appendThinkingLevelChange(thinkingLevel);\n\t\t\t}\n\t\t} else {\n\t\t\tif (model) {\n\t\t\t\tawait sessionManager.appendModelChange(model.provider, model.id);\n\t\t\t}\n\t\t\tawait sessionManager.appendThinkingLevelChange(thinkingLevel);\n\t\t}\n\t\tif (!hasServiceTierEntry) {\n\t\t\tawait sessionManager.appendServiceTierChange(serviceTierPreference);\n\t\t}\n\n\t\tsession = new AgentSession({\n\t\t\tinvocationOutputLimits: options.invocationOutputLimits,\n\t\t\trequestTokenBudget: options.requestTokenBudget,\n\t\t\tcontextMode,\n\t\t\tagent,\n\t\t\tsessionManager,\n\t\t\tsettingsManager,\n\t\t\tserviceTierPreference,\n\t\t\tcwd,\n\t\t\t// Only the explicit dir — the default may not match injected custom storage.\n\t\t\tagentDir: options.agentDir,\n\t\t\tscopedModels: options.scopedModels,\n\t\t\tresourceLoader,\n\t\t\tcustomTools: options.customTools,\n\t\t\tmodelRegistry,\n\t\t\tmcpManager,\n\t\t\tinitialActiveToolNames,\n\t\t\tallowedToolNames,\n\t\t\tincludeGoals,\n\t\t\tincludeCompactSkill: options.includeCompactSkill,\n\t\t\trlmHeartbeatController: options.rlmHeartbeatController,\n\t\t\tagentMessageController: options.agentMessageController,\n\t\t\tagentObserveController: options.agentObserveController,\n\t\t\textensionRunnerRef,\n\t\t\trlmDepth: options.rlmDepth,\n\t\t\trlmMaxDepth: options.rlmMaxDepth,\n\t\t\trlmSessionDir: options.rlmSessionDir,\n\t\t\trlmParentNodeId: options.rlmParentNodeId,\n\t\t\trlmParentAgent: options.rlmParentAgent,\n\t\t\trlmChildAdmission: options.rlmChildAdmission,\n\t\t\trlmSubagentCapacity: options.rlmSubagentCapacity,\n\t\t\trlmRootAdmission: options.rlmRootAdmission,\n\t\t\tsemanticParentSessionId: options.semanticParentSessionId,\n\t\t\tsemanticSpawnedByRequestId: options.semanticSpawnedByRequestId,\n\t\t\tsubagentRuntimeHost: options.subagentRuntimeHost,\n\t\t\tsessionStartEvent: options.sessionStartEvent,\n\t\t\tprewarmIpythonKernel: options.prewarmIpythonKernel,\n\t\t\tautonomous: options.autonomous,\n\t\t\tserializedRefine: options.serializedRefine,\n\t\t\tinitialGoal: options.initialGoal,\n\t\t});\n\t\tawait session.initialize();\n\t\tconst extensionsResult = resourceLoader.getExtensions();\n\n\t\treturn {\n\t\t\tsession,\n\t\t\textensionsResult,\n\t\t\tmodelFallbackMessage,\n\t\t};\n\t} catch (error) {\n\t\ttry {\n\t\t\tconst admitted = options.rlmChildAdmission?.session ?? options.rlmRootAdmission?.session;\n\t\t\tconst failedSession = session ?? (admitted?.sessionManager === sessionManager ? admitted : undefined);\n\t\t\tif (failedSession) await failedSession.disposeAsync();\n\t\t\telse {\n\t\t\t\tawait sessionManager.close();\n\t\t\t\tawait options.rlmChildAdmission?.confirmUnboundCleanup();\n\t\t\t}\n\t\t} catch (cleanupError) {\n\t\t\tif (cleanupError === error || (error instanceof AggregateError && error.errors.includes(cleanupError)))\n\t\t\t\tthrow error;\n\t\t\tthrow new AggregateError([error, cleanupError], \"Session creation and cleanup failed\");\n\t\t}\n\t\tthrow error;\n\t}\n}\n"]}
|
|
@@ -6,6 +6,7 @@ export declare function readSessionBootstrap(sessionManager: SessionManager, lim
|
|
|
6
6
|
includeMessages?: boolean;
|
|
7
7
|
allowPendingToolPublic?: boolean;
|
|
8
8
|
initialContextMode?: ContextMode;
|
|
9
|
+
purpose?: "request" | "read";
|
|
9
10
|
}): Promise<{
|
|
10
11
|
context: SessionContext;
|
|
11
12
|
hasExistingSession: boolean;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"session-bootstrap.d.ts","sourceRoot":"","sources":["../../src/core/session-bootstrap.ts"],"names":[],"mappings":"AAAA,OAAO,EAA4B,KAAK,sBAAsB,EAAE,MAAM,wBAAwB,CAAC;AAC/F,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,oBAAoB,CAAC;AACtD,OAAO,KAAK,EAAE,cAAc,EAAgB,cAAc,EAAE,MAAM,sBAAsB,CAAC;AAsBzF,6FAA6F;AAC7F,wBAAsB,oBAAoB,CACzC,cAAc,EAAE,cAAc,EAC9B,MAAM,EAAE,sBAAsB,EAC9B,OAAO,GAAE;
|
|
1
|
+
{"version":3,"file":"session-bootstrap.d.ts","sourceRoot":"","sources":["../../src/core/session-bootstrap.ts"],"names":[],"mappings":"AAAA,OAAO,EAA4B,KAAK,sBAAsB,EAAE,MAAM,wBAAwB,CAAC;AAC/F,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,oBAAoB,CAAC;AACtD,OAAO,KAAK,EAAE,cAAc,EAAgB,cAAc,EAAE,MAAM,sBAAsB,CAAC;AAsBzF,6FAA6F;AAC7F,wBAAsB,oBAAoB,CACzC,cAAc,EAAE,cAAc,EAC9B,MAAM,EAAE,sBAAsB,EAC9B,OAAO,GAAE;IACR,eAAe,CAAC,EAAE,OAAO,CAAC;IAC1B,sBAAsB,CAAC,EAAE,OAAO,CAAC;IACjC,kBAAkB,CAAC,EAAE,WAAW,CAAC;IACjC,OAAO,CAAC,EAAE,SAAS,GAAG,MAAM,CAAC;CACxB;;;;;GAmEN","sourcesContent":["import { CanonicalContextCompiler, type CanonicalContextLimits } from \"./canonical-context.js\";\nimport type { ContextMode } from \"./context-epoch.js\";\nimport type { SessionContext, SessionEntry, SessionManager } from \"./session-manager.js\";\n\nfunction restoreBootstrapSetting(context: SessionContext, entry: SessionEntry): void {\n\tswitch (entry.type) {\n\t\tcase \"model_change\":\n\t\t\tcontext.model = { provider: entry.provider, modelId: entry.modelId };\n\t\t\tbreak;\n\t\tcase \"message\":\n\t\t\tif (entry.message.role !== \"assistant\") throw new Error(\"Bootstrap model source is not an assistant\");\n\t\t\tcontext.model = { provider: entry.message.provider, modelId: entry.message.model };\n\t\t\tbreak;\n\t\tcase \"thinking_level_change\":\n\t\t\tcontext.thinkingLevel = entry.thinkingLevel;\n\t\t\tbreak;\n\t\tcase \"service_tier_change\":\n\t\t\tcontext.serviceTier = entry.serviceTier;\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tthrow new Error(\"Unexpected bootstrap setting source kind\");\n\t}\n}\n\n/** Restore settings and presence from one captured branch, including messages by default. */\nexport async function readSessionBootstrap(\n\tsessionManager: SessionManager,\n\tlimits: CanonicalContextLimits,\n\toptions: {\n\t\tincludeMessages?: boolean;\n\t\tallowPendingToolPublic?: boolean;\n\t\tinitialContextMode?: ContextMode;\n\t\tpurpose?: \"request\" | \"read\";\n\t} = {},\n) {\n\tlimits = { ...limits };\n\tconst includeMessages = options.includeMessages ?? true;\n\tif (!sessionManager.supportsCapturedHistoryReads()) {\n\t\tconst context: SessionContext = includeMessages\n\t\t\t? sessionManager.buildSessionContext()\n\t\t\t: { messages: [], thinkingLevel: \"off\", serviceTier: \"default\", model: null };\n\t\tconst branch = sessionManager.getBranch();\n\t\tif (!includeMessages) {\n\t\t\tfor (const entry of branch) {\n\t\t\t\tif (\n\t\t\t\t\tentry.type === \"model_change\" ||\n\t\t\t\t\tentry.type === \"thinking_level_change\" ||\n\t\t\t\t\tentry.type === \"service_tier_change\" ||\n\t\t\t\t\t(entry.type === \"message\" && entry.message.role === \"assistant\")\n\t\t\t\t)\n\t\t\t\t\trestoreBootstrapSetting(context, entry);\n\t\t\t}\n\t\t}\n\t\treturn {\n\t\t\tcontext,\n\t\t\thasExistingSession: includeMessages\n\t\t\t\t? context.messages.length > 0\n\t\t\t\t: branch.some(\n\t\t\t\t\t\t(entry) =>\n\t\t\t\t\t\t\tentry.type === \"compaction\" ||\n\t\t\t\t\t\t\tentry.type === \"custom_message\" ||\n\t\t\t\t\t\t\t(entry.type === \"message\" && !!entry.message) ||\n\t\t\t\t\t\t\t(entry.type === \"branch_summary\" && !!entry.summary),\n\t\t\t\t\t),\n\t\t\thasThinkingEntry: branch.some((entry) => entry.type === \"thinking_level_change\"),\n\t\t\thasServiceTierEntry: branch.some((entry) => entry.type === \"service_tier_change\"),\n\t\t};\n\t}\n\treturn sessionManager.readBranchHistory(async (view) => {\n\t\tconst bootstrap = await view.branchBootstrap();\n\t\tconst context: SessionContext = { messages: [], thinkingLevel: \"off\", serviceTier: \"default\", model: null };\n\t\tlet sourceBytes = 0;\n\t\tfor (const ref of [bootstrap.model, bootstrap.thinkingLevel, bootstrap.serviceTier]) {\n\t\t\tif (!ref) continue;\n\t\t\tconst remaining = limits.maxSourceBytes - sourceBytes;\n\t\t\tsourceBytes += ref.locator.length;\n\t\t\tif (sourceBytes > limits.maxSourceBytes) throw new Error(\"Bootstrap source byte budget exceeded\");\n\t\t\tconst hydrated = await view.hydrateEntry(ref.id, remaining);\n\t\t\tif (!hydrated) throw new Error(\"Bootstrap setting source is unavailable\");\n\t\t\trestoreBootstrapSetting(context, hydrated.entry);\n\t\t}\n\t\t// Native session construction may restore an unadmittable raw plan. It grants no transport permission.\n\t\tif (includeMessages)\n\t\t\tcontext.messages = await new CanonicalContextCompiler().compile(\n\t\t\t\tview.branchContext,\n\t\t\t\tlimits,\n\t\t\t\tundefined,\n\t\t\t\t{},\n\t\t\t\tundefined,\n\t\t\t\toptions.initialContextMode ?? \"on\",\n\t\t\t\toptions.allowPendingToolPublic,\n\t\t\t\toptions.purpose,\n\t\t\t);\n\t\treturn {\n\t\t\tcontext,\n\t\t\thasExistingSession: bootstrap.hasContextMessages,\n\t\t\thasThinkingEntry: bootstrap.thinkingLevel !== null,\n\t\t\thasServiceTierEntry: bootstrap.serviceTier !== null,\n\t\t};\n\t});\n}\n"]}
|
|
@@ -67,7 +67,7 @@ export async function readSessionBootstrap(sessionManager, limits, options = {})
|
|
|
67
67
|
}
|
|
68
68
|
// Native session construction may restore an unadmittable raw plan. It grants no transport permission.
|
|
69
69
|
if (includeMessages)
|
|
70
|
-
context.messages = await new CanonicalContextCompiler().compile(view.branchContext, limits, undefined, {}, undefined, options.initialContextMode ?? "on", options.allowPendingToolPublic);
|
|
70
|
+
context.messages = await new CanonicalContextCompiler().compile(view.branchContext, limits, undefined, {}, undefined, options.initialContextMode ?? "on", options.allowPendingToolPublic, options.purpose);
|
|
71
71
|
return {
|
|
72
72
|
context,
|
|
73
73
|
hasExistingSession: bootstrap.hasContextMessages,
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"session-bootstrap.js","sourceRoot":"","sources":["../../src/core/session-bootstrap.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,wBAAwB,EAA+B,MAAM,wBAAwB,CAAC;AAI/F,SAAS,uBAAuB,CAAC,OAAuB,EAAE,KAAmB,EAAQ;IACpF,QAAQ,KAAK,CAAC,IAAI,EAAE,CAAC;QACpB,KAAK,cAAc;YAClB,OAAO,CAAC,KAAK,GAAG,EAAE,QAAQ,EAAE,KAAK,CAAC,QAAQ,EAAE,OAAO,EAAE,KAAK,CAAC,OAAO,EAAE,CAAC;YACrE,MAAM;QACP,KAAK,SAAS;YACb,IAAI,KAAK,CAAC,OAAO,CAAC,IAAI,KAAK,WAAW;gBAAE,MAAM,IAAI,KAAK,CAAC,4CAA4C,CAAC,CAAC;YACtG,OAAO,CAAC,KAAK,GAAG,EAAE,QAAQ,EAAE,KAAK,CAAC,OAAO,CAAC,QAAQ,EAAE,OAAO,EAAE,KAAK,CAAC,OAAO,CAAC,KAAK,EAAE,CAAC;YACnF,MAAM;QACP,KAAK,uBAAuB;YAC3B,OAAO,CAAC,aAAa,GAAG,KAAK,CAAC,aAAa,CAAC;YAC5C,MAAM;QACP,KAAK,qBAAqB;YACzB,OAAO,CAAC,WAAW,GAAG,KAAK,CAAC,WAAW,CAAC;YACxC,MAAM;QACP;YACC,MAAM,IAAI,KAAK,CAAC,0CAA0C,CAAC,CAAC;IAC9D,CAAC;AAAA,CACD;AAED,6FAA6F;AAC7F,MAAM,CAAC,KAAK,UAA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I,EAClC,OAAO,CAAC,sBAAsB,EAC9B,OAAO,CAAC,OAAO,CACf,CAAC;QACH,OAAO;YACN,OAAO;YACP,kBAAkB,EAAE,SAAS,CAAC,kBAAkB;YAChD,gBAAgB,EAAE,SAAS,CAAC,aAAa,KAAK,IAAI;YAClD,mBAAmB,EAAE,SAAS,CAAC,WAAW,KAAK,IAAI;SACnD,CAAC;IAAA,CACF,CAAC,CAAC;AAAA,CACH","sourcesContent":["import { CanonicalContextCompiler, type CanonicalContextLimits } from \"./canonical-context.js\";\nimport type { ContextMode } from \"./context-epoch.js\";\nimport type { SessionContext, SessionEntry, SessionManager } from \"./session-manager.js\";\n\nfunction restoreBootstrapSetting(context: SessionContext, entry: SessionEntry): void {\n\tswitch (entry.type) {\n\t\tcase \"model_change\":\n\t\t\tcontext.model = { provider: entry.provider, modelId: entry.modelId };\n\t\t\tbreak;\n\t\tcase \"message\":\n\t\t\tif (entry.message.role !== \"assistant\") throw new Error(\"Bootstrap model source is not an assistant\");\n\t\t\tcontext.model = { provider: entry.message.provider, modelId: entry.message.model };\n\t\t\tbreak;\n\t\tcase \"thinking_level_change\":\n\t\t\tcontext.thinkingLevel = entry.thinkingLevel;\n\t\t\tbreak;\n\t\tcase \"service_tier_change\":\n\t\t\tcontext.serviceTier = entry.serviceTier;\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tthrow new Error(\"Unexpected bootstrap setting source kind\");\n\t}\n}\n\n/** Restore settings and presence from one captured branch, including messages by default. */\nexport async function readSessionBootstrap(\n\tsessionManager: SessionManager,\n\tlimits: CanonicalContextLimits,\n\toptions: {\n\t\tincludeMessages?: boolean;\n\t\tallowPendingToolPublic?: boolean;\n\t\tinitialContextMode?: ContextMode;\n\t\tpurpose?: \"request\" | \"read\";\n\t} = {},\n) {\n\tlimits = { ...limits };\n\tconst includeMessages = options.includeMessages ?? true;\n\tif (!sessionManager.supportsCapturedHistoryReads()) {\n\t\tconst context: SessionContext = includeMessages\n\t\t\t? sessionManager.buildSessionContext()\n\t\t\t: { messages: [], thinkingLevel: \"off\", serviceTier: \"default\", model: null };\n\t\tconst branch = sessionManager.getBranch();\n\t\tif (!includeMessages) {\n\t\t\tfor (const entry of branch) {\n\t\t\t\tif (\n\t\t\t\t\tentry.type === \"model_change\" ||\n\t\t\t\t\tentry.type === \"thinking_level_change\" ||\n\t\t\t\t\tentry.type === \"service_tier_change\" ||\n\t\t\t\t\t(entry.type === \"message\" && entry.message.role === \"assistant\")\n\t\t\t\t)\n\t\t\t\t\trestoreBootstrapSetting(context, entry);\n\t\t\t}\n\t\t}\n\t\treturn {\n\t\t\tcontext,\n\t\t\thasExistingSession: includeMessages\n\t\t\t\t? context.messages.length > 0\n\t\t\t\t: branch.some(\n\t\t\t\t\t\t(entry) =>\n\t\t\t\t\t\t\tentry.type === \"compaction\" ||\n\t\t\t\t\t\t\tentry.type === \"custom_message\" ||\n\t\t\t\t\t\t\t(entry.type === \"message\" && !!entry.message) ||\n\t\t\t\t\t\t\t(entry.type === \"branch_summary\" && !!entry.summary),\n\t\t\t\t\t),\n\t\t\thasThinkingEntry: branch.some((entry) => entry.type === \"thinking_level_change\"),\n\t\t\thasServiceTierEntry: branch.some((entry) => entry.type === \"service_tier_change\"),\n\t\t};\n\t}\n\treturn sessionManager.readBranchHistory(async (view) => {\n\t\tconst bootstrap = await view.branchBootstrap();\n\t\tconst context: SessionContext = { messages: [], thinkingLevel: \"off\", serviceTier: \"default\", model: null };\n\t\tlet sourceBytes = 0;\n\t\tfor (const ref of [bootstrap.model, bootstrap.thinkingLevel, bootstrap.serviceTier]) {\n\t\t\tif (!ref) continue;\n\t\t\tconst remaining = limits.maxSourceBytes - sourceBytes;\n\t\t\tsourceBytes += ref.locator.length;\n\t\t\tif (sourceBytes > limits.maxSourceBytes) throw new Error(\"Bootstrap source byte budget exceeded\");\n\t\t\tconst hydrated = await view.hydrateEntry(ref.id, remaining);\n\t\t\tif (!hydrated) throw new Error(\"Bootstrap setting source is unavailable\");\n\t\t\trestoreBootstrapSetting(context, hydrated.entry);\n\t\t}\n\t\t// Native session construction may restore an unadmittable raw plan. It grants no transport permission.\n\t\tif (includeMessages)\n\t\t\tcontext.messages = await new CanonicalContextCompiler().compile(\n\t\t\t\tview.branchContext,\n\t\t\t\tlimits,\n\t\t\t\tundefined,\n\t\t\t\t{},\n\t\t\t\tundefined,\n\t\t\t\toptions.initialContextMode ?? \"on\",\n\t\t\t\toptions.allowPendingToolPublic,\n\t\t\t\toptions.purpose,\n\t\t\t);\n\t\treturn {\n\t\t\tcontext,\n\t\t\thasExistingSession: bootstrap.hasContextMessages,\n\t\t\thasThinkingEntry: bootstrap.thinkingLevel !== null,\n\t\t\thasServiceTierEntry: bootstrap.serviceTier !== null,\n\t\t};\n\t});\n}\n"]}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@ponythewhite/base-context",
|
|
3
|
-
"version": "1.0.
|
|
3
|
+
"version": "1.0.7",
|
|
4
4
|
"description": "Synerise base-context: a coding and research agent with durable context and a persistent Python REPL",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"bin": {
|
|
@@ -42,9 +42,9 @@
|
|
|
42
42
|
},
|
|
43
43
|
"dependencies": {
|
|
44
44
|
"@agentclientprotocol/sdk": "^1.3.0",
|
|
45
|
-
"@ponythewhite/base-context-agent": "1.0.
|
|
46
|
-
"@ponythewhite/base-context-ai": "1.0.
|
|
47
|
-
"@ponythewhite/base-context-tui": "1.0.
|
|
45
|
+
"@ponythewhite/base-context-agent": "1.0.7",
|
|
46
|
+
"@ponythewhite/base-context-ai": "1.0.7",
|
|
47
|
+
"@ponythewhite/base-context-tui": "1.0.7",
|
|
48
48
|
"@silvia-odwyer/photon-node": "^0.3.4",
|
|
49
49
|
"chalk": "^5.5.0",
|
|
50
50
|
"cli-highlight": "^2.1.11",
|