@ai-agent-forge/agent-forge 0.85.23 → 0.86.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -2,6 +2,15 @@
2
2
 
3
3
  ## [Unreleased]
4
4
 
5
+ ## [0.86.0] - 2026-09-30
6
+ ### Removed
7
+
8
+ - Send-boundary one-turn image expiry in the SDK's convertToLlm wrapper (shipped default-on in 0.85.24). Reverted to plain `convertToLlm(messages)` together with the agent-core mechanism: the snake-workflow seat experiment measured ~4x total input increase (144,082 vs 35,249 tokens over 4 rounds) from cache re-billing after mid-history rewrites on this gateway.
9
+
10
+ ## [0.85.24] - 2026-09-30
11
+ ### Changed
12
+
13
+ - Image expiry counting follows model requests (default: expire after the first assistant response that saw the image), gated by an 8K-token tail window — see `@agent-forge/agent` 0.85.24. Deterministic coverage extended in `test/context-payload-policy.test.ts` (seen-once expiry, keepRequests=N, window deferral).
5
14
  ## [0.85.23] - 2026-09-30
6
15
  ### Changed
7
16
 
@@ -1,5 +1,5 @@
1
1
  {
2
- "generatedAt": "2026-09-30T12:34:53.742Z",
2
+ "generatedAt": "2026-09-30T14:04:54.835Z",
3
3
  "inputCount": 3560,
4
4
  "inputs": {
5
5
  "node_modules/@anthropic-ai/sdk/_vendor/partial-json-parser/parser.mjs": "717f9403f2d3ee0f2077aeb7f0ca7eaff7cc9bcdbb054ac23c6c0361fa03cd1f",
@@ -2187,7 +2187,7 @@
2187
2187
  "packages/agent-forge/dist/core/resolve-config-value.js": "01fdb1673990635bb419c7418eefa298b6a1c6fbb3c6193d3b05a4902e51992d",
2188
2188
  "packages/agent-forge/dist/core/resource-loader.js": "8546706a1ef7aafedcc6c20f5d223554792b4fb2fde6125362c89b7c9482ab58",
2189
2189
  "packages/agent-forge/dist/core/runtime-credentials.js": "2bf389ca2b04bd4dcee56433ca845cd8d9d96d0ccf84d2d0e9ad2a5e3957bda1",
2190
- "packages/agent-forge/dist/core/sdk.js": "9853a1b075349d7a15051ba33a2af31a01d3cbe6ea3d64767ed4e09f16ca4b7f",
2190
+ "packages/agent-forge/dist/core/sdk.js": "c61baa3d5663a07c44975e870b31a6e82d6f186ef1cd76e8ecb8f7fe846d0e8a",
2191
2191
  "packages/agent-forge/dist/core/session-cwd.js": "d7d23660fffd1e6f22a12f0dbefa9fb1f5bfde7c1131b6176ec27ba57b6cfd16",
2192
2192
  "packages/agent-forge/dist/core/session-export.js": "999dd59dac4f17d0fa305e3da1ee7062b80799cc2a7bff5b065eb0453b4cd8c0",
2193
2193
  "packages/agent-forge/dist/core/session-manager.js": "86d5ea5d397e7ce6aa68cc4e5975ae2b20172ad3bab38dc9b441ea925b9479cb",
@@ -2539,7 +2539,7 @@
2539
2539
  "packages/agent-forge/src/core/resolve-config-value.ts": "0f53dad47fe5d5d8837c022b7951ccd3bd5a9b577bd662f0986272110e83bcc7",
2540
2540
  "packages/agent-forge/src/core/resource-loader.ts": "27cf0824af77cb162d1f647a3dd37868b55204ce94599ef9f5c6b8eaeaa24111",
2541
2541
  "packages/agent-forge/src/core/runtime-credentials.ts": "0f4ba10220256b2997100dd326f83b0f07cd492a38885a5276c3934388d6cf69",
2542
- "packages/agent-forge/src/core/sdk.ts": "79d424f30921a1750dfe207cbbd9bf89799d8fbae39c42ca02cd57677f844217",
2542
+ "packages/agent-forge/src/core/sdk.ts": "3b3fe7a259cf72ec3eb4c56462bcff052e58d58b96e639260341af2a3a97ba1b",
2543
2543
  "packages/agent-forge/src/core/session-cwd.ts": "581c849ce1ccb50da0ee9eabb3c34b80aed757aafcb79784349229e50df4d727",
2544
2544
  "packages/agent-forge/src/core/session-export.ts": "38b61f46b0d12d322d962067a821d3673399f240d10770e0c8a9776c9e38ee02",
2545
2545
  "packages/agent-forge/src/core/session-manager.ts": "9117c8238c5b0d7f1e2770598295ae0ba40f8fc41651f3a3d6d1b28ef83c8646",
@@ -2780,7 +2780,7 @@
2780
2780
  "packages/agent/dist/agent.js": "32fdc72bff08ec3e54805ecd9dff39d171148e6f14bb10d89524d65024dd95ed",
2781
2781
  "packages/agent/dist/harness/agent-harness.js": "21fdb3355adafd53c26337617a73918ba49e9832c42cde8b71c469abeecb5916",
2782
2782
  "packages/agent/dist/harness/compaction/branch-summarization.js": "a076f14bd4e815693d5d42c81c110f68ad40d72652fa61fa916a7e516e82bd2b",
2783
- "packages/agent/dist/harness/compaction/compaction.js": "9e2b435669b3f6b702f28598b41639f8416191611e67d2d45c17ca2e33e42369",
2783
+ "packages/agent/dist/harness/compaction/compaction.js": "01a22485522738d4673b53848e20039a939f18aa77b43f8453c86486f214447d",
2784
2784
  "packages/agent/dist/harness/compaction/utils.js": "3cd34076fcd2cb016ab5bde9d9aa3e2e259d20ed6a5848b49893e941b7e13bf7",
2785
2785
  "packages/agent/dist/harness/messages.js": "201ad9a53d6c101224764929c703dc99b8d9a19384327cf606712a11ec87f521",
2786
2786
  "packages/agent/dist/harness/prompt-templates.js": "a3fd10825495ab9b25dbc635b34d23131a46c55ad35e3c477707b7462562bea7",
@@ -2811,7 +2811,7 @@
2811
2811
  "packages/agent/dist/harness/types.js": "8aa91d66f770ac7046886e6a915abcf6c5e5a1f9eed7b25086f839a9b726962e",
2812
2812
  "packages/agent/dist/harness/utils/shell-output.js": "899fecfd9e91f7f189cb76f4099f431679d83b35f25f841b73faa12e0c680eb2",
2813
2813
  "packages/agent/dist/harness/utils/truncate.js": "d265bdde1c575add9f3e02c6066aeeabda7e96cf1f6a49c5aa6da8cf924bdd70",
2814
- "packages/agent/dist/index.js": "0bdccea8c2947782a685871b619305722a5736f3b25d54ca037b3ae8e83cf6ab",
2814
+ "packages/agent/dist/index.js": "d48d932f939125a6dca4a644345f3d7ea67461229aa32976d3afb009f6e1ed35",
2815
2815
  "packages/agent/dist/proxy.js": "9da0971466ba8042e871a051e6073ba903c580b8959141e08e1fa31c152bde46",
2816
2816
  "packages/agent/dist/search/index.js": "55c69a20cc2ba96d52ce1813bc1fdde4fe651eb8c4ccd9e7e9744b2d5981655e",
2817
2817
  "packages/agent/dist/search/scanning.js": "58ed602ce21315af8d45a6890dd14a3e0bb22c2ccea1df26ae24a4a2ff4068a3",
@@ -2821,7 +2821,7 @@
2821
2821
  "packages/agent/src/agent.ts": "e8b50d9ffa4960e5f3414cd1ececec9e3a0bca2c4fd9a75006aefdd4a3e20391",
2822
2822
  "packages/agent/src/harness/agent-harness.ts": "3297f5ae67f84e0bc663c2d297671f1f59a006de83d2877c791e9a33e8e8f69d",
2823
2823
  "packages/agent/src/harness/compaction/branch-summarization.ts": "74ed3ca28c0a67b39bb16509e251860b891d0a8629ebe4ab75876093bd0b7830",
2824
- "packages/agent/src/harness/compaction/compaction.ts": "34dbc2cf3e182505b5506516a4098de781d27003d2d4bcc3afc699663327759e",
2824
+ "packages/agent/src/harness/compaction/compaction.ts": "bb0b9f86b066e2e8f2d88d3a1db8d143a32517a3f3fece28bfcb3d0c7815a9ba",
2825
2825
  "packages/agent/src/harness/compaction/utils.ts": "cdb08c8de612e785c1356405657530221b94272160798390fada02dd34249243",
2826
2826
  "packages/agent/src/harness/env/nodejs.ts": "485860c326689a4a9922b2e6b03cf1b945b3c6d48f5a53ac9b80510048c31bac",
2827
2827
  "packages/agent/src/harness/events.ts": "ba43b8d888113db8ea89f0b9396a4f6dd1cffc3c8739abff308293bac3e2d536",
@@ -2860,7 +2860,7 @@
2860
2860
  "packages/agent/src/harness/types.ts": "481fc414421f806f8a91aeeb7bdfe0f552d2318b68312af743b9b127d51c7156",
2861
2861
  "packages/agent/src/harness/utils/shell-output.ts": "8fd2bbcce48a35d8801c49feb4d8592bce89bf28c4fce7f0645656e6b00b9d35",
2862
2862
  "packages/agent/src/harness/utils/truncate.ts": "5fad606060248f86bedd8bc74ea8b04cf8d8b82e6ecd084cd84ed3f310a822e3",
2863
- "packages/agent/src/index.ts": "22c58084437d5970b5082c4f4e49ac91615281475820a22a78f5611fa86a3c62",
2863
+ "packages/agent/src/index.ts": "1580340d02c56171858c20163cc0c0eaf3f1e75481dec19dd3f01aa2cfa09c05",
2864
2864
  "packages/agent/src/node.ts": "63d8dc9b22d93b3b1172ed1f1e83cc62bb370789f56f8dd31affb5c2a0a8dff3",
2865
2865
  "packages/agent/src/proxy.ts": "68f4fa5ce569b0ec5980e0458a36f717f52f59e22a4b8eb33e5932b97ac3e9a3",
2866
2866
  "packages/agent/src/search/index.ts": "69989ca6ca98c870ef211e6b855072901b41f95a8822379fadf53705d974486b",
@@ -612,7 +612,7 @@ Summarize the prefix to provide context for the retained suffix:
612
612
  ## Context for Suffix
613
613
  - [Information needed to understand the retained recent work]
614
614
 
615
- Be concise. Focus on what's needed to understand the kept suffix.`,STALE_IMAGE_PLACEHOLDER_TEXT="[image from an earlier turn omitted to save context; the analysis of it remains in this conversation, and you can re-read the source file to view it again]";function hasImagePart(content){return Array.isArray(content)&&content.some(part=>part.type==="image")}function expireStaleImageParts(messages,keepTurns=1){let boundary=-1,turnsSeen=0;for(let i=messages.length-1;i>=0;i--){let role=messages[i].role;if(!(role!=="user"&&role!=="bashExecution")&&(turnsSeen+=1,!(turnsSeen<keepTurns))){boundary=i;break}}if(boundary<=0)return messages;let changed=!1,mapped=messages.map((message,index3)=>{if(index3>=boundary)return message;let content=message.content;return hasImagePart(content)?(changed=!0,{...message,content:content.map(part=>part.type==="image"?{type:"text",text:STALE_IMAGE_PLACEHOLDER_TEXT}:part)}):message});return changed?mapped:messages}var BRANCH_SUMMARY_PROMPT=`Create a structured summary of this conversation branch for context when returning later.
615
+ Be concise. Focus on what's needed to understand the kept suffix.`;var BRANCH_SUMMARY_PROMPT=`Create a structured summary of this conversation branch for context when returning later.
616
616
 
617
617
  Use this EXACT format:
618
618
 
@@ -1066,7 +1066,7 @@ ${issue.fallbackCwd}`}var MissingSessionCwdError=class extends Error{issue;const
1066
1066
  `,1)[0]??"";return{header:parseHeader3(firstLine),bytes}}function readAgentSession(options){if(!isAgentSessionId2(options.sessionId))return;let dir=agentSessionsDir2(options.agentDir),filePath=findSessionFile2(dir,options.sessionId);if(filePath===void 0)return;let text,bytes;try{bytes=statSync16(filePath).size,text=readFileSync19(filePath,{encoding:"utf-8",flag:"r"})}catch{return}let maxBytes=options.maxBytes??DEFAULT_MAX_BYTES4,truncated=text.length>maxBytes,lines=(truncated?text.slice(0,maxBytes):text).split(`
1067
1067
  `).filter(line=>line.trim()!==""),header=lines.length>0?parseHeader3(lines[0]):void 0,entries=[];for(let line of lines.slice(header===void 0?0:1))try{entries.push(JSON.parse(line))}catch{}let parentAgentSession=typeof header?.parentAgentSession=="string"?header.parentAgentSession:void 0,agentRole=typeof header?.agentRole=="string"?header.agentRole:void 0,cwd=typeof header?.cwd=="string"?header.cwd:void 0,createdAt=typeof header?.timestamp=="string"?header.timestamp:void 0;return{sessionId:options.sessionId,...parentAgentSession===void 0?{}:{parentAgentSession},...agentRole===void 0?{}:{agentRole},...cwd===void 0?{}:{cwd},...createdAt===void 0?{}:{createdAt},bytes,entryCount:entries.length,truncated,entries:Object.freeze(entries)}}function listAgentSessions(options){let names2,dir;try{dir=agentSessionsDir2(options.agentDir),names2=readdirSync14(dir).filter(name=>name.endsWith(".jsonl"))}catch{return Object.freeze([])}let summaries=[];for(let name of names2){let stem=name.slice(0,-6),separator=stem.lastIndexOf("_"),sessionId=separator===-1?stem:stem.slice(separator+1);if(!isAgentSessionId2(sessionId))continue;let filePath=join48(dir,name),scanned,modifiedAt;try{scanned=readHeader(filePath),modifiedAt=statSync16(filePath).mtimeMs}catch{continue}let parentAgentSession=typeof scanned.header?.parentAgentSession=="string"?scanned.header.parentAgentSession:void 0;if(options.parentAgentSession!==void 0&&parentAgentSession!==options.parentAgentSession)continue;let agentRole=typeof scanned.header?.agentRole=="string"?scanned.header.agentRole:void 0,createdAt=typeof scanned.header?.timestamp=="string"?scanned.header.timestamp:void 0;summaries.push({sessionId,...parentAgentSession===void 0?{}:{parentAgentSession},...agentRole===void 0?{}:{agentRole},...createdAt===void 0?{}:{createdAt},modifiedAt,bytes:scanned.bytes})}return summaries.sort((left,right)=>right.modifiedAt-left.modifiedAt),Object.freeze(summaries.slice(0,options.limit??DEFAULT_LIST_LIMIT))}function createCodingAgentFacade(session){return{version:1,prompt:(text,options)=>session.prompt(text,options),steer:(text,images,options)=>session.steer(text,images,options),abort:()=>session.abort(),waitForIdle:()=>session.waitForIdle(),compact:customInstructions=>session.compact(customInstructions),navigateTree:(targetId,options)=>session.navigateTree(targetId,options),reload:options=>session.reload(options),setModel:(model,options)=>session.setModel(model,options),setThinkingLevel:(level,options)=>session.setThinkingLevel(level,options),setActiveToolsByName:toolNames=>session.setActiveToolsByName(toolNames),getQueuedMessages:()=>({steering:session.getSteeringMessages(),followUp:session.getFollowUpMessages()}),clearQueue:()=>session.clearQueue(),recordSuiteMismatch:(originalSuiteId,currentSuiteId)=>session.recordSuiteMismatch(originalSuiteId,currentSuiteId),getSessionAPI:()=>session.getSessionAPI(),isIdle:()=>session.isIdle,getState:()=>session.state,getModel:()=>session.model,getToolNames:()=>session.getActiveToolNames(),getSessionId:()=>session.sessionId,getHeader:()=>session.sessionManager.getHeader(),subscribe:listener=>session.subscribe(listener),subscribeRawEventGate:listener=>session.agent.subscribe(()=>listener()),getSessionName:()=>session.sessionName,isCompacting:()=>session.isCompacting,isStreaming:()=>session.isStreaming,getContextUsage:()=>session.getContextUsage(),getSystemPrompt:()=>session.systemPrompt,getScopedModels:()=>session.scopedModels,getTree:()=>session.sessionManager.getTree(),getLeafId:()=>session.sessionManager.getLeafId(),getPromptTemplates:()=>session.promptTemplates,getToolDefinition:name=>session.getToolDefinition(name),getCwd:()=>session.sessionManager.getCwd(),getEntries:()=>session.sessionManager.getEntries(),getPendingMessageCount:()=>session.pendingMessageCount,followUp:(text,images,options)=>session.followUp(text,images,options),setScopedModels:scopedModels=>session.setScopedModels(scopedModels),cycleModel:(direction,options)=>session.cycleModel(direction,options),cycleThinkingLevel:options=>session.cycleThinkingLevel(options),setSteeringMode:mode=>session.setSteeringMode(mode),setFollowUpMode:mode=>session.setFollowUpMode(mode),setAutoCompactionEnabled:enabled=>session.setAutoCompactionEnabled(enabled),setSessionName:name=>session.setSessionName(name),abortBash:()=>session.abortBash(),abortCompaction:()=>session.abortCompaction(),abortRetry:()=>session.abortRetry(),abortBranchSummary:()=>session.abortBranchSummary(),captureBashEpoch:()=>session.captureBashEpoch(),isBashEpochCurrent:epoch=>session.isBashEpochCurrent(epoch),emitUserBash:excludeFromContext=>session.emitUserBash(excludeFromContext),executeBash:(command,onChunk,options)=>session.executeBash(command,onChunk,options),recordBashResult:(command,result,options)=>session.recordBashResult(command,result,options),getThinkingLevel:()=>session.thinkingLevel,getSteeringMode:()=>session.steeringMode,getFollowUpMode:()=>session.followUpMode,getSessionFile:()=>session.sessionFile,isAutoCompactionEnabled:()=>session.autoCompactionEnabled,getAvailableThinkingLevels:()=>session.getAvailableThinkingLevels(),getUserMessagesForForking:()=>session.getUserMessagesForForking(),getLastAssistantText:()=>session.getLastAssistantText(),getSessionStats:()=>session.getSessionStats(),setAutoRetryEnabled:enabled=>session.setAutoRetryEnabled(enabled),exportToHtml:(outputPath,options)=>session.exportToHtml(outputPath,options),appendLabelChange:(entryId,label)=>session.sessionManager.appendLabelChange(entryId,label),getSkills:()=>session.resourceLoader.getSkills(),getPrompts:()=>session.resourceLoader.getPrompts(),getThemes:()=>session.resourceLoader.getThemes(),getAgentsFiles:()=>session.resourceLoader.getAgentsFiles(),getSystemPromptSource:()=>session.resourceLoader.getSystemPromptSource(),getAppendSystemPromptSources:()=>session.resourceLoader.getAppendSystemPromptSources(),getSuiteId:()=>readSessionSuiteBinding(session.getSessionAPI().getBranchEntries())?.suiteId,getAvailableModels:()=>session.modelRuntime.getAvailableSnapshot(),isUsingSubscription:providerId=>session.modelRuntime.isUsingSubscription(providerId),getModelsError:()=>session.modelRuntime.getError(),getModelCatalog:()=>session.modelRuntime,checkProviderAuth:providerId=>session.modelRuntime.checkAuth(providerId),getProviderAuth:providerId=>session.modelRuntime.getAuth(providerId),getModelPriceSource:()=>session.modelRuntime,getModelAuthRuntime:()=>session.modelRuntime,getContextEntries:()=>session.sessionManager.buildContextEntries(),getSteeringMessages:()=>session.getSteeringMessages(),getFollowUpMessages:()=>session.getFollowUpMessages(),getRetryAttempt:()=>session.retryAttempt,isBashRunning:()=>session.isBashRunning,exportToJsonl:outputPath=>session.exportToJsonl(outputPath),dispose:()=>session.dispose()}}function createCodingAgentRuntimeFacade(runtime){let sessionManager=()=>runtime.session.sessionManager;return{version:1,newSession:(...args)=>runtime.newSession(...args),fork:(...args)=>runtime.fork(...args),switchSession:(...args)=>runtime.switchSession(...args),importFromJsonl:(...args)=>runtime.importFromJsonl(...args),dispose:()=>runtime.dispose(),setBeforeSessionInvalidate:beforeSessionInvalidate=>runtime.setBeforeSessionInvalidate(beforeSessionInvalidate),setRebindSession:rebindSession=>runtime.setRebindSession(rebindSession),getSessionFacade:()=>createCodingAgentFacade(runtime.session),listSessions:onProgress=>SessionManager.list(sessionManager().getCwd(),sessionManager().getSessionDir(),onProgress),listAllSessions:onProgress=>sessionManager().usesDefaultSessionDir()?SessionManager.listAll(onProgress):SessionManager.listAll(sessionManager().getSessionDir(),onProgress),getSessionFile:()=>sessionManager().getSessionFile(),getSessionDir:()=>sessionManager().getSessionDir(),usesDefaultSessionDir:()=>sessionManager().usesDefaultSessionDir(),isPersisted:()=>sessionManager().isPersisted(),getSessionId:()=>sessionManager().getSessionId()}}function areTimingsEnabled(){let configuredValue=process.env.AGENT_FORGE_TIMING;return configuredValue===void 0?process.env.PI_TIMING==="1":configuredValue==="1"}var ENABLED=areTimingsEnabled(),timingNamespaces=new Map;function resetTimings(namespace="main"){ENABLED&&timingNamespaces.set(namespace,{timings:[],lastTime:Date.now()})}function time(label,namespace="main"){if(!ENABLED)return;let now=Date.now();timingNamespaces.has(namespace)||resetTimings(namespace);let timingNamespace=timingNamespaces.get(namespace);timingNamespace.timings.push({label,ms:now-timingNamespace.lastTime}),timingNamespace.lastTime=now}function printTimingGroup(title,timings){let printableTimings=timings.filter(timing=>timing.ms>=0);if(printableTimings.length!==0){console.error(`
1068
1068
  --- ${title} ---`);for(let t of printableTimings)console.error(` ${t.label}: ${t.ms}ms`);console.error(` TOTAL: ${printableTimings.reduce((a,b2)=>a+b2.ms,0)}ms`),console.error(`${"-".repeat(title.length+8)}
1069
- `)}}function printTimings(){if(ENABLED)for(let[namespace,timingNamespace]of timingNamespaces)printTimingGroup(`Startup Timings: ${namespace}`,timingNamespace.timings)}setDefaultStreamFn(streamSimple);var AGENT_TASK_SETTLED_STATUSES=new Set(["queued","admitted","running","succeeded","failed","cancelled","timed_out","drain_timeout","runner_lost"]);function parseAgentTaskSettledDigestLine(line){let parsed;try{parsed=JSON.parse(line)}catch{return}if(typeof parsed!="object"||parsed===null||Array.isArray(parsed))return;let record=parsed;if(!(typeof record.taskId!="string"||record.taskId==="")&&!(typeof record.sessionId!="string"||record.sessionId==="")&&!(typeof record.status!="string"||!AGENT_TASK_SETTLED_STATUSES.has(record.status))&&!(record.reasonCode!==void 0&&(typeof record.reasonCode!="string"||record.reasonCode==="")))return{taskId:record.taskId,taskSessionId:record.sessionId,status:record.status,...record.reasonCode===void 0?{}:{reasonCode:record.reasonCode}}}function deliverAgentTaskSettledDigestLine(session,line,hostLogger){let facts=parseAgentTaskSettledDigestLine(line);if(facts===void 0){hostLogger?.warn("sdk","background delegation settlement line is not a valid agent.task.settled source",{cause:line});return}session?.dispatchAgentTaskSettled(facts)}var OBSERVABILITY_PACKAGE_ID="agent-forge.plugin.observability",SUBAGENT_DELEGATE_PACKAGE_ID="agent-forge.plugin.subagent-delegate",MEMORY_PACKAGE_ID="agent-forge.plugin.memory",isMemoryModeV1=value=>value==="off"||value==="light"||value==="full";function resolveSdkMemoryMode(explicitMode,env2,settingsMode){if(explicitMode!==void 0)return isMemoryModeV1(explicitMode)?{mode:explicitMode}:{mode:"off",invalidEnvValue:explicitMode};let configured=env2.AGENT_FORGE_MEMORY_MODE?.trim().toLowerCase();if(configured!==void 0&&configured!=="")return isMemoryModeV1(configured)?{mode:configured}:{mode:"off",invalidEnvValue:configured};let fromSettings=settingsMode?.trim().toLowerCase();if(fromSettings!==void 0&&fromSettings!=="")return isMemoryModeV1(fromSettings)?{mode:fromSettings}:{mode:"off",invalidSettingsValue:fromSettings};let legacy=env2.AGENT_FORGE_MEMORY_VECTOR?.trim().toLowerCase();return legacy!==void 0&&legacy!==""?isMemoryModeV1(legacy)?{mode:legacy}:{mode:"off",invalidEnvValue:legacy}:{mode:"off"}}function getDefaultAgentDir(){return getAgentDir()}function injectAfterLastUserMessage(messages,injection){for(let index3=messages.length-1;index3>=0;index3-=1)if(messages[index3]?.role==="user")return[...messages.slice(0,index3+1),injection,...messages.slice(index3+1)];return messages}async function readCapabilityPluginManifestForOrdering(manifestPath){let raw;try{raw=JSON.parse(await readFile9(manifestPath,"utf8"))}catch(error2){throw new Error(`Failed to read capability plugin manifest ${manifestPath}: ${error2 instanceof Error?error2.message:String(error2)}`)}return parseCapabilityPluginManifest(raw,manifestPath)}async function createAgentSession(options={}){let cwd=resolvePath(options.cwd??options.sessionManager?.getCwd()??process.cwd()),agentDir=options.agentDir?resolvePath(options.agentDir):getDefaultAgentDir(),resourceLoader=options.resourceLoader,authPath=options.agentDir?join49(agentDir,"auth.json"):void 0,modelsPath=options.agentDir?join49(agentDir,"models.json"):void 0,modelRuntime=options.modelRuntime??await ModelRuntime.create({authPath,modelsPath,credentials:options.credentials}),settingsManager=options.settingsManager??SettingsManager.create(cwd,agentDir),suiteId=resolveSuiteId({explicit:options.suite,envSuite:process.env[SUITE_ENV_VAR],settings:settingsManager,agentDir}),suiteAssembly=createSuiteAssembly({cwd,agentDir,suiteId,pluginProfileId:options.pluginProfileId,selectedPluginIds:options.selectedPluginIds,disabledPluginIds:options.disabledPluginIds,pluginHost:options.pluginHost,verifiedPlugins:options.verifiedPlugins,manifestOverrides:options.manifestOverrides,pluginProfile:options.pluginProfile}),suiteWorkspace=suiteAssembly.workspace,resolvedAgentProfile=buildResolvedAgentProfileV1({suiteId,workspace:suiteWorkspace,...suiteAssembly.pluginProfile===void 0?{}:{pluginProfile:suiteAssembly.pluginProfile}}),capabilityWiring=options.suiteCapabilityWiring??!options.resourceLoader,capabilityDiagnostics=[],suitePreferenceDiagnostics=[],capabilitySkillsFilter,communicationMailbox,selfMailbox=()=>(communicationMailbox??=createSubagentMailbox({agentDir,ownerParentSessionId:()=>agentSessionRef.current?.sessionId}),communicationMailbox),communicationWiring=options.enableAgentTasks===!1&&options.subagentCommunicationWiring===void 0?void 0:{drainEscalations:sessionId=>selfMailbox().drainEscalations(sessionId),...options.subagentCommunicationWiring??{}},backgroundDigest={pending:[]},settingsMemoryMode=settingsManager.getMemoryModeSetting(),memoryModeOption=options.memoryCapability?.mode,memoryModeResolution=resolveSdkMemoryMode(memoryModeOption,process.env,settingsMemoryMode);if(capabilityWiring){suiteWorkspace.suite.capabilities.includes("builtin.memory")&&(memoryModeResolution.invalidEnvValue!==void 0&&capabilityDiagnostics.push(`invalid AGENT_FORGE_MEMORY_MODE value "${memoryModeResolution.invalidEnvValue}"; memory stays off (fail-closed)`),memoryModeResolution.invalidSettingsValue!==void 0&&capabilityDiagnostics.push(`invalid memory.mode setting "${memoryModeResolution.invalidSettingsValue}"; memory stays off (fail-closed)`),memoryModeResolution.mode==="off"&&capabilityDiagnostics.push("memory disabled (mode=off) \u2014 set memory.mode (light|full) in settings.json to enable"));let suiteDefinition=suiteWorkspace.suite,suiteLocalSkillsDir=suiteAssembly.localSkillsDir;capabilitySkillsFilter=skills=>filterSuiteSkills(suiteDefinition,skills,{localSkillsDir:suiteLocalSkillsDir}).kept}let sessionManager=options.sessionManager??SessionManager.create(cwd,getDefaultSessionDir(cwd,agentDir)),hostLogger=options.hostLogger,traceOptions=options.traceOptions,observabilityCapture={},observabilityLogMirror={},observabilityGetMetrics={},traceService;options.traceEnabled!==!1&&(traceService={adapter:{getTraceFilePath:()=>{let sessionFilePath=sessionManager.getSessionFile();return sessionFilePath===void 0?null:getTraceFilePathForSession(sessionFilePath)},captureProviderPayload:(payload2,model2)=>{observabilityCapture.current?.(payload2,model2)},onSinkFailure:error2=>{hostLogger?.error("observability","trace sink failure",{cause:error2})},getTurnCorrelationId:()=>agentSessionRef.current?.getTurnCorrelationId(),getParentAgentSessionId:()=>sessionManager.getHeader()?.parentAgentSession,getParentTraceId:()=>sessionManager.getHeader()?.parentTraceId,registerFacade:facade=>{observabilityCapture.current=facade?.captureProviderPayload,observabilityLogMirror.current=facade?.mirrorPluginLog,observabilityGetMetrics.current=facade?.getMetrics}},...traceOptions===void 0?{}:{options:traceOptions}}),resourceLoader||(resourceLoader=new DefaultResourceLoader({cwd,agentDir,settingsManager,...suiteAssembly.loaderOverrides,...suiteAssembly.localSkillsDir===void 0?{}:{additionalSkillPaths:[suiteAssembly.localSkillsDir]}}),await resourceLoader.reload(),time("resourceLoader.reload"));let existingSession=sessionManager.buildSessionContext(),hasExistingSession=existingSession.messages.length>0,branchEntries=sessionManager.getBranch(),sessionSuiteBinding=readSessionSuiteBinding(branchEntries),hasConversation=branchEntries.some(entry=>entry.type==="message"&&entry.message?.role==="user");if(hasConversation&&sessionSuiteBinding!==void 0&&!options.allowSuiteRebind){if(sessionSuiteBinding.suiteId!==suiteId)throw new SuiteRebindError(`Session is bound to suite "${sessionSuiteBinding.suiteId}" and cannot resume with "${suiteId}"; rerun with --rebind-suite to adopt the new suite, or create a new session`);if(sessionSuiteBinding.profileIdentity!==void 0&&!profileIdentitiesCompatible(sessionSuiteBinding.profileIdentity,suiteWorkspace.identity))throw new SuiteRebindError("Session Profile identity drift detected (the active plugin set changed since the conversation started); rerun with --rebind-suite to adopt the new plugin set, or create a new session")}let hasThinkingEntry=sessionManager.getBranch().some(entry=>entry.type==="thinking_level_change"),model=options.model,modelFallbackMessage;if(!model&&hasExistingSession&&existingSession.model){let restoredModel=modelRuntime.getModel(existingSession.model.provider,existingSession.model.modelId);restoredModel&&modelRuntime.hasConfiguredAuth(restoredModel.provider)&&(model=restoredModel),model||(modelFallbackMessage=`Could not restore model ${existingSession.model.provider}/${existingSession.model.modelId}`)}let suiteModelPreference=suiteWorkspace.suite.model;if(!model&&suiteModelPreference!==null){let suiteModel=findExactModelReferenceMatch(suiteModelPreference,[...modelRuntime.getModels()]);suiteModel&&modelRuntime.hasConfiguredAuth(suiteModel.provider)?model=suiteModel:suitePreferenceDiagnostics.push(`Suite "${suiteId}" model "${suiteModelPreference}" does not resolve to an authenticated model; using the normal model resolution instead.`)}model||(model=(await findInitialModel({scopedModels:[],isContinuing:hasExistingSession,defaultProvider:settingsManager.getDefaultProvider(),defaultModelId:settingsManager.getDefaultModel(),defaultThinkingLevel:settingsManager.getDefaultThinkingLevel(),modelThinkingLevels:settingsManager.getAllModelThinkingLevels(),modelRuntime})).model,model?modelFallbackMessage&&(modelFallbackMessage+=`. Using ${model.provider}/${model.id}`):modelFallbackMessage=formatNoModelsAvailableMessage());let thinkingLevel=options.thinkingLevel;thinkingLevel===void 0&&hasExistingSession&&hasThinkingEntry&&(thinkingLevel=existingSession.thinkingLevel);let suiteThinkingPreference=suiteWorkspace.suite.thinking;if(thinkingLevel===void 0&&suiteThinkingPreference!==null&&(isValidThinkingLevel(suiteThinkingPreference)?thinkingLevel=suiteThinkingPreference:suitePreferenceDiagnostics.push(`Suite "${suiteId}" thinking "${suiteThinkingPreference}" is not a valid thinking level; using the normal thinking resolution instead.`)),thinkingLevel===void 0&&hasExistingSession&&(thinkingLevel=settingsManager.getDefaultThinkingLevel()??DEFAULT_THINKING_LEVEL),thinkingLevel===void 0&&model){let perModel=settingsManager.getModelThinkingLevel(model.provider,model.id);perModel&&(thinkingLevel=perModel)}thinkingLevel===void 0&&(thinkingLevel=settingsManager.getDefaultThinkingLevel()??DEFAULT_THINKING_LEVEL),model?thinkingLevel=clampThinkingLevel(model,thinkingLevel):thinkingLevel="off";let defaultActiveToolNames=options.capabilityMode==="readonly"?["read","grep","find","ls"]:["read","bash","edit","write"],configuredDefaultToolNames=settingsManager.getDefaultTools(),allowedToolNames=options.tools??(options.noTools==="all"?[]:void 0),excludedToolNames=options.excludeTools,excludedToolNameSet=excludedToolNames?new Set(excludedToolNames):void 0,initialActiveToolNames=((options.tools===void 0&&options.noTools===void 0&&options.capabilityMode!=="readonly"?[...suiteWorkspace.suite.tools]:void 0)??options.tools??(options.noTools?[]:configuredDefaultToolNames??defaultActiveToolNames)).filter(name=>!excludedToolNameSet?.has(name)),agent,convertToLlmWithBlockImages=messages=>{let expired=expireStaleImageParts(messages),converted=convertToLlm2(expired);return settingsManager.getBlockImages()?converted.map(msg=>{if(msg.role==="user"||msg.role==="toolResult"){let content=msg.content;if(Array.isArray(content)&&content.some(c2=>c2.type==="image")){let filteredContent=content.map(c2=>c2.type==="image"?{type:"text",text:"Image reading is disabled."}:c2).filter((c2,i,arr)=>!(c2.type==="text"&&c2.text==="Image reading is disabled."&&i>0&&arr[i-1].type==="text"&&arr[i-1].text==="Image reading is disabled."));return{...msg,content:filteredContent}}}return msg}):converted},agentSessionRef={},customStreamFn=options.streamFn;agent=new Agent({initialState:{systemPrompt:"",model,thinkingLevel,tools:[]},convertToLlm:convertToLlmWithBlockImages,streamFn:customStreamFn?(model2,context,streamOptions)=>customStreamFn(model2,context,streamOptions):async(model2,context,options2)=>{let providerRetrySettings=settingsManager.getProviderRetrySettings(),httpIdleTimeoutMs=settingsManager.getHttpIdleTimeoutMs(),effectiveTimeoutMs=httpIdleTimeoutMs===0?2147483647:httpIdleTimeoutMs,timeoutMs=options2?.timeoutMs??providerRetrySettings.timeoutMs??effectiveTimeoutMs,websocketConnectTimeoutMs=options2?.websocketConnectTimeoutMs??settingsManager.getWebSocketConnectTimeoutMs();try{return modelRuntime.streamSimple(model2,context,{...options2,timeoutMs,websocketConnectTimeoutMs,maxRetries:options2?.maxRetries??providerRetrySettings.maxRetries,maxRetryDelayMs:options2?.maxRetryDelayMs??providerRetrySettings.maxRetryDelayMs,transformHeaders:async requestHeaders=>{let session2=agentSessionRef.current;if(!session2)throw new Error("Capability runtime is not initialized for provider request");return session2.getCapabilityRuntime().transformProviderHeaders({model:model2,...options2?.sessionId===void 0?{}:{sessionId:options2.sessionId},headers:requestHeaders})}})}catch(error2){throw hostLogger?.error("sdk","provider stream failed",{cause:error2}),error2}},onPayload:async(payload2,model2)=>{try{traceService?.adapter.captureProviderPayload(payload2,model2?.id)}catch(error2){hostLogger?.warn("sdk","trace payload capture failed",{cause:error2})}},sessionId:sessionManager.getSessionId(),transformContext:async messages=>{let result=messages;if(backgroundDigest.pending.length>0){let drained=backgroundDigest.pending.splice(0);result=injectAfterLastUserMessage(result,{role:"user",content:["Background subagent tasks settled:",...drained.map(line=>`- ${line}`)].join(`
1069
+ `)}}function printTimings(){if(ENABLED)for(let[namespace,timingNamespace]of timingNamespaces)printTimingGroup(`Startup Timings: ${namespace}`,timingNamespace.timings)}setDefaultStreamFn(streamSimple);var AGENT_TASK_SETTLED_STATUSES=new Set(["queued","admitted","running","succeeded","failed","cancelled","timed_out","drain_timeout","runner_lost"]);function parseAgentTaskSettledDigestLine(line){let parsed;try{parsed=JSON.parse(line)}catch{return}if(typeof parsed!="object"||parsed===null||Array.isArray(parsed))return;let record=parsed;if(!(typeof record.taskId!="string"||record.taskId==="")&&!(typeof record.sessionId!="string"||record.sessionId==="")&&!(typeof record.status!="string"||!AGENT_TASK_SETTLED_STATUSES.has(record.status))&&!(record.reasonCode!==void 0&&(typeof record.reasonCode!="string"||record.reasonCode==="")))return{taskId:record.taskId,taskSessionId:record.sessionId,status:record.status,...record.reasonCode===void 0?{}:{reasonCode:record.reasonCode}}}function deliverAgentTaskSettledDigestLine(session,line,hostLogger){let facts=parseAgentTaskSettledDigestLine(line);if(facts===void 0){hostLogger?.warn("sdk","background delegation settlement line is not a valid agent.task.settled source",{cause:line});return}session?.dispatchAgentTaskSettled(facts)}var OBSERVABILITY_PACKAGE_ID="agent-forge.plugin.observability",SUBAGENT_DELEGATE_PACKAGE_ID="agent-forge.plugin.subagent-delegate",MEMORY_PACKAGE_ID="agent-forge.plugin.memory",isMemoryModeV1=value=>value==="off"||value==="light"||value==="full";function resolveSdkMemoryMode(explicitMode,env2,settingsMode){if(explicitMode!==void 0)return isMemoryModeV1(explicitMode)?{mode:explicitMode}:{mode:"off",invalidEnvValue:explicitMode};let configured=env2.AGENT_FORGE_MEMORY_MODE?.trim().toLowerCase();if(configured!==void 0&&configured!=="")return isMemoryModeV1(configured)?{mode:configured}:{mode:"off",invalidEnvValue:configured};let fromSettings=settingsMode?.trim().toLowerCase();if(fromSettings!==void 0&&fromSettings!=="")return isMemoryModeV1(fromSettings)?{mode:fromSettings}:{mode:"off",invalidSettingsValue:fromSettings};let legacy=env2.AGENT_FORGE_MEMORY_VECTOR?.trim().toLowerCase();return legacy!==void 0&&legacy!==""?isMemoryModeV1(legacy)?{mode:legacy}:{mode:"off",invalidEnvValue:legacy}:{mode:"off"}}function getDefaultAgentDir(){return getAgentDir()}function injectAfterLastUserMessage(messages,injection){for(let index3=messages.length-1;index3>=0;index3-=1)if(messages[index3]?.role==="user")return[...messages.slice(0,index3+1),injection,...messages.slice(index3+1)];return messages}async function readCapabilityPluginManifestForOrdering(manifestPath){let raw;try{raw=JSON.parse(await readFile9(manifestPath,"utf8"))}catch(error2){throw new Error(`Failed to read capability plugin manifest ${manifestPath}: ${error2 instanceof Error?error2.message:String(error2)}`)}return parseCapabilityPluginManifest(raw,manifestPath)}async function createAgentSession(options={}){let cwd=resolvePath(options.cwd??options.sessionManager?.getCwd()??process.cwd()),agentDir=options.agentDir?resolvePath(options.agentDir):getDefaultAgentDir(),resourceLoader=options.resourceLoader,authPath=options.agentDir?join49(agentDir,"auth.json"):void 0,modelsPath=options.agentDir?join49(agentDir,"models.json"):void 0,modelRuntime=options.modelRuntime??await ModelRuntime.create({authPath,modelsPath,credentials:options.credentials}),settingsManager=options.settingsManager??SettingsManager.create(cwd,agentDir),suiteId=resolveSuiteId({explicit:options.suite,envSuite:process.env[SUITE_ENV_VAR],settings:settingsManager,agentDir}),suiteAssembly=createSuiteAssembly({cwd,agentDir,suiteId,pluginProfileId:options.pluginProfileId,selectedPluginIds:options.selectedPluginIds,disabledPluginIds:options.disabledPluginIds,pluginHost:options.pluginHost,verifiedPlugins:options.verifiedPlugins,manifestOverrides:options.manifestOverrides,pluginProfile:options.pluginProfile}),suiteWorkspace=suiteAssembly.workspace,resolvedAgentProfile=buildResolvedAgentProfileV1({suiteId,workspace:suiteWorkspace,...suiteAssembly.pluginProfile===void 0?{}:{pluginProfile:suiteAssembly.pluginProfile}}),capabilityWiring=options.suiteCapabilityWiring??!options.resourceLoader,capabilityDiagnostics=[],suitePreferenceDiagnostics=[],capabilitySkillsFilter,communicationMailbox,selfMailbox=()=>(communicationMailbox??=createSubagentMailbox({agentDir,ownerParentSessionId:()=>agentSessionRef.current?.sessionId}),communicationMailbox),communicationWiring=options.enableAgentTasks===!1&&options.subagentCommunicationWiring===void 0?void 0:{drainEscalations:sessionId=>selfMailbox().drainEscalations(sessionId),...options.subagentCommunicationWiring??{}},backgroundDigest={pending:[]},settingsMemoryMode=settingsManager.getMemoryModeSetting(),memoryModeOption=options.memoryCapability?.mode,memoryModeResolution=resolveSdkMemoryMode(memoryModeOption,process.env,settingsMemoryMode);if(capabilityWiring){suiteWorkspace.suite.capabilities.includes("builtin.memory")&&(memoryModeResolution.invalidEnvValue!==void 0&&capabilityDiagnostics.push(`invalid AGENT_FORGE_MEMORY_MODE value "${memoryModeResolution.invalidEnvValue}"; memory stays off (fail-closed)`),memoryModeResolution.invalidSettingsValue!==void 0&&capabilityDiagnostics.push(`invalid memory.mode setting "${memoryModeResolution.invalidSettingsValue}"; memory stays off (fail-closed)`),memoryModeResolution.mode==="off"&&capabilityDiagnostics.push("memory disabled (mode=off) \u2014 set memory.mode (light|full) in settings.json to enable"));let suiteDefinition=suiteWorkspace.suite,suiteLocalSkillsDir=suiteAssembly.localSkillsDir;capabilitySkillsFilter=skills=>filterSuiteSkills(suiteDefinition,skills,{localSkillsDir:suiteLocalSkillsDir}).kept}let sessionManager=options.sessionManager??SessionManager.create(cwd,getDefaultSessionDir(cwd,agentDir)),hostLogger=options.hostLogger,traceOptions=options.traceOptions,observabilityCapture={},observabilityLogMirror={},observabilityGetMetrics={},traceService;options.traceEnabled!==!1&&(traceService={adapter:{getTraceFilePath:()=>{let sessionFilePath=sessionManager.getSessionFile();return sessionFilePath===void 0?null:getTraceFilePathForSession(sessionFilePath)},captureProviderPayload:(payload2,model2)=>{observabilityCapture.current?.(payload2,model2)},onSinkFailure:error2=>{hostLogger?.error("observability","trace sink failure",{cause:error2})},getTurnCorrelationId:()=>agentSessionRef.current?.getTurnCorrelationId(),getParentAgentSessionId:()=>sessionManager.getHeader()?.parentAgentSession,getParentTraceId:()=>sessionManager.getHeader()?.parentTraceId,registerFacade:facade=>{observabilityCapture.current=facade?.captureProviderPayload,observabilityLogMirror.current=facade?.mirrorPluginLog,observabilityGetMetrics.current=facade?.getMetrics}},...traceOptions===void 0?{}:{options:traceOptions}}),resourceLoader||(resourceLoader=new DefaultResourceLoader({cwd,agentDir,settingsManager,...suiteAssembly.loaderOverrides,...suiteAssembly.localSkillsDir===void 0?{}:{additionalSkillPaths:[suiteAssembly.localSkillsDir]}}),await resourceLoader.reload(),time("resourceLoader.reload"));let existingSession=sessionManager.buildSessionContext(),hasExistingSession=existingSession.messages.length>0,branchEntries=sessionManager.getBranch(),sessionSuiteBinding=readSessionSuiteBinding(branchEntries),hasConversation=branchEntries.some(entry=>entry.type==="message"&&entry.message?.role==="user");if(hasConversation&&sessionSuiteBinding!==void 0&&!options.allowSuiteRebind){if(sessionSuiteBinding.suiteId!==suiteId)throw new SuiteRebindError(`Session is bound to suite "${sessionSuiteBinding.suiteId}" and cannot resume with "${suiteId}"; rerun with --rebind-suite to adopt the new suite, or create a new session`);if(sessionSuiteBinding.profileIdentity!==void 0&&!profileIdentitiesCompatible(sessionSuiteBinding.profileIdentity,suiteWorkspace.identity))throw new SuiteRebindError("Session Profile identity drift detected (the active plugin set changed since the conversation started); rerun with --rebind-suite to adopt the new plugin set, or create a new session")}let hasThinkingEntry=sessionManager.getBranch().some(entry=>entry.type==="thinking_level_change"),model=options.model,modelFallbackMessage;if(!model&&hasExistingSession&&existingSession.model){let restoredModel=modelRuntime.getModel(existingSession.model.provider,existingSession.model.modelId);restoredModel&&modelRuntime.hasConfiguredAuth(restoredModel.provider)&&(model=restoredModel),model||(modelFallbackMessage=`Could not restore model ${existingSession.model.provider}/${existingSession.model.modelId}`)}let suiteModelPreference=suiteWorkspace.suite.model;if(!model&&suiteModelPreference!==null){let suiteModel=findExactModelReferenceMatch(suiteModelPreference,[...modelRuntime.getModels()]);suiteModel&&modelRuntime.hasConfiguredAuth(suiteModel.provider)?model=suiteModel:suitePreferenceDiagnostics.push(`Suite "${suiteId}" model "${suiteModelPreference}" does not resolve to an authenticated model; using the normal model resolution instead.`)}model||(model=(await findInitialModel({scopedModels:[],isContinuing:hasExistingSession,defaultProvider:settingsManager.getDefaultProvider(),defaultModelId:settingsManager.getDefaultModel(),defaultThinkingLevel:settingsManager.getDefaultThinkingLevel(),modelThinkingLevels:settingsManager.getAllModelThinkingLevels(),modelRuntime})).model,model?modelFallbackMessage&&(modelFallbackMessage+=`. Using ${model.provider}/${model.id}`):modelFallbackMessage=formatNoModelsAvailableMessage());let thinkingLevel=options.thinkingLevel;thinkingLevel===void 0&&hasExistingSession&&hasThinkingEntry&&(thinkingLevel=existingSession.thinkingLevel);let suiteThinkingPreference=suiteWorkspace.suite.thinking;if(thinkingLevel===void 0&&suiteThinkingPreference!==null&&(isValidThinkingLevel(suiteThinkingPreference)?thinkingLevel=suiteThinkingPreference:suitePreferenceDiagnostics.push(`Suite "${suiteId}" thinking "${suiteThinkingPreference}" is not a valid thinking level; using the normal thinking resolution instead.`)),thinkingLevel===void 0&&hasExistingSession&&(thinkingLevel=settingsManager.getDefaultThinkingLevel()??DEFAULT_THINKING_LEVEL),thinkingLevel===void 0&&model){let perModel=settingsManager.getModelThinkingLevel(model.provider,model.id);perModel&&(thinkingLevel=perModel)}thinkingLevel===void 0&&(thinkingLevel=settingsManager.getDefaultThinkingLevel()??DEFAULT_THINKING_LEVEL),model?thinkingLevel=clampThinkingLevel(model,thinkingLevel):thinkingLevel="off";let defaultActiveToolNames=options.capabilityMode==="readonly"?["read","grep","find","ls"]:["read","bash","edit","write"],configuredDefaultToolNames=settingsManager.getDefaultTools(),allowedToolNames=options.tools??(options.noTools==="all"?[]:void 0),excludedToolNames=options.excludeTools,excludedToolNameSet=excludedToolNames?new Set(excludedToolNames):void 0,initialActiveToolNames=((options.tools===void 0&&options.noTools===void 0&&options.capabilityMode!=="readonly"?[...suiteWorkspace.suite.tools]:void 0)??options.tools??(options.noTools?[]:configuredDefaultToolNames??defaultActiveToolNames)).filter(name=>!excludedToolNameSet?.has(name)),agent,convertToLlmWithBlockImages=messages=>{let converted=convertToLlm2(messages);return settingsManager.getBlockImages()?converted.map(msg=>{if(msg.role==="user"||msg.role==="toolResult"){let content=msg.content;if(Array.isArray(content)&&content.some(c2=>c2.type==="image")){let filteredContent=content.map(c2=>c2.type==="image"?{type:"text",text:"Image reading is disabled."}:c2).filter((c2,i,arr)=>!(c2.type==="text"&&c2.text==="Image reading is disabled."&&i>0&&arr[i-1].type==="text"&&arr[i-1].text==="Image reading is disabled."));return{...msg,content:filteredContent}}}return msg}):converted},agentSessionRef={},customStreamFn=options.streamFn;agent=new Agent({initialState:{systemPrompt:"",model,thinkingLevel,tools:[]},convertToLlm:convertToLlmWithBlockImages,streamFn:customStreamFn?(model2,context,streamOptions)=>customStreamFn(model2,context,streamOptions):async(model2,context,options2)=>{let providerRetrySettings=settingsManager.getProviderRetrySettings(),httpIdleTimeoutMs=settingsManager.getHttpIdleTimeoutMs(),effectiveTimeoutMs=httpIdleTimeoutMs===0?2147483647:httpIdleTimeoutMs,timeoutMs=options2?.timeoutMs??providerRetrySettings.timeoutMs??effectiveTimeoutMs,websocketConnectTimeoutMs=options2?.websocketConnectTimeoutMs??settingsManager.getWebSocketConnectTimeoutMs();try{return modelRuntime.streamSimple(model2,context,{...options2,timeoutMs,websocketConnectTimeoutMs,maxRetries:options2?.maxRetries??providerRetrySettings.maxRetries,maxRetryDelayMs:options2?.maxRetryDelayMs??providerRetrySettings.maxRetryDelayMs,transformHeaders:async requestHeaders=>{let session2=agentSessionRef.current;if(!session2)throw new Error("Capability runtime is not initialized for provider request");return session2.getCapabilityRuntime().transformProviderHeaders({model:model2,...options2?.sessionId===void 0?{}:{sessionId:options2.sessionId},headers:requestHeaders})}})}catch(error2){throw hostLogger?.error("sdk","provider stream failed",{cause:error2}),error2}},onPayload:async(payload2,model2)=>{try{traceService?.adapter.captureProviderPayload(payload2,model2?.id)}catch(error2){hostLogger?.warn("sdk","trace payload capture failed",{cause:error2})}},sessionId:sessionManager.getSessionId(),transformContext:async messages=>{let result=messages;if(backgroundDigest.pending.length>0){let drained=backgroundDigest.pending.splice(0);result=injectAfterLastUserMessage(result,{role:"user",content:["Background subagent tasks settled:",...drained.map(line=>`- ${line}`)].join(`
1070
1070
  `),timestamp:Date.now()})}return result},steeringMode:settingsManager.getSteeringMode(),followUpMode:settingsManager.getFollowUpMode(),transport:settingsManager.getTransport(),thinkingBudgets:settingsManager.getThinkingBudgets(),maxRetryDelayMs:settingsManager.getProviderRetrySettings().maxRetryDelayMs}),hasExistingSession?(agent.state.messages=existingSession.messages,hasThinkingEntry||sessionManager.appendThinkingLevelChange(thinkingLevel)):(model&&sessionManager.appendModelChange(model.provider,model.id),sessionManager.appendThinkingLevelChange(thinkingLevel));let session=new AgentSession({agent,sessionManager,settingsManager,cwd,scopedModels:options.scopedModels,resourceLoader,customTools:options.customTools,modelRuntime,initialActiveToolNames,allowedToolNames,excludedToolNames,sessionStartEvent:options.sessionStartEvent,capabilityMode:options.capabilityMode,contextStrategyName:options.contextStrategyName,retryPolicyName:options.retryPolicyName,compactionPolicyName:options.compactionPolicyName,overflowPolicyName:options.overflowPolicyName,branchSummaryPolicyName:options.branchSummaryPolicyName,runLoopStrategyName:options.runLoopStrategyName,agentTaskAdapter:options.enableAgentTasks===!1?void 0:options.agentTaskAdapter,...options.agentTaskResults===void 0?{}:{agentTaskResults:options.agentTaskResults},...options.enableAgentTasks===!1?{}:{agentSessionReader:async sessionId=>{let parentSession=agentSessionRef.current;if(parentSession===void 0)return;let read=readAgentSession({agentDir,sessionId});if(!(read===void 0||read.parentAgentSession!==parentSession.sessionId))return{sessionId:read.sessionId,...read.parentAgentSession===void 0?{}:{parentAgentSession:read.parentAgentSession},...read.agentRole===void 0?{}:{agentRole:read.agentRole},...read.createdAt===void 0?{}:{createdAt:read.createdAt},bytes:read.bytes,entryCount:read.entryCount,truncated:read.truncated,entries:read.entries}},agentSessionLister:async()=>{let parentSession=agentSessionRef.current;return parentSession===void 0?[]:listAgentSessions({agentDir,parentAgentSession:parentSession.sessionId}).map(summary=>({sessionId:summary.sessionId,...summary.agentRole===void 0?{}:{agentRole:summary.agentRole},...summary.createdAt===void 0?{}:{createdAt:summary.createdAt},modifiedAt:summary.modifiedAt,bytes:summary.bytes}))}},agentComposition:options.agentComposition,interactionHost:options.interactionHost,hostLogger:options.hostLogger,logRecordMirrorRef:observabilityLogMirror,observabilityGetMetricsRef:observabilityGetMetrics,agentDir,...communicationWiring===void 0?{}:{communication:communicationWiring},...options.enableAgentTasks===!1?{}:{turnContext:{backgroundDigestSink:line=>{backgroundDigest.pending.length>=20&&backgroundDigest.pending.shift(),backgroundDigest.pending.push(line),deliverAgentTaskSettledDigestLine(agentSessionRef.current,line,hostLogger)},getTurnCorrelationId:()=>agentSessionRef.current?.getTurnCorrelationId()}},...options.enableAgentTasks===!1?{}:{roleAssociations:suiteWorkspace.suite.associations.roles},...traceService===void 0?{}:{traceService},...options.memoryCapability?.storage===void 0?{}:{memoryStorage:options.memoryCapability.storage},orientationPrompt:ORIENTATION_PROMPTS[suiteWorkspace.suite.orientation],...capabilitySkillsFilter===void 0?{}:{capabilitySkillsFilter}});agentSessionRef.current=session,(!hasExistingSession||sessionSuiteBinding!==void 0&&!hasConversation||options.allowSuiteRebind)&&session.sessionManager.appendCustomEntry(SUITE_SESSION_ENTRY_TYPE,{suiteId,profileIdentity:suiteWorkspace.identity});let pluginRejections=[],recordRejection=async(code,manifestPath,pluginId,message)=>{let rejection=Object.freeze({code,manifestPath,...pluginId===void 0?{}:{pluginId},message});pluginRejections.push(rejection),hostLogger?.error("sdk",`capability plugin rejected: ${message}`,{sessionId:session.sessionId,fields:{code:rejection.code,pluginId:rejection.pluginId,manifestPath:rejection.manifestPath}});try{await session.getCapabilityRuntime().recordPluginRejection(rejection)}catch{}},rejectionMessage=error2=>error2 instanceof Error?error2.message:String(error2);try{let discoveredManifestPaths=options.discoverCapabilityPlugins===!1?[]:discoverCapabilityPluginManifests([join49(agentDir,"plugins"),join49(cwd,CONFIG_DIR_NAME,"plugins")]),suiteLocalManifestPaths=capabilityWiring&&options.discoverCapabilityPlugins!==!1&&suiteAssembly.localPluginsDir!==void 0?discoverCapabilityPluginManifests([suiteAssembly.localPluginsDir]):[],disabledPluginIdSet=new Set(options.disabledPluginIds??[]),profilePluginIds=suiteAssembly.pluginProfile!==void 0&&suiteAssembly.pluginProfile.status==="resolved"?new Set(suiteAssembly.pluginProfile.profile.pluginIds.filter(pluginId=>!disabledPluginIdSet.has(pluginId))):new Set,passthroughCapabilityPluginIds=[],capabilityPackageIds=suiteWorkspace.suite.capabilities.flatMap(entry=>{let mappedPluginId=BUILTIN_CAPABILITY_PACKAGE_IDS[entry];return mappedPluginId!==void 0?[mappedPluginId]:(passthroughCapabilityPluginIds.push(entry),[entry])});if(options.traceEnabled!==!1&&capabilityPackageIds.push(OBSERVABILITY_PACKAGE_ID),memoryModeResolution.mode==="off"){let memoryIndex=capabilityPackageIds.indexOf(MEMORY_PACKAGE_ID);memoryIndex>=0&&capabilityPackageIds.splice(memoryIndex,1)}for(let pluginId of capabilityPackageIds)disabledPluginIdSet.has(pluginId)||profilePluginIds.add(pluginId);if(capabilityWiring&&passthroughCapabilityPluginIds.length>0){let installedPluginIdSet=new Set((options.installedCapabilityPlugins??[]).map(plugin=>plugin.pluginId));for(let pluginId of passthroughCapabilityPluginIds)installedPluginIdSet.has(pluginId)||capabilityDiagnostics.push(`Suite "${suiteId}" capability "${pluginId}" has no installed active plugin; install it with agent-forge plugin install or remove the declaration`)}let installedPluginManifestPaths=[],skippedInstalledPluginIds=[];for(let plugin of options.installedCapabilityPlugins??[])profilePluginIds.has(plugin.pluginId)?installedPluginManifestPaths.push(plugin.manifestPath):skippedInstalledPluginIds.push(plugin.pluginId);skippedInstalledPluginIds.length>0&&capabilityDiagnostics.push(`Installed capability plugins stay unloaded because the active profile did not select them: ${skippedInstalledPluginIds.sort().join(", ")}`);let manifestPaths=[...suiteLocalManifestPaths,...installedPluginManifestPaths,...discoveredManifestPaths,...options.capabilityPluginPaths??[]],explicitCandidatePaths=new Set([...suiteLocalManifestPaths,...installedPluginManifestPaths,...options.capabilityPluginPaths??[]]),loadedManifestPaths=new Set,explicitManifestPaths=new Set,candidatePaths=[];for(let manifestPath of manifestPaths){let resolvedManifestPath=resolve18(cwd,manifestPath),manifestIdentity=existsSync22(resolvedManifestPath)?realpathSync4(resolvedManifestPath):resolvedManifestPath;loadedManifestPaths.has(manifestIdentity)||(loadedManifestPaths.add(manifestIdentity),explicitCandidatePaths.has(manifestPath)&&explicitManifestPaths.add(manifestIdentity),candidatePaths.push(manifestIdentity))}let manifestEntries=[];for(let manifestPath of candidatePaths)try{let manifest=await readCapabilityPluginManifestForOrdering(manifestPath);if(manifest.hostVersion!==void 0){if(!(0,import_semver5.satisfies)(VERSION,manifest.hostVersion)){await recordRejection("host_version_incompatible",manifestPath,manifest.id,`Plugin ${manifest.id} declares host version range "${manifest.hostVersion}", but the host is ${VERSION}. Upgrade the host into the declared range, or install a plugin version that supports host ${VERSION}.`);continue}}else capabilityDiagnostics.push(`Capability plugin ${manifest.id} (${manifestPath}) does not declare "hostVersion"; it loads, but published plugins must declare a host semver range (e.g. ">=${VERSION}").`);manifestEntries.push({path:manifestPath,manifest})}catch(error2){await recordRejection("invalid_manifest",manifestPath,void 0,rejectionMessage(error2))}let poolFilter=capabilityWiring?{suite:suiteWorkspace.suite,decide:(manifestId,manifestPath)=>decideSuiteCapabilityPlugin(suiteWorkspace.suite,{manifestId,manifestPath},{cwd})}:void 0,seenPluginIds=new Set,uniqueEntries=[],discoveredPluginIds=[];for(let entry of manifestEntries){if(discoveredPluginIds.push(entry.manifest.id),poolFilter&&!explicitManifestPaths.has(entry.path)){let decision=poolFilter.decide(entry.manifest.id,entry.path);if(!decision.keep){decision.diagnostic&&capabilityDiagnostics.push(decision.diagnostic);continue}}if(seenPluginIds.has(entry.manifest.id)){await recordRejection("duplicate_plugin_id",entry.path,entry.manifest.id,`Capability plugin is already loaded: ${entry.manifest.id}; the first manifest in discovery order wins`);continue}seenPluginIds.add(entry.manifest.id),uniqueEntries.push(entry)}poolFilter&&capabilityDiagnostics.push(...suiteDanglingPluginAssociations(poolFilter.suite,discoveredPluginIds));let capabilityIdentity=(id,version)=>`${id}\0${version}`,survivors=new Set(uniqueEntries),removedInLastPass=!0;for(;removedInLastPass;){removedInLastPass=!1;let providers=new Set;for(let entry of survivors)for(let declaration of entry.manifest.provides??[])providers.add(capabilityIdentity(declaration.id,declaration.version));for(let entry of[...survivors]){let missing=(entry.manifest.requires??[]).filter(requirement=>!requirement.optional&&!providers.has(capabilityIdentity(requirement.id,requirement.version)));missing.length!==0&&(await recordRejection("missing_dependency",entry.path,entry.manifest.id,`Plugin capability is required but unavailable: ${missing.map(requirement=>`${requirement.id}@${requirement.version}`).join(", ")} (${entry.manifest.id})`),survivors.delete(entry),removedInLastPass=!0)}}let pathByManifest=new Map([...survivors].map(entry=>[entry.manifest,entry.path]));for(let manifest of resolvePluginCapabilityOrder([...survivors].map(entry=>entry.manifest))){let manifestPath=pathByManifest.get(manifest);if(!manifestPath)throw new Error(`Capability plugin manifest path is unavailable: ${manifest.id}`);try{await session.loadCapabilityPluginManifest(manifestPath,{...manifest.id===SUBAGENT_DELEGATE_PACKAGE_ID&&options.subagentPoolFromSelfInvocation===!0?{configOverride:{runnerEntryAuto:!0}}:{},...manifest.id===MEMORY_PACKAGE_ID?{configOverride:{...memoryModeOption===void 0?{}:{memoryMode:memoryModeOption},...settingsMemoryMode===void 0?{}:{memorySettingsMode:settingsMemoryMode}}}:{}})}catch(error2){await recordRejection("plugin_load_failed",manifestPath,manifest.id,rejectionMessage(error2))}}hasExistingSession&&options.contextStrategyName&&await session.replaceContext(existingSession.messages)}catch(error2){throw await session.dispose(),error2}return hostLogger?.info("sdk","agent session created",{sessionId:session.sessionId,fields:{suite:suiteId,...model===void 0?{}:{model:`${model.provider}/${model.id}`},trace:options.traceEnabled!==!1}}),{session,modelFallbackMessage,pluginRejections:Object.freeze(pluginRejections.slice()),suiteDiagnostics:Object.freeze([...suiteAssembly.collectDiagnostics(),...capabilityDiagnostics,...suitePreferenceDiagnostics]),...suiteAssembly.pluginProfile===void 0?{}:{pluginProfile:suiteAssembly.pluginProfile},resolvedAgentProfile}}async function createStableAgentSession(options={}){let result=await createAgentSession(options);return{facade:createCodingAgentFacade(result.session),sessionAPI:result.session.getSessionAPI(),modelFallbackMessage:result.modelFallbackMessage}}async function createStableAgentSessionRuntime(createRuntime,options){let runtime=await createAgentSessionRuntime(createRuntime,options);return{runtimeFacade:createCodingAgentRuntimeFacade(runtime)}}var MCP_CONFIG_FILENAME="mcp.json",MCP_POOL_DIR="mcp/pool",MCP_POOL_BRIDGE_DIR="_bridge",MCP_SERVER_NAME_PATTERN=/^[A-Za-z0-9][A-Za-z0-9._-]*$/,MCP_HTTP_PLUGIN_SOURCE_PATH=fileURLToPath5(new URL("../plugins/mcp-http.ts",import.meta.url)),MCP_HTTP_PLUGIN_DIST_PATH=fileURLToPath5(new URL("../../dist/plugins/mcp-http.js",import.meta.url));function isHttpUrl(value){try{let protocol=new URL(value).protocol;return protocol==="http:"||protocol==="https:"}catch{return!1}}function parseMcpConfig(path15){let servers=new Map,diagnostics=[],value;try{value=JSON.parse(readFileSync20(path15,"utf8"))}catch(error2){return error2.code==="ENOENT"?{servers,diagnostics}:(diagnostics.push(`MCP config at ${path15} is unreadable; ignoring it. Errors: ${error2 instanceof Error?error2.message:String(error2)}`),{servers,diagnostics})}if(typeof value!="object"||value===null||Array.isArray(value))return diagnostics.push(`MCP config at ${path15} must be an object with an "mcpServers" map; ignoring it.`),{servers,diagnostics};let mcpServers=value.mcpServers;if(mcpServers===void 0)return{servers,diagnostics};if(typeof mcpServers!="object"||mcpServers===null||Array.isArray(mcpServers))return diagnostics.push(`MCP config at ${path15} must carry an "mcpServers" object; ignoring it.`),{servers,diagnostics};for(let[name,entry]of Object.entries(mcpServers)){if(!MCP_SERVER_NAME_PATTERN.test(name)){diagnostics.push(`MCP server name "${name}" in ${path15} is invalid (must match ${MCP_SERVER_NAME_PATTERN.source}); ignoring it.`);continue}if(typeof entry!="object"||entry===null||Array.isArray(entry)){diagnostics.push(`MCP server "${name}" in ${path15} must be an object with a "command" or "url"; ignoring it.`);continue}let config=entry;if(config.url!==void 0&&(typeof config.url!="string"||config.url.trim().length===0)){diagnostics.push(`MCP server "${name}" in ${path15} requires "url" to be a non-empty string; ignoring it.`);continue}let hasCommand=typeof config.command=="string"&&config.command.trim().length>0,hasUrl=typeof config.url=="string"&&config.url.trim().length>0;if(hasCommand&&hasUrl){diagnostics.push(`MCP server "${name}" in ${path15} accepts either "command" (stdio server) or "url" (remote HTTP server), not both; ignoring it.`);continue}if(!hasCommand&&!hasUrl){diagnostics.push(`MCP server "${name}" in ${path15} requires a non-empty string "command" (stdio server) or "url" (remote HTTP server); ignoring it.`);continue}if(hasUrl&&!isHttpUrl(config.url)){diagnostics.push(`MCP server "${name}" in ${path15} requires "url" to be a valid http:// or https:// URL; ignoring it.`);continue}if(config.args!==void 0&&(!Array.isArray(config.args)||!config.args.every(arg=>typeof arg=="string"))){diagnostics.push(`MCP server "${name}" in ${path15} requires "args" to be a string array; ignoring it.`);continue}if(config.deferredTools!==void 0&&typeof config.deferredTools!="boolean"){diagnostics.push(`MCP server "${name}" in ${path15} requires "deferredTools" to be a boolean; ignoring it.`);continue}if(config.headers!==void 0){if(hasCommand)diagnostics.push(`MCP server "${name}" in ${path15} carries "headers" but headers only apply to remote "url" (HTTP) servers; ignoring them.`);else if(!(typeof config.headers=="object"&&config.headers!==null&&!Array.isArray(config.headers)&&Object.values(config.headers).every(headerValue=>typeof headerValue=="string"&&headerValue.length>0))){diagnostics.push(`MCP server "${name}" in ${path15} requires "headers" to be an object with non-empty string values; ignoring it.`);continue}}servers.set(name,{args:config.args??[],deferredTools:config.deferredTools===!0?!0:void 0,...hasCommand?{command:config.command}:{url:config.url,...config.headers===void 0?{}:{headers:config.headers}}})}return{servers,diagnostics}}var MCP_POOL_BRIDGE_SOURCE=`// Generated by the suite MCP registration pool (agent-session-services). Do not edit.
1071
1071
  import { spawn } from 'node:child_process';
1072
1072
  import { existsSync } from 'node:fs';
@@ -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{APP_NAME,configureHttpDispatcher,main}from"./chunks/chunk-OTAKR2WB.js";import"./chunks/chunk-JUUC5AZY.js";import"./chunks/chunk-XDUWOHPL.js";import"./chunks/chunk-3QKHSPQL.js";import"./chunks/chunk-DRQDKNXA.js";import"./chunks/chunk-7ZY7IXZD.js";import"./chunks/chunk-V46XUTK3.js";import"./chunks/chunk-WGLBM2BP.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{APP_NAME,configureHttpDispatcher,main}from"./chunks/chunk-2L25YYPC.js";import"./chunks/chunk-JUUC5AZY.js";import"./chunks/chunk-XDUWOHPL.js";import"./chunks/chunk-3QKHSPQL.js";import"./chunks/chunk-DRQDKNXA.js";import"./chunks/chunk-7ZY7IXZD.js";import"./chunks/chunk-V46XUTK3.js";import"./chunks/chunk-WGLBM2BP.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));