@ai-agent-forge/agent-forge 0.88.9 → 0.88.10

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (29) hide show
  1. package/CHANGELOG.md +6 -0
  2. package/bundled-plugins/agent-loop-policy/agent-forge.json +1 -1
  3. package/bundled-plugins/agent-loop-policy/plugin.json +1 -1
  4. package/bundled-plugins/alignment/agent-forge.json +1 -1
  5. package/bundled-plugins/alignment/plugin.json +1 -1
  6. package/bundled-plugins/browser-playwright/agent-forge.json +1 -1
  7. package/bundled-plugins/browser-playwright/plugin.json +1 -1
  8. package/bundled-plugins/coding-tools/agent-forge.json +1 -1
  9. package/bundled-plugins/coding-tools/plugin.json +1 -1
  10. package/bundled-plugins/compaction-policy/agent-forge.json +1 -1
  11. package/bundled-plugins/compaction-policy/plugin.json +1 -1
  12. package/bundled-plugins/overflow-policy/agent-forge.json +1 -1
  13. package/bundled-plugins/overflow-policy/plugin.json +1 -1
  14. package/bundled-plugins/provider-failover/agent-forge.json +1 -1
  15. package/bundled-plugins/provider-failover/plugin.json +1 -1
  16. package/bundled-plugins/retry-policy/agent-forge.json +1 -1
  17. package/bundled-plugins/retry-policy/plugin.json +1 -1
  18. package/dist/bundle/.build-manifest.json +3 -3
  19. package/dist/bundle/chunks/{chunk-VWNIFYQA.js → chunk-ZZCUNSGO.js} +1 -1
  20. package/dist/bundle/cli.js +1 -1
  21. package/dist/bundle/index.js +1 -1
  22. package/dist/bundle/rpc-entry.js +1 -1
  23. package/dist/plugins/ecosystem/node-disk-registry-source.d.ts.map +1 -1
  24. package/dist/plugins/ecosystem/node-disk-registry-source.js +12 -0
  25. package/dist/plugins/ecosystem/node-disk-registry-source.js.map +1 -1
  26. package/examples/extensions/with-deps/package-lock.json +2 -2
  27. package/examples/extensions/with-deps/package.json +1 -1
  28. package/examples/extensions/with-deps/plugin.json +1 -1
  29. package/package.json +1 -1
@@ -1,3 +1,3 @@
1
1
  #!/usr/bin/env node
2
2
  import { createRequire as __piCreateRequire } from "node:module"; const require = __piCreateRequire(import.meta.url);
3
- import{configureHttpDispatcher,main}from"./chunks/chunk-VWNIFYQA.js";import{APP_NAME}from"./chunks/chunk-F73USSXE.js";import"./chunks/chunk-JUUC5AZY.js";import"./chunks/chunk-XDUWOHPL.js";import"./chunks/chunk-3QKHSPQL.js";import"./chunks/chunk-HXGAAJQQ.js";import"./chunks/chunk-BVVSHK6W.js";import"./chunks/chunk-TRDNDS6A.js";import"./chunks/chunk-K3S6GTL7.js";import"./chunks/chunk-5LRQFZFE.js";import"./chunks/chunk-4L3WN2XY.js";process.title=APP_NAME;process.env.AGENT_FORGE="true";process.env.AI_AGENT="agent-forge";process.emitWarning=(()=>{});configureHttpDispatcher();main(process.argv.slice(2));
3
+ import{configureHttpDispatcher,main}from"./chunks/chunk-ZZCUNSGO.js";import{APP_NAME}from"./chunks/chunk-F73USSXE.js";import"./chunks/chunk-JUUC5AZY.js";import"./chunks/chunk-XDUWOHPL.js";import"./chunks/chunk-3QKHSPQL.js";import"./chunks/chunk-HXGAAJQQ.js";import"./chunks/chunk-BVVSHK6W.js";import"./chunks/chunk-TRDNDS6A.js";import"./chunks/chunk-K3S6GTL7.js";import"./chunks/chunk-5LRQFZFE.js";import"./chunks/chunk-4L3WN2XY.js";process.title=APP_NAME;process.env.AGENT_FORGE="true";process.env.AI_AGENT="agent-forge";process.emitWarning=(()=>{});configureHttpDispatcher();main(process.argv.slice(2));
@@ -1,5 +1,5 @@
1
1
  import { createRequire as __piCreateRequire } from "node:module"; const require = __piCreateRequire(import.meta.url);
2
- import{renderDiff}from"./chunks/chunk-4BD6FSZA.js";import{AgentCompositionRuntime,AgentSession,AgentSessionRuntime,ArminComponent,AssistantMessageComponent,BOOTSTRAP_LIFECYCLE_PLUGIN_ID,BashExecutionComponent,BranchSummaryMessageComponent,CAPABILITY_CALL_EVENT_ID,CAPABILITY_CALL_EVENT_VERSION,CodingAgentServerService,CodingAgentSessionRuntime,CompactionSummaryMessageComponent,CredentialSynchronizationError,CustomEditor,CustomMessageComponent,DEFAULT_COMPACTION_POLICY_NAME,DEFAULT_RETRY_POLICY_NAME,DEFAULT_SUITE_ID,DefaultPackageManager,DefaultResourceLoader,DialogEditorComponent,DialogInputComponent,DialogSelectorComponent,DurableServiceErrorV1,DynamicBorder,FooterComponent,InteractiveMode,LoginDialogComponent,MODEL_RESPONSE_EVENT_ID,MODEL_RESPONSE_EVENT_VERSION,MODEL_STREAM_EVENT_ID,MODEL_STREAM_EVENT_VERSION,ModelRuntime,ModelSelectorComponent,OAuthSelectorComponent,OPERATION_CANCEL_EVENT_ID,OPERATION_CANCEL_EVENT_VERSION,OPERATION_END_EVENT_ID,OPERATION_END_EVENT_VERSION,OPERATION_START_EVENT_ID,OPERATION_START_EVENT_VERSION,OPERATION_STEP_EVENT_ID,OPERATION_STEP_EVENT_VERSION,PLUGIN_DISPOSE_EVENT_ID,PLUGIN_DISPOSE_EVENT_VERSION,PLUGIN_READY_EVENT_ID,PLUGIN_READY_EVENT_VERSION,PluginManagerEntryComponent,RpcClient,SESSION_COMPACTION_COMMIT_EVENT_ID,SESSION_COMPACTION_COMMIT_EVENT_VERSION,SESSION_CONTEXT_REPLACED_EVENT_ID,SESSION_CONTEXT_REPLACED_EVENT_VERSION,SESSION_RELOAD_EVENT_ID,SESSION_RELOAD_EVENT_VERSION,SUITE_DELETE_CONFIRM_TOKEN,SessionSelectorComponent,SettingsManager,SettingsSelectorComponent,SkillInvocationMessageComponent,SuiteLifecycleError,SuiteResolutionError,TOOL_CALL_EVENT_ID,TOOL_CALL_EVENT_VERSION,TOOL_COMMIT_EVENT_ID,TOOL_COMMIT_EVENT_VERSION,TOOL_EXECUTE_EVENT_ID,TOOL_EXECUTE_EVENT_VERSION,TOOL_RESULT_EVENT_ID,TOOL_RESULT_EVENT_VERSION,TOOL_RESULT_RAW_EVENT_ID,TOOL_RESULT_RAW_EVENT_VERSION,TOOL_RESULT_TRANSFORM_EVENT_ID,TOOL_RESULT_TRANSFORM_EVENT_VERSION,ThinkingSelectorComponent,ToolExecutionComponent,TreeSelectorComponent,UserMessageComponent,UserMessageSelectorComponent,assembleCodingAgentServer,assembleProfile,buildProfileIdentityV1,buildResolvedAgentProfileV1,clearDanglingSuiteSettings,copyToClipboard,createAgentCompositionRuntime,createAgentSession,createAgentSessionFromServices,createAgentSessionRuntime,createAgentSessionServices,createCapabilityRuntime,createDurableService,createFileDurableStoreBackend,createFileSessionSource,createHostOutputProjector,createProfileLock,createProfileMigrationPolicy,createProfileRegistry,createStableAgentSession,createStableAgentSessionRuntime,createStdioChannelAdapter,createSuite,createSyntheticSourceInfo,deleteSuite,discoverCapabilityPluginManifests,durableLogPath,ecosystem_exports,findSuiteSessionRefs,formatSkillsForPrompt,installBootstrapLifecycle,isBuiltinSuiteId,listBuiltinPluginManifestsV1,listBuiltinPluginProfilesV1,listSuiteIds,loadCapabilityPlugin,loadCapabilityPluginFromManifest,loadCapabilityPluginSync,loadProjectContextFiles,loadSkills,loadSkillsFromDir,main,parseArgs,parseFrontmatter,parseSkillBlock,plugin_manager_controller_exports,plugin_selection_controller_exports,profileIdentitiesCompatible,projectSessionTranscript,readStoredCredential,replaceProfileLock,replaceProfilePlugin,resetSuite,resolveBuiltinPluginProfileV1,resolveCliModel,resolveModelScopeWithDiagnostics,resolvePluginCapabilityOrder,runPrintMode,runRpcMode,stableJsonDigest,startCodingAgentRemoteServer,stripFrontmatter,validateCapabilityCallEventDataV1,validateExecutionFactsV1,validateModelResponseEventDataV1,validateModelStreamEventDataV1,validateOperationCancelEventDataV1,validateOperationEndEventDataV1,validateOperationStartEventDataV1,validateOperationStepEventDataV1,validatePluginDisposeEventDataV1,validatePluginReadyEventDataV1,validateRetryScheduleV1,validateSessionCompactionCommitEventDataV1,validateSessionContextReplacedEventDataV1,validateSessionReloadEventDataV1,validateToolCallEventDataV1,validateToolCommitEventDataV1,validateToolExecuteEventDataV1,validateToolResultEventDataV1,validateToolResultRawEventDataV1,validateToolResultTransformEventDataV1,verifyProfileLock}from"./chunks/chunk-VWNIFYQA.js";import{CONFIG_DIR_NAME,CURRENT_SESSION_VERSION,CancellableLoader,Container,DEFAULT_COMPACTION_SETTINGS,DEFAULT_MAX_BYTES,DEFAULT_MAX_LINES,EXPERIMENTAL_PUBLIC_API_VERSION,FileSessionStorageProvider,LifecycleExecuteError,LifecycleTransformError,Loader,MEMORY_RECALL_TOOL_NAME,SUMMARY_MODEL_INVOCATION_ERROR_CODES,SelectList,SessionHeaderScanLimitError,SessionManager,Spacer,Text,Theme,VERSION,buildContextEntries,buildSessionContext,calculateContextTokens,collectEntriesForBranchSummary,compact,convertToLlm,convertToPng,createDisposableRegistration,createEventEnvelope,createLocalBashOperations,createLocalShellOperations,defineTool,detachedSessionSnapshot,detectSupportedImageMimeTypeFromFile,dist_exports2 as dist_exports,estimateTokens,findCutPoint,findTurnStartIndex,formatDimensionNote,formatSize,generateBranchSummary,generateDiffString,generateSummary,generateSummaryWithUsage,generateUnifiedPatch,getAgentDir,getAvailableThemes,getDocsPath,getExamplesPath,getLanguageFromPath,getLastAssistantUsage,getLatestCompactionEntry,getMarkdownTheme,getPackageDir,getPowerShellConfig,getReadmePath,getSelectListTheme,getSessionsDir,getSettingsListTheme,getShellConfig,highlightCode,initTheme,keyHint,keyText,killProcessTree,migrateSessionEntries,parseCapabilityPluginManifest,parseSessionEntries,prepareBranchEntries,rawKeyHint,resizeImage,sanitizeBinaryOutput,serializeConversation,sessionEntryToContextMessages,shouldCompact,truncateHead,truncateLine,truncateTail,truncateToVisualLines,withFileMutationQueue}from"./chunks/chunk-F73USSXE.js";import"./chunks/chunk-JUUC5AZY.js";import"./chunks/chunk-XDUWOHPL.js";import"./chunks/chunk-3QKHSPQL.js";import{t}from"./chunks/chunk-HXGAAJQQ.js";import"./chunks/chunk-BVVSHK6W.js";import"./chunks/chunk-TRDNDS6A.js";import"./chunks/chunk-K3S6GTL7.js";import"./chunks/chunk-5LRQFZFE.js";import"./chunks/chunk-4L3WN2XY.js";function contentHash(bytes){let hash=2166136261;for(let byte of bytes)hash^=byte,hash=Math.imul(hash,16777619);return(hash>>>0).toString(36)}function toStat(entry){return{artifactId:entry.ref.artifactId,sessionId:entry.ref.sessionId,operationId:entry.ref.operationId,kind:entry.ref.kind,mediaType:entry.ref.mediaType,sizeBytes:entry.ref.sizeBytes,state:entry.ended?"ended":"available",...entry.ended?{endReason:entry.endReason}:{}}}function createArtifactStore(options={}){let now=options.now??(()=>Date.now()),artifacts=new Map,sequenceByIdentity=new Map,globalWriteSequence=0;return{write(input){if(input.bytes.length===0)throw new Error("Artifact bytes must not be empty");let identity=`${input.sessionId}\0${input.operationId}`,sequence=(sequenceByIdentity.get(identity)??0)+1;sequenceByIdentity.set(identity,sequence),globalWriteSequence+=1;let artifactId=`art-${contentHash(input.bytes)}-${sequence}-${globalWriteSequence}`,ref={artifactId,sessionId:input.sessionId,operationId:input.operationId,kind:input.kind,mediaType:input.mediaType,sizeBytes:input.bytes.length,truncated:!1,createdAt:now()};return artifacts.set(artifactId,{ref,bytes:input.bytes,ended:!1}),{ref}},read(input){let entry=artifacts.get(input.artifactId);if(!entry)throw new Error(t("Artifact not found: {artifactId}",{artifactId:input.artifactId}));if(entry.ref.sessionId!==input.sessionId)throw new Error(t("Artifact {artifactId} belongs to a different session",{artifactId:input.artifactId}));if(entry.ended)throw new Error(t("Artifact {artifactId} lifecycle has ended: {reason}",{artifactId:input.artifactId,reason:entry.endReason??"ended"}));return{mediaType:entry.ref.mediaType,bytes:entry.bytes}},stat(artifactId){let entry=artifacts.get(artifactId);return entry===void 0?void 0:toStat(entry)},list(sessionId){return[...artifacts.values()].filter(entry=>entry.ref.sessionId===sessionId).map(entry=>toStat(entry))},endLifecycle(artifactId,input){let entry=artifacts.get(artifactId);if(!entry)throw new Error(t("Artifact not found: {artifactId}",{artifactId}));if(entry.ended)throw new Error(t("Artifact {artifactId} lifecycle has already ended",{artifactId}));return entry.ended=!0,entry.endReason=input.reason,entry.bytes=new Uint8Array(0),toStat(entry)}}}function planArtifactPages(store,input){if(!Number.isSafeInteger(input.pageSize)||input.pageSize<1)return{status:"invalid_page_size",pageSize:input.pageSize};let stat=store.stat(input.artifactId);if(!stat)return{status:"unavailable",reason:`Artifact not found: ${input.artifactId}`};if(stat.state==="ended")return{status:"unavailable",reason:`Artifact ${input.artifactId} lifecycle has ended: ${stat.endReason??"ended"}`};let totalBytes=stat.sizeBytes??0,pages=[];for(let offset=0;offset<totalBytes;offset+=input.pageSize)pages.push({index:pages.length,offset,size:Math.min(input.pageSize,totalBytes-offset)});return{status:"planned",totalBytes,pageSize:input.pageSize,pages:Object.freeze(pages)}}function readArtifactPage(store,input){if(!Number.isSafeInteger(input.pageSize)||input.pageSize<1)return{status:"unavailable",reason:`Invalid page size: ${input.pageSize}`};let plan=planArtifactPages(store,{artifactId:input.artifactId,pageSize:input.pageSize});if(plan.status!=="planned")return{status:"unavailable",reason:plan.status==="unavailable"?plan.reason:`Invalid page size: ${plan.pageSize}`};let page=plan.pages[input.index];if(!page)return{status:"unavailable",reason:`Page ${input.index} is outside the plan (${plan.pages.length} pages)`};let bytes;try{bytes=store.read({artifactId:input.artifactId,sessionId:input.sessionId}).bytes}catch(error){return{status:"unavailable",reason:error instanceof Error?error.message:String(error)}}let slice=bytes.slice(page.offset,page.offset+page.size),nextOffset=page.offset+page.size,hasMore=nextOffset<plan.totalBytes;return{status:"ok",index:page.index,offset:page.offset,bytes:slice,hasMore,...hasMore?{nextOffset}:{}}}var AGENT_CAPABILITY_CONTRACT_ID="agent-forge/agent-capability-contract",AGENT_CAPABILITY_CONTRACT_VERSION=1,AGENT_ERROR_CODES_V1=["provider_error","operation_timeout","operation_cancelled","idempotency_conflict","revision_conflict","revision_unavailable","unsupported_capability","invalid_request","invalid_ref","not_found","cancelled","unsupported","busy","session_locked","unauthorized","not_implemented","internal_error"],agentErrorCodeSet=new Set(AGENT_ERROR_CODES_V1);function isRegisteredAgentErrorCodeV1(code){return agentErrorCodeSet.has(code)}var PROTOCOL_ERROR_CODE_TO_AGENT_CODE_V1=Object.freeze({version:"unsupported",busy:"busy",session_locked:"session_locked",not_found:"not_found",invalid_request:"invalid_request",unauthorized:"unauthorized",not_implemented:"not_implemented",internal_error:"internal_error"});function mapProtocolErrorCodeToAgentErrorV1(code){return PROTOCOL_ERROR_CODE_TO_AGENT_CODE_V1[code]}function toErrorEnvelopeV1(error){let message=error instanceof Error?error.message:String(error),name=error instanceof Error?error.name:void 0,code;if(error&&typeof error=="object"&&"code"in error){let raw=error.code;typeof raw=="string"&&raw.trim()!==""&&(code=raw)}code===void 0&&(code="internal_error");let mapped=PROTOCOL_ERROR_CODE_TO_AGENT_CODE_V1[code];return buildErrorEnvelopeV1({version:1,code:mapped??code,message,retryable:!1,...name===void 0?{}:{name}})}function isPlainRecord(value){if(value===null||typeof value!="object"||Array.isArray(value))return!1;let prototype=Object.getPrototypeOf(value);return prototype===Object.prototype||prototype===null}function assertPlainRecord(value,label){if(!isPlainRecord(value))throw new Error(t("{label} must be a plain object",{label}))}function assertExactKeys(value,required,optional,label){let allowed=new Set([...required,...optional]),unsupported=Object.keys(value).filter(key=>!allowed.has(key)).sort();if(unsupported.length>0)throw new Error(t("{label} has unsupported fields: {fields}",{label,fields:unsupported.join(", ")}));for(let key of required)if(!(key in value))throw new Error(t("{label} is missing required field: {key}",{label,key}))}function assertNonEmptyString(value,label){if(typeof value!="string"||value.trim().length===0)throw new Error(t("{label} must be a non-empty string",{label}))}function assertPositiveSafeInteger(value,label){if(typeof value!="number"||!Number.isSafeInteger(value)||value<1)throw new Error(t("{label} must be a positive safe integer",{label}))}function assertNonNegativeSafeInteger(value,label){if(typeof value!="number"||!Number.isSafeInteger(value)||value<0)throw new Error(t("{label} must be a non-negative safe integer",{label}))}function assertJsonValue(value,label,seen=new WeakSet){if(!(value===null||typeof value=="boolean"||typeof value=="string")){if(typeof value=="number"){if(Number.isFinite(value))return;throw new Error(t("{label} must contain finite JSON numbers",{label}))}if(typeof value!="object")throw new Error(t("{label} must be JSON-compatible",{label}));if(seen.has(value))throw new Error(t("{label} must not contain cycles",{label}));if(seen.add(value),Array.isArray(value))for(let[index,child]of value.entries())assertJsonValue(child,`${label}[${index}]`,seen);else{if(!isPlainRecord(value))throw new Error(t("{label} must contain only plain JSON objects",{label}));for(let[key,child]of Object.entries(value))assertJsonValue(child,`${label}.${key}`,seen)}seen.delete(value)}}function detachedFreeze(value,seen=new WeakMap){if(value===null||typeof value!="object")return value;let existing=seen.get(value);if(existing!==void 0)return existing;if(Array.isArray(value)){let result2=[];seen.set(value,result2);for(let child of value)result2.push(detachedFreeze(child,seen));return Object.freeze(result2)}let result={};seen.set(value,result);for(let[key,child]of Object.entries(value))result[key]=detachedFreeze(child,seen);return Object.freeze(result)}function capabilitySort(left,right){return left.id<right.id?-1:left.id>right.id?1:left.version-right.version}function validateCapabilityRefs(value,label){if(!Array.isArray(value))throw new Error(t("{label} must be an array",{label}));let refs=value.map((item,index)=>validateCapabilityRefV1(item,`${label}[${index}]`)),seen=new Set;for(let ref of refs){let key=`${ref.id}\0${ref.version}`;if(seen.has(key))throw new Error(t("{label} contains duplicate capability: {capability}",{label,capability:`${ref.id}@${ref.version}`}));seen.add(key)}return Object.freeze(refs.sort(capabilitySort))}function validateHostTransport(value,label){if(value!=="in-process"&&value!=="stdio"&&value!=="http"&&value!=="rpc"&&value!=="unix"&&value!=="websocket")throw new Error(t("{label} is invalid",{label}))}function validateCapabilityRefV1(value,label="Capability reference"){return assertPlainRecord(value,label),assertExactKeys(value,["id","version"],[],label),assertNonEmptyString(value.id,`${label}.id`),assertPositiveSafeInteger(value.version,`${label}.version`),detachedFreeze({id:value.id,version:value.version})}function validateHostContextV1(value){if(assertPlainRecord(value,"Host context"),assertExactKeys(value,["mode","features","transports"],[],"Host context"),value.mode!=="readonly"&&value.mode!=="full-control")throw new Error(t("Host context.mode is invalid"));if(!Array.isArray(value.features))throw new Error(t("Host context.features must be an array"));let features=value.features.map((feature,index)=>(assertNonEmptyString(feature,`Host context.features[${index}]`),feature));if(new Set(features).size!==features.length)throw new Error(t("Host context.features must not contain duplicates"));if(!Array.isArray(value.transports))throw new Error(t("Host context.transports must be an array"));let transports=value.transports.map((transport,index)=>(validateHostTransport(transport,`Host context.transports[${index}]`),transport));if(new Set(transports).size!==transports.length)throw new Error(t("Host context.transports must not contain duplicates"));return detachedFreeze({mode:value.mode,features:[...features].sort(),transports:[...transports].sort()})}function buildHostContextV1(input){return validateHostContextV1(input)}function validateContractCompatibilityRequirementsV1(value){assertPlainRecord(value,"Contract compatibility requirements"),assertExactKeys(value,["contractId","version","mode","features","transports","capabilities"],[],"Contract compatibility requirements"),assertNonEmptyString(value.contractId,"Contract compatibility requirements.contractId"),assertPositiveSafeInteger(value.version,"Contract compatibility requirements.version");let hostContext=validateHostContextV1({mode:value.mode,features:value.features,transports:value.transports}),capabilities=validateCapabilityRefs(value.capabilities,"Contract compatibility requirements.capabilities");return detachedFreeze({contractId:value.contractId,version:value.version,mode:hostContext.mode,features:hostContext.features,transports:hostContext.transports,capabilities})}function buildContractCompatibilityRequirementsV1(input){return validateContractCompatibilityRequirementsV1(input)}var CONTRACT_COMPATIBILITY_ISSUE_CODES_V1=["unsupported_contract","host_mode_mismatch","unsupported_feature","unsupported_transport","unsupported_capability"];function validateContractCompatibilityResultV1(value){if(assertPlainRecord(value,"Contract compatibility result"),assertExactKeys(value,["version","compatible","issues"],[],"Contract compatibility result"),value.version!==1)throw new Error(t("Contract compatibility result.version must be 1"));if(typeof value.compatible!="boolean")throw new Error(t("Contract compatibility result.compatible must be boolean"));if(!Array.isArray(value.issues))throw new Error(t("Contract compatibility result.issues must be an array"));if(value.compatible&&value.issues.length>0)throw new Error(t("Contract compatibility result.compatible must be false when issues exist"));if(!value.compatible&&value.issues.length===0)throw new Error(t("Contract compatibility result.compatible must be true when no issues exist"));let issues=value.issues.map((entry,index)=>{if(assertPlainRecord(entry,`Contract compatibility result.issues[${index}]`),assertExactKeys(entry,["code","error"],["missingFeatures","missingTransports","missingCapabilities"],`Contract compatibility result.issues[${index}]`),!CONTRACT_COMPATIBILITY_ISSUE_CODES_V1.includes(entry.code))throw new Error(t("Contract compatibility result.issues[{index}].code is invalid",{index}));let error=validateErrorEnvelopeV1(entry.error),missingFeatures=entry.missingFeatures;if(missingFeatures!==void 0&&(!Array.isArray(missingFeatures)||missingFeatures.some(item=>typeof item!="string")))throw new Error(t("Contract compatibility result.issues[{index}].missingFeatures must be strings",{index}));let missingTransports=entry.missingTransports;if(missingTransports!==void 0&&(!Array.isArray(missingTransports)||missingTransports.some(item=>typeof item!="string")))throw new Error(t("Contract compatibility result.issues[{index}].missingTransports must be strings",{index}));let missingCapabilities=entry.missingCapabilities;missingCapabilities!==void 0&&validateCapabilityRefs(missingCapabilities,`Contract compatibility result.issues[${index}].missingCapabilities`);let issue={code:entry.code,error,...missingFeatures===void 0?{}:{missingFeatures:Object.freeze(missingFeatures.map(item=>item))},...missingTransports===void 0?{}:{missingTransports:Object.freeze(missingTransports.map(item=>item))},...missingCapabilities===void 0?{}:{missingCapabilities:validateCapabilityRefs(missingCapabilities,"missingCapabilities")}};return detachedFreeze(issue)});return detachedFreeze({version:1,compatible:value.compatible,issues:Object.freeze(issues)})}function validateAgentCapabilityContractV1(value){if(assertPlainRecord(value,"Agent capability contract"),assertExactKeys(value,["contractId","version","capabilities","hostContext"],[],"Agent capability contract"),value.contractId!==AGENT_CAPABILITY_CONTRACT_ID)throw new Error(t("Agent capability contract.contractId must be {contractId}",{contractId:AGENT_CAPABILITY_CONTRACT_ID}));if(value.version!==1)throw new Error(t("Agent capability contract.version must be 1"));let capabilities=validateCapabilityRefs(value.capabilities,"Agent capability contract.capabilities"),hostContext=validateHostContextV1(value.hostContext);return detachedFreeze({contractId:value.contractId,version:1,capabilities,hostContext})}function buildAgentCapabilityContractV1(input){return validateAgentCapabilityContractV1({...input,version:input.version??1})}function validateAgentProfileV1(value){assertPlainRecord(value,"Agent profile"),assertExactKeys(value,["id","version","rootAgent","requiredPlugins"],["optionalPlugins","defaults"],"Agent profile"),assertNonEmptyString(value.id,"Agent profile.id"),assertPositiveSafeInteger(value.version,"Agent profile.version"),assertNonEmptyString(value.rootAgent,"Agent profile.rootAgent");let validatePluginIds=(candidate,label)=>{if(!Array.isArray(candidate))throw new Error(t("{label} must be an array",{label}));let ids=candidate.map((id,index)=>(assertNonEmptyString(id,`${label}[${index}]`),id));if(new Set(ids).size!==ids.length)throw new Error(t("{label} must not contain duplicates",{label}));return Object.freeze([...ids].sort())},requiredPlugins=validatePluginIds(value.requiredPlugins,"Agent profile.requiredPlugins"),optionalPlugins=value.optionalPlugins===void 0?void 0:validatePluginIds(value.optionalPlugins,"Agent profile.optionalPlugins");if(optionalPlugins?.some(id=>requiredPlugins.includes(id)))throw new Error(t("Agent profile.optionalPlugins must not overlap requiredPlugins"));return value.defaults!==void 0&&assertJsonValue(value.defaults,"Agent profile.defaults"),detachedFreeze({id:value.id,version:value.version,rootAgent:value.rootAgent,requiredPlugins,...optionalPlugins===void 0?{}:{optionalPlugins},...value.defaults===void 0?{}:{defaults:value.defaults}})}function buildAgentProfileV1(input){return validateAgentProfileV1(input)}function validateArtifactRefV1(value){if(assertPlainRecord(value,"Artifact reference"),assertExactKeys(value,["sessionId","operationId","artifactId","kind","mediaType","truncated","createdAt"],["sizeBytes"],"Artifact reference"),assertNonEmptyString(value.sessionId,"Artifact reference.sessionId"),assertNonEmptyString(value.operationId,"Artifact reference.operationId"),assertNonEmptyString(value.artifactId,"Artifact reference.artifactId"),assertNonEmptyString(value.kind,"Artifact reference.kind"),assertNonEmptyString(value.mediaType,"Artifact reference.mediaType"),value.sizeBytes!==void 0&&assertNonNegativeSafeInteger(value.sizeBytes,"Artifact reference.sizeBytes"),typeof value.truncated!="boolean")throw new Error(t("Artifact reference.truncated must be boolean"));return assertNonNegativeSafeInteger(value.createdAt,"Artifact reference.createdAt"),detachedFreeze({sessionId:value.sessionId,operationId:value.operationId,artifactId:value.artifactId,kind:value.kind,mediaType:value.mediaType,...value.sizeBytes===void 0?{}:{sizeBytes:value.sizeBytes},truncated:value.truncated,createdAt:value.createdAt})}function buildArtifactRefV1(input){return validateArtifactRefV1(input)}function checkContractCompatibilityV1(candidateInput,requirementsInput){let candidate=validateAgentCapabilityContractV1(candidateInput),requirements=validateContractCompatibilityRequirementsV1(requirementsInput),issues=[];(candidate.contractId!==requirements.contractId||candidate.version!==requirements.version)&&issues.push({code:"unsupported_contract",error:commandError("unsupported_contract",`Contract is unsupported: ${requirements.contractId}@${requirements.version}`)}),candidate.hostContext.mode!==requirements.mode&&issues.push({code:"host_mode_mismatch",error:commandError("host_mode_mismatch",`Host mode is incompatible: required ${requirements.mode}, received ${candidate.hostContext.mode}`)});let missingFeatures=requirements.features.filter(feature=>!candidate.hostContext.features.includes(feature));missingFeatures.length>0&&issues.push({code:"unsupported_feature",error:commandError("unsupported_feature",`Host features are unsupported: ${missingFeatures.join(", ")}`),missingFeatures:Object.freeze([...missingFeatures])});let missingTransports=requirements.transports.filter(transport=>!candidate.hostContext.transports.includes(transport));missingTransports.length>0&&issues.push({code:"unsupported_transport",error:commandError("unsupported_transport",`Host transports are unsupported: ${missingTransports.join(", ")}`),missingTransports:Object.freeze([...missingTransports])});let missingCapabilities=requirements.capabilities.filter(required=>!candidate.capabilities.some(available=>available.id===required.id&&available.version===required.version));return missingCapabilities.length>0&&issues.push({code:"unsupported_capability",error:commandError("unsupported_capability",`Capabilities are unsupported: ${missingCapabilities.map(item=>`${item.id}@${item.version}`).join(", ")}`),missingCapabilities:Object.freeze([...missingCapabilities])}),detachedFreeze({version:1,compatible:issues.length===0,issues})}function validateAgentRole(value,label){if(value!=="root-agent-controller"&&value!=="child-agent-controller")throw new Error(t("{label} is invalid",{label}))}function validateAgentDefinitionSnapshotV1(value){if(assertPlainRecord(value,"Agent definition snapshot"),assertExactKeys(value,["version","id","definitionVersion","role","capabilities"],["owner"],"Agent definition snapshot"),value.version!==1)throw new Error(t("Agent definition snapshot.version must be 1"));assertNonEmptyString(value.id,"Agent definition snapshot.id"),assertPositiveSafeInteger(value.definitionVersion,"Agent definition snapshot.definitionVersion"),validateAgentRole(value.role,"Agent definition snapshot.role");let capabilities=validateCapabilityRefs(value.capabilities,"Agent definition snapshot.capabilities");return value.owner!==void 0&&assertNonEmptyString(value.owner,"Agent definition snapshot.owner"),detachedFreeze({version:1,id:value.id,definitionVersion:value.definitionVersion,role:value.role,capabilities,...value.owner===void 0?{}:{owner:value.owner}})}function buildAgentDefinitionSnapshotV1(input){return validateAgentDefinitionSnapshotV1(input)}function validateAgentInstanceSnapshotV1(value){if(assertPlainRecord(value,"Agent instance snapshot"),assertExactKeys(value,["version","id","definitionId","definitionVersion","role","status","revision"],["parentInstanceId","leaseOwner"],"Agent instance snapshot"),value.version!==1)throw new Error(t("Agent instance snapshot.version must be 1"));if(assertNonEmptyString(value.id,"Agent instance snapshot.id"),assertNonEmptyString(value.definitionId,"Agent instance snapshot.definitionId"),assertPositiveSafeInteger(value.definitionVersion,"Agent instance snapshot.definitionVersion"),validateAgentRole(value.role,"Agent instance snapshot.role"),value.status!=="created"&&value.status!=="running"&&value.status!=="succeeded"&&value.status!=="failed"&&value.status!=="cancelled"&&value.status!=="disposed")throw new Error(t("Agent instance snapshot.status is invalid"));return assertNonNegativeSafeInteger(value.revision,"Agent instance snapshot.revision"),value.parentInstanceId!==void 0&&assertNonEmptyString(value.parentInstanceId,"Agent instance snapshot.parentInstanceId"),value.leaseOwner!==void 0&&assertNonEmptyString(value.leaseOwner,"Agent instance snapshot.leaseOwner"),detachedFreeze({version:1,id:value.id,definitionId:value.definitionId,definitionVersion:value.definitionVersion,role:value.role,status:value.status,revision:value.revision,...value.parentInstanceId===void 0?{}:{parentInstanceId:value.parentInstanceId},...value.leaseOwner===void 0?{}:{leaseOwner:value.leaseOwner}})}function buildAgentInstanceSnapshotV1(input){return validateAgentInstanceSnapshotV1(input)}function validateSessionRevisionV1(value){if(assertPlainRecord(value,"Session revision"),assertExactKeys(value,["version","sessionId","sequence","leafId"],[],"Session revision"),value.version!==1)throw new Error(t("Session revision.version must be 1"));if(assertNonEmptyString(value.sessionId,"Session revision.sessionId"),assertNonNegativeSafeInteger(value.sequence,"Session revision.sequence"),value.leafId!==null&&value.leafId!==void 0&&assertNonEmptyString(value.leafId,"Session revision.leafId"),value.leafId===void 0)throw new Error(t("Session revision.leafId is required"));return detachedFreeze({version:1,sessionId:value.sessionId,sequence:value.sequence,leafId:value.leafId})}function buildSessionRevisionV1(input){return validateSessionRevisionV1(input)}function validateSessionSnapshotV1(value){if(assertPlainRecord(value,"Session snapshot"),assertExactKeys(value,["version","sessionId","revision"],[],"Session snapshot"),value.version!==1)throw new Error(t("Session snapshot.version must be 1"));assertNonEmptyString(value.sessionId,"Session snapshot.sessionId");let revision=validateSessionRevisionV1(value.revision);if(revision.sessionId!==value.sessionId)throw new Error(t("Session snapshot.revision.sessionId must match sessionId"));return detachedFreeze({version:1,sessionId:value.sessionId,revision})}function buildSessionSnapshotV1(input){return validateSessionSnapshotV1(input)}function validateErrorEnvelopeV1(value){if(assertPlainRecord(value,"Error envelope"),assertExactKeys(value,["version","code","message","retryable"],["details","name"],"Error envelope"),value.version!==1)throw new Error(t("Error envelope.version must be 1"));if(assertNonEmptyString(value.code,"Error envelope.code"),typeof value.message!="string")throw new Error(t("Error envelope.message must be a string"));if(typeof value.retryable!="boolean")throw new Error(t("Error envelope.retryable must be a boolean"));return value.name!==void 0&&assertNonEmptyString(value.name,"Error envelope.name"),value.details!==void 0&&assertJsonValue(value.details,"Error envelope.details"),detachedFreeze({version:1,code:value.code,message:value.message,retryable:value.retryable,...value.details===void 0?{}:{details:value.details},...value.name===void 0?{}:{name:value.name}})}function buildErrorEnvelopeV1(input){return validateErrorEnvelopeV1(input)}function validateOperationTerminalStatus(value,label){if(value!=="succeeded"&&value!=="failed"&&value!=="cancelled"&&value!=="timed_out")throw new Error(t("{label} is invalid",{label}))}function validateOperationTerminalV1(value){if(assertPlainRecord(value,"Operation terminal"),!("version"in value)||!("status"in value))throw new Error(t("Operation terminal is missing required field: version or status"));if(value.version!==1)throw new Error(t("Operation terminal.version must be 1"));if(validateOperationTerminalStatus(value.status,"Operation terminal.status"),value.status==="succeeded")return assertExactKeys(value,["version","status"],["result"],"Operation terminal"),value.result!==void 0&&assertJsonValue(value.result,"Operation terminal.result"),detachedFreeze({version:1,status:"succeeded",...value.result===void 0?{}:{result:value.result}});assertExactKeys(value,["version","status","error"],[],"Operation terminal");let error=validateErrorEnvelopeV1(value.error);return detachedFreeze({version:1,status:value.status,error})}function buildOperationTerminalV1(input){return validateOperationTerminalV1(input)}function validateOperationSnapshotV1(value){if(assertPlainRecord(value,"Operation snapshot"),assertExactKeys(value,["version","operationId","kind","status"],["terminal","instanceId","sessionId","inputRevision"],"Operation snapshot"),value.version!==1)throw new Error(t("Operation snapshot.version must be 1"));if(assertNonEmptyString(value.operationId,"Operation snapshot.operationId"),assertNonEmptyString(value.kind,"Operation snapshot.kind"),value.status!=="queued"&&value.status!=="running"&&value.status!=="succeeded"&&value.status!=="failed"&&value.status!=="cancelled"&&value.status!=="timed_out")throw new Error(t("Operation snapshot.status is invalid"));if((value.status==="queued"||value.status==="running")&&value.terminal!==void 0)throw new Error(t("Operation snapshot active status must not have a terminal"));if(value.status!=="queued"&&value.status!=="running"&&value.terminal===void 0)throw new Error(t("Operation snapshot terminal status requires a terminal"));let terminal=value.terminal===void 0?void 0:validateOperationTerminalV1(value.terminal);if(terminal!==void 0&&terminal.status!==value.status)throw new Error(t("Operation snapshot.terminal.status must match status"));value.instanceId!==void 0&&assertNonEmptyString(value.instanceId,"Operation snapshot.instanceId"),value.sessionId!==void 0&&assertNonEmptyString(value.sessionId,"Operation snapshot.sessionId");let inputRevision=value.inputRevision===void 0?void 0:validateSessionRevisionV1(value.inputRevision);if(inputRevision!==void 0&&value.sessionId!==void 0&&inputRevision.sessionId!==value.sessionId)throw new Error(t("Operation snapshot.inputRevision.sessionId must match sessionId"));return detachedFreeze({version:1,operationId:value.operationId,kind:value.kind,status:value.status,...terminal===void 0?{}:{terminal},...value.instanceId===void 0?{}:{instanceId:value.instanceId},...value.sessionId===void 0?{}:{sessionId:value.sessionId},...inputRevision===void 0?{}:{inputRevision}})}function buildOperationSnapshotV1(input){return validateOperationSnapshotV1(input)}function validateCommandRequestV1(value){if(assertPlainRecord(value,"Command request"),assertExactKeys(value,["version","operationId","idempotencyKey","command","target","input","hostContext"],["expectedRevision"],"Command request"),value.version!==1)throw new Error(t("Command request.version must be 1"));assertNonEmptyString(value.operationId,"Command request.operationId"),assertNonEmptyString(value.idempotencyKey,"Command request.idempotencyKey"),assertNonEmptyString(value.command,"Command request.command"),assertNonEmptyString(value.target,"Command request.target"),assertJsonValue(value.input,"Command request.input");let expectedRevision=value.expectedRevision===void 0?void 0:validateSessionRevisionV1(value.expectedRevision);if(expectedRevision!==void 0&&expectedRevision.sessionId!==value.target)throw new Error(t("Command request.expectedRevision.sessionId does not match target"));let hostContext=validateHostContextV1(value.hostContext);return detachedFreeze({version:1,operationId:value.operationId,idempotencyKey:value.idempotencyKey,command:value.command,target:value.target,input:value.input,...expectedRevision===void 0?{}:{expectedRevision},hostContext})}function buildCommandRequestV1(input){return validateCommandRequestV1({...input,version:input.version??1})}function validateCommandAdmissionV1(value){if(assertPlainRecord(value,"Command admission"),assertExactKeys(value,["version","status","request"],["operation","error"],"Command admission"),value.version!==1)throw new Error(t("Command admission.version must be 1"));if(value.status!=="accepted"&&value.status!=="existing"&&value.status!=="rejected")throw new Error(t("Command admission.status is invalid"));let request=validateCommandRequestV1(value.request),operation=value.operation===void 0?void 0:validateOperationSnapshotV1(value.operation);if((value.status==="accepted"||value.status==="existing")&&operation===void 0)throw new Error(t("Command admission accepted status requires an operation"));if(value.status==="rejected"&&value.error===void 0)throw new Error(t("Command admission rejected status requires an error"));let error=value.error===void 0?void 0:validateErrorEnvelopeV1(value.error);return detachedFreeze({version:1,status:value.status,request,...operation===void 0?{}:{operation},...error===void 0?{}:{error}})}function canonicalJson(value){if(value===null||typeof value!="object")return JSON.stringify(value);if(Array.isArray(value))return`[${value.map(canonicalJson).join(",")}]`;let record=value;return`{${Object.keys(record).sort().map(key=>`${JSON.stringify(key)}:${canonicalJson(record[key])}`).join(",")}}`}function sameRevision(left,right){return left.sessionId===right.sessionId&&left.sequence===right.sequence&&left.leafId===right.leafId}function commandError(code,message,details){return buildErrorEnvelopeV1({version:1,code,message,retryable:!1,...details===void 0?{}:{details}})}function rejectedAdmission(request,error){return detachedFreeze({version:1,status:"rejected",request,error})}function createCommandOperationRegistryV1(){let entries=new Map,read=operationId=>{assertNonEmptyString(operationId,"operationId");let entry=entries.get(operationId);if(!entry)throw new Error(t("Operation is not retained: {operationId}",{operationId}));return entry},write=(entry,operation)=>(entry.operation=operation,operation),terminal=entry=>entry.operation.terminal!==void 0;return Object.freeze({admit(input,currentRevision){let request=validateCommandRequestV1(input),current=currentRevision===void 0?void 0:validateSessionRevisionV1(currentRevision),fingerprint=canonicalJson(request),existing=entries.get(request.operationId);if(existing)return existing.fingerprint===fingerprint?detachedFreeze({version:1,status:"existing",request,operation:existing.operation}):rejectedAdmission(request,commandError("idempotency_conflict",`Operation ID is already bound to different input: ${request.operationId}`));if(request.expectedRevision!==void 0){if(current===void 0)return rejectedAdmission(request,commandError("revision_unavailable",`Current revision is required for: ${request.target}`));if(!sameRevision(request.expectedRevision,current))return rejectedAdmission(request,commandError("revision_conflict",`Expected revision does not match: ${request.target}`,{expectedRevision:request.expectedRevision,currentRevision:current}))}let operation=buildOperationSnapshotV1({version:1,operationId:request.operationId,kind:`command:${request.command}`,status:"queued",...request.expectedRevision===void 0?{}:{sessionId:request.expectedRevision.sessionId,inputRevision:request.expectedRevision}});return entries.set(request.operationId,{request,fingerprint,operation}),detachedFreeze({version:1,status:"accepted",request,operation})},start(operationId){let entry=read(operationId);return entry.operation.status!=="queued"?entry.operation:write(entry,buildOperationSnapshotV1({...entry.operation,status:"running"}))},complete(operationId,terminalSnapshot){let entry=read(operationId),nextTerminal=validateOperationTerminalV1(terminalSnapshot);if(terminal(entry)){if(canonicalJson(entry.operation.terminal)!==canonicalJson(nextTerminal))throw new Error(t("Operation already has a different terminal result: {operationId}",{operationId}));return entry.operation}return write(entry,buildOperationSnapshotV1({...entry.operation,status:nextTerminal.status,terminal:nextTerminal}))},cancel(operationId){let entry=read(operationId);return terminal(entry)?entry.operation:write(entry,buildOperationSnapshotV1({...entry.operation,status:"cancelled",terminal:{version:1,status:"cancelled",error:commandError("operation_cancelled",`Operation cancelled: ${operationId}`)}}))},get(operationId){return assertNonEmptyString(operationId,"operationId"),entries.get(operationId)?.operation},release(operationId){assertNonEmptyString(operationId,"operationId"),entries.delete(operationId)}})}function buildCanonicalContractVectorsV1(){let hostContext=buildHostContextV1({mode:"full-control",features:["agent.run","session.snapshot"],transports:["in-process"]}),contract=buildAgentCapabilityContractV1({contractId:AGENT_CAPABILITY_CONTRACT_ID,capabilities:[{id:"agent.run",version:1}],hostContext}),profile=buildAgentProfileV1({id:"coding-agent",version:1,rootAgent:"coding-agent.root",requiredPlugins:["bootstrap-tools"],optionalPlugins:["bootstrap-skills"],defaults:{mode:"full-control",context:{strategy:"default"}}}),artifact=buildArtifactRefV1({sessionId:"session-vector-1",operationId:"vector-operation-1",artifactId:"artifact-vector-1",kind:"operation_record",mediaType:"application/json",sizeBytes:13,truncated:!1,createdAt:0}),revision=buildSessionRevisionV1({version:1,sessionId:"session-vector-1",sequence:0,leafId:null}),definition=buildAgentDefinitionSnapshotV1({version:1,id:"coding-agent.root",definitionVersion:1,role:"root-agent-controller",capabilities:[{id:"agent.run",version:1}],owner:"coding-agent"}),instance=buildAgentInstanceSnapshotV1({version:1,id:"instance-vector-1",definitionId:definition.id,definitionVersion:definition.definitionVersion,role:definition.role,status:"created",revision:0}),session=buildSessionSnapshotV1({version:1,sessionId:revision.sessionId,revision}),error=buildErrorEnvelopeV1({version:1,code:"provider_error",message:"provider failed",retryable:!0}),command=buildCommandRequestV1({operationId:"vector-operation-1",idempotencyKey:"vector-request-1",command:"agent.run",target:"session-vector-1",input:{prompt:"vector"},expectedRevision:{version:1,sessionId:"session-vector-1",sequence:0,leafId:null},hostContext}),registry=createCommandOperationRegistryV1(),accepted=registry.admit(command,command.expectedRevision);if(accepted.status!=="accepted"||accepted.operation===void 0)throw new Error(t("Canonical contract vector admission failed"));let running=registry.start(command.operationId),terminal=registry.complete(command.operationId,{version:1,status:"succeeded",result:{ok:!0}}),event=buildEventEnvelopeV1({id:"vector-event-1",deliveryId:"vector-delivery-1",type:"operation.end",source:"canonical-vector",category:"authoritative",deliveryGuarantee:"best-effort",timestamp:0,operationId:command.operationId,correlationId:command.operationId,data:{version:1,operationId:command.operationId,operationKind:command.command,status:"succeeded"}});return detachedFreeze({version:1,contract,definition,instance,session,revision,error,profile,artifact,command,accepted,running,terminal,event})}function buildCanonicalContractFixtureVectorsV1(){let base=buildCanonicalContractVectorsV1(),registry=createCommandOperationRegistryV1(),request=buildCommandRequestV1({operationId:"fixture-operation-1",idempotencyKey:"fixture-request-1",command:"agent.run",target:"session-fixture-1",input:{prompt:"fixture"},expectedRevision:{version:1,sessionId:"session-fixture-1",sequence:1,leafId:"leaf-1"},hostContext:base.contract.hostContext});registry.admit(request,request.expectedRevision);let existing=registry.admit(request,request.expectedRevision),idempotencyConflict=registry.admit({...request,input:{prompt:"different"}},request.expectedRevision),revisionConflict=registry.admit({...request,operationId:"fixture-operation-2",idempotencyKey:"fixture-request-2"},{version:1,sessionId:"session-fixture-1",sequence:2,leafId:"leaf-2"}),cancelled=registry.cancel(request.operationId),terminalReplay=registry.complete(request.operationId,cancelled.terminal);if(registry.admit(buildCommandRequestV1({...request,operationId:"fixture-operation-failed",idempotencyKey:"fixture-request-failed"}),request.expectedRevision).status!=="accepted")throw new Error(t("Canonical contract failed vector admission failed"));let failedTerminal=registry.complete("fixture-operation-failed",{version:1,status:"failed",error:buildErrorEnvelopeV1({version:1,code:"provider_error",message:"provider failed",retryable:!0})});if(registry.admit(buildCommandRequestV1({...request,operationId:"fixture-operation-timeout",idempotencyKey:"fixture-request-timeout"}),request.expectedRevision).status!=="accepted")throw new Error(t("Canonical contract timeout vector admission failed"));let timedOutTerminal=registry.complete("fixture-operation-timeout",{version:1,status:"timed_out",error:buildErrorEnvelopeV1({version:1,code:"operation_timeout",message:"operation timed out",retryable:!0})}),unsupported=buildUnsupportedCapabilityV1({id:"fixture.missing",version:1}),observation=buildEventEnvelopeV1({id:"fixture-event-1",deliveryId:"fixture-delivery-1",type:"fixture.observation",source:"canonical-vector",timestamp:0,data:{observed:!0}}),correlated=buildEventEnvelopeV1({id:"fixture-event-correlated",deliveryId:"fixture-delivery-correlated",type:"operation.end",source:"canonical-vector",category:"authoritative",timestamp:0,operationId:"fixture-operation-1",correlationId:"fixture-operation-1",data:{status:"cancelled"}}),steer=buildCommandRequestV1({operationId:"fixture-operation-steer",idempotencyKey:"fixture-request-steer",command:"session.steer",target:"session-fixture-1",input:{text:"steer"},expectedRevision:request.expectedRevision,hostContext:base.contract.hostContext}),operationStep=buildEventEnvelopeV1({id:"fixture-event-step",deliveryId:"fixture-delivery-step",type:"operation.step",source:"canonical-vector",category:"progress",timestamp:0,operationId:"fixture-operation-steer",correlationId:"fixture-operation-steer",data:{version:1,operationId:"fixture-operation-steer",operationKind:"session.steer",step:1,message:"accepted"}}),compatibilityRequirements=overrides=>buildContractCompatibilityRequirementsV1({contractId:AGENT_CAPABILITY_CONTRACT_ID,version:1,mode:"full-control",features:[],transports:[],capabilities:[],...overrides}),compatibilityAccepted=checkContractCompatibilityV1(base.contract,compatibilityRequirements({features:["agent.run","session.snapshot"],transports:["in-process"],capabilities:[{id:"agent.run",version:1}]})),compatibilityContractUnsupported=checkContractCompatibilityV1(base.contract,compatibilityRequirements({version:2})),compatibilityCapabilityVersionUnsupported=checkContractCompatibilityV1(base.contract,compatibilityRequirements({capabilities:[{id:"agent.run",version:2}]})),compatibilityFeatureSubset=checkContractCompatibilityV1(base.contract,compatibilityRequirements({features:["agent.run","session.compact"]}));return detachedFreeze([{id:"agent-definition",value:base.definition},{id:"agent-instance",value:base.instance},{id:"session-snapshot",value:base.session},{id:"session-revision",value:base.revision},{id:"error-envelope",value:base.error},{id:"profile-snapshot",value:base.profile},{id:"artifact-reference",value:base.artifact},{id:"command-success",value:base.terminal},{id:"command-failed-terminal",value:failedTerminal},{id:"command-timed-out-terminal",value:timedOutTerminal},{id:"command-idempotency-replay",value:existing},{id:"command-idempotency-conflict",value:idempotencyConflict},{id:"command-revision-conflict",value:revisionConflict},{id:"command-cancel-terminal",value:cancelled},{id:"command-terminal-replay",value:terminalReplay},{id:"capability-unsupported",value:unsupported},{id:"event-without-operation",value:observation},{id:"event-with-operation",value:correlated},{id:"command-steer",value:steer},{id:"event-operation-step",value:operationStep},{id:"compatibility-accepted",value:compatibilityAccepted},{id:"compatibility-contract-unsupported",value:compatibilityContractUnsupported},{id:"compatibility-capability-version-unsupported",value:compatibilityCapabilityVersionUnsupported},{id:"compatibility-feature-subset",value:compatibilityFeatureSubset}])}function validateEventEnvelopeV1(value){if(assertPlainRecord(value,"Event envelope"),assertExactKeys(value,["version","id","deliveryId","type","source","category","deliveryGuarantee","timestamp","data"],["operationId","correlationId","causationId"],"Event envelope"),value.version!==1)throw new Error(t("Event envelope.version must be 1"));if(assertNonEmptyString(value.id,"Event envelope.id"),assertNonEmptyString(value.deliveryId,"Event envelope.deliveryId"),assertNonEmptyString(value.type,"Event envelope.type"),assertNonEmptyString(value.source,"Event envelope.source"),value.category!=="authoritative"&&value.category!=="progress"&&value.category!=="observation")throw new Error(t("Event envelope.category is invalid"));if(value.deliveryGuarantee!=="best-effort"&&value.deliveryGuarantee!=="at-least-once")throw new Error(t("Event envelope.deliveryGuarantee is invalid"));if(assertNonNegativeSafeInteger(value.timestamp,"Event envelope.timestamp"),assertJsonValue(value.data,"Event envelope.data"),value.operationId!==void 0&&assertNonEmptyString(value.operationId,"Event envelope.operationId"),value.correlationId!==void 0&&assertNonEmptyString(value.correlationId,"Event envelope.correlationId"),value.causationId!==void 0&&assertNonEmptyString(value.causationId,"Event envelope.causationId"),value.operationId===void 0&&value.correlationId!==void 0)throw new Error(t("Event envelope.correlationId requires a real operationId"));if(value.operationId!==void 0&&value.correlationId===void 0)throw new Error(t("Event envelope.operationId requires correlationId"));return detachedFreeze({version:1,id:value.id,deliveryId:value.deliveryId,type:value.type,source:value.source,category:value.category,deliveryGuarantee:value.deliveryGuarantee,timestamp:value.timestamp,data:value.data,...value.operationId===void 0?{}:{operationId:value.operationId},...value.correlationId===void 0?{}:{correlationId:value.correlationId},...value.causationId===void 0?{}:{causationId:value.causationId}})}function buildEventEnvelopeV1(input){return validateEventEnvelopeV1({...input,version:input.version??1,category:input.category??"observation",deliveryGuarantee:input.deliveryGuarantee??"best-effort"})}function buildUnsupportedCapabilityV1(capability){let reference=validateCapabilityRefV1(capability),error=buildErrorEnvelopeV1({version:1,code:"unsupported_capability",message:`Capability is unsupported: ${reference.id}@${reference.version}`,retryable:!1});return detachedFreeze({status:"unsupported",capability:reference,error})}function resolveCapabilityV1(requested,supported){let reference=validateCapabilityRefV1(requested);return validateCapabilityRefs(supported,"Supported capabilities").some(candidate=>candidate.id===reference.id&&candidate.version===reference.version)?detachedFreeze({status:"supported",capability:reference}):buildUnsupportedCapabilityV1(reference)}function assertCapabilitySupportedV1(requested,supported){let resolution=resolveCapabilityV1(requested,supported);if(resolution.status==="unsupported")throw new Error(resolution.error.message);return resolution.capability}var validateAgentCapabilityContract=validateAgentCapabilityContractV1,buildAgentCapabilityContract=buildAgentCapabilityContractV1,validateEventEnvelope=validateEventEnvelopeV1,buildEventEnvelope=buildEventEnvelopeV1;function detachedFreeze2(value,seen=new WeakMap){if(value===null||typeof value!="object")return value;let existing=seen.get(value);if(existing!==void 0)return existing;if(Array.isArray(value)){let copy2=[];seen.set(value,copy2);for(let child of value)copy2.push(detachedFreeze2(child,seen));return Object.freeze(copy2)}let copy=Object.create(null);seen.set(value,copy);for(let[key,child]of Object.entries(value))copy[key]=detachedFreeze2(child,seen);return Object.freeze(copy)}function assertActive(disposed,label){if(disposed)throw new Error(t("Embedded SDK binding is disposed: {label}",{label}))}function errorEnvelope(error,code){let message=error instanceof Error?error.message:String(error);return buildErrorEnvelopeV1({version:1,code,message,retryable:!1,...error instanceof Error?{name:error.name}:{}})}function agentDefinitionSnapshot(definition){return buildAgentDefinitionSnapshotV1({version:1,id:definition.id,definitionVersion:definition.version,role:definition.role,capabilities:[],...definition.owner===void 0?{}:{owner:definition.owner}})}function agentInstanceSnapshot(snapshot){return buildAgentInstanceSnapshotV1({version:1,id:snapshot.id,definitionId:snapshot.definitionId,definitionVersion:snapshot.definitionVersion,role:snapshot.role,status:snapshot.status,revision:snapshot.revision,...snapshot.parentInstanceId===void 0?{}:{parentInstanceId:snapshot.parentInstanceId},...snapshot.leaseOwner===void 0?{}:{leaseOwner:snapshot.leaseOwner}})}function resultSnapshot(result){return result.status==="succeeded"?detachedFreeze2({status:"succeeded",output:canonicalOutput(result.output,`wait:${result.revision}`),revision:result.revision}):detachedFreeze2({status:result.status,revision:result.revision,...result.error===void 0?{}:{error:errorEnvelope(result.error,`agent_${result.status}`)}})}function canonicalOutput(value,operationId){return buildOperationSnapshotV1({version:1,operationId,kind:"agent.run",status:"succeeded",terminal:{version:1,status:"succeeded",result:value}}),detachedFreeze2(value)}function canonicalInput(value){if(value===void 0)throw new Error(t("Embedded SDK run input must be JSON-compatible"));return buildOperationSnapshotV1({version:1,operationId:"embedded-sdk:input",kind:"agent.run",status:"succeeded",terminal:{version:1,status:"succeeded",result:value}}),detachedFreeze2(value)}function createEmbeddedSessionBindingV1(session){if(!session.getRevision)throw new Error(t("Embedded SDK session requires revision support"));let getRevision=()=>detachedFreeze2(session.getRevision()),context=session.getContextSnapshot&&session.commitContext?Object.freeze({version:1,get:()=>detachedFreeze2(session.getContextSnapshot()),commit:request=>session.commitContext(request)}):void 0;return Object.freeze({version:1,getSessionId:()=>session.getSessionId(),getRevision,snapshot:()=>buildSessionSnapshotV1({version:1,sessionId:session.getSessionId(),revision:getRevision()}),getMessages:()=>detachedFreeze2(session.getMessages()),getBranchEntries:()=>detachedFreeze2(session.getBranchEntries()),isIdle:()=>session.isIdle(),prompt:text=>session.prompt(text),steer:text=>session.steer?session.steer(text):Promise.reject(new Error("Embedded SDK session does not support steer")),abort:()=>session.abort(),waitForIdle:()=>session.waitForIdle(),...context===void 0?{}:{context}})}function createEmbeddedSdkBindingV1(options={}){let composition=options.composition??createAgentCompositionRuntime(),ownsComposition=options.ownsComposition??options.composition===void 0,defaultFeatures=["agent-composition-v1",...options.session===void 0?[]:["session","session-revision-v1","context"]],hostContext=detachedFreeze2({mode:options.mode??"full-control",features:[...options.features??defaultFeatures].sort(),transports:["in-process"]}),session=options.session===void 0?void 0:createEmbeddedSessionBindingV1(options.session),contract=buildAgentCapabilityContractV1({contractId:"agent-forge/agent-capability-contract",capabilities:[],hostContext}),definitions=new Map,instances=new Map,listeners=new Map,sequence=0,disposePromise,disposed=!1,nextId=kind=>(sequence+=1,options.idFactory?.(kind,sequence)??`embedded-sdk:${kind}:${sequence}`),emit=(type,data,operationId)=>{let event=buildEventEnvelopeV1({id:nextId("event"),deliveryId:nextId("delivery"),type,source:"embedded-sdk",timestamp:options.clock?.()??0,category:type===OPERATION_START_EVENT_ID||type===OPERATION_CANCEL_EVENT_ID||type===OPERATION_END_EVENT_ID?"authoritative":"observation",deliveryGuarantee:"best-effort",data,...operationId===void 0?{}:{operationId,correlationId:operationId}});for(let listener of listeners.values())try{listener(event)}catch{}},resolveDefinition=definition=>{let snapshot="snapshot"in definition?definition.snapshot:definition,definitionVersion="definitionVersion"in snapshot?snapshot.definitionVersion:snapshot.version,resolved=definitions.get(`${snapshot.id}@${definitionVersion}`);if(resolved)return resolved;if(options.composition!==void 0)return composition.get(snapshot.id,definitionVersion);throw new Error(t("Embedded SDK has no defined Agent: {id}@{version}",{id:snapshot.id,version:definitionVersion}))},binding={version:1,contract,hostContext,...session===void 0?{}:{session},define(definition){assertActive(disposed,"define");let registered=composition.define(definition);return definitions.set(`${registered.id}@${registered.version}`,registered),detachedFreeze2({snapshot:agentDefinitionSnapshot(registered)})},create(definition,instanceOptions={}){assertActive(disposed,"create");let raw=composition.create(resolveDefinition(definition),instanceOptions),instanceDisposed=!1,instanceDisposePromise,leases=new WeakMap,wrapper={id:raw.id,snapshot:()=>(assertActive(disposed||instanceDisposed,raw.id),agentInstanceSnapshot(raw.snapshot())),acquireControllerLease:async owner=>{assertActive(disposed||instanceDisposed,raw.id);let lease=await raw.acquireControllerLease(owner),projected=Object.freeze({id:lease.id,instanceId:lease.instanceId,owner:lease.owner,revision:lease.revision,isActive:()=>!disposed&&!instanceDisposed&&lease.isActive(),release:async()=>{assertActive(disposed||instanceDisposed,raw.id),await lease.release()}});return leases.set(projected,lease),projected},run:(input,runOptions)=>{assertActive(disposed||instanceDisposed,raw.id);let lease=leases.get(runOptions.lease);if(!lease)throw new Error(t("Embedded SDK lease does not belong to Agent instance: {id}",{id:raw.id}));let operation=raw.run(canonicalInput(input),{lease,signal:runOptions.signal}),terminal,cancelEmitted=!1,reportCancel=()=>{cancelEmitted||(cancelEmitted=!0,emit(OPERATION_CANCEL_EVENT_ID,validateOperationCancelEventDataV1({version:1,operationId:operation.id,operationKind:"agent.run"}),operation.id))};operation.signal.addEventListener("abort",reportCancel,{once:!0}),operation.signal.aborted&&reportCancel(),runOptions.signal?.aborted||emit(OPERATION_START_EVENT_ID,validateOperationStartEventDataV1({version:1,operationId:operation.id,operationKind:"agent.run"}),operation.id);let result=operation.result.then(value=>{try{let output=canonicalOutput(value,operation.id);return terminal={version:1,status:"succeeded",result:output},emit(OPERATION_END_EVENT_ID,validateOperationEndEventDataV1({version:1,operationId:operation.id,operationKind:"agent.run",status:"succeeded"}),operation.id),output}catch(error){throw terminal={version:1,status:"failed",error:errorEnvelope(error,"agent_invalid_result")},emit(OPERATION_END_EVENT_ID,validateOperationEndEventDataV1({version:1,operationId:operation.id,operationKind:"agent.run",status:"failed",errorMessage:error instanceof Error?error.message:String(error)}),operation.id),error}},error=>{let status=operation.status()==="cancelled"?"cancelled":"failed";throw terminal={version:1,status,error:errorEnvelope(error,`agent_${status}`)},emit(OPERATION_END_EVENT_ID,validateOperationEndEventDataV1({version:1,operationId:operation.id,operationKind:"agent.run",status,errorMessage:error instanceof Error?error.message:String(error)}),operation.id),error});return Object.freeze({id:operation.id,result,snapshot:()=>buildOperationSnapshotV1({version:1,operationId:operation.id,kind:"agent.run",status:terminal?.status??operation.status(),...terminal===void 0&&operation.status()==="cancelled"?{terminal:{version:1,status:"cancelled",error:errorEnvelope(new Error("Operation cancelled"),"agent_cancelled")}}:terminal===void 0?{}:{terminal},instanceId:raw.id}),cancel:async reason=>{assertActive(disposed||instanceDisposed,raw.id),!(operation.status()!=="queued"&&operation.status()!=="running")&&await operation.cancel(reason)}})},wait:async()=>detachedFreeze2(resultSnapshot(await raw.wait())),cancel:async reason=>{assertActive(disposed||instanceDisposed,raw.id),await raw.cancel(reason)},dispose:async()=>(instanceDisposePromise??=(async()=>{instanceDisposed||(instanceDisposed=!0,await raw.dispose(),instances.delete(raw.id))})(),instanceDisposePromise)};return instances.set(raw.id,wrapper),Object.freeze(wrapper)},listInstances:()=>Object.freeze([...instances.values()].map(instance=>instance.snapshot()).sort((left,right)=>left.id.localeCompare(right.id))),subscribe(listener){assertActive(disposed,"subscribe");let id=`embedded-sdk:subscription:${++sequence}`,released=!1;return listeners.set(id,listener),Object.freeze({id,dispose:()=>{released||(released=!0,listeners.delete(id))}})},dispose:async()=>(disposePromise??=(async()=>{if(disposed)return;disposed=!0;let failures=[];for(let instance of[...instances.values()])try{await instance.dispose()}catch(error){failures.push(error)}if(listeners.clear(),ownsComposition&&"disposeDefinitions"in composition)try{composition.disposeDefinitions([...definitions.values()])}catch(error){failures.push(error)}if(definitions.clear(),failures.length===1)throw failures[0];if(failures.length>1)throw new AggregateError(failures,t("Embedded SDK disposal failed"))})(),disposePromise)};return Object.freeze(binding)}var createEmbeddedSdkBinding=createEmbeddedSdkBindingV1;import{EventEmitter}from"node:events";function createEventBus(){let emitter=new EventEmitter;return{emit:(channel,data)=>{emitter.emit(channel,data)},on:(channel,handler)=>{let safeHandler=async data=>{try{await handler(data)}catch(err){console.error(`Event handler error (${channel}):`,err)}};return emitter.on(channel,safeHandler),()=>emitter.off(channel,safeHandler)},clear:()=>{emitter.removeAllListeners()}}}var ModelRegistry=class{runtime;constructor(runtime){this.runtime=runtime}refresh(options){return this.runtime.refresh(options)}getError(){return this.runtime.getError()}getAll(){return[...this.runtime.getModels()]}getAvailable(){return[...this.runtime.getAvailableSnapshot()]}find(provider,modelId){return this.runtime.getModel(provider,modelId)}hasConfiguredAuth(model){return this.runtime.hasConfiguredAuth(model.provider)}async getApiKeyAndHeaders(model){try{let resolution=await this.runtime.getAuth(model);if(!resolution){let compatibility=this.runtime.getCompatibilityRequestConfig(model);return compatibility.authHeader?{ok:!1,error:`No API key found for "${model.provider}"`}:{ok:!0,headers:compatibility.headers}}return{ok:!0,apiKey:resolution.auth.apiKey,headers:resolution.auth.headers,...resolution.auth.baseUrl?{baseUrl:resolution.auth.baseUrl}:{},env:resolution.env}}catch(error){let cause=error instanceof Error?error.cause:void 0,message=cause instanceof Error?cause.message:error instanceof Error?error.message:String(error);return{ok:!1,error:message==="authHeader requires a resolved API key"?`No API key found for "${model.provider}"`:message}}}getProviderAuthStatus(provider){return this.runtime.getProviderAuthStatus(provider)}getProvider(provider){return this.runtime.getProvider(provider)}stream(model,context,options){return this.runtime.stream(model,context,options)}complete(model,context,options){return this.runtime.complete(model,context,options)}streamSimple(model,context,options){return this.runtime.streamSimple(model,context,options)}getProviderDisplayName(provider){return this.runtime.getProvider(provider)?.name??provider}getProviderAuth(provider){return this.runtime.getAuth(provider)}async getApiKeyForProvider(provider){try{return(await this.runtime.getAuth(provider))?.auth.apiKey}catch{return}}isUsingOAuth(model){return this.runtime.isUsingOAuth(model.provider)}registerProvider(providerOrName,config){if(typeof providerOrName=="string"){if(!config)throw new Error(t("Provider config is required when registering by name"));this.runtime.registerProvider(providerOrName,config);return}this.runtime.registerNativeProvider(providerOrName)}unregisterProvider(providerName){this.runtime.unregisterProvider(providerName)}getRegisteredProviderConfig(providerName){return this.runtime.getRegisteredProviderConfig(providerName)}getRegisteredNativeProvider(providerName){return this.runtime.getRegisteredNativeProvider(providerName)}getRegisteredProviderIds(){return this.runtime.getRegisteredProviderIds()}};function retryBackoffMs(policy,attempt){return Math.min(policy.baseWaitMs*2**(attempt-1),policy.maxWaitMs)}function createAgentRetryScheduler(){let terminalStates=new Map;return{schedule(input){let existing=terminalStates.get(input.operationId);if(existing)return{...existing,duplicate:!0};let signal=input.signal,now=input.now??(()=>0),sleep=input.sleep??(()=>{}),attempts=[],finish=outcome=>(terminalStates.set(input.operationId,outcome),outcome);for(let attempt=1;attempt<=input.policy.attemptLimit;attempt+=1){if(signal?.aborted)return finish({status:"cancelled",operationId:input.operationId,attempts});let at=now(),step=input.task(attempt);if(step.ok)return attempts.push({attempt,at,ok:!0,waitedMs:0}),finish({status:"succeeded",operationId:input.operationId,result:step.result,attempts});if(!step.retryable)return attempts.push({attempt,at,ok:!1,failure:step.reason,retryable:!1,waitedMs:0}),finish({status:"failed_terminal",operationId:input.operationId,reason:step.reason,attempts});let waitedMs=retryBackoffMs(input.policy,attempt);if(attempts.push({attempt,at,ok:!1,failure:step.reason,retryable:!0,waitedMs}),attempt<input.policy.attemptLimit&&(sleep(waitedMs),signal?.aborted))return finish({status:"cancelled",operationId:input.operationId,attempts})}return finish({status:"exhausted",operationId:input.operationId,attempts})},terminalOf(operationId){return terminalStates.get(operationId)}}}function createAutoCompactionExecutor(options){let coordinator=options.coordinator,policy=options.policy,inProgress=!1;return{get inProgress(){return inProgress},maybeCompact(input){if(!policy.enabled)return{status:"disabled"};if(inProgress)return{status:"busy"};if(input.currentTokens<policy.tokenThreshold)return{status:"below_threshold",currentTokens:input.currentTokens,threshold:policy.tokenThreshold};inProgress=!0;try{let staged=coordinator.stage({operationId:input.operationId,expectedRevision:coordinator.currentRevision,payload:null});if(staged.status==="stale")return{status:"stale",currentRevision:staged.currentRevision};if(staged.status==="duplicate")return{status:"cancelled"};if(input.signal?.aborted)return coordinator.cancelStage(staged.staged.token),{status:"cancelled"};let summary;try{summary=input.summarize(input.signal)}catch(error){return coordinator.cancelStage(staged.staged.token),{status:"summary_failed",reason:error instanceof Error?error.message:String(error)}}if(input.signal?.aborted)return coordinator.cancelStage(staged.staged.token),{status:"cancelled"};let outcome=coordinator.commitStage({token:staged.staged.token,apply:()=>{}});return outcome.status==="stale"?{status:"stale",currentRevision:outcome.currentRevision}:outcome.status==="committed"?{status:"completed",revision:outcome.revision,summary}:(coordinator.cancelStage(staged.staged.token),{status:"cancelled"})}finally{inProgress=!1}}}}function createBranchStateMigration(){return{migrate({entries,fromBranch,toBranch}){let source=entries.filter(entry=>entry.branch===fromBranch);return source.length===0?{status:"empty_source",fromBranch}:{status:"migrated",fromBranch,toBranch,migrated:Object.freeze(source.map(entry=>({key:entry.key,value:entry.value})))}},scan(entries,branch){return Object.freeze(entries.filter(entry=>entry.branch===branch))}}}function createReloadTransaction(){return{reload(items){let failures=[];for(let[index,item]of items.entries()){let failure=item.validate();failure!==null&&failures.push({index,reason:failure})}if(failures.length>0)return{status:"rolled_back",failures:Object.freeze(failures)};for(let item of items)item.commit();return{status:"committed",count:items.length}}}}function createHostCheckpointCoordinator(options={}){let revision=options.startRevision??0,staged=new Map,committed=new Map,tokenSequence=0;return{get currentRevision(){return revision},stage(input){if(typeof input.operationId!="string"||input.operationId.trim().length===0)throw new Error(t("Checkpoint operationId must be a non-empty string"));let appliedRevision=committed.get(input.operationId);if(appliedRevision!==void 0)return{status:"duplicate",revision:appliedRevision};if(input.expectedRevision!==revision)return{status:"stale",currentRevision:revision};tokenSequence+=1;let token=`ckpt-${tokenSequence}`,entry={operationId:input.operationId,expectedRevision:input.expectedRevision,payload:input.payload,state:"staged"};return staged.set(token,entry),{status:"staged",staged:{token,operationId:input.operationId,expectedRevision:input.expectedRevision,currentRevision:revision}}},commitStage({token,apply}){let entry=staged.get(token);if(!entry)return{status:"unknown_token"};if(entry.state==="cancelled")return{status:"cancelled"};if(entry.expectedRevision!==revision)return staged.delete(token),{status:"stale",currentRevision:revision};try{apply(entry.payload,revision+1)}catch(error){return staged.delete(token),{status:"write_failed",reason:error instanceof Error?error.message:String(error)}}return revision+=1,committed.set(entry.operationId,revision),staged.delete(token),{status:"committed",revision}},cancelStage(token){let entry=staged.get(token);return entry?committed.has(entry.operationId)?{status:"already_committed"}:(entry.state="cancelled",{status:"cancelled"}):{status:"unknown_token"}},committedOperationIds(){return Object.freeze([...committed.keys()].sort())}}}function createManualCompactionExecutor(options){let coordinator=options.coordinator,state="idle",currentOperationId;return{get state(){return state},requestCompaction(input){if(state==="in_progress")return{status:"busy",currentOperationId:currentOperationId??"unknown"};if(input.pluginId.trim().length===0)throw new Error(t("Compaction pluginId must be a non-empty string"));state="in_progress",currentOperationId=input.operationId;try{let staged=coordinator.stage({operationId:input.operationId,expectedRevision:coordinator.currentRevision,payload:null});if(staged.status==="stale")return{status:"stale",currentRevision:staged.currentRevision};if(staged.status==="duplicate")return{status:"completed",revision:staged.revision,summary:{duplicate:!0}};let summary;try{summary=input.summarize()}catch(error){return coordinator.cancelStage(staged.staged.token),{status:"summary_failed",reason:error instanceof Error?error.message:String(error)}}let outcome=coordinator.commitStage({token:staged.staged.token,apply:(payload,revision)=>{}});return outcome.status==="stale"?{status:"stale",currentRevision:outcome.currentRevision}:outcome.status==="committed"?{status:"completed",revision:outcome.revision,summary}:{status:"summary_failed",reason:`Unexpected checkpoint outcome: ${outcome.status}`}}finally{state="idle",currentOperationId=void 0}}}}function createOutputReducer(){return{fold(records){let groups=[],pendingTool=null,flushTool=()=>{pendingTool&&(groups.push(pendingTool),pendingTool=null)};for(let record of records){if(record.channel==="tool"&&record.correlationId!==void 0){let isCall=record.severity==="info"&&record.summary.endsWith("called");pendingTool&&pendingTool.correlationId!==record.correlationId&&flushTool(),pendingTool||(pendingTool={kind:"tool",toolName:record.code??record.summary,correlationId:record.correlationId,detailsRef:`trace:${record.traceId}#call:${record.correlationId}`,calls:0,ok:0,failed:0,records:[]}),pendingTool.records.push(record),isCall?pendingTool.calls+=1:record.severity==="ok"?pendingTool.ok+=1:record.severity==="error"&&(pendingTool.failed+=1);continue}flushTool();let last=groups.at(-1);last?.kind==="records"?(last.records.push(record),last.detailsRef=`trace:${record.traceId}#records:${last.records.length}`):groups.push({kind:"records",detailsRef:`trace:${record.traceId}#records:1`,records:[record]})}flushTool();let foldedToolGroups=0,frozenGroups=groups.map(group=>{let base={...group,records:Object.freeze([...group.records])};if(base.kind==="tool"){foldedToolGroups+=1;let firstAt=base.records[0]?.at??0,lastAt=base.records.at(-1)?.at??firstAt;return Object.freeze({...base,durationMs:Math.max(lastAt-firstAt,0)})}return Object.freeze(base)});return{groups:Object.freeze(frozenGroups),totalRecords:records.length,foldedToolGroups}},unfold(folded){return Object.freeze(folded.groups.flatMap(group=>[...group.records]))}}}var INTERNAL_FIELD_KEYS=["memoryId","memoryIds","score","scores","ranking","queryPlan","budget","budgets","agentRole","pluginRole","lease","leaseId","purgeState","rawSources"];function isArtifactLike(value){return typeof value=="object"&&value!==null&&"artifactId"in value&&"sessionId"in value&&"kind"in value}function toArtifactRef(value){if(!(typeof value.sessionId!="string"||typeof value.operationId!="string"||typeof value.artifactId!="string"||typeof value.kind!="string"||typeof value.mediaType!="string"||typeof value.truncated!="boolean"||typeof value.createdAt!="number"))return{sessionId:value.sessionId,operationId:value.operationId,artifactId:value.artifactId,kind:value.kind,mediaType:value.mediaType,...typeof value.sizeBytes=="number"?{sizeBytes:value.sizeBytes}:{},truncated:value.truncated,createdAt:value.createdAt}}function createHostOutputSerializer(){return{project(input,context){if(context.policyVersion.trim().length===0)return{text:"",diagnostics:["output_projection_rejected: policyVersion must be a non-empty string"],rejected:{code:"output_projection_rejected",reason:"policyVersion must be a non-empty string"}};let redactions=[],diagnostics=[],artifacts=[],showInternal=context.surface==="inspector"&&context.inspectorAuthorized,isAllowedKey=key=>!INTERNAL_FIELD_KEYS.includes(key)||showInternal,renderValue=(key,value,path)=>{if(!isAllowedKey(key))return redactions.push(`${path}.${key}`),`[redacted:${key}]`;if(isArtifactLike(value)){let ref=toArtifactRef(value);return ref?(artifacts.push(ref),`[artifact:${ref.artifactId}]`):(diagnostics.push(`output_projection_rejected: ${path}.${key} is a malformed artifact reference`),`[unrenderable:${key}]`)}return typeof value=="string"?value:typeof value=="number"||typeof value=="boolean"?String(value):value===null?"null":Array.isArray(value)?`[${value.map(item=>renderValue(key,item,path)).join(", ")}]`:typeof value=="object"?`{${Object.entries(value).map(([nestedKey,nestedValue])=>`${nestedKey}:${renderValue(nestedKey,nestedValue,`${path}.${key}`)}`).join(", ")}}`:(diagnostics.push(`output_projection_rejected: ${path}.${key} cannot be serialized`),`[unrenderable:${key}]`)},textParts=[];for(let[key,value]of Object.entries(input)){if(key==="artifacts"&&Array.isArray(value)){for(let entry of value)if(isArtifactLike(entry)){let ref=toArtifactRef(entry);ref?artifacts.push(ref):diagnostics.push("output_projection_rejected: artifacts entry is malformed")}else diagnostics.push("output_projection_rejected: artifacts entry is malformed");continue}textParts.push(`${key}=${renderValue(key,value,"root")}`)}return{text:textParts.join(`
2
+ import{renderDiff}from"./chunks/chunk-4BD6FSZA.js";import{AgentCompositionRuntime,AgentSession,AgentSessionRuntime,ArminComponent,AssistantMessageComponent,BOOTSTRAP_LIFECYCLE_PLUGIN_ID,BashExecutionComponent,BranchSummaryMessageComponent,CAPABILITY_CALL_EVENT_ID,CAPABILITY_CALL_EVENT_VERSION,CodingAgentServerService,CodingAgentSessionRuntime,CompactionSummaryMessageComponent,CredentialSynchronizationError,CustomEditor,CustomMessageComponent,DEFAULT_COMPACTION_POLICY_NAME,DEFAULT_RETRY_POLICY_NAME,DEFAULT_SUITE_ID,DefaultPackageManager,DefaultResourceLoader,DialogEditorComponent,DialogInputComponent,DialogSelectorComponent,DurableServiceErrorV1,DynamicBorder,FooterComponent,InteractiveMode,LoginDialogComponent,MODEL_RESPONSE_EVENT_ID,MODEL_RESPONSE_EVENT_VERSION,MODEL_STREAM_EVENT_ID,MODEL_STREAM_EVENT_VERSION,ModelRuntime,ModelSelectorComponent,OAuthSelectorComponent,OPERATION_CANCEL_EVENT_ID,OPERATION_CANCEL_EVENT_VERSION,OPERATION_END_EVENT_ID,OPERATION_END_EVENT_VERSION,OPERATION_START_EVENT_ID,OPERATION_START_EVENT_VERSION,OPERATION_STEP_EVENT_ID,OPERATION_STEP_EVENT_VERSION,PLUGIN_DISPOSE_EVENT_ID,PLUGIN_DISPOSE_EVENT_VERSION,PLUGIN_READY_EVENT_ID,PLUGIN_READY_EVENT_VERSION,PluginManagerEntryComponent,RpcClient,SESSION_COMPACTION_COMMIT_EVENT_ID,SESSION_COMPACTION_COMMIT_EVENT_VERSION,SESSION_CONTEXT_REPLACED_EVENT_ID,SESSION_CONTEXT_REPLACED_EVENT_VERSION,SESSION_RELOAD_EVENT_ID,SESSION_RELOAD_EVENT_VERSION,SUITE_DELETE_CONFIRM_TOKEN,SessionSelectorComponent,SettingsManager,SettingsSelectorComponent,SkillInvocationMessageComponent,SuiteLifecycleError,SuiteResolutionError,TOOL_CALL_EVENT_ID,TOOL_CALL_EVENT_VERSION,TOOL_COMMIT_EVENT_ID,TOOL_COMMIT_EVENT_VERSION,TOOL_EXECUTE_EVENT_ID,TOOL_EXECUTE_EVENT_VERSION,TOOL_RESULT_EVENT_ID,TOOL_RESULT_EVENT_VERSION,TOOL_RESULT_RAW_EVENT_ID,TOOL_RESULT_RAW_EVENT_VERSION,TOOL_RESULT_TRANSFORM_EVENT_ID,TOOL_RESULT_TRANSFORM_EVENT_VERSION,ThinkingSelectorComponent,ToolExecutionComponent,TreeSelectorComponent,UserMessageComponent,UserMessageSelectorComponent,assembleCodingAgentServer,assembleProfile,buildProfileIdentityV1,buildResolvedAgentProfileV1,clearDanglingSuiteSettings,copyToClipboard,createAgentCompositionRuntime,createAgentSession,createAgentSessionFromServices,createAgentSessionRuntime,createAgentSessionServices,createCapabilityRuntime,createDurableService,createFileDurableStoreBackend,createFileSessionSource,createHostOutputProjector,createProfileLock,createProfileMigrationPolicy,createProfileRegistry,createStableAgentSession,createStableAgentSessionRuntime,createStdioChannelAdapter,createSuite,createSyntheticSourceInfo,deleteSuite,discoverCapabilityPluginManifests,durableLogPath,ecosystem_exports,findSuiteSessionRefs,formatSkillsForPrompt,installBootstrapLifecycle,isBuiltinSuiteId,listBuiltinPluginManifestsV1,listBuiltinPluginProfilesV1,listSuiteIds,loadCapabilityPlugin,loadCapabilityPluginFromManifest,loadCapabilityPluginSync,loadProjectContextFiles,loadSkills,loadSkillsFromDir,main,parseArgs,parseFrontmatter,parseSkillBlock,plugin_manager_controller_exports,plugin_selection_controller_exports,profileIdentitiesCompatible,projectSessionTranscript,readStoredCredential,replaceProfileLock,replaceProfilePlugin,resetSuite,resolveBuiltinPluginProfileV1,resolveCliModel,resolveModelScopeWithDiagnostics,resolvePluginCapabilityOrder,runPrintMode,runRpcMode,stableJsonDigest,startCodingAgentRemoteServer,stripFrontmatter,validateCapabilityCallEventDataV1,validateExecutionFactsV1,validateModelResponseEventDataV1,validateModelStreamEventDataV1,validateOperationCancelEventDataV1,validateOperationEndEventDataV1,validateOperationStartEventDataV1,validateOperationStepEventDataV1,validatePluginDisposeEventDataV1,validatePluginReadyEventDataV1,validateRetryScheduleV1,validateSessionCompactionCommitEventDataV1,validateSessionContextReplacedEventDataV1,validateSessionReloadEventDataV1,validateToolCallEventDataV1,validateToolCommitEventDataV1,validateToolExecuteEventDataV1,validateToolResultEventDataV1,validateToolResultRawEventDataV1,validateToolResultTransformEventDataV1,verifyProfileLock}from"./chunks/chunk-ZZCUNSGO.js";import{CONFIG_DIR_NAME,CURRENT_SESSION_VERSION,CancellableLoader,Container,DEFAULT_COMPACTION_SETTINGS,DEFAULT_MAX_BYTES,DEFAULT_MAX_LINES,EXPERIMENTAL_PUBLIC_API_VERSION,FileSessionStorageProvider,LifecycleExecuteError,LifecycleTransformError,Loader,MEMORY_RECALL_TOOL_NAME,SUMMARY_MODEL_INVOCATION_ERROR_CODES,SelectList,SessionHeaderScanLimitError,SessionManager,Spacer,Text,Theme,VERSION,buildContextEntries,buildSessionContext,calculateContextTokens,collectEntriesForBranchSummary,compact,convertToLlm,convertToPng,createDisposableRegistration,createEventEnvelope,createLocalBashOperations,createLocalShellOperations,defineTool,detachedSessionSnapshot,detectSupportedImageMimeTypeFromFile,dist_exports2 as dist_exports,estimateTokens,findCutPoint,findTurnStartIndex,formatDimensionNote,formatSize,generateBranchSummary,generateDiffString,generateSummary,generateSummaryWithUsage,generateUnifiedPatch,getAgentDir,getAvailableThemes,getDocsPath,getExamplesPath,getLanguageFromPath,getLastAssistantUsage,getLatestCompactionEntry,getMarkdownTheme,getPackageDir,getPowerShellConfig,getReadmePath,getSelectListTheme,getSessionsDir,getSettingsListTheme,getShellConfig,highlightCode,initTheme,keyHint,keyText,killProcessTree,migrateSessionEntries,parseCapabilityPluginManifest,parseSessionEntries,prepareBranchEntries,rawKeyHint,resizeImage,sanitizeBinaryOutput,serializeConversation,sessionEntryToContextMessages,shouldCompact,truncateHead,truncateLine,truncateTail,truncateToVisualLines,withFileMutationQueue}from"./chunks/chunk-F73USSXE.js";import"./chunks/chunk-JUUC5AZY.js";import"./chunks/chunk-XDUWOHPL.js";import"./chunks/chunk-3QKHSPQL.js";import{t}from"./chunks/chunk-HXGAAJQQ.js";import"./chunks/chunk-BVVSHK6W.js";import"./chunks/chunk-TRDNDS6A.js";import"./chunks/chunk-K3S6GTL7.js";import"./chunks/chunk-5LRQFZFE.js";import"./chunks/chunk-4L3WN2XY.js";function contentHash(bytes){let hash=2166136261;for(let byte of bytes)hash^=byte,hash=Math.imul(hash,16777619);return(hash>>>0).toString(36)}function toStat(entry){return{artifactId:entry.ref.artifactId,sessionId:entry.ref.sessionId,operationId:entry.ref.operationId,kind:entry.ref.kind,mediaType:entry.ref.mediaType,sizeBytes:entry.ref.sizeBytes,state:entry.ended?"ended":"available",...entry.ended?{endReason:entry.endReason}:{}}}function createArtifactStore(options={}){let now=options.now??(()=>Date.now()),artifacts=new Map,sequenceByIdentity=new Map,globalWriteSequence=0;return{write(input){if(input.bytes.length===0)throw new Error("Artifact bytes must not be empty");let identity=`${input.sessionId}\0${input.operationId}`,sequence=(sequenceByIdentity.get(identity)??0)+1;sequenceByIdentity.set(identity,sequence),globalWriteSequence+=1;let artifactId=`art-${contentHash(input.bytes)}-${sequence}-${globalWriteSequence}`,ref={artifactId,sessionId:input.sessionId,operationId:input.operationId,kind:input.kind,mediaType:input.mediaType,sizeBytes:input.bytes.length,truncated:!1,createdAt:now()};return artifacts.set(artifactId,{ref,bytes:input.bytes,ended:!1}),{ref}},read(input){let entry=artifacts.get(input.artifactId);if(!entry)throw new Error(t("Artifact not found: {artifactId}",{artifactId:input.artifactId}));if(entry.ref.sessionId!==input.sessionId)throw new Error(t("Artifact {artifactId} belongs to a different session",{artifactId:input.artifactId}));if(entry.ended)throw new Error(t("Artifact {artifactId} lifecycle has ended: {reason}",{artifactId:input.artifactId,reason:entry.endReason??"ended"}));return{mediaType:entry.ref.mediaType,bytes:entry.bytes}},stat(artifactId){let entry=artifacts.get(artifactId);return entry===void 0?void 0:toStat(entry)},list(sessionId){return[...artifacts.values()].filter(entry=>entry.ref.sessionId===sessionId).map(entry=>toStat(entry))},endLifecycle(artifactId,input){let entry=artifacts.get(artifactId);if(!entry)throw new Error(t("Artifact not found: {artifactId}",{artifactId}));if(entry.ended)throw new Error(t("Artifact {artifactId} lifecycle has already ended",{artifactId}));return entry.ended=!0,entry.endReason=input.reason,entry.bytes=new Uint8Array(0),toStat(entry)}}}function planArtifactPages(store,input){if(!Number.isSafeInteger(input.pageSize)||input.pageSize<1)return{status:"invalid_page_size",pageSize:input.pageSize};let stat=store.stat(input.artifactId);if(!stat)return{status:"unavailable",reason:`Artifact not found: ${input.artifactId}`};if(stat.state==="ended")return{status:"unavailable",reason:`Artifact ${input.artifactId} lifecycle has ended: ${stat.endReason??"ended"}`};let totalBytes=stat.sizeBytes??0,pages=[];for(let offset=0;offset<totalBytes;offset+=input.pageSize)pages.push({index:pages.length,offset,size:Math.min(input.pageSize,totalBytes-offset)});return{status:"planned",totalBytes,pageSize:input.pageSize,pages:Object.freeze(pages)}}function readArtifactPage(store,input){if(!Number.isSafeInteger(input.pageSize)||input.pageSize<1)return{status:"unavailable",reason:`Invalid page size: ${input.pageSize}`};let plan=planArtifactPages(store,{artifactId:input.artifactId,pageSize:input.pageSize});if(plan.status!=="planned")return{status:"unavailable",reason:plan.status==="unavailable"?plan.reason:`Invalid page size: ${plan.pageSize}`};let page=plan.pages[input.index];if(!page)return{status:"unavailable",reason:`Page ${input.index} is outside the plan (${plan.pages.length} pages)`};let bytes;try{bytes=store.read({artifactId:input.artifactId,sessionId:input.sessionId}).bytes}catch(error){return{status:"unavailable",reason:error instanceof Error?error.message:String(error)}}let slice=bytes.slice(page.offset,page.offset+page.size),nextOffset=page.offset+page.size,hasMore=nextOffset<plan.totalBytes;return{status:"ok",index:page.index,offset:page.offset,bytes:slice,hasMore,...hasMore?{nextOffset}:{}}}var AGENT_CAPABILITY_CONTRACT_ID="agent-forge/agent-capability-contract",AGENT_CAPABILITY_CONTRACT_VERSION=1,AGENT_ERROR_CODES_V1=["provider_error","operation_timeout","operation_cancelled","idempotency_conflict","revision_conflict","revision_unavailable","unsupported_capability","invalid_request","invalid_ref","not_found","cancelled","unsupported","busy","session_locked","unauthorized","not_implemented","internal_error"],agentErrorCodeSet=new Set(AGENT_ERROR_CODES_V1);function isRegisteredAgentErrorCodeV1(code){return agentErrorCodeSet.has(code)}var PROTOCOL_ERROR_CODE_TO_AGENT_CODE_V1=Object.freeze({version:"unsupported",busy:"busy",session_locked:"session_locked",not_found:"not_found",invalid_request:"invalid_request",unauthorized:"unauthorized",not_implemented:"not_implemented",internal_error:"internal_error"});function mapProtocolErrorCodeToAgentErrorV1(code){return PROTOCOL_ERROR_CODE_TO_AGENT_CODE_V1[code]}function toErrorEnvelopeV1(error){let message=error instanceof Error?error.message:String(error),name=error instanceof Error?error.name:void 0,code;if(error&&typeof error=="object"&&"code"in error){let raw=error.code;typeof raw=="string"&&raw.trim()!==""&&(code=raw)}code===void 0&&(code="internal_error");let mapped=PROTOCOL_ERROR_CODE_TO_AGENT_CODE_V1[code];return buildErrorEnvelopeV1({version:1,code:mapped??code,message,retryable:!1,...name===void 0?{}:{name}})}function isPlainRecord(value){if(value===null||typeof value!="object"||Array.isArray(value))return!1;let prototype=Object.getPrototypeOf(value);return prototype===Object.prototype||prototype===null}function assertPlainRecord(value,label){if(!isPlainRecord(value))throw new Error(t("{label} must be a plain object",{label}))}function assertExactKeys(value,required,optional,label){let allowed=new Set([...required,...optional]),unsupported=Object.keys(value).filter(key=>!allowed.has(key)).sort();if(unsupported.length>0)throw new Error(t("{label} has unsupported fields: {fields}",{label,fields:unsupported.join(", ")}));for(let key of required)if(!(key in value))throw new Error(t("{label} is missing required field: {key}",{label,key}))}function assertNonEmptyString(value,label){if(typeof value!="string"||value.trim().length===0)throw new Error(t("{label} must be a non-empty string",{label}))}function assertPositiveSafeInteger(value,label){if(typeof value!="number"||!Number.isSafeInteger(value)||value<1)throw new Error(t("{label} must be a positive safe integer",{label}))}function assertNonNegativeSafeInteger(value,label){if(typeof value!="number"||!Number.isSafeInteger(value)||value<0)throw new Error(t("{label} must be a non-negative safe integer",{label}))}function assertJsonValue(value,label,seen=new WeakSet){if(!(value===null||typeof value=="boolean"||typeof value=="string")){if(typeof value=="number"){if(Number.isFinite(value))return;throw new Error(t("{label} must contain finite JSON numbers",{label}))}if(typeof value!="object")throw new Error(t("{label} must be JSON-compatible",{label}));if(seen.has(value))throw new Error(t("{label} must not contain cycles",{label}));if(seen.add(value),Array.isArray(value))for(let[index,child]of value.entries())assertJsonValue(child,`${label}[${index}]`,seen);else{if(!isPlainRecord(value))throw new Error(t("{label} must contain only plain JSON objects",{label}));for(let[key,child]of Object.entries(value))assertJsonValue(child,`${label}.${key}`,seen)}seen.delete(value)}}function detachedFreeze(value,seen=new WeakMap){if(value===null||typeof value!="object")return value;let existing=seen.get(value);if(existing!==void 0)return existing;if(Array.isArray(value)){let result2=[];seen.set(value,result2);for(let child of value)result2.push(detachedFreeze(child,seen));return Object.freeze(result2)}let result={};seen.set(value,result);for(let[key,child]of Object.entries(value))result[key]=detachedFreeze(child,seen);return Object.freeze(result)}function capabilitySort(left,right){return left.id<right.id?-1:left.id>right.id?1:left.version-right.version}function validateCapabilityRefs(value,label){if(!Array.isArray(value))throw new Error(t("{label} must be an array",{label}));let refs=value.map((item,index)=>validateCapabilityRefV1(item,`${label}[${index}]`)),seen=new Set;for(let ref of refs){let key=`${ref.id}\0${ref.version}`;if(seen.has(key))throw new Error(t("{label} contains duplicate capability: {capability}",{label,capability:`${ref.id}@${ref.version}`}));seen.add(key)}return Object.freeze(refs.sort(capabilitySort))}function validateHostTransport(value,label){if(value!=="in-process"&&value!=="stdio"&&value!=="http"&&value!=="rpc"&&value!=="unix"&&value!=="websocket")throw new Error(t("{label} is invalid",{label}))}function validateCapabilityRefV1(value,label="Capability reference"){return assertPlainRecord(value,label),assertExactKeys(value,["id","version"],[],label),assertNonEmptyString(value.id,`${label}.id`),assertPositiveSafeInteger(value.version,`${label}.version`),detachedFreeze({id:value.id,version:value.version})}function validateHostContextV1(value){if(assertPlainRecord(value,"Host context"),assertExactKeys(value,["mode","features","transports"],[],"Host context"),value.mode!=="readonly"&&value.mode!=="full-control")throw new Error(t("Host context.mode is invalid"));if(!Array.isArray(value.features))throw new Error(t("Host context.features must be an array"));let features=value.features.map((feature,index)=>(assertNonEmptyString(feature,`Host context.features[${index}]`),feature));if(new Set(features).size!==features.length)throw new Error(t("Host context.features must not contain duplicates"));if(!Array.isArray(value.transports))throw new Error(t("Host context.transports must be an array"));let transports=value.transports.map((transport,index)=>(validateHostTransport(transport,`Host context.transports[${index}]`),transport));if(new Set(transports).size!==transports.length)throw new Error(t("Host context.transports must not contain duplicates"));return detachedFreeze({mode:value.mode,features:[...features].sort(),transports:[...transports].sort()})}function buildHostContextV1(input){return validateHostContextV1(input)}function validateContractCompatibilityRequirementsV1(value){assertPlainRecord(value,"Contract compatibility requirements"),assertExactKeys(value,["contractId","version","mode","features","transports","capabilities"],[],"Contract compatibility requirements"),assertNonEmptyString(value.contractId,"Contract compatibility requirements.contractId"),assertPositiveSafeInteger(value.version,"Contract compatibility requirements.version");let hostContext=validateHostContextV1({mode:value.mode,features:value.features,transports:value.transports}),capabilities=validateCapabilityRefs(value.capabilities,"Contract compatibility requirements.capabilities");return detachedFreeze({contractId:value.contractId,version:value.version,mode:hostContext.mode,features:hostContext.features,transports:hostContext.transports,capabilities})}function buildContractCompatibilityRequirementsV1(input){return validateContractCompatibilityRequirementsV1(input)}var CONTRACT_COMPATIBILITY_ISSUE_CODES_V1=["unsupported_contract","host_mode_mismatch","unsupported_feature","unsupported_transport","unsupported_capability"];function validateContractCompatibilityResultV1(value){if(assertPlainRecord(value,"Contract compatibility result"),assertExactKeys(value,["version","compatible","issues"],[],"Contract compatibility result"),value.version!==1)throw new Error(t("Contract compatibility result.version must be 1"));if(typeof value.compatible!="boolean")throw new Error(t("Contract compatibility result.compatible must be boolean"));if(!Array.isArray(value.issues))throw new Error(t("Contract compatibility result.issues must be an array"));if(value.compatible&&value.issues.length>0)throw new Error(t("Contract compatibility result.compatible must be false when issues exist"));if(!value.compatible&&value.issues.length===0)throw new Error(t("Contract compatibility result.compatible must be true when no issues exist"));let issues=value.issues.map((entry,index)=>{if(assertPlainRecord(entry,`Contract compatibility result.issues[${index}]`),assertExactKeys(entry,["code","error"],["missingFeatures","missingTransports","missingCapabilities"],`Contract compatibility result.issues[${index}]`),!CONTRACT_COMPATIBILITY_ISSUE_CODES_V1.includes(entry.code))throw new Error(t("Contract compatibility result.issues[{index}].code is invalid",{index}));let error=validateErrorEnvelopeV1(entry.error),missingFeatures=entry.missingFeatures;if(missingFeatures!==void 0&&(!Array.isArray(missingFeatures)||missingFeatures.some(item=>typeof item!="string")))throw new Error(t("Contract compatibility result.issues[{index}].missingFeatures must be strings",{index}));let missingTransports=entry.missingTransports;if(missingTransports!==void 0&&(!Array.isArray(missingTransports)||missingTransports.some(item=>typeof item!="string")))throw new Error(t("Contract compatibility result.issues[{index}].missingTransports must be strings",{index}));let missingCapabilities=entry.missingCapabilities;missingCapabilities!==void 0&&validateCapabilityRefs(missingCapabilities,`Contract compatibility result.issues[${index}].missingCapabilities`);let issue={code:entry.code,error,...missingFeatures===void 0?{}:{missingFeatures:Object.freeze(missingFeatures.map(item=>item))},...missingTransports===void 0?{}:{missingTransports:Object.freeze(missingTransports.map(item=>item))},...missingCapabilities===void 0?{}:{missingCapabilities:validateCapabilityRefs(missingCapabilities,"missingCapabilities")}};return detachedFreeze(issue)});return detachedFreeze({version:1,compatible:value.compatible,issues:Object.freeze(issues)})}function validateAgentCapabilityContractV1(value){if(assertPlainRecord(value,"Agent capability contract"),assertExactKeys(value,["contractId","version","capabilities","hostContext"],[],"Agent capability contract"),value.contractId!==AGENT_CAPABILITY_CONTRACT_ID)throw new Error(t("Agent capability contract.contractId must be {contractId}",{contractId:AGENT_CAPABILITY_CONTRACT_ID}));if(value.version!==1)throw new Error(t("Agent capability contract.version must be 1"));let capabilities=validateCapabilityRefs(value.capabilities,"Agent capability contract.capabilities"),hostContext=validateHostContextV1(value.hostContext);return detachedFreeze({contractId:value.contractId,version:1,capabilities,hostContext})}function buildAgentCapabilityContractV1(input){return validateAgentCapabilityContractV1({...input,version:input.version??1})}function validateAgentProfileV1(value){assertPlainRecord(value,"Agent profile"),assertExactKeys(value,["id","version","rootAgent","requiredPlugins"],["optionalPlugins","defaults"],"Agent profile"),assertNonEmptyString(value.id,"Agent profile.id"),assertPositiveSafeInteger(value.version,"Agent profile.version"),assertNonEmptyString(value.rootAgent,"Agent profile.rootAgent");let validatePluginIds=(candidate,label)=>{if(!Array.isArray(candidate))throw new Error(t("{label} must be an array",{label}));let ids=candidate.map((id,index)=>(assertNonEmptyString(id,`${label}[${index}]`),id));if(new Set(ids).size!==ids.length)throw new Error(t("{label} must not contain duplicates",{label}));return Object.freeze([...ids].sort())},requiredPlugins=validatePluginIds(value.requiredPlugins,"Agent profile.requiredPlugins"),optionalPlugins=value.optionalPlugins===void 0?void 0:validatePluginIds(value.optionalPlugins,"Agent profile.optionalPlugins");if(optionalPlugins?.some(id=>requiredPlugins.includes(id)))throw new Error(t("Agent profile.optionalPlugins must not overlap requiredPlugins"));return value.defaults!==void 0&&assertJsonValue(value.defaults,"Agent profile.defaults"),detachedFreeze({id:value.id,version:value.version,rootAgent:value.rootAgent,requiredPlugins,...optionalPlugins===void 0?{}:{optionalPlugins},...value.defaults===void 0?{}:{defaults:value.defaults}})}function buildAgentProfileV1(input){return validateAgentProfileV1(input)}function validateArtifactRefV1(value){if(assertPlainRecord(value,"Artifact reference"),assertExactKeys(value,["sessionId","operationId","artifactId","kind","mediaType","truncated","createdAt"],["sizeBytes"],"Artifact reference"),assertNonEmptyString(value.sessionId,"Artifact reference.sessionId"),assertNonEmptyString(value.operationId,"Artifact reference.operationId"),assertNonEmptyString(value.artifactId,"Artifact reference.artifactId"),assertNonEmptyString(value.kind,"Artifact reference.kind"),assertNonEmptyString(value.mediaType,"Artifact reference.mediaType"),value.sizeBytes!==void 0&&assertNonNegativeSafeInteger(value.sizeBytes,"Artifact reference.sizeBytes"),typeof value.truncated!="boolean")throw new Error(t("Artifact reference.truncated must be boolean"));return assertNonNegativeSafeInteger(value.createdAt,"Artifact reference.createdAt"),detachedFreeze({sessionId:value.sessionId,operationId:value.operationId,artifactId:value.artifactId,kind:value.kind,mediaType:value.mediaType,...value.sizeBytes===void 0?{}:{sizeBytes:value.sizeBytes},truncated:value.truncated,createdAt:value.createdAt})}function buildArtifactRefV1(input){return validateArtifactRefV1(input)}function checkContractCompatibilityV1(candidateInput,requirementsInput){let candidate=validateAgentCapabilityContractV1(candidateInput),requirements=validateContractCompatibilityRequirementsV1(requirementsInput),issues=[];(candidate.contractId!==requirements.contractId||candidate.version!==requirements.version)&&issues.push({code:"unsupported_contract",error:commandError("unsupported_contract",`Contract is unsupported: ${requirements.contractId}@${requirements.version}`)}),candidate.hostContext.mode!==requirements.mode&&issues.push({code:"host_mode_mismatch",error:commandError("host_mode_mismatch",`Host mode is incompatible: required ${requirements.mode}, received ${candidate.hostContext.mode}`)});let missingFeatures=requirements.features.filter(feature=>!candidate.hostContext.features.includes(feature));missingFeatures.length>0&&issues.push({code:"unsupported_feature",error:commandError("unsupported_feature",`Host features are unsupported: ${missingFeatures.join(", ")}`),missingFeatures:Object.freeze([...missingFeatures])});let missingTransports=requirements.transports.filter(transport=>!candidate.hostContext.transports.includes(transport));missingTransports.length>0&&issues.push({code:"unsupported_transport",error:commandError("unsupported_transport",`Host transports are unsupported: ${missingTransports.join(", ")}`),missingTransports:Object.freeze([...missingTransports])});let missingCapabilities=requirements.capabilities.filter(required=>!candidate.capabilities.some(available=>available.id===required.id&&available.version===required.version));return missingCapabilities.length>0&&issues.push({code:"unsupported_capability",error:commandError("unsupported_capability",`Capabilities are unsupported: ${missingCapabilities.map(item=>`${item.id}@${item.version}`).join(", ")}`),missingCapabilities:Object.freeze([...missingCapabilities])}),detachedFreeze({version:1,compatible:issues.length===0,issues})}function validateAgentRole(value,label){if(value!=="root-agent-controller"&&value!=="child-agent-controller")throw new Error(t("{label} is invalid",{label}))}function validateAgentDefinitionSnapshotV1(value){if(assertPlainRecord(value,"Agent definition snapshot"),assertExactKeys(value,["version","id","definitionVersion","role","capabilities"],["owner"],"Agent definition snapshot"),value.version!==1)throw new Error(t("Agent definition snapshot.version must be 1"));assertNonEmptyString(value.id,"Agent definition snapshot.id"),assertPositiveSafeInteger(value.definitionVersion,"Agent definition snapshot.definitionVersion"),validateAgentRole(value.role,"Agent definition snapshot.role");let capabilities=validateCapabilityRefs(value.capabilities,"Agent definition snapshot.capabilities");return value.owner!==void 0&&assertNonEmptyString(value.owner,"Agent definition snapshot.owner"),detachedFreeze({version:1,id:value.id,definitionVersion:value.definitionVersion,role:value.role,capabilities,...value.owner===void 0?{}:{owner:value.owner}})}function buildAgentDefinitionSnapshotV1(input){return validateAgentDefinitionSnapshotV1(input)}function validateAgentInstanceSnapshotV1(value){if(assertPlainRecord(value,"Agent instance snapshot"),assertExactKeys(value,["version","id","definitionId","definitionVersion","role","status","revision"],["parentInstanceId","leaseOwner"],"Agent instance snapshot"),value.version!==1)throw new Error(t("Agent instance snapshot.version must be 1"));if(assertNonEmptyString(value.id,"Agent instance snapshot.id"),assertNonEmptyString(value.definitionId,"Agent instance snapshot.definitionId"),assertPositiveSafeInteger(value.definitionVersion,"Agent instance snapshot.definitionVersion"),validateAgentRole(value.role,"Agent instance snapshot.role"),value.status!=="created"&&value.status!=="running"&&value.status!=="succeeded"&&value.status!=="failed"&&value.status!=="cancelled"&&value.status!=="disposed")throw new Error(t("Agent instance snapshot.status is invalid"));return assertNonNegativeSafeInteger(value.revision,"Agent instance snapshot.revision"),value.parentInstanceId!==void 0&&assertNonEmptyString(value.parentInstanceId,"Agent instance snapshot.parentInstanceId"),value.leaseOwner!==void 0&&assertNonEmptyString(value.leaseOwner,"Agent instance snapshot.leaseOwner"),detachedFreeze({version:1,id:value.id,definitionId:value.definitionId,definitionVersion:value.definitionVersion,role:value.role,status:value.status,revision:value.revision,...value.parentInstanceId===void 0?{}:{parentInstanceId:value.parentInstanceId},...value.leaseOwner===void 0?{}:{leaseOwner:value.leaseOwner}})}function buildAgentInstanceSnapshotV1(input){return validateAgentInstanceSnapshotV1(input)}function validateSessionRevisionV1(value){if(assertPlainRecord(value,"Session revision"),assertExactKeys(value,["version","sessionId","sequence","leafId"],[],"Session revision"),value.version!==1)throw new Error(t("Session revision.version must be 1"));if(assertNonEmptyString(value.sessionId,"Session revision.sessionId"),assertNonNegativeSafeInteger(value.sequence,"Session revision.sequence"),value.leafId!==null&&value.leafId!==void 0&&assertNonEmptyString(value.leafId,"Session revision.leafId"),value.leafId===void 0)throw new Error(t("Session revision.leafId is required"));return detachedFreeze({version:1,sessionId:value.sessionId,sequence:value.sequence,leafId:value.leafId})}function buildSessionRevisionV1(input){return validateSessionRevisionV1(input)}function validateSessionSnapshotV1(value){if(assertPlainRecord(value,"Session snapshot"),assertExactKeys(value,["version","sessionId","revision"],[],"Session snapshot"),value.version!==1)throw new Error(t("Session snapshot.version must be 1"));assertNonEmptyString(value.sessionId,"Session snapshot.sessionId");let revision=validateSessionRevisionV1(value.revision);if(revision.sessionId!==value.sessionId)throw new Error(t("Session snapshot.revision.sessionId must match sessionId"));return detachedFreeze({version:1,sessionId:value.sessionId,revision})}function buildSessionSnapshotV1(input){return validateSessionSnapshotV1(input)}function validateErrorEnvelopeV1(value){if(assertPlainRecord(value,"Error envelope"),assertExactKeys(value,["version","code","message","retryable"],["details","name"],"Error envelope"),value.version!==1)throw new Error(t("Error envelope.version must be 1"));if(assertNonEmptyString(value.code,"Error envelope.code"),typeof value.message!="string")throw new Error(t("Error envelope.message must be a string"));if(typeof value.retryable!="boolean")throw new Error(t("Error envelope.retryable must be a boolean"));return value.name!==void 0&&assertNonEmptyString(value.name,"Error envelope.name"),value.details!==void 0&&assertJsonValue(value.details,"Error envelope.details"),detachedFreeze({version:1,code:value.code,message:value.message,retryable:value.retryable,...value.details===void 0?{}:{details:value.details},...value.name===void 0?{}:{name:value.name}})}function buildErrorEnvelopeV1(input){return validateErrorEnvelopeV1(input)}function validateOperationTerminalStatus(value,label){if(value!=="succeeded"&&value!=="failed"&&value!=="cancelled"&&value!=="timed_out")throw new Error(t("{label} is invalid",{label}))}function validateOperationTerminalV1(value){if(assertPlainRecord(value,"Operation terminal"),!("version"in value)||!("status"in value))throw new Error(t("Operation terminal is missing required field: version or status"));if(value.version!==1)throw new Error(t("Operation terminal.version must be 1"));if(validateOperationTerminalStatus(value.status,"Operation terminal.status"),value.status==="succeeded")return assertExactKeys(value,["version","status"],["result"],"Operation terminal"),value.result!==void 0&&assertJsonValue(value.result,"Operation terminal.result"),detachedFreeze({version:1,status:"succeeded",...value.result===void 0?{}:{result:value.result}});assertExactKeys(value,["version","status","error"],[],"Operation terminal");let error=validateErrorEnvelopeV1(value.error);return detachedFreeze({version:1,status:value.status,error})}function buildOperationTerminalV1(input){return validateOperationTerminalV1(input)}function validateOperationSnapshotV1(value){if(assertPlainRecord(value,"Operation snapshot"),assertExactKeys(value,["version","operationId","kind","status"],["terminal","instanceId","sessionId","inputRevision"],"Operation snapshot"),value.version!==1)throw new Error(t("Operation snapshot.version must be 1"));if(assertNonEmptyString(value.operationId,"Operation snapshot.operationId"),assertNonEmptyString(value.kind,"Operation snapshot.kind"),value.status!=="queued"&&value.status!=="running"&&value.status!=="succeeded"&&value.status!=="failed"&&value.status!=="cancelled"&&value.status!=="timed_out")throw new Error(t("Operation snapshot.status is invalid"));if((value.status==="queued"||value.status==="running")&&value.terminal!==void 0)throw new Error(t("Operation snapshot active status must not have a terminal"));if(value.status!=="queued"&&value.status!=="running"&&value.terminal===void 0)throw new Error(t("Operation snapshot terminal status requires a terminal"));let terminal=value.terminal===void 0?void 0:validateOperationTerminalV1(value.terminal);if(terminal!==void 0&&terminal.status!==value.status)throw new Error(t("Operation snapshot.terminal.status must match status"));value.instanceId!==void 0&&assertNonEmptyString(value.instanceId,"Operation snapshot.instanceId"),value.sessionId!==void 0&&assertNonEmptyString(value.sessionId,"Operation snapshot.sessionId");let inputRevision=value.inputRevision===void 0?void 0:validateSessionRevisionV1(value.inputRevision);if(inputRevision!==void 0&&value.sessionId!==void 0&&inputRevision.sessionId!==value.sessionId)throw new Error(t("Operation snapshot.inputRevision.sessionId must match sessionId"));return detachedFreeze({version:1,operationId:value.operationId,kind:value.kind,status:value.status,...terminal===void 0?{}:{terminal},...value.instanceId===void 0?{}:{instanceId:value.instanceId},...value.sessionId===void 0?{}:{sessionId:value.sessionId},...inputRevision===void 0?{}:{inputRevision}})}function buildOperationSnapshotV1(input){return validateOperationSnapshotV1(input)}function validateCommandRequestV1(value){if(assertPlainRecord(value,"Command request"),assertExactKeys(value,["version","operationId","idempotencyKey","command","target","input","hostContext"],["expectedRevision"],"Command request"),value.version!==1)throw new Error(t("Command request.version must be 1"));assertNonEmptyString(value.operationId,"Command request.operationId"),assertNonEmptyString(value.idempotencyKey,"Command request.idempotencyKey"),assertNonEmptyString(value.command,"Command request.command"),assertNonEmptyString(value.target,"Command request.target"),assertJsonValue(value.input,"Command request.input");let expectedRevision=value.expectedRevision===void 0?void 0:validateSessionRevisionV1(value.expectedRevision);if(expectedRevision!==void 0&&expectedRevision.sessionId!==value.target)throw new Error(t("Command request.expectedRevision.sessionId does not match target"));let hostContext=validateHostContextV1(value.hostContext);return detachedFreeze({version:1,operationId:value.operationId,idempotencyKey:value.idempotencyKey,command:value.command,target:value.target,input:value.input,...expectedRevision===void 0?{}:{expectedRevision},hostContext})}function buildCommandRequestV1(input){return validateCommandRequestV1({...input,version:input.version??1})}function validateCommandAdmissionV1(value){if(assertPlainRecord(value,"Command admission"),assertExactKeys(value,["version","status","request"],["operation","error"],"Command admission"),value.version!==1)throw new Error(t("Command admission.version must be 1"));if(value.status!=="accepted"&&value.status!=="existing"&&value.status!=="rejected")throw new Error(t("Command admission.status is invalid"));let request=validateCommandRequestV1(value.request),operation=value.operation===void 0?void 0:validateOperationSnapshotV1(value.operation);if((value.status==="accepted"||value.status==="existing")&&operation===void 0)throw new Error(t("Command admission accepted status requires an operation"));if(value.status==="rejected"&&value.error===void 0)throw new Error(t("Command admission rejected status requires an error"));let error=value.error===void 0?void 0:validateErrorEnvelopeV1(value.error);return detachedFreeze({version:1,status:value.status,request,...operation===void 0?{}:{operation},...error===void 0?{}:{error}})}function canonicalJson(value){if(value===null||typeof value!="object")return JSON.stringify(value);if(Array.isArray(value))return`[${value.map(canonicalJson).join(",")}]`;let record=value;return`{${Object.keys(record).sort().map(key=>`${JSON.stringify(key)}:${canonicalJson(record[key])}`).join(",")}}`}function sameRevision(left,right){return left.sessionId===right.sessionId&&left.sequence===right.sequence&&left.leafId===right.leafId}function commandError(code,message,details){return buildErrorEnvelopeV1({version:1,code,message,retryable:!1,...details===void 0?{}:{details}})}function rejectedAdmission(request,error){return detachedFreeze({version:1,status:"rejected",request,error})}function createCommandOperationRegistryV1(){let entries=new Map,read=operationId=>{assertNonEmptyString(operationId,"operationId");let entry=entries.get(operationId);if(!entry)throw new Error(t("Operation is not retained: {operationId}",{operationId}));return entry},write=(entry,operation)=>(entry.operation=operation,operation),terminal=entry=>entry.operation.terminal!==void 0;return Object.freeze({admit(input,currentRevision){let request=validateCommandRequestV1(input),current=currentRevision===void 0?void 0:validateSessionRevisionV1(currentRevision),fingerprint=canonicalJson(request),existing=entries.get(request.operationId);if(existing)return existing.fingerprint===fingerprint?detachedFreeze({version:1,status:"existing",request,operation:existing.operation}):rejectedAdmission(request,commandError("idempotency_conflict",`Operation ID is already bound to different input: ${request.operationId}`));if(request.expectedRevision!==void 0){if(current===void 0)return rejectedAdmission(request,commandError("revision_unavailable",`Current revision is required for: ${request.target}`));if(!sameRevision(request.expectedRevision,current))return rejectedAdmission(request,commandError("revision_conflict",`Expected revision does not match: ${request.target}`,{expectedRevision:request.expectedRevision,currentRevision:current}))}let operation=buildOperationSnapshotV1({version:1,operationId:request.operationId,kind:`command:${request.command}`,status:"queued",...request.expectedRevision===void 0?{}:{sessionId:request.expectedRevision.sessionId,inputRevision:request.expectedRevision}});return entries.set(request.operationId,{request,fingerprint,operation}),detachedFreeze({version:1,status:"accepted",request,operation})},start(operationId){let entry=read(operationId);return entry.operation.status!=="queued"?entry.operation:write(entry,buildOperationSnapshotV1({...entry.operation,status:"running"}))},complete(operationId,terminalSnapshot){let entry=read(operationId),nextTerminal=validateOperationTerminalV1(terminalSnapshot);if(terminal(entry)){if(canonicalJson(entry.operation.terminal)!==canonicalJson(nextTerminal))throw new Error(t("Operation already has a different terminal result: {operationId}",{operationId}));return entry.operation}return write(entry,buildOperationSnapshotV1({...entry.operation,status:nextTerminal.status,terminal:nextTerminal}))},cancel(operationId){let entry=read(operationId);return terminal(entry)?entry.operation:write(entry,buildOperationSnapshotV1({...entry.operation,status:"cancelled",terminal:{version:1,status:"cancelled",error:commandError("operation_cancelled",`Operation cancelled: ${operationId}`)}}))},get(operationId){return assertNonEmptyString(operationId,"operationId"),entries.get(operationId)?.operation},release(operationId){assertNonEmptyString(operationId,"operationId"),entries.delete(operationId)}})}function buildCanonicalContractVectorsV1(){let hostContext=buildHostContextV1({mode:"full-control",features:["agent.run","session.snapshot"],transports:["in-process"]}),contract=buildAgentCapabilityContractV1({contractId:AGENT_CAPABILITY_CONTRACT_ID,capabilities:[{id:"agent.run",version:1}],hostContext}),profile=buildAgentProfileV1({id:"coding-agent",version:1,rootAgent:"coding-agent.root",requiredPlugins:["bootstrap-tools"],optionalPlugins:["bootstrap-skills"],defaults:{mode:"full-control",context:{strategy:"default"}}}),artifact=buildArtifactRefV1({sessionId:"session-vector-1",operationId:"vector-operation-1",artifactId:"artifact-vector-1",kind:"operation_record",mediaType:"application/json",sizeBytes:13,truncated:!1,createdAt:0}),revision=buildSessionRevisionV1({version:1,sessionId:"session-vector-1",sequence:0,leafId:null}),definition=buildAgentDefinitionSnapshotV1({version:1,id:"coding-agent.root",definitionVersion:1,role:"root-agent-controller",capabilities:[{id:"agent.run",version:1}],owner:"coding-agent"}),instance=buildAgentInstanceSnapshotV1({version:1,id:"instance-vector-1",definitionId:definition.id,definitionVersion:definition.definitionVersion,role:definition.role,status:"created",revision:0}),session=buildSessionSnapshotV1({version:1,sessionId:revision.sessionId,revision}),error=buildErrorEnvelopeV1({version:1,code:"provider_error",message:"provider failed",retryable:!0}),command=buildCommandRequestV1({operationId:"vector-operation-1",idempotencyKey:"vector-request-1",command:"agent.run",target:"session-vector-1",input:{prompt:"vector"},expectedRevision:{version:1,sessionId:"session-vector-1",sequence:0,leafId:null},hostContext}),registry=createCommandOperationRegistryV1(),accepted=registry.admit(command,command.expectedRevision);if(accepted.status!=="accepted"||accepted.operation===void 0)throw new Error(t("Canonical contract vector admission failed"));let running=registry.start(command.operationId),terminal=registry.complete(command.operationId,{version:1,status:"succeeded",result:{ok:!0}}),event=buildEventEnvelopeV1({id:"vector-event-1",deliveryId:"vector-delivery-1",type:"operation.end",source:"canonical-vector",category:"authoritative",deliveryGuarantee:"best-effort",timestamp:0,operationId:command.operationId,correlationId:command.operationId,data:{version:1,operationId:command.operationId,operationKind:command.command,status:"succeeded"}});return detachedFreeze({version:1,contract,definition,instance,session,revision,error,profile,artifact,command,accepted,running,terminal,event})}function buildCanonicalContractFixtureVectorsV1(){let base=buildCanonicalContractVectorsV1(),registry=createCommandOperationRegistryV1(),request=buildCommandRequestV1({operationId:"fixture-operation-1",idempotencyKey:"fixture-request-1",command:"agent.run",target:"session-fixture-1",input:{prompt:"fixture"},expectedRevision:{version:1,sessionId:"session-fixture-1",sequence:1,leafId:"leaf-1"},hostContext:base.contract.hostContext});registry.admit(request,request.expectedRevision);let existing=registry.admit(request,request.expectedRevision),idempotencyConflict=registry.admit({...request,input:{prompt:"different"}},request.expectedRevision),revisionConflict=registry.admit({...request,operationId:"fixture-operation-2",idempotencyKey:"fixture-request-2"},{version:1,sessionId:"session-fixture-1",sequence:2,leafId:"leaf-2"}),cancelled=registry.cancel(request.operationId),terminalReplay=registry.complete(request.operationId,cancelled.terminal);if(registry.admit(buildCommandRequestV1({...request,operationId:"fixture-operation-failed",idempotencyKey:"fixture-request-failed"}),request.expectedRevision).status!=="accepted")throw new Error(t("Canonical contract failed vector admission failed"));let failedTerminal=registry.complete("fixture-operation-failed",{version:1,status:"failed",error:buildErrorEnvelopeV1({version:1,code:"provider_error",message:"provider failed",retryable:!0})});if(registry.admit(buildCommandRequestV1({...request,operationId:"fixture-operation-timeout",idempotencyKey:"fixture-request-timeout"}),request.expectedRevision).status!=="accepted")throw new Error(t("Canonical contract timeout vector admission failed"));let timedOutTerminal=registry.complete("fixture-operation-timeout",{version:1,status:"timed_out",error:buildErrorEnvelopeV1({version:1,code:"operation_timeout",message:"operation timed out",retryable:!0})}),unsupported=buildUnsupportedCapabilityV1({id:"fixture.missing",version:1}),observation=buildEventEnvelopeV1({id:"fixture-event-1",deliveryId:"fixture-delivery-1",type:"fixture.observation",source:"canonical-vector",timestamp:0,data:{observed:!0}}),correlated=buildEventEnvelopeV1({id:"fixture-event-correlated",deliveryId:"fixture-delivery-correlated",type:"operation.end",source:"canonical-vector",category:"authoritative",timestamp:0,operationId:"fixture-operation-1",correlationId:"fixture-operation-1",data:{status:"cancelled"}}),steer=buildCommandRequestV1({operationId:"fixture-operation-steer",idempotencyKey:"fixture-request-steer",command:"session.steer",target:"session-fixture-1",input:{text:"steer"},expectedRevision:request.expectedRevision,hostContext:base.contract.hostContext}),operationStep=buildEventEnvelopeV1({id:"fixture-event-step",deliveryId:"fixture-delivery-step",type:"operation.step",source:"canonical-vector",category:"progress",timestamp:0,operationId:"fixture-operation-steer",correlationId:"fixture-operation-steer",data:{version:1,operationId:"fixture-operation-steer",operationKind:"session.steer",step:1,message:"accepted"}}),compatibilityRequirements=overrides=>buildContractCompatibilityRequirementsV1({contractId:AGENT_CAPABILITY_CONTRACT_ID,version:1,mode:"full-control",features:[],transports:[],capabilities:[],...overrides}),compatibilityAccepted=checkContractCompatibilityV1(base.contract,compatibilityRequirements({features:["agent.run","session.snapshot"],transports:["in-process"],capabilities:[{id:"agent.run",version:1}]})),compatibilityContractUnsupported=checkContractCompatibilityV1(base.contract,compatibilityRequirements({version:2})),compatibilityCapabilityVersionUnsupported=checkContractCompatibilityV1(base.contract,compatibilityRequirements({capabilities:[{id:"agent.run",version:2}]})),compatibilityFeatureSubset=checkContractCompatibilityV1(base.contract,compatibilityRequirements({features:["agent.run","session.compact"]}));return detachedFreeze([{id:"agent-definition",value:base.definition},{id:"agent-instance",value:base.instance},{id:"session-snapshot",value:base.session},{id:"session-revision",value:base.revision},{id:"error-envelope",value:base.error},{id:"profile-snapshot",value:base.profile},{id:"artifact-reference",value:base.artifact},{id:"command-success",value:base.terminal},{id:"command-failed-terminal",value:failedTerminal},{id:"command-timed-out-terminal",value:timedOutTerminal},{id:"command-idempotency-replay",value:existing},{id:"command-idempotency-conflict",value:idempotencyConflict},{id:"command-revision-conflict",value:revisionConflict},{id:"command-cancel-terminal",value:cancelled},{id:"command-terminal-replay",value:terminalReplay},{id:"capability-unsupported",value:unsupported},{id:"event-without-operation",value:observation},{id:"event-with-operation",value:correlated},{id:"command-steer",value:steer},{id:"event-operation-step",value:operationStep},{id:"compatibility-accepted",value:compatibilityAccepted},{id:"compatibility-contract-unsupported",value:compatibilityContractUnsupported},{id:"compatibility-capability-version-unsupported",value:compatibilityCapabilityVersionUnsupported},{id:"compatibility-feature-subset",value:compatibilityFeatureSubset}])}function validateEventEnvelopeV1(value){if(assertPlainRecord(value,"Event envelope"),assertExactKeys(value,["version","id","deliveryId","type","source","category","deliveryGuarantee","timestamp","data"],["operationId","correlationId","causationId"],"Event envelope"),value.version!==1)throw new Error(t("Event envelope.version must be 1"));if(assertNonEmptyString(value.id,"Event envelope.id"),assertNonEmptyString(value.deliveryId,"Event envelope.deliveryId"),assertNonEmptyString(value.type,"Event envelope.type"),assertNonEmptyString(value.source,"Event envelope.source"),value.category!=="authoritative"&&value.category!=="progress"&&value.category!=="observation")throw new Error(t("Event envelope.category is invalid"));if(value.deliveryGuarantee!=="best-effort"&&value.deliveryGuarantee!=="at-least-once")throw new Error(t("Event envelope.deliveryGuarantee is invalid"));if(assertNonNegativeSafeInteger(value.timestamp,"Event envelope.timestamp"),assertJsonValue(value.data,"Event envelope.data"),value.operationId!==void 0&&assertNonEmptyString(value.operationId,"Event envelope.operationId"),value.correlationId!==void 0&&assertNonEmptyString(value.correlationId,"Event envelope.correlationId"),value.causationId!==void 0&&assertNonEmptyString(value.causationId,"Event envelope.causationId"),value.operationId===void 0&&value.correlationId!==void 0)throw new Error(t("Event envelope.correlationId requires a real operationId"));if(value.operationId!==void 0&&value.correlationId===void 0)throw new Error(t("Event envelope.operationId requires correlationId"));return detachedFreeze({version:1,id:value.id,deliveryId:value.deliveryId,type:value.type,source:value.source,category:value.category,deliveryGuarantee:value.deliveryGuarantee,timestamp:value.timestamp,data:value.data,...value.operationId===void 0?{}:{operationId:value.operationId},...value.correlationId===void 0?{}:{correlationId:value.correlationId},...value.causationId===void 0?{}:{causationId:value.causationId}})}function buildEventEnvelopeV1(input){return validateEventEnvelopeV1({...input,version:input.version??1,category:input.category??"observation",deliveryGuarantee:input.deliveryGuarantee??"best-effort"})}function buildUnsupportedCapabilityV1(capability){let reference=validateCapabilityRefV1(capability),error=buildErrorEnvelopeV1({version:1,code:"unsupported_capability",message:`Capability is unsupported: ${reference.id}@${reference.version}`,retryable:!1});return detachedFreeze({status:"unsupported",capability:reference,error})}function resolveCapabilityV1(requested,supported){let reference=validateCapabilityRefV1(requested);return validateCapabilityRefs(supported,"Supported capabilities").some(candidate=>candidate.id===reference.id&&candidate.version===reference.version)?detachedFreeze({status:"supported",capability:reference}):buildUnsupportedCapabilityV1(reference)}function assertCapabilitySupportedV1(requested,supported){let resolution=resolveCapabilityV1(requested,supported);if(resolution.status==="unsupported")throw new Error(resolution.error.message);return resolution.capability}var validateAgentCapabilityContract=validateAgentCapabilityContractV1,buildAgentCapabilityContract=buildAgentCapabilityContractV1,validateEventEnvelope=validateEventEnvelopeV1,buildEventEnvelope=buildEventEnvelopeV1;function detachedFreeze2(value,seen=new WeakMap){if(value===null||typeof value!="object")return value;let existing=seen.get(value);if(existing!==void 0)return existing;if(Array.isArray(value)){let copy2=[];seen.set(value,copy2);for(let child of value)copy2.push(detachedFreeze2(child,seen));return Object.freeze(copy2)}let copy=Object.create(null);seen.set(value,copy);for(let[key,child]of Object.entries(value))copy[key]=detachedFreeze2(child,seen);return Object.freeze(copy)}function assertActive(disposed,label){if(disposed)throw new Error(t("Embedded SDK binding is disposed: {label}",{label}))}function errorEnvelope(error,code){let message=error instanceof Error?error.message:String(error);return buildErrorEnvelopeV1({version:1,code,message,retryable:!1,...error instanceof Error?{name:error.name}:{}})}function agentDefinitionSnapshot(definition){return buildAgentDefinitionSnapshotV1({version:1,id:definition.id,definitionVersion:definition.version,role:definition.role,capabilities:[],...definition.owner===void 0?{}:{owner:definition.owner}})}function agentInstanceSnapshot(snapshot){return buildAgentInstanceSnapshotV1({version:1,id:snapshot.id,definitionId:snapshot.definitionId,definitionVersion:snapshot.definitionVersion,role:snapshot.role,status:snapshot.status,revision:snapshot.revision,...snapshot.parentInstanceId===void 0?{}:{parentInstanceId:snapshot.parentInstanceId},...snapshot.leaseOwner===void 0?{}:{leaseOwner:snapshot.leaseOwner}})}function resultSnapshot(result){return result.status==="succeeded"?detachedFreeze2({status:"succeeded",output:canonicalOutput(result.output,`wait:${result.revision}`),revision:result.revision}):detachedFreeze2({status:result.status,revision:result.revision,...result.error===void 0?{}:{error:errorEnvelope(result.error,`agent_${result.status}`)}})}function canonicalOutput(value,operationId){return buildOperationSnapshotV1({version:1,operationId,kind:"agent.run",status:"succeeded",terminal:{version:1,status:"succeeded",result:value}}),detachedFreeze2(value)}function canonicalInput(value){if(value===void 0)throw new Error(t("Embedded SDK run input must be JSON-compatible"));return buildOperationSnapshotV1({version:1,operationId:"embedded-sdk:input",kind:"agent.run",status:"succeeded",terminal:{version:1,status:"succeeded",result:value}}),detachedFreeze2(value)}function createEmbeddedSessionBindingV1(session){if(!session.getRevision)throw new Error(t("Embedded SDK session requires revision support"));let getRevision=()=>detachedFreeze2(session.getRevision()),context=session.getContextSnapshot&&session.commitContext?Object.freeze({version:1,get:()=>detachedFreeze2(session.getContextSnapshot()),commit:request=>session.commitContext(request)}):void 0;return Object.freeze({version:1,getSessionId:()=>session.getSessionId(),getRevision,snapshot:()=>buildSessionSnapshotV1({version:1,sessionId:session.getSessionId(),revision:getRevision()}),getMessages:()=>detachedFreeze2(session.getMessages()),getBranchEntries:()=>detachedFreeze2(session.getBranchEntries()),isIdle:()=>session.isIdle(),prompt:text=>session.prompt(text),steer:text=>session.steer?session.steer(text):Promise.reject(new Error("Embedded SDK session does not support steer")),abort:()=>session.abort(),waitForIdle:()=>session.waitForIdle(),...context===void 0?{}:{context}})}function createEmbeddedSdkBindingV1(options={}){let composition=options.composition??createAgentCompositionRuntime(),ownsComposition=options.ownsComposition??options.composition===void 0,defaultFeatures=["agent-composition-v1",...options.session===void 0?[]:["session","session-revision-v1","context"]],hostContext=detachedFreeze2({mode:options.mode??"full-control",features:[...options.features??defaultFeatures].sort(),transports:["in-process"]}),session=options.session===void 0?void 0:createEmbeddedSessionBindingV1(options.session),contract=buildAgentCapabilityContractV1({contractId:"agent-forge/agent-capability-contract",capabilities:[],hostContext}),definitions=new Map,instances=new Map,listeners=new Map,sequence=0,disposePromise,disposed=!1,nextId=kind=>(sequence+=1,options.idFactory?.(kind,sequence)??`embedded-sdk:${kind}:${sequence}`),emit=(type,data,operationId)=>{let event=buildEventEnvelopeV1({id:nextId("event"),deliveryId:nextId("delivery"),type,source:"embedded-sdk",timestamp:options.clock?.()??0,category:type===OPERATION_START_EVENT_ID||type===OPERATION_CANCEL_EVENT_ID||type===OPERATION_END_EVENT_ID?"authoritative":"observation",deliveryGuarantee:"best-effort",data,...operationId===void 0?{}:{operationId,correlationId:operationId}});for(let listener of listeners.values())try{listener(event)}catch{}},resolveDefinition=definition=>{let snapshot="snapshot"in definition?definition.snapshot:definition,definitionVersion="definitionVersion"in snapshot?snapshot.definitionVersion:snapshot.version,resolved=definitions.get(`${snapshot.id}@${definitionVersion}`);if(resolved)return resolved;if(options.composition!==void 0)return composition.get(snapshot.id,definitionVersion);throw new Error(t("Embedded SDK has no defined Agent: {id}@{version}",{id:snapshot.id,version:definitionVersion}))},binding={version:1,contract,hostContext,...session===void 0?{}:{session},define(definition){assertActive(disposed,"define");let registered=composition.define(definition);return definitions.set(`${registered.id}@${registered.version}`,registered),detachedFreeze2({snapshot:agentDefinitionSnapshot(registered)})},create(definition,instanceOptions={}){assertActive(disposed,"create");let raw=composition.create(resolveDefinition(definition),instanceOptions),instanceDisposed=!1,instanceDisposePromise,leases=new WeakMap,wrapper={id:raw.id,snapshot:()=>(assertActive(disposed||instanceDisposed,raw.id),agentInstanceSnapshot(raw.snapshot())),acquireControllerLease:async owner=>{assertActive(disposed||instanceDisposed,raw.id);let lease=await raw.acquireControllerLease(owner),projected=Object.freeze({id:lease.id,instanceId:lease.instanceId,owner:lease.owner,revision:lease.revision,isActive:()=>!disposed&&!instanceDisposed&&lease.isActive(),release:async()=>{assertActive(disposed||instanceDisposed,raw.id),await lease.release()}});return leases.set(projected,lease),projected},run:(input,runOptions)=>{assertActive(disposed||instanceDisposed,raw.id);let lease=leases.get(runOptions.lease);if(!lease)throw new Error(t("Embedded SDK lease does not belong to Agent instance: {id}",{id:raw.id}));let operation=raw.run(canonicalInput(input),{lease,signal:runOptions.signal}),terminal,cancelEmitted=!1,reportCancel=()=>{cancelEmitted||(cancelEmitted=!0,emit(OPERATION_CANCEL_EVENT_ID,validateOperationCancelEventDataV1({version:1,operationId:operation.id,operationKind:"agent.run"}),operation.id))};operation.signal.addEventListener("abort",reportCancel,{once:!0}),operation.signal.aborted&&reportCancel(),runOptions.signal?.aborted||emit(OPERATION_START_EVENT_ID,validateOperationStartEventDataV1({version:1,operationId:operation.id,operationKind:"agent.run"}),operation.id);let result=operation.result.then(value=>{try{let output=canonicalOutput(value,operation.id);return terminal={version:1,status:"succeeded",result:output},emit(OPERATION_END_EVENT_ID,validateOperationEndEventDataV1({version:1,operationId:operation.id,operationKind:"agent.run",status:"succeeded"}),operation.id),output}catch(error){throw terminal={version:1,status:"failed",error:errorEnvelope(error,"agent_invalid_result")},emit(OPERATION_END_EVENT_ID,validateOperationEndEventDataV1({version:1,operationId:operation.id,operationKind:"agent.run",status:"failed",errorMessage:error instanceof Error?error.message:String(error)}),operation.id),error}},error=>{let status=operation.status()==="cancelled"?"cancelled":"failed";throw terminal={version:1,status,error:errorEnvelope(error,`agent_${status}`)},emit(OPERATION_END_EVENT_ID,validateOperationEndEventDataV1({version:1,operationId:operation.id,operationKind:"agent.run",status,errorMessage:error instanceof Error?error.message:String(error)}),operation.id),error});return Object.freeze({id:operation.id,result,snapshot:()=>buildOperationSnapshotV1({version:1,operationId:operation.id,kind:"agent.run",status:terminal?.status??operation.status(),...terminal===void 0&&operation.status()==="cancelled"?{terminal:{version:1,status:"cancelled",error:errorEnvelope(new Error("Operation cancelled"),"agent_cancelled")}}:terminal===void 0?{}:{terminal},instanceId:raw.id}),cancel:async reason=>{assertActive(disposed||instanceDisposed,raw.id),!(operation.status()!=="queued"&&operation.status()!=="running")&&await operation.cancel(reason)}})},wait:async()=>detachedFreeze2(resultSnapshot(await raw.wait())),cancel:async reason=>{assertActive(disposed||instanceDisposed,raw.id),await raw.cancel(reason)},dispose:async()=>(instanceDisposePromise??=(async()=>{instanceDisposed||(instanceDisposed=!0,await raw.dispose(),instances.delete(raw.id))})(),instanceDisposePromise)};return instances.set(raw.id,wrapper),Object.freeze(wrapper)},listInstances:()=>Object.freeze([...instances.values()].map(instance=>instance.snapshot()).sort((left,right)=>left.id.localeCompare(right.id))),subscribe(listener){assertActive(disposed,"subscribe");let id=`embedded-sdk:subscription:${++sequence}`,released=!1;return listeners.set(id,listener),Object.freeze({id,dispose:()=>{released||(released=!0,listeners.delete(id))}})},dispose:async()=>(disposePromise??=(async()=>{if(disposed)return;disposed=!0;let failures=[];for(let instance of[...instances.values()])try{await instance.dispose()}catch(error){failures.push(error)}if(listeners.clear(),ownsComposition&&"disposeDefinitions"in composition)try{composition.disposeDefinitions([...definitions.values()])}catch(error){failures.push(error)}if(definitions.clear(),failures.length===1)throw failures[0];if(failures.length>1)throw new AggregateError(failures,t("Embedded SDK disposal failed"))})(),disposePromise)};return Object.freeze(binding)}var createEmbeddedSdkBinding=createEmbeddedSdkBindingV1;import{EventEmitter}from"node:events";function createEventBus(){let emitter=new EventEmitter;return{emit:(channel,data)=>{emitter.emit(channel,data)},on:(channel,handler)=>{let safeHandler=async data=>{try{await handler(data)}catch(err){console.error(`Event handler error (${channel}):`,err)}};return emitter.on(channel,safeHandler),()=>emitter.off(channel,safeHandler)},clear:()=>{emitter.removeAllListeners()}}}var ModelRegistry=class{runtime;constructor(runtime){this.runtime=runtime}refresh(options){return this.runtime.refresh(options)}getError(){return this.runtime.getError()}getAll(){return[...this.runtime.getModels()]}getAvailable(){return[...this.runtime.getAvailableSnapshot()]}find(provider,modelId){return this.runtime.getModel(provider,modelId)}hasConfiguredAuth(model){return this.runtime.hasConfiguredAuth(model.provider)}async getApiKeyAndHeaders(model){try{let resolution=await this.runtime.getAuth(model);if(!resolution){let compatibility=this.runtime.getCompatibilityRequestConfig(model);return compatibility.authHeader?{ok:!1,error:`No API key found for "${model.provider}"`}:{ok:!0,headers:compatibility.headers}}return{ok:!0,apiKey:resolution.auth.apiKey,headers:resolution.auth.headers,...resolution.auth.baseUrl?{baseUrl:resolution.auth.baseUrl}:{},env:resolution.env}}catch(error){let cause=error instanceof Error?error.cause:void 0,message=cause instanceof Error?cause.message:error instanceof Error?error.message:String(error);return{ok:!1,error:message==="authHeader requires a resolved API key"?`No API key found for "${model.provider}"`:message}}}getProviderAuthStatus(provider){return this.runtime.getProviderAuthStatus(provider)}getProvider(provider){return this.runtime.getProvider(provider)}stream(model,context,options){return this.runtime.stream(model,context,options)}complete(model,context,options){return this.runtime.complete(model,context,options)}streamSimple(model,context,options){return this.runtime.streamSimple(model,context,options)}getProviderDisplayName(provider){return this.runtime.getProvider(provider)?.name??provider}getProviderAuth(provider){return this.runtime.getAuth(provider)}async getApiKeyForProvider(provider){try{return(await this.runtime.getAuth(provider))?.auth.apiKey}catch{return}}isUsingOAuth(model){return this.runtime.isUsingOAuth(model.provider)}registerProvider(providerOrName,config){if(typeof providerOrName=="string"){if(!config)throw new Error(t("Provider config is required when registering by name"));this.runtime.registerProvider(providerOrName,config);return}this.runtime.registerNativeProvider(providerOrName)}unregisterProvider(providerName){this.runtime.unregisterProvider(providerName)}getRegisteredProviderConfig(providerName){return this.runtime.getRegisteredProviderConfig(providerName)}getRegisteredNativeProvider(providerName){return this.runtime.getRegisteredNativeProvider(providerName)}getRegisteredProviderIds(){return this.runtime.getRegisteredProviderIds()}};function retryBackoffMs(policy,attempt){return Math.min(policy.baseWaitMs*2**(attempt-1),policy.maxWaitMs)}function createAgentRetryScheduler(){let terminalStates=new Map;return{schedule(input){let existing=terminalStates.get(input.operationId);if(existing)return{...existing,duplicate:!0};let signal=input.signal,now=input.now??(()=>0),sleep=input.sleep??(()=>{}),attempts=[],finish=outcome=>(terminalStates.set(input.operationId,outcome),outcome);for(let attempt=1;attempt<=input.policy.attemptLimit;attempt+=1){if(signal?.aborted)return finish({status:"cancelled",operationId:input.operationId,attempts});let at=now(),step=input.task(attempt);if(step.ok)return attempts.push({attempt,at,ok:!0,waitedMs:0}),finish({status:"succeeded",operationId:input.operationId,result:step.result,attempts});if(!step.retryable)return attempts.push({attempt,at,ok:!1,failure:step.reason,retryable:!1,waitedMs:0}),finish({status:"failed_terminal",operationId:input.operationId,reason:step.reason,attempts});let waitedMs=retryBackoffMs(input.policy,attempt);if(attempts.push({attempt,at,ok:!1,failure:step.reason,retryable:!0,waitedMs}),attempt<input.policy.attemptLimit&&(sleep(waitedMs),signal?.aborted))return finish({status:"cancelled",operationId:input.operationId,attempts})}return finish({status:"exhausted",operationId:input.operationId,attempts})},terminalOf(operationId){return terminalStates.get(operationId)}}}function createAutoCompactionExecutor(options){let coordinator=options.coordinator,policy=options.policy,inProgress=!1;return{get inProgress(){return inProgress},maybeCompact(input){if(!policy.enabled)return{status:"disabled"};if(inProgress)return{status:"busy"};if(input.currentTokens<policy.tokenThreshold)return{status:"below_threshold",currentTokens:input.currentTokens,threshold:policy.tokenThreshold};inProgress=!0;try{let staged=coordinator.stage({operationId:input.operationId,expectedRevision:coordinator.currentRevision,payload:null});if(staged.status==="stale")return{status:"stale",currentRevision:staged.currentRevision};if(staged.status==="duplicate")return{status:"cancelled"};if(input.signal?.aborted)return coordinator.cancelStage(staged.staged.token),{status:"cancelled"};let summary;try{summary=input.summarize(input.signal)}catch(error){return coordinator.cancelStage(staged.staged.token),{status:"summary_failed",reason:error instanceof Error?error.message:String(error)}}if(input.signal?.aborted)return coordinator.cancelStage(staged.staged.token),{status:"cancelled"};let outcome=coordinator.commitStage({token:staged.staged.token,apply:()=>{}});return outcome.status==="stale"?{status:"stale",currentRevision:outcome.currentRevision}:outcome.status==="committed"?{status:"completed",revision:outcome.revision,summary}:(coordinator.cancelStage(staged.staged.token),{status:"cancelled"})}finally{inProgress=!1}}}}function createBranchStateMigration(){return{migrate({entries,fromBranch,toBranch}){let source=entries.filter(entry=>entry.branch===fromBranch);return source.length===0?{status:"empty_source",fromBranch}:{status:"migrated",fromBranch,toBranch,migrated:Object.freeze(source.map(entry=>({key:entry.key,value:entry.value})))}},scan(entries,branch){return Object.freeze(entries.filter(entry=>entry.branch===branch))}}}function createReloadTransaction(){return{reload(items){let failures=[];for(let[index,item]of items.entries()){let failure=item.validate();failure!==null&&failures.push({index,reason:failure})}if(failures.length>0)return{status:"rolled_back",failures:Object.freeze(failures)};for(let item of items)item.commit();return{status:"committed",count:items.length}}}}function createHostCheckpointCoordinator(options={}){let revision=options.startRevision??0,staged=new Map,committed=new Map,tokenSequence=0;return{get currentRevision(){return revision},stage(input){if(typeof input.operationId!="string"||input.operationId.trim().length===0)throw new Error(t("Checkpoint operationId must be a non-empty string"));let appliedRevision=committed.get(input.operationId);if(appliedRevision!==void 0)return{status:"duplicate",revision:appliedRevision};if(input.expectedRevision!==revision)return{status:"stale",currentRevision:revision};tokenSequence+=1;let token=`ckpt-${tokenSequence}`,entry={operationId:input.operationId,expectedRevision:input.expectedRevision,payload:input.payload,state:"staged"};return staged.set(token,entry),{status:"staged",staged:{token,operationId:input.operationId,expectedRevision:input.expectedRevision,currentRevision:revision}}},commitStage({token,apply}){let entry=staged.get(token);if(!entry)return{status:"unknown_token"};if(entry.state==="cancelled")return{status:"cancelled"};if(entry.expectedRevision!==revision)return staged.delete(token),{status:"stale",currentRevision:revision};try{apply(entry.payload,revision+1)}catch(error){return staged.delete(token),{status:"write_failed",reason:error instanceof Error?error.message:String(error)}}return revision+=1,committed.set(entry.operationId,revision),staged.delete(token),{status:"committed",revision}},cancelStage(token){let entry=staged.get(token);return entry?committed.has(entry.operationId)?{status:"already_committed"}:(entry.state="cancelled",{status:"cancelled"}):{status:"unknown_token"}},committedOperationIds(){return Object.freeze([...committed.keys()].sort())}}}function createManualCompactionExecutor(options){let coordinator=options.coordinator,state="idle",currentOperationId;return{get state(){return state},requestCompaction(input){if(state==="in_progress")return{status:"busy",currentOperationId:currentOperationId??"unknown"};if(input.pluginId.trim().length===0)throw new Error(t("Compaction pluginId must be a non-empty string"));state="in_progress",currentOperationId=input.operationId;try{let staged=coordinator.stage({operationId:input.operationId,expectedRevision:coordinator.currentRevision,payload:null});if(staged.status==="stale")return{status:"stale",currentRevision:staged.currentRevision};if(staged.status==="duplicate")return{status:"completed",revision:staged.revision,summary:{duplicate:!0}};let summary;try{summary=input.summarize()}catch(error){return coordinator.cancelStage(staged.staged.token),{status:"summary_failed",reason:error instanceof Error?error.message:String(error)}}let outcome=coordinator.commitStage({token:staged.staged.token,apply:(payload,revision)=>{}});return outcome.status==="stale"?{status:"stale",currentRevision:outcome.currentRevision}:outcome.status==="committed"?{status:"completed",revision:outcome.revision,summary}:{status:"summary_failed",reason:`Unexpected checkpoint outcome: ${outcome.status}`}}finally{state="idle",currentOperationId=void 0}}}}function createOutputReducer(){return{fold(records){let groups=[],pendingTool=null,flushTool=()=>{pendingTool&&(groups.push(pendingTool),pendingTool=null)};for(let record of records){if(record.channel==="tool"&&record.correlationId!==void 0){let isCall=record.severity==="info"&&record.summary.endsWith("called");pendingTool&&pendingTool.correlationId!==record.correlationId&&flushTool(),pendingTool||(pendingTool={kind:"tool",toolName:record.code??record.summary,correlationId:record.correlationId,detailsRef:`trace:${record.traceId}#call:${record.correlationId}`,calls:0,ok:0,failed:0,records:[]}),pendingTool.records.push(record),isCall?pendingTool.calls+=1:record.severity==="ok"?pendingTool.ok+=1:record.severity==="error"&&(pendingTool.failed+=1);continue}flushTool();let last=groups.at(-1);last?.kind==="records"?(last.records.push(record),last.detailsRef=`trace:${record.traceId}#records:${last.records.length}`):groups.push({kind:"records",detailsRef:`trace:${record.traceId}#records:1`,records:[record]})}flushTool();let foldedToolGroups=0,frozenGroups=groups.map(group=>{let base={...group,records:Object.freeze([...group.records])};if(base.kind==="tool"){foldedToolGroups+=1;let firstAt=base.records[0]?.at??0,lastAt=base.records.at(-1)?.at??firstAt;return Object.freeze({...base,durationMs:Math.max(lastAt-firstAt,0)})}return Object.freeze(base)});return{groups:Object.freeze(frozenGroups),totalRecords:records.length,foldedToolGroups}},unfold(folded){return Object.freeze(folded.groups.flatMap(group=>[...group.records]))}}}var INTERNAL_FIELD_KEYS=["memoryId","memoryIds","score","scores","ranking","queryPlan","budget","budgets","agentRole","pluginRole","lease","leaseId","purgeState","rawSources"];function isArtifactLike(value){return typeof value=="object"&&value!==null&&"artifactId"in value&&"sessionId"in value&&"kind"in value}function toArtifactRef(value){if(!(typeof value.sessionId!="string"||typeof value.operationId!="string"||typeof value.artifactId!="string"||typeof value.kind!="string"||typeof value.mediaType!="string"||typeof value.truncated!="boolean"||typeof value.createdAt!="number"))return{sessionId:value.sessionId,operationId:value.operationId,artifactId:value.artifactId,kind:value.kind,mediaType:value.mediaType,...typeof value.sizeBytes=="number"?{sizeBytes:value.sizeBytes}:{},truncated:value.truncated,createdAt:value.createdAt}}function createHostOutputSerializer(){return{project(input,context){if(context.policyVersion.trim().length===0)return{text:"",diagnostics:["output_projection_rejected: policyVersion must be a non-empty string"],rejected:{code:"output_projection_rejected",reason:"policyVersion must be a non-empty string"}};let redactions=[],diagnostics=[],artifacts=[],showInternal=context.surface==="inspector"&&context.inspectorAuthorized,isAllowedKey=key=>!INTERNAL_FIELD_KEYS.includes(key)||showInternal,renderValue=(key,value,path)=>{if(!isAllowedKey(key))return redactions.push(`${path}.${key}`),`[redacted:${key}]`;if(isArtifactLike(value)){let ref=toArtifactRef(value);return ref?(artifacts.push(ref),`[artifact:${ref.artifactId}]`):(diagnostics.push(`output_projection_rejected: ${path}.${key} is a malformed artifact reference`),`[unrenderable:${key}]`)}return typeof value=="string"?value:typeof value=="number"||typeof value=="boolean"?String(value):value===null?"null":Array.isArray(value)?`[${value.map(item=>renderValue(key,item,path)).join(", ")}]`:typeof value=="object"?`{${Object.entries(value).map(([nestedKey,nestedValue])=>`${nestedKey}:${renderValue(nestedKey,nestedValue,`${path}.${key}`)}`).join(", ")}}`:(diagnostics.push(`output_projection_rejected: ${path}.${key} cannot be serialized`),`[unrenderable:${key}]`)},textParts=[];for(let[key,value]of Object.entries(input)){if(key==="artifacts"&&Array.isArray(value)){for(let entry of value)if(isArtifactLike(entry)){let ref=toArtifactRef(entry);ref?artifacts.push(ref):diagnostics.push("output_projection_rejected: artifacts entry is malformed")}else diagnostics.push("output_projection_rejected: artifacts entry is malformed");continue}textParts.push(`${key}=${renderValue(key,value,"root")}`)}return{text:textParts.join(`
3
3
  `),...artifacts.length>0?{artifacts:Object.freeze(artifacts)}:{},...redactions.length>0?{redactions:Object.freeze([...redactions])}:{},...diagnostics.length>0?{diagnostics:Object.freeze([...diagnostics])}:{}}}}}var CLASSIFICATION_TABLE=[["context_overflow",["context length","maximum context","context window","token limit","too many tokens","overflow"]],["rate_limit",["rate limit","429","too many requests"]],["auth",["401","403","unauthorized","forbidden","invalid api key"]],["transient",["timeout","econnreset","econnrefused","socket hang up","502","503"]]];function createOverflowRecovery(options){let coordinator=options.coordinator,classify=error=>{let rawName=error instanceof Error?error.name:typeof error=="object"&&error!==null&&"name"in error?String(error.name):"unknown",rawMessage=error instanceof Error?error.message:String(error),haystack=`${rawName} ${rawMessage}`.toLowerCase();for(let[errorClass,patterns]of CLASSIFICATION_TABLE)if(patterns.some(pattern=>haystack.includes(pattern)))return{errorClass,rawMessage,rawName};return{errorClass:"unknown",rawMessage,rawName}};return{classify,recover({operationId,error,shrink}){let classification=classify(error);if(classification.errorClass!=="context_overflow")return{status:"not_recoverable",errorClass:classification.errorClass,rawMessage:classification.rawMessage,hint:"Only context overflow is recoverable here; rate-limit retry belongs to 2A.4"};let staged=coordinator.stage({operationId,expectedRevision:coordinator.currentRevision,payload:null});if(staged.status==="stale")return{status:"stale",currentRevision:staged.currentRevision,errorClass:classification.errorClass,rawMessage:classification.rawMessage};if(staged.status==="duplicate")return{status:"recovered",revision:staged.revision,shrunk:{duplicate:!0}};let shrunk;try{shrunk=shrink(classification)}catch(shrinkError){return coordinator.cancelStage(staged.staged.token),{status:"projection_failed",errorClass:classification.errorClass,rawMessage:classification.rawMessage,reason:shrinkError instanceof Error?shrinkError.message:String(shrinkError)}}let outcome=coordinator.commitStage({token:staged.staged.token,apply:()=>{}});return outcome.status==="stale"?{status:"stale",currentRevision:outcome.currentRevision,errorClass:classification.errorClass,rawMessage:classification.rawMessage}:outcome.status==="committed"?{status:"recovered",revision:outcome.revision,shrunk}:{status:"projection_failed",errorClass:classification.errorClass,rawMessage:classification.rawMessage,reason:`Unexpected checkpoint outcome: ${outcome.status}`}}}}function createSummaryRetryExecutor(options){let coordinator=options.coordinator,policy=options.policy,now=options.now??(()=>0),sleep=options.sleep??(()=>{});if(policy.attemptLimit<1)throw new Error(t("Summary retry attemptLimit must be at least 1"));if(policy.baseWaitMs<0||policy.maxWaitMs<policy.baseWaitMs)throw new Error(t("Summary retry wait bounds are invalid"));return{execute({operationId,summarize}){let attempts=[];for(let attempt=1;attempt<=policy.attemptLimit;attempt+=1){let at=now(),staged=coordinator.stage({operationId:`${operationId}#${attempt}`,expectedRevision:coordinator.currentRevision,payload:null});if(staged.status==="stale")return{status:"stale",operationId,currentRevision:staged.currentRevision,attempts};if(staged.status==="duplicate")return{status:"succeeded",operationId,revision:staged.revision,summary:{duplicate:!0},attempts};let summary;try{summary=summarize(attempt)}catch(error){coordinator.cancelStage(staged.staged.token);let waitedMs=retryBackoffMs(policy,attempt);attempts.push({attempt,at,ok:!1,failure:error instanceof Error?error.message:String(error),waitedMs}),attempt<policy.attemptLimit&&sleep(waitedMs);continue}let outcome=coordinator.commitStage({token:staged.staged.token,apply:()=>{}});if(outcome.status==="stale")return attempts.push({attempt,at,ok:!0,waitedMs:0}),{status:"stale",operationId,currentRevision:outcome.currentRevision,attempts};if(outcome.status==="committed")return attempts.push({attempt,at,ok:!0,waitedMs:0}),{status:"succeeded",operationId,revision:outcome.revision,summary,attempts}}return{status:"exhausted",operationId,attempts}}}}function createMigrationTool(){let steps=new Map;return{registerStep(step){let key=`${step.fromVersion}->${step.toVersion}`;if(steps.has(key))throw new Error(`Migration step already registered: ${key}`);steps.set(key,step)},migrate({version,targetVersion,data}){if(version===targetVersion)return{status:"already_current",version,data};let applied=[],currentVersion=version,currentData=data;for(;currentVersion!==targetVersion;){let step=steps.get(`${currentVersion}->${targetVersion}`);if(step){try{currentData=step.migrate(currentData)}catch(error){return{status:"failed",data,evidence:Object.freeze([...applied]),failure:{fromVersion:currentVersion,toVersion:targetVersion,reason:error instanceof Error?error.message:String(error)}}}applied.push({fromVersion:currentVersion,toVersion:targetVersion,applied:!0}),currentVersion=targetVersion;break}let nextHop=[...steps.values()].find(candidate=>candidate.fromVersion===currentVersion);if(!nextHop)return{status:"no_path",fromVersion:version,targetVersion};try{currentData=nextHop.migrate(currentData)}catch(error){return{status:"failed",data,evidence:Object.freeze([...applied]),failure:{fromVersion:nextHop.fromVersion,toVersion:nextHop.toVersion,reason:error instanceof Error?error.message:String(error)}}}applied.push({fromVersion:nextHop.fromVersion,toVersion:nextHop.toVersion,applied:!0}),currentVersion=nextHop.toVersion}return{status:"migrated",version:currentVersion,data:currentData,evidence:Object.freeze([...applied])}}}}var BorderedLoader=class extends Container{loader;cancellable;signalController;constructor(tui,theme,message,options){super(),this.cancellable=options?.cancellable??!0;let borderColor=s=>theme.fg("border",s);this.addChild(new DynamicBorder(borderColor)),this.cancellable?this.loader=new CancellableLoader(tui,s=>theme.fg("accent",s),s=>theme.fg("muted",s),message):(this.signalController=new AbortController,this.loader=new Loader(tui,s=>theme.fg("accent",s),s=>theme.fg("muted",s),message)),this.addChild(this.loader),this.cancellable&&(this.addChild(new Spacer(1)),this.addChild(new Text(keyHint("tui.select.cancel",t("cancel")),1,0))),this.addChild(new Spacer(1)),this.addChild(new DynamicBorder(borderColor))}get signal(){return this.cancellable?this.loader.signal:this.signalController?.signal??new AbortController().signal}set onAbort(fn){this.cancellable&&(this.loader.onAbort=fn)}handleInput(data){this.cancellable&&this.loader.handleInput(data)}dispose(){"dispose"in this.loader&&typeof this.loader.dispose=="function"?this.loader.dispose():"stop"in this.loader&&typeof this.loader.stop=="function"&&this.loader.stop()}};var SHOW_IMAGES_SELECT_LIST_LAYOUT={minPrimaryColumnWidth:12,maxPrimaryColumnWidth:32},ShowImagesSelectorComponent=class extends Container{selectList;constructor(currentValue,onSelect,onCancel){super();let items=[{value:"yes",label:t("Yes"),description:t("Show images inline in terminal")},{value:"no",label:t("No"),description:t("Show text placeholder instead")}];this.addChild(new DynamicBorder),this.selectList=new SelectList(items,5,getSelectListTheme(),SHOW_IMAGES_SELECT_LIST_LAYOUT),this.selectList.setSelectedIndex(currentValue?0:1),this.selectList.onSelect=item=>{onSelect(item.value==="yes")},this.selectList.onCancel=()=>{onCancel()},this.addChild(this.selectList),this.addChild(new DynamicBorder)}getSelectList(){return this.selectList}};var THEME_SELECT_LIST_LAYOUT={minPrimaryColumnWidth:12,maxPrimaryColumnWidth:32},ThemeSelectorComponent=class extends Container{selectList;onPreview;constructor(currentTheme,onSelect,onCancel,onPreview){super(),this.onPreview=onPreview;let themes=getAvailableThemes(),themeItems=themes.map(name=>({value:name,label:name,description:name===currentTheme?t("(current)"):void 0}));this.addChild(new DynamicBorder),this.selectList=new SelectList(themeItems,10,getSelectListTheme(),THEME_SELECT_LIST_LAYOUT);let currentIndex=themes.indexOf(currentTheme);currentIndex!==-1&&this.selectList.setSelectedIndex(currentIndex),this.selectList.onSelect=item=>{onSelect(item.value)},this.selectList.onCancel=()=>{onCancel()},this.selectList.onSelectionChange=item=>{this.onPreview(item.value)},this.addChild(this.selectList),this.addChild(new DynamicBorder)}getSelectList(){return this.selectList}};function compareVersions(a,b){let pa=a.split(".").map(part=>Number.parseInt(part,10)||0),pb=b.split(".").map(part=>Number.parseInt(part,10)||0),length=Math.max(pa.length,pb.length);for(let index=0;index<length;index+=1){let diff=(pa[index]??0)-(pb[index]??0);if(diff!==0)return diff}return 0}function createIntegrityAdapter(){return{seal(input){let manifest={pluginId:input.pluginId,version:input.version,source:input.source,payload:input.payload};return Object.freeze({...manifest,digest:stableJsonDigest(manifest)})},verify(manifest,expectation){let actualDigest=stableJsonDigest({pluginId:manifest.pluginId,version:manifest.version,source:manifest.source,payload:manifest.payload});if(expectation.digest!==void 0&&expectation.digest!==actualDigest)return{status:"tampered",expectedDigest:expectation.digest,actualDigest};if(expectation.sourceEquals!==void 0&&manifest.source!==expectation.sourceEquals)return{status:"source_rejected",reason:`Source "${manifest.source}" is not the accepted "${expectation.sourceEquals}"`,source:manifest.source};let range=expectation.versionRange;return range?.min!==void 0&&compareVersions(manifest.version,range.min)<0?{status:"incompatible",reason:`Version ${manifest.version} is below the required ${range.min}`,version:manifest.version}:range?.max!==void 0&&compareVersions(manifest.version,range.max)>0?{status:"incompatible",reason:`Version ${manifest.version} is above the accepted ${range.max}`,version:manifest.version}:{status:"accepted",pluginId:manifest.pluginId,version:manifest.version,digest:actualDigest}}}}function createPluginHost(options){let plugins=[...options.plugins],errors=[],stateRef={current:"created"},messageOf=error=>error instanceof Error?error.message:String(error);return{get state(){return stateRef.current},get errors(){return Object.freeze([...errors])},async start(){let failures=0;for(let plugin of plugins)if(plugin.start)try{await plugin.start()}catch(error){failures+=1,errors.push({pluginId:plugin.pluginId,phase:"start",message:messageOf(error)})}return failures===0?(stateRef.current="started",{state:"started",errors:Object.freeze([...errors])}):failures===plugins.length?(stateRef.current="failed",{state:"failed",errors:Object.freeze([...errors])}):(stateRef.current="partial",{state:"partial",errors:Object.freeze([...errors])})},async dispose(){if(stateRef.current==="disposed")return{errors:Object.freeze([...errors]),leakedResources:Object.freeze([])};for(let plugin of[...plugins].reverse())if(plugin.dispose)try{await plugin.dispose()}catch(error){errors.push({pluginId:plugin.pluginId,phase:"dispose",message:messageOf(error)})}let leaked=[];for(let plugin of plugins)if(plugin.resources)for(let resource of plugin.resources()){try{await resource.release()}catch(error){errors.push({pluginId:plugin.pluginId,phase:"dispose",message:`resource ${resource.name}: ${messageOf(error)}`})}leaked.push(`${plugin.pluginId}/${resource.name}`)}return stateRef.current="disposed",{errors:Object.freeze([...errors]),leakedResources:Object.freeze(leaked)}}}}function createPluginSupervisor(options){let policy=options.policy,now=options.now??(()=>0),entries=new Map,events=[],queue=[];for(let plugin of options.plugins)entries.set(plugin.pluginId,{pluginId:plugin.pluginId,health:"healthy",restarts:0,lastBeatAt:now()});return{supervise(plugin){entries.set(plugin.pluginId,{pluginId:plugin.pluginId,health:"healthy",restarts:0,lastBeatAt:now()})},beat(pluginId){let entry=entries.get(pluginId);if(!entry)throw new Error(t("Unknown supervised plugin: {pluginId}",{pluginId}));entry.lastBeatAt=now(),entry.health="healthy",events.push({kind:"beat",pluginId,at:entry.lastBeatAt})},tick(at){for(let entry of entries.values())entry.health!=="unhealthy"&&at-entry.lastBeatAt>policy.heartbeatIntervalMs&&(entry.health="unhealthy",events.push({kind:"unhealthy",pluginId:entry.pluginId,at}))},restart(pluginId){let entry=entries.get(pluginId);if(!entry)return{status:"unknown"};if(entry.health==="exhausted")return{status:"exhausted",attempts:entry.restarts};if(entry.nextRestartAllowedAt!==void 0&&now()<entry.nextRestartAllowedAt)return{status:"restarted",attempt:entry.restarts};if(entry.restarts+=1,entry.restarts>policy.restartLimit)return entry.health="exhausted",events.push({kind:"exhausted",pluginId,at:now(),attempts:entry.restarts-1}),{status:"exhausted",attempts:entry.restarts-1};options.restartPlugin?.(pluginId,entry.restarts),entry.health="healthy",entry.lastBeatAt=now();let backoff=Math.min(policy.baseRestartMs*2**(entry.restarts-1),Number.MAX_SAFE_INTEGER);return entry.nextRestartAllowedAt=now()+backoff,events.push({kind:"restart",pluginId,at:now(),attempt:entry.restarts}),{status:"restarted",attempt:entry.restarts}},enqueue(event){return queue.length>=policy.queueCap?(events.push({kind:"queue_full",at:now()}),{status:"queue_full",size:queue.length}):(queue.push(event),{status:"enqueued",size:queue.length})},drain(){return Object.freeze(queue.splice(0,queue.length))},health(){return Object.freeze([...entries.values()].map(entry=>({...entry})))},get queueSize(){return queue.length}}}function createSessionShare(options){let now=options.now??(()=>Date.now()),contracts=new Map,shareSequence=0,shareIdOf=sessionId=>{shareSequence+=1;let hash=2166136261,value=`${sessionId}#${shareSequence}`;for(let index=0;index<value.length;index+=1)hash^=value.charCodeAt(index),hash=Math.imul(hash,16777619);return`share-${(hash>>>0).toString(36)}`};return{transport:options.transport,createShare(input){let contract={shareId:shareIdOf(input.sessionId),sessionId:input.sessionId,permission:"read_only",scope:input.scope,createdAt:now(),...input.expiresAt===void 0?{}:{expiresAt:input.expiresAt}};return contracts.set(contract.shareId,{contract}),contract},resolve({shareId,request,now:at}){let record=contracts.get(shareId);if(!record)return{status:"not_found",shareId};let currentTime=at??now();if(record.revokedReason!==void 0)return{status:"denied",reason:`Share ${shareId} is revoked: ${record.revokedReason}`};if(record.contract.expiresAt!==void 0&&currentTime>record.contract.expiresAt)return{status:"denied",reason:`Share ${shareId} expired at ${record.contract.expiresAt}`};let{scope}=record.contract;switch(request.kind){case"messages":return scope.messages?{status:"resolved",kind:"messages",content:options.readMessages(record.contract.sessionId)}:{status:"denied",reason:"Messages are outside the share scope"};case"diagnostics":return scope.diagnostics?{status:"resolved",kind:"diagnostics",content:options.readDiagnostics(record.contract.sessionId)}:{status:"denied",reason:"Diagnostics are outside the share scope"};case"artifact":return scope.artifacts.includes(request.artifactId)?{status:"resolved",kind:"artifact",artifact:options.readArtifact({sessionId:record.contract.sessionId,artifactId:request.artifactId})}:{status:"denied",reason:`Artifact ${request.artifactId} is not in the share whitelist`}}},revoke(shareId,input){let record=contracts.get(shareId);if(!record)throw new Error(t("Share not found: {shareId}",{shareId}));if(record.revokedReason!==void 0)throw new Error(t("Share {shareId} has already been revoked",{shareId}));return record.revokedReason=input.reason,record.contract}}}function escapeHtml(value){return value.replaceAll("&","&amp;").replaceAll("<","&lt;").replaceAll(">","&gt;").replaceAll('"',"&quot;").replaceAll("'","&#39;")}function failureView(shareId,reason){return[`<article class="share-share-failure" data-share="${escapeHtml(shareId)}">`,"<h1>Share unavailable</h1>",`<p class="share-reason">${escapeHtml(reason)}</p>`,"</article>"].join(`
4
4
  `)}function createShareViewer(){return{render({contract,result}){if(result.status!=="resolved"){let reason=result.status==="denied"?result.reason:`Unknown share: ${result.shareId}`;return{shareId:contract.shareId,state:"failed",html:failureView(contract.shareId,reason),payload:{shareId:contract.shareId,state:"failed",reason}}}let bodyHtml,payload;switch(result.kind){case"messages":{let content=result.content,turns=Array.isArray(content.turns)?content.turns:[];bodyHtml=["<h1>Shared messages</h1>",'<ol class="share-turns">',...turns.map(turn=>`<li>${escapeHtml(String(turn))}</li>`),"</ol>"].join(`
5
5
  `),payload={shareId:contract.shareId,state:"resolved",kind:"messages",turns:[...turns]};break}case"diagnostics":{bodyHtml=`<h1>Shared diagnostics</h1><pre class="share-diagnostics">${escapeHtml(JSON.stringify(result.content))}</pre>`,payload={shareId:contract.shareId,state:"resolved",kind:"diagnostics",content:result.content};break}case"artifact":{bodyHtml=["<h1>Shared artifact</h1>",`<p class="share-artifact" data-artifact="${escapeHtml(result.artifact.artifactId)}">`,`${escapeHtml(result.artifact.mediaType)} \xB7 ${escapeHtml(result.artifact.bytesBase64)}`,"</p>"].join(`
@@ -1,3 +1,3 @@
1
1
  #!/usr/bin/env node
2
2
  import { createRequire as __piCreateRequire } from "node:module"; const require = __piCreateRequire(import.meta.url);
3
- import{configureHttpDispatcher,main}from"./chunks/chunk-VWNIFYQA.js";import{APP_NAME}from"./chunks/chunk-F73USSXE.js";import"./chunks/chunk-JUUC5AZY.js";import"./chunks/chunk-XDUWOHPL.js";import"./chunks/chunk-3QKHSPQL.js";import"./chunks/chunk-HXGAAJQQ.js";import"./chunks/chunk-BVVSHK6W.js";import"./chunks/chunk-TRDNDS6A.js";import"./chunks/chunk-K3S6GTL7.js";import"./chunks/chunk-5LRQFZFE.js";import"./chunks/chunk-4L3WN2XY.js";process.title=`${APP_NAME}-rpc`;process.env.AGENT_FORGE="true";process.env.AI_AGENT="agent-forge";process.emitWarning=(()=>{});configureHttpDispatcher();main(["--mode","rpc",...process.argv.slice(2)]);
3
+ import{configureHttpDispatcher,main}from"./chunks/chunk-ZZCUNSGO.js";import{APP_NAME}from"./chunks/chunk-F73USSXE.js";import"./chunks/chunk-JUUC5AZY.js";import"./chunks/chunk-XDUWOHPL.js";import"./chunks/chunk-3QKHSPQL.js";import"./chunks/chunk-HXGAAJQQ.js";import"./chunks/chunk-BVVSHK6W.js";import"./chunks/chunk-TRDNDS6A.js";import"./chunks/chunk-K3S6GTL7.js";import"./chunks/chunk-5LRQFZFE.js";import"./chunks/chunk-4L3WN2XY.js";process.title=`${APP_NAME}-rpc`;process.env.AGENT_FORGE="true";process.env.AI_AGENT="agent-forge";process.emitWarning=(()=>{});configureHttpDispatcher();main(["--mode","rpc",...process.argv.slice(2)]);
@@ -1 +1 @@
1
- {"version":3,"file":"node-disk-registry-source.d.ts","sourceRoot":"","sources":["../../../src/plugins/ecosystem/node-disk-registry-source.ts"],"names":[],"mappings":"AAIA,OAAO,KAAK,EAAoC,sBAAsB,EAAE,MAAM,eAAe,CAAC;AAG9F,QAAA,MAAM,oCAAoC,GAAa,CAAC;AACxD,oEAAoE;AACpE,eAAO,MAAM,qCAAqC,QAAc,CAAC;AACjE,+EAA+E;AAC/E,eAAO,MAAM,wCAAwC,QAAY,CAAC;AAClE,6FAA6F;AAC7F,eAAO,MAAM,iCAAiC,MAAM,CAAC;AAOrD,MAAM,MAAM,iCAAiC,GAC1C,WAAW,GACX,uBAAuB,GACvB,eAAe,GACf,kBAAkB,GAClB,mBAAmB,GACnB,kBAAkB,GAClB,WAAW,CAAC;AAEf;;;GAGG;AACH,qBAAa,6BAA8B,SAAQ,KAAK;IACvD,QAAQ,CAAC,IAAI,EAAE,iCAAiC,CAAC;IAEjD,YAAY,IAAI,EAAE,iCAAiC,EAAE,OAAO,EAAE,MAAM,EAInE;CACD;AAED,MAAM,WAAW,+BAA+B;IAC/C,0FAA0F;IAC1F,QAAQ,CAAC,aAAa,EAAE,MAAM,CAAC;CAC/B;AAED,MAAM,WAAW,oCAAoC;IACpD,QAAQ,CAAC,QAAQ,EAAE,MAAM,CAAC;IAC1B,QAAQ,CAAC,aAAa,EAAE,MAAM,CAAC;IAC/B,QAAQ,CAAC,MAAM,CAAC,EAAE,WAAW,CAAC;CAC9B;AAED,MAAM,WAAW,wBAAyB,SAAQ,sBAAsB;IACvE,QAAQ,CAAC,OAAO,EAAE,OAAO,oCAAoC,CAAC;IAC9D;;;;;;OAMG;IACH,QAAQ,CAAC,6BAA6B,CAAC,EAAE,CACxC,KAAK,EAAE,oCAAoC,KACvC,OAAO,CAAC,MAAM,GAAG,SAAS,CAAC,CAAC;CACjC;AA6JD;;;;;;GAMG;AACH,wBAAgB,oCAAoC,CACnD,OAAO,EAAE,+BAA+B,GACtC,wBAAwB,CAqD1B","sourcesContent":["import { open } from \"node:fs/promises\";\nimport { isAbsolute, join } from \"node:path\";\nimport { t } from \"../../core/i18n/index.ts\";\nimport { withinInstallStoreRoot } from \"./install-store-paths.ts\";\nimport type { PluginRegistryManifestEnvelopeV1, PluginRegistrySourceV1 } from \"./registry.ts\";\nimport type { PluginManifestV1 } from \"./types.ts\";\n\nconst NODE_DISK_REGISTRY_SOURCE_VERSION_V1 = 1 as const;\n/** Maximum index.v1.json bytes accepted by this source boundary. */\nexport const MAX_NODE_DISK_REGISTRY_INDEX_BYTES_V1 = 1024 * 1024;\n/** Maximum per-installation agent-forge.json bytes accepted by this source. */\nexport const MAX_NODE_DISK_REGISTRY_MANIFEST_BYTES_V1 = 64 * 1024;\n/** Maximum index records projected by one list() call; matches the registry manifest cap. */\nexport const MAX_NODE_DISK_REGISTRY_RECORDS_V1 = 256;\n\nconst INDEX_FILE_V1 = \"index.v1.json\";\nconst ECOSYSTEM_MANIFEST_FILE_V1 = \"agent-forge.json\";\nconst CAPABILITY_MANIFEST_FILE_V1 = \"plugin.json\";\nconst NODE_PACKAGE_FORMAT_VERSION_V1 = 1;\n\nexport type NodeDiskRegistrySourceErrorCodeV1 =\n\t| \"cancelled\"\n\t| \"invalid_configuration\"\n\t| \"invalid_index\"\n\t| \"invalid_manifest\"\n\t| \"identity_mismatch\"\n\t| \"too_many_records\"\n\t| \"io_failed\";\n\n/**\n * Deliberately does not retain filesystem exceptions or file contents: callers\n * must not turn registry diagnostics into a path or package disclosure.\n */\nexport class NodeDiskRegistrySourceErrorV1 extends Error {\n\treadonly code: NodeDiskRegistrySourceErrorCodeV1;\n\n\tconstructor(code: NodeDiskRegistrySourceErrorCodeV1, message: string) {\n\t\tsuper(message);\n\t\tthis.name = \"NodeDiskRegistrySourceErrorV1\";\n\t\tthis.code = code;\n\t}\n}\n\nexport interface NodeDiskRegistrySourceOptionsV1 {\n\t/** Absolute host-owned default install store directory. It is never returned in a DTO. */\n\treadonly rootDirectory: string;\n}\n\nexport interface NodeDiskRegistrySourceResolveInputV1 {\n\treadonly pluginId: string;\n\treadonly pluginVersion: string;\n\treadonly signal?: AbortSignal;\n}\n\nexport interface NodeDiskRegistrySourceV1 extends PluginRegistrySourceV1 {\n\treadonly version: typeof NODE_DISK_REGISTRY_SOURCE_VERSION_V1;\n\t/**\n\t * Internal host channel (D-075 S2): absolute `plugin.json` path of the\n\t * installation directory matching `{pluginId, pluginVersion}` in the store\n\t * index, for the sdk's installed-plugin code loading. Registry snapshots\n\t * still carry no paths; undefined means no matching record or the manifest\n\t * file is absent from the installation directory.\n\t */\n\treadonly resolveCapabilityManifestPath?: (\n\t\tinput: NodeDiskRegistrySourceResolveInputV1,\n\t) => Promise<string | undefined>;\n}\n\ninterface DiskIndexRecordV1 {\n\treadonly installationRef: string;\n\treadonly directory: string;\n\treadonly pluginId: string;\n\treadonly pluginVersion: string;\n\treadonly manifestDigest: string;\n\treadonly scope: \"global\" | \"project\";\n\treadonly scopeRef: string;\n\treadonly state: \"installed\" | \"active\" | \"retained\";\n}\n\nconst INDEX_KEYS_V1 = [\n\t\"installationRef\",\n\t\"directory\",\n\t\"pluginId\",\n\t\"pluginVersion\",\n\t\"manifestDigest\",\n\t\"scope\",\n\t\"scopeRef\",\n\t\"state\",\n] as const;\n\nfunction opaqueField(value: unknown, max: number): value is string {\n\treturn (\n\t\ttypeof value === \"string\" &&\n\t\tvalue.length > 0 &&\n\t\tvalue.length <= max &&\n\t\t!/[\\u0000-\\u001f\\u007f]/u.test(value) &&\n\t\t!/\\s/u.test(value) &&\n\t\t!/^(?:file:|[a-z]:[\\\\/]|[\\\\/]{1,2}|\\\\\\\\)/iu.test(value)\n\t);\n}\n\nfunction boundedField(value: unknown, max: number): value is string {\n\treturn typeof value === \"string\" && value.length > 0 && value.length <= max && !/[\\u0000-\\u001f\\u007f]/u.test(value);\n}\n\nfunction validateRecord(root: string, value: unknown, index: number): DiskIndexRecordV1 {\n\tif (value === null || typeof value !== \"object\" || Array.isArray(value))\n\t\tthrow new NodeDiskRegistrySourceErrorV1(\"invalid_index\", t(\"Index record {index} is not an object\", { index }));\n\tconst record = value as Record<string, unknown>;\n\tconst keys = INDEX_KEYS_V1;\n\tif (Object.keys(record).length !== keys.length || keys.some((key) => !(key in record)))\n\t\tthrow new NodeDiskRegistrySourceErrorV1(\n\t\t\t\"invalid_index\",\n\t\t\tt(\"Index record {index} has an invalid schema\", { index }),\n\t\t);\n\tif (\n\t\t!opaqueField(record.installationRef, 2048) ||\n\t\t!boundedField(record.directory, 2048) ||\n\t\t!boundedField(record.pluginId, 256) ||\n\t\t!boundedField(record.pluginVersion, 256) ||\n\t\t!boundedField(record.manifestDigest, 512) ||\n\t\t!opaqueField(record.scopeRef, 2048) ||\n\t\t(record.scope !== \"global\" && record.scope !== \"project\") ||\n\t\t(record.state !== \"installed\" && record.state !== \"active\" && record.state !== \"retained\") ||\n\t\t!withinInstallStoreRoot(root, record.directory)\n\t)\n\t\tthrow new NodeDiskRegistrySourceErrorV1(\"invalid_index\", t(\"Index record {index} is invalid\", { index }));\n\treturn {\n\t\tinstallationRef: record.installationRef,\n\t\tdirectory: record.directory,\n\t\tpluginId: record.pluginId,\n\t\tpluginVersion: record.pluginVersion,\n\t\tmanifestDigest: record.manifestDigest,\n\t\tscope: record.scope,\n\t\tscopeRef: record.scopeRef,\n\t\tstate: record.state,\n\t};\n}\n\nfunction parseIndex(root: string, raw: string): readonly DiskIndexRecordV1[] {\n\tlet parsed: unknown;\n\ttry {\n\t\tparsed = JSON.parse(raw);\n\t} catch {\n\t\tthrow new NodeDiskRegistrySourceErrorV1(\"invalid_index\", t(\"Install store index JSON is invalid\"));\n\t}\n\tif (parsed === null || typeof parsed !== \"object\" || Array.isArray(parsed))\n\t\tthrow new NodeDiskRegistrySourceErrorV1(\"invalid_index\", t(\"Install store index is not an object\"));\n\tconst value = parsed as Record<string, unknown>;\n\tif (\n\t\tObject.keys(value).length !== 2 ||\n\t\tvalue.version !== NODE_DISK_REGISTRY_SOURCE_VERSION_V1 ||\n\t\t!Array.isArray(value.records)\n\t)\n\t\tthrow new NodeDiskRegistrySourceErrorV1(\"invalid_index\", t(\"Install store index schema is unsupported\"));\n\tif (value.records.length > MAX_NODE_DISK_REGISTRY_RECORDS_V1)\n\t\tthrow new NodeDiskRegistrySourceErrorV1(\"too_many_records\", t(\"Install store index exceeds the record limit\"));\n\treturn value.records.map((record, index) => validateRecord(root, record, index));\n}\n\n/** Read a bounded UTF-8 file; the absolute path never appears in a thrown message. */\nasync function readBoundedFile(path: string, maxBytes: number, label: string): Promise<string> {\n\tconst handle = await open(path, \"r\");\n\ttry {\n\t\tconst stat = await handle.stat();\n\t\tif (!stat.isFile() || stat.size > maxBytes)\n\t\t\tthrow new NodeDiskRegistrySourceErrorV1(\n\t\t\t\tlabel === \"index\" ? \"invalid_index\" : \"invalid_manifest\",\n\t\t\t\tt(\"{label} exceeds the size limit\", { label }),\n\t\t\t);\n\t\treturn await handle.readFile(\"utf8\");\n\t} finally {\n\t\tawait handle.close().catch(() => undefined);\n\t}\n}\n\nfunction parseManifest(record: DiskIndexRecordV1, raw: string): PluginManifestV1 {\n\tlet parsed: unknown;\n\ttry {\n\t\tparsed = JSON.parse(raw);\n\t} catch {\n\t\tthrow new NodeDiskRegistrySourceErrorV1(\"invalid_manifest\", t(\"Installed plugin manifest JSON is invalid\"));\n\t}\n\tif (parsed === null || typeof parsed !== \"object\" || Array.isArray(parsed))\n\t\tthrow new NodeDiskRegistrySourceErrorV1(\"invalid_manifest\", t(\"Installed plugin manifest is not an object\"));\n\tconst value = { ...(parsed as Record<string, unknown>) };\n\tif (value.packageFormatVersion !== undefined && value.packageFormatVersion !== NODE_PACKAGE_FORMAT_VERSION_V1)\n\t\tthrow new NodeDiskRegistrySourceErrorV1(\"invalid_manifest\", t(\"Installed plugin package format is unsupported\"));\n\t// The package envelope version is an install-host field; it is not part of\n\t// PluginManifestV1 and the stable manifest digest excludes it.\n\tdelete value.packageFormatVersion;\n\tif (value.id !== record.pluginId || value.pluginVersion !== record.pluginVersion)\n\t\tthrow new NodeDiskRegistrySourceErrorV1(\n\t\t\t\"identity_mismatch\",\n\t\t\tt(\"Installed plugin manifest identity does not match index record for {identity}\", {\n\t\t\t\tidentity: `${record.pluginId}@${record.pluginVersion}`,\n\t\t\t}),\n\t\t);\n\treturn value as unknown as PluginManifestV1;\n}\n\n/** Read the install store index records; undefined when the store is empty. */\nasync function readIndexRecords(\n\trootDirectory: string,\n\tsignal: AbortSignal | undefined,\n): Promise<readonly DiskIndexRecordV1[] | undefined> {\n\tif (signal?.aborted)\n\t\tthrow new NodeDiskRegistrySourceErrorV1(\"cancelled\", t(\"Disk registry source read was cancelled\"));\n\tlet rawIndex: string;\n\ttry {\n\t\trawIndex = await readBoundedFile(\n\t\t\tjoin(rootDirectory, INDEX_FILE_V1),\n\t\t\tMAX_NODE_DISK_REGISTRY_INDEX_BYTES_V1,\n\t\t\t\"index\",\n\t\t);\n\t} catch (error) {\n\t\tif (error instanceof NodeDiskRegistrySourceErrorV1) throw error;\n\t\tif (error instanceof Error && \"code\" in error && error.code === \"ENOENT\") return undefined;\n\t\tthrow new NodeDiskRegistrySourceErrorV1(\"io_failed\", t(\"Install store index could not be read\"));\n\t}\n\treturn parseIndex(rootDirectory, rawIndex);\n}\n\n/**\n * Read-only registry source over the default install store. It projects the\n * persistent index and each installation instance's ecosystem manifest as\n * bounded envelopes for the registry's own digest verification. It never\n * writes the index or installation directories, and installation directories\n * stay inside the host-owned store.\n */\nexport function createNodeDiskPluginRegistrySourceV1(\n\toptions: NodeDiskRegistrySourceOptionsV1,\n): NodeDiskRegistrySourceV1 {\n\tconst rootDirectory = options.rootDirectory;\n\tif (typeof rootDirectory !== \"string\" || !isAbsolute(rootDirectory) || rootDirectory.trim() === \"\")\n\t\tthrow new NodeDiskRegistrySourceErrorV1(\n\t\t\t\"invalid_configuration\",\n\t\t\tt(\"Install store root directory must be absolute\"),\n\t\t);\n\treturn {\n\t\tversion: NODE_DISK_REGISTRY_SOURCE_VERSION_V1,\n\t\tlist: async ({ signal } = {}) => {\n\t\t\tconst records = await readIndexRecords(rootDirectory, signal);\n\t\t\tif (records === undefined) return Object.freeze([]);\n\t\t\tconst envelopes: PluginRegistryManifestEnvelopeV1[] = [];\n\t\t\tfor (const record of records) {\n\t\t\t\tif (signal?.aborted)\n\t\t\t\t\tthrow new NodeDiskRegistrySourceErrorV1(\"cancelled\", t(\"Disk registry source read was cancelled\"));\n\t\t\t\tlet rawManifest: string;\n\t\t\t\ttry {\n\t\t\t\t\trawManifest = await readBoundedFile(\n\t\t\t\t\t\tjoin(record.directory, ECOSYSTEM_MANIFEST_FILE_V1),\n\t\t\t\t\t\tMAX_NODE_DISK_REGISTRY_MANIFEST_BYTES_V1,\n\t\t\t\t\t\t\"manifest\",\n\t\t\t\t\t);\n\t\t\t\t} catch (error) {\n\t\t\t\t\tif (error instanceof NodeDiskRegistrySourceErrorV1) throw error;\n\t\t\t\t\tthrow new NodeDiskRegistrySourceErrorV1(\"io_failed\", t(\"Installed plugin manifest could not be read\"));\n\t\t\t\t}\n\t\t\t\tconst manifest = parseManifest(record, rawManifest);\n\t\t\t\tenvelopes.push({\n\t\t\t\t\tmanifest,\n\t\t\t\t\tsource: record.installationRef,\n\t\t\t\t\tmanifestDigest: record.manifestDigest,\n\t\t\t\t});\n\t\t\t}\n\t\t\treturn Object.freeze(envelopes);\n\t\t},\n\t\tresolveCapabilityManifestPath: async ({ pluginId, pluginVersion, signal }) => {\n\t\t\tconst records = await readIndexRecords(rootDirectory, signal);\n\t\t\tif (records === undefined) return undefined;\n\t\t\tconst record = records.find(\n\t\t\t\t(candidate) => candidate.pluginId === pluginId && candidate.pluginVersion === pluginVersion,\n\t\t\t);\n\t\t\tif (record === undefined) return undefined;\n\t\t\tconst manifestPath = join(record.directory, CAPABILITY_MANIFEST_FILE_V1);\n\t\t\ttry {\n\t\t\t\tconst handle = await open(manifestPath, \"r\");\n\t\t\t\tawait handle.close().catch(() => undefined);\n\t\t\t} catch {\n\t\t\t\treturn undefined;\n\t\t\t}\n\t\t\treturn manifestPath;\n\t\t},\n\t};\n}\n"]}
1
+ {"version":3,"file":"node-disk-registry-source.d.ts","sourceRoot":"","sources":["../../../src/plugins/ecosystem/node-disk-registry-source.ts"],"names":[],"mappings":"AAIA,OAAO,KAAK,EAAoC,sBAAsB,EAAE,MAAM,eAAe,CAAC;AAG9F,QAAA,MAAM,oCAAoC,GAAa,CAAC;AACxD,oEAAoE;AACpE,eAAO,MAAM,qCAAqC,QAAc,CAAC;AACjE,+EAA+E;AAC/E,eAAO,MAAM,wCAAwC,QAAY,CAAC;AAClE,6FAA6F;AAC7F,eAAO,MAAM,iCAAiC,MAAM,CAAC;AAOrD,MAAM,MAAM,iCAAiC,GAC1C,WAAW,GACX,uBAAuB,GACvB,eAAe,GACf,kBAAkB,GAClB,mBAAmB,GACnB,kBAAkB,GAClB,WAAW,CAAC;AAEf;;;GAGG;AACH,qBAAa,6BAA8B,SAAQ,KAAK;IACvD,QAAQ,CAAC,IAAI,EAAE,iCAAiC,CAAC;IAEjD,YAAY,IAAI,EAAE,iCAAiC,EAAE,OAAO,EAAE,MAAM,EAInE;CACD;AAED,MAAM,WAAW,+BAA+B;IAC/C,0FAA0F;IAC1F,QAAQ,CAAC,aAAa,EAAE,MAAM,CAAC;CAC/B;AAED,MAAM,WAAW,oCAAoC;IACpD,QAAQ,CAAC,QAAQ,EAAE,MAAM,CAAC;IAC1B,QAAQ,CAAC,aAAa,EAAE,MAAM,CAAC;IAC/B,QAAQ,CAAC,MAAM,CAAC,EAAE,WAAW,CAAC;CAC9B;AAED,MAAM,WAAW,wBAAyB,SAAQ,sBAAsB;IACvE,QAAQ,CAAC,OAAO,EAAE,OAAO,oCAAoC,CAAC;IAC9D;;;;;;OAMG;IACH,QAAQ,CAAC,6BAA6B,CAAC,EAAE,CACxC,KAAK,EAAE,oCAAoC,KACvC,OAAO,CAAC,MAAM,GAAG,SAAS,CAAC,CAAC;CACjC;AA6JD;;;;;;GAMG;AACH,wBAAgB,oCAAoC,CACnD,OAAO,EAAE,+BAA+B,GACtC,wBAAwB,CAoE1B","sourcesContent":["import { open } from \"node:fs/promises\";\nimport { isAbsolute, join } from \"node:path\";\nimport { t } from \"../../core/i18n/index.ts\";\nimport { withinInstallStoreRoot } from \"./install-store-paths.ts\";\nimport type { PluginRegistryManifestEnvelopeV1, PluginRegistrySourceV1 } from \"./registry.ts\";\nimport type { PluginManifestV1 } from \"./types.ts\";\n\nconst NODE_DISK_REGISTRY_SOURCE_VERSION_V1 = 1 as const;\n/** Maximum index.v1.json bytes accepted by this source boundary. */\nexport const MAX_NODE_DISK_REGISTRY_INDEX_BYTES_V1 = 1024 * 1024;\n/** Maximum per-installation agent-forge.json bytes accepted by this source. */\nexport const MAX_NODE_DISK_REGISTRY_MANIFEST_BYTES_V1 = 64 * 1024;\n/** Maximum index records projected by one list() call; matches the registry manifest cap. */\nexport const MAX_NODE_DISK_REGISTRY_RECORDS_V1 = 256;\n\nconst INDEX_FILE_V1 = \"index.v1.json\";\nconst ECOSYSTEM_MANIFEST_FILE_V1 = \"agent-forge.json\";\nconst CAPABILITY_MANIFEST_FILE_V1 = \"plugin.json\";\nconst NODE_PACKAGE_FORMAT_VERSION_V1 = 1;\n\nexport type NodeDiskRegistrySourceErrorCodeV1 =\n\t| \"cancelled\"\n\t| \"invalid_configuration\"\n\t| \"invalid_index\"\n\t| \"invalid_manifest\"\n\t| \"identity_mismatch\"\n\t| \"too_many_records\"\n\t| \"io_failed\";\n\n/**\n * Deliberately does not retain filesystem exceptions or file contents: callers\n * must not turn registry diagnostics into a path or package disclosure.\n */\nexport class NodeDiskRegistrySourceErrorV1 extends Error {\n\treadonly code: NodeDiskRegistrySourceErrorCodeV1;\n\n\tconstructor(code: NodeDiskRegistrySourceErrorCodeV1, message: string) {\n\t\tsuper(message);\n\t\tthis.name = \"NodeDiskRegistrySourceErrorV1\";\n\t\tthis.code = code;\n\t}\n}\n\nexport interface NodeDiskRegistrySourceOptionsV1 {\n\t/** Absolute host-owned default install store directory. It is never returned in a DTO. */\n\treadonly rootDirectory: string;\n}\n\nexport interface NodeDiskRegistrySourceResolveInputV1 {\n\treadonly pluginId: string;\n\treadonly pluginVersion: string;\n\treadonly signal?: AbortSignal;\n}\n\nexport interface NodeDiskRegistrySourceV1 extends PluginRegistrySourceV1 {\n\treadonly version: typeof NODE_DISK_REGISTRY_SOURCE_VERSION_V1;\n\t/**\n\t * Internal host channel (D-075 S2): absolute `plugin.json` path of the\n\t * installation directory matching `{pluginId, pluginVersion}` in the store\n\t * index, for the sdk's installed-plugin code loading. Registry snapshots\n\t * still carry no paths; undefined means no matching record or the manifest\n\t * file is absent from the installation directory.\n\t */\n\treadonly resolveCapabilityManifestPath?: (\n\t\tinput: NodeDiskRegistrySourceResolveInputV1,\n\t) => Promise<string | undefined>;\n}\n\ninterface DiskIndexRecordV1 {\n\treadonly installationRef: string;\n\treadonly directory: string;\n\treadonly pluginId: string;\n\treadonly pluginVersion: string;\n\treadonly manifestDigest: string;\n\treadonly scope: \"global\" | \"project\";\n\treadonly scopeRef: string;\n\treadonly state: \"installed\" | \"active\" | \"retained\";\n}\n\nconst INDEX_KEYS_V1 = [\n\t\"installationRef\",\n\t\"directory\",\n\t\"pluginId\",\n\t\"pluginVersion\",\n\t\"manifestDigest\",\n\t\"scope\",\n\t\"scopeRef\",\n\t\"state\",\n] as const;\n\nfunction opaqueField(value: unknown, max: number): value is string {\n\treturn (\n\t\ttypeof value === \"string\" &&\n\t\tvalue.length > 0 &&\n\t\tvalue.length <= max &&\n\t\t!/[\\u0000-\\u001f\\u007f]/u.test(value) &&\n\t\t!/\\s/u.test(value) &&\n\t\t!/^(?:file:|[a-z]:[\\\\/]|[\\\\/]{1,2}|\\\\\\\\)/iu.test(value)\n\t);\n}\n\nfunction boundedField(value: unknown, max: number): value is string {\n\treturn typeof value === \"string\" && value.length > 0 && value.length <= max && !/[\\u0000-\\u001f\\u007f]/u.test(value);\n}\n\nfunction validateRecord(root: string, value: unknown, index: number): DiskIndexRecordV1 {\n\tif (value === null || typeof value !== \"object\" || Array.isArray(value))\n\t\tthrow new NodeDiskRegistrySourceErrorV1(\"invalid_index\", t(\"Index record {index} is not an object\", { index }));\n\tconst record = value as Record<string, unknown>;\n\tconst keys = INDEX_KEYS_V1;\n\tif (Object.keys(record).length !== keys.length || keys.some((key) => !(key in record)))\n\t\tthrow new NodeDiskRegistrySourceErrorV1(\n\t\t\t\"invalid_index\",\n\t\t\tt(\"Index record {index} has an invalid schema\", { index }),\n\t\t);\n\tif (\n\t\t!opaqueField(record.installationRef, 2048) ||\n\t\t!boundedField(record.directory, 2048) ||\n\t\t!boundedField(record.pluginId, 256) ||\n\t\t!boundedField(record.pluginVersion, 256) ||\n\t\t!boundedField(record.manifestDigest, 512) ||\n\t\t!opaqueField(record.scopeRef, 2048) ||\n\t\t(record.scope !== \"global\" && record.scope !== \"project\") ||\n\t\t(record.state !== \"installed\" && record.state !== \"active\" && record.state !== \"retained\") ||\n\t\t!withinInstallStoreRoot(root, record.directory)\n\t)\n\t\tthrow new NodeDiskRegistrySourceErrorV1(\"invalid_index\", t(\"Index record {index} is invalid\", { index }));\n\treturn {\n\t\tinstallationRef: record.installationRef,\n\t\tdirectory: record.directory,\n\t\tpluginId: record.pluginId,\n\t\tpluginVersion: record.pluginVersion,\n\t\tmanifestDigest: record.manifestDigest,\n\t\tscope: record.scope,\n\t\tscopeRef: record.scopeRef,\n\t\tstate: record.state,\n\t};\n}\n\nfunction parseIndex(root: string, raw: string): readonly DiskIndexRecordV1[] {\n\tlet parsed: unknown;\n\ttry {\n\t\tparsed = JSON.parse(raw);\n\t} catch {\n\t\tthrow new NodeDiskRegistrySourceErrorV1(\"invalid_index\", t(\"Install store index JSON is invalid\"));\n\t}\n\tif (parsed === null || typeof parsed !== \"object\" || Array.isArray(parsed))\n\t\tthrow new NodeDiskRegistrySourceErrorV1(\"invalid_index\", t(\"Install store index is not an object\"));\n\tconst value = parsed as Record<string, unknown>;\n\tif (\n\t\tObject.keys(value).length !== 2 ||\n\t\tvalue.version !== NODE_DISK_REGISTRY_SOURCE_VERSION_V1 ||\n\t\t!Array.isArray(value.records)\n\t)\n\t\tthrow new NodeDiskRegistrySourceErrorV1(\"invalid_index\", t(\"Install store index schema is unsupported\"));\n\tif (value.records.length > MAX_NODE_DISK_REGISTRY_RECORDS_V1)\n\t\tthrow new NodeDiskRegistrySourceErrorV1(\"too_many_records\", t(\"Install store index exceeds the record limit\"));\n\treturn value.records.map((record, index) => validateRecord(root, record, index));\n}\n\n/** Read a bounded UTF-8 file; the absolute path never appears in a thrown message. */\nasync function readBoundedFile(path: string, maxBytes: number, label: string): Promise<string> {\n\tconst handle = await open(path, \"r\");\n\ttry {\n\t\tconst stat = await handle.stat();\n\t\tif (!stat.isFile() || stat.size > maxBytes)\n\t\t\tthrow new NodeDiskRegistrySourceErrorV1(\n\t\t\t\tlabel === \"index\" ? \"invalid_index\" : \"invalid_manifest\",\n\t\t\t\tt(\"{label} exceeds the size limit\", { label }),\n\t\t\t);\n\t\treturn await handle.readFile(\"utf8\");\n\t} finally {\n\t\tawait handle.close().catch(() => undefined);\n\t}\n}\n\nfunction parseManifest(record: DiskIndexRecordV1, raw: string): PluginManifestV1 {\n\tlet parsed: unknown;\n\ttry {\n\t\tparsed = JSON.parse(raw);\n\t} catch {\n\t\tthrow new NodeDiskRegistrySourceErrorV1(\"invalid_manifest\", t(\"Installed plugin manifest JSON is invalid\"));\n\t}\n\tif (parsed === null || typeof parsed !== \"object\" || Array.isArray(parsed))\n\t\tthrow new NodeDiskRegistrySourceErrorV1(\"invalid_manifest\", t(\"Installed plugin manifest is not an object\"));\n\tconst value = { ...(parsed as Record<string, unknown>) };\n\tif (value.packageFormatVersion !== undefined && value.packageFormatVersion !== NODE_PACKAGE_FORMAT_VERSION_V1)\n\t\tthrow new NodeDiskRegistrySourceErrorV1(\"invalid_manifest\", t(\"Installed plugin package format is unsupported\"));\n\t// The package envelope version is an install-host field; it is not part of\n\t// PluginManifestV1 and the stable manifest digest excludes it.\n\tdelete value.packageFormatVersion;\n\tif (value.id !== record.pluginId || value.pluginVersion !== record.pluginVersion)\n\t\tthrow new NodeDiskRegistrySourceErrorV1(\n\t\t\t\"identity_mismatch\",\n\t\t\tt(\"Installed plugin manifest identity does not match index record for {identity}\", {\n\t\t\t\tidentity: `${record.pluginId}@${record.pluginVersion}`,\n\t\t\t}),\n\t\t);\n\treturn value as unknown as PluginManifestV1;\n}\n\n/** Read the install store index records; undefined when the store is empty. */\nasync function readIndexRecords(\n\trootDirectory: string,\n\tsignal: AbortSignal | undefined,\n): Promise<readonly DiskIndexRecordV1[] | undefined> {\n\tif (signal?.aborted)\n\t\tthrow new NodeDiskRegistrySourceErrorV1(\"cancelled\", t(\"Disk registry source read was cancelled\"));\n\tlet rawIndex: string;\n\ttry {\n\t\trawIndex = await readBoundedFile(\n\t\t\tjoin(rootDirectory, INDEX_FILE_V1),\n\t\t\tMAX_NODE_DISK_REGISTRY_INDEX_BYTES_V1,\n\t\t\t\"index\",\n\t\t);\n\t} catch (error) {\n\t\tif (error instanceof NodeDiskRegistrySourceErrorV1) throw error;\n\t\tif (error instanceof Error && \"code\" in error && error.code === \"ENOENT\") return undefined;\n\t\tthrow new NodeDiskRegistrySourceErrorV1(\"io_failed\", t(\"Install store index could not be read\"));\n\t}\n\treturn parseIndex(rootDirectory, rawIndex);\n}\n\n/**\n * Read-only registry source over the default install store. It projects the\n * persistent index and each installation instance's ecosystem manifest as\n * bounded envelopes for the registry's own digest verification. It never\n * writes the index or installation directories, and installation directories\n * stay inside the host-owned store.\n */\nexport function createNodeDiskPluginRegistrySourceV1(\n\toptions: NodeDiskRegistrySourceOptionsV1,\n): NodeDiskRegistrySourceV1 {\n\tconst rootDirectory = options.rootDirectory;\n\tif (typeof rootDirectory !== \"string\" || !isAbsolute(rootDirectory) || rootDirectory.trim() === \"\")\n\t\tthrow new NodeDiskRegistrySourceErrorV1(\n\t\t\t\"invalid_configuration\",\n\t\t\tt(\"Install store root directory must be absolute\"),\n\t\t);\n\treturn {\n\t\tversion: NODE_DISK_REGISTRY_SOURCE_VERSION_V1,\n\t\tlist: async ({ signal } = {}) => {\n\t\t\tconst records = await readIndexRecords(rootDirectory, signal);\n\t\t\tif (records === undefined) return Object.freeze([]);\n\t\t\tconst envelopes: PluginRegistryManifestEnvelopeV1[] = [];\n\t\t\t// index 按 installationRef 键控,重装/对齐重试会为同一 pluginId@version\n\t\t\t// 追加多条记录(2026-10-08 实证同身份 4 条、摘要零冲突)。同一身份内容\n\t\t\t// 一致(同一 tarball),按身份只投影一次;摘要冲突才是存储不一致。\n\t\t\tconst projectedDigests = new Map<string, string>();\n\t\t\tfor (const record of records) {\n\t\t\t\tif (signal?.aborted)\n\t\t\t\t\tthrow new NodeDiskRegistrySourceErrorV1(\"cancelled\", t(\"Disk registry source read was cancelled\"));\n\t\t\t\tconst identity = `${record.pluginId}@${record.pluginVersion}`;\n\t\t\t\tconst projectedDigest = projectedDigests.get(identity);\n\t\t\t\tif (projectedDigest !== undefined) {\n\t\t\t\t\tif (projectedDigest !== record.manifestDigest)\n\t\t\t\t\t\tthrow new NodeDiskRegistrySourceErrorV1(\n\t\t\t\t\t\t\t\"invalid_index\",\n\t\t\t\t\t\t\tt(\"Install store index contains conflicting manifests for {identity}\", { identity }),\n\t\t\t\t\t\t);\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tlet rawManifest: string;\n\t\t\t\ttry {\n\t\t\t\t\trawManifest = await readBoundedFile(\n\t\t\t\t\t\tjoin(record.directory, ECOSYSTEM_MANIFEST_FILE_V1),\n\t\t\t\t\t\tMAX_NODE_DISK_REGISTRY_MANIFEST_BYTES_V1,\n\t\t\t\t\t\t\"manifest\",\n\t\t\t\t\t);\n\t\t\t\t} catch (error) {\n\t\t\t\t\tif (error instanceof NodeDiskRegistrySourceErrorV1) throw error;\n\t\t\t\t\tthrow new NodeDiskRegistrySourceErrorV1(\"io_failed\", t(\"Installed plugin manifest could not be read\"));\n\t\t\t\t}\n\t\t\t\tconst manifest = parseManifest(record, rawManifest);\n\t\t\t\tenvelopes.push({\n\t\t\t\t\tmanifest,\n\t\t\t\t\tsource: record.installationRef,\n\t\t\t\t\tmanifestDigest: record.manifestDigest,\n\t\t\t\t});\n\t\t\t\tprojectedDigests.set(identity, record.manifestDigest);\n\t\t\t}\n\t\t\treturn Object.freeze(envelopes);\n\t\t},\n\t\tresolveCapabilityManifestPath: async ({ pluginId, pluginVersion, signal }) => {\n\t\t\tconst records = await readIndexRecords(rootDirectory, signal);\n\t\t\tif (records === undefined) return undefined;\n\t\t\tconst record = records.find(\n\t\t\t\t(candidate) => candidate.pluginId === pluginId && candidate.pluginVersion === pluginVersion,\n\t\t\t);\n\t\t\tif (record === undefined) return undefined;\n\t\t\tconst manifestPath = join(record.directory, CAPABILITY_MANIFEST_FILE_V1);\n\t\t\ttry {\n\t\t\t\tconst handle = await open(manifestPath, \"r\");\n\t\t\t\tawait handle.close().catch(() => undefined);\n\t\t\t} catch {\n\t\t\t\treturn undefined;\n\t\t\t}\n\t\t\treturn manifestPath;\n\t\t},\n\t};\n}\n"]}
@@ -163,9 +163,20 @@ export function createNodeDiskPluginRegistrySourceV1(options) {
163
163
  if (records === undefined)
164
164
  return Object.freeze([]);
165
165
  const envelopes = [];
166
+ // index 按 installationRef 键控,重装/对齐重试会为同一 pluginId@version
167
+ // 追加多条记录(2026-10-08 实证同身份 4 条、摘要零冲突)。同一身份内容
168
+ // 一致(同一 tarball),按身份只投影一次;摘要冲突才是存储不一致。
169
+ const projectedDigests = new Map();
166
170
  for (const record of records) {
167
171
  if (signal?.aborted)
168
172
  throw new NodeDiskRegistrySourceErrorV1("cancelled", t("Disk registry source read was cancelled"));
173
+ const identity = `${record.pluginId}@${record.pluginVersion}`;
174
+ const projectedDigest = projectedDigests.get(identity);
175
+ if (projectedDigest !== undefined) {
176
+ if (projectedDigest !== record.manifestDigest)
177
+ throw new NodeDiskRegistrySourceErrorV1("invalid_index", t("Install store index contains conflicting manifests for {identity}", { identity }));
178
+ continue;
179
+ }
169
180
  let rawManifest;
170
181
  try {
171
182
  rawManifest = await readBoundedFile(join(record.directory, ECOSYSTEM_MANIFEST_FILE_V1), MAX_NODE_DISK_REGISTRY_MANIFEST_BYTES_V1, "manifest");
@@ -181,6 +192,7 @@ export function createNodeDiskPluginRegistrySourceV1(options) {
181
192
  source: record.installationRef,
182
193
  manifestDigest: record.manifestDigest,
183
194
  });
195
+ projectedDigests.set(identity, record.manifestDigest);
184
196
  }
185
197
  return Object.freeze(envelopes);
186
198
  },