@ai-agent-forge/agent-forge 0.85.21 → 0.85.23
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 +8 -0
- package/dist/bundle/.build-manifest.json +9 -9
- package/dist/bundle/chunks/{chunk-NMLW4KE7.js → chunk-OTAKR2WB.js} +7 -5
- package/dist/bundle/cli.js +1 -1
- package/dist/bundle/index.js +1 -1
- package/dist/bundle/rpc-entry.js +1 -1
- package/dist/core/sdk.d.ts.map +1 -1
- package/dist/core/sdk.js +10 -2
- package/dist/core/sdk.js.map +1 -1
- package/dist/modes/interactive/components/footer.d.ts.map +1 -1
- package/dist/modes/interactive/components/footer.js +39 -0
- package/dist/modes/interactive/components/footer.js.map +1 -1
- package/package.json +1 -1
package/CHANGELOG.md
CHANGED
|
@@ -2,6 +2,14 @@
|
|
|
2
2
|
|
|
3
3
|
## [Unreleased]
|
|
4
4
|
|
|
5
|
+
## [0.85.23] - 2026-09-30
|
|
6
|
+
### Changed
|
|
7
|
+
|
|
8
|
+
- One-turn image expiry at the send boundary (user decision, cache-verified): every model request now placeholder-reduces image parts of COMPLETED turns (`expireStaleImageParts(messages, keepTurns=1)` in the SDK's convertToLlm wrapper) — an image costs its ~5.6K tokens once instead of on every later turn, the active turn's images ride untouched, session storage keeps the originals, and the placeholder says the analysis stays in the conversation. Gateway cache measurements behind the timing (3.7K/45K/89K-token probes): append-style requests keep ~99.7% cache hit, tail mutations 88-99.9%, mid-history rewrites 40-50% — expiring right after the turn pins the mutation to the tail. Deterministic coverage in `test/one-turn-image-expiry.test.ts` (capturing streamFn at the SDK send seam).
|
|
9
|
+
## [0.85.22] - 2026-09-30
|
|
10
|
+
### Changed
|
|
11
|
+
|
|
12
|
+
- Context-layer policy slices (user decision: only provable net wins): the compaction summarization prompts now instruct conclusion-vs-payload classification — payloads (long logs, raw console output, image contents) are reduced to one-line references instead of being reproduced into the summary, while conclusions (decisions, failure summaries, paths, user-stated facts) must be preserved. Deterministic coverage in `test/context-payload-policy.test.ts`.
|
|
5
13
|
## [0.85.21] - 2026-09-30
|
|
6
14
|
|
|
7
15
|
## [0.85.20] - 2026-09-30
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
{
|
|
2
|
-
"generatedAt": "2026-09-
|
|
2
|
+
"generatedAt": "2026-09-30T12:34:53.742Z",
|
|
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": "
|
|
2190
|
+
"packages/agent-forge/dist/core/sdk.js": "9853a1b075349d7a15051ba33a2af31a01d3cbe6ea3d64767ed4e09f16ca4b7f",
|
|
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",
|
|
@@ -2255,7 +2255,7 @@
|
|
|
2255
2255
|
"packages/agent-forge/dist/modes/interactive/components/diff.js": "4d4d8accd933bda88cbbd34440ddfdc1160d8eaebdd42a8033cafba8cadf27a9",
|
|
2256
2256
|
"packages/agent-forge/dist/modes/interactive/components/dynamic-border.js": "bf7d221ef1c6f2334a6a6b247a1554ebad018931417c651065689802ab7fd2e9",
|
|
2257
2257
|
"packages/agent-forge/dist/modes/interactive/components/first-time-setup.js": "71bd0b3fb50da9df6cbf77193c36043a3a075fe82879f6b993cb942635e94e0b",
|
|
2258
|
-
"packages/agent-forge/dist/modes/interactive/components/footer.js": "
|
|
2258
|
+
"packages/agent-forge/dist/modes/interactive/components/footer.js": "2f15e827493d35fa1df711983d2893feb6662422287982160021301cf100ed08",
|
|
2259
2259
|
"packages/agent-forge/dist/modes/interactive/components/index.js": "f77dc299f503ade5c61e7e4b5444efe82735855f324ab54cbe19f809d67ec443",
|
|
2260
2260
|
"packages/agent-forge/dist/modes/interactive/components/keybinding-hints.js": "e069455b09f6c91b628ad94e6e466b3574d2614e8bdda59c82f3a5c1fa6ce1e3",
|
|
2261
2261
|
"packages/agent-forge/dist/modes/interactive/components/login-dialog.js": "fd70f14f81423f8d86e4e58a435fb0a9127a66f385cb4d238721d04ff0f040dd",
|
|
@@ -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": "
|
|
2542
|
+
"packages/agent-forge/src/core/sdk.ts": "79d424f30921a1750dfe207cbbd9bf89799d8fbae39c42ca02cd57677f844217",
|
|
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",
|
|
@@ -2611,7 +2611,7 @@
|
|
|
2611
2611
|
"packages/agent-forge/src/modes/interactive/components/diff.ts": "b43f8d91ba9f19088dc9dc86126091c3fdfca25eac6461f5510f5e1e9ddd6491",
|
|
2612
2612
|
"packages/agent-forge/src/modes/interactive/components/dynamic-border.ts": "7bd584d21464215d68823cbee753b0a5ee730cfbf6627d5193e06483d1b62827",
|
|
2613
2613
|
"packages/agent-forge/src/modes/interactive/components/first-time-setup.ts": "8f0f6586950d791ba208253629d573754a34821d369b68b06c37f79b579cda57",
|
|
2614
|
-
"packages/agent-forge/src/modes/interactive/components/footer.ts": "
|
|
2614
|
+
"packages/agent-forge/src/modes/interactive/components/footer.ts": "9b94cb98488e8bcda28b3f6de4af1951fe231a2ee3f343c9631ec190c88d2aca",
|
|
2615
2615
|
"packages/agent-forge/src/modes/interactive/components/index.ts": "ab2fd962401ec94454bba62bdf25b88bf63fc98d91096399bf686bfab4ac6a55",
|
|
2616
2616
|
"packages/agent-forge/src/modes/interactive/components/keybinding-hints.ts": "edf1ee40ff7cedb0791d7bf8e4729d60002ff147b88697782494726331d0ce58",
|
|
2617
2617
|
"packages/agent-forge/src/modes/interactive/components/login-dialog.ts": "92195870f87ad623fb39a0e61798ad726a533f8462732f0d209c16feed9a0004",
|
|
@@ -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": "
|
|
2783
|
+
"packages/agent/dist/harness/compaction/compaction.js": "9e2b435669b3f6b702f28598b41639f8416191611e67d2d45c17ca2e33e42369",
|
|
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": "
|
|
2814
|
+
"packages/agent/dist/index.js": "0bdccea8c2947782a685871b619305722a5736f3b25d54ca037b3ae8e83cf6ab",
|
|
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": "
|
|
2824
|
+
"packages/agent/src/harness/compaction/compaction.ts": "34dbc2cf3e182505b5506516a4098de781d27003d2d4bcc3afc699663327759e",
|
|
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": "
|
|
2863
|
+
"packages/agent/src/index.ts": "22c58084437d5970b5082c4f4e49ac91615281475820a22a78f5611fa86a3c62",
|
|
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",
|
|
@@ -558,7 +558,8 @@ Use this EXACT format:
|
|
|
558
558
|
1. [Ordered list of what should happen next]
|
|
559
559
|
|
|
560
560
|
## Critical Context
|
|
561
|
-
- [
|
|
561
|
+
- [Conclusions only: decisions, failure summaries, exact file paths, identifiers, user-stated facts]
|
|
562
|
+
- [Payloads (long logs, raw console output, image contents) must NOT be reproduced \u2014 reduce each to a one-line reference of what it was and where it lives (e.g. "build log of X: failed, full output in session history"), because the continuation model can re-read sources on demand]
|
|
562
563
|
- [Or "(none)" if not applicable]
|
|
563
564
|
|
|
564
565
|
Keep each section concise. Preserve exact file paths, function names, error messages, and user-stated constraints.`,UPDATE_SUMMARIZATION_PROMPT=`The messages above are NEW conversation messages to incorporate into the existing summary provided in <previous-summary> tags.
|
|
@@ -595,7 +596,8 @@ Use this EXACT format:
|
|
|
595
596
|
1. [Update based on current state]
|
|
596
597
|
|
|
597
598
|
## Critical Context
|
|
598
|
-
- [Preserve important
|
|
599
|
+
- [Preserve important conclusions, add new if needed]
|
|
600
|
+
- [Payloads (long logs, raw console output, image contents) must NOT be reproduced \u2014 keep or reduce them to one-line references of what they were and where they live]
|
|
599
601
|
|
|
600
602
|
Keep each section concise. Preserve exact file paths, function names, error messages, and user-stated constraints.`;var TURN_PREFIX_SUMMARIZATION_PROMPT=`This is the PREFIX of a turn that was too large to keep. The SUFFIX (recent work) is retained.
|
|
601
603
|
|
|
@@ -610,7 +612,7 @@ Summarize the prefix to provide context for the retained suffix:
|
|
|
610
612
|
## Context for Suffix
|
|
611
613
|
- [Information needed to understand the retained recent work]
|
|
612
614
|
|
|
613
|
-
Be concise. Focus on what's needed to understand the kept suffix
|
|
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.
|
|
614
616
|
|
|
615
617
|
Use this EXACT format:
|
|
616
618
|
|
|
@@ -1064,7 +1066,7 @@ ${issue.fallbackCwd}`}var MissingSessionCwdError=class extends Error{issue;const
|
|
|
1064
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(`
|
|
1065
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(`
|
|
1066
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)}
|
|
1067
|
-
`)}}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(`
|
|
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(`
|
|
1068
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.
|
|
1069
1071
|
import { spawn } from 'node:child_process';
|
|
1070
1072
|
import { existsSync } from 'node:fs';
|
|
@@ -1322,7 +1324,7 @@ ${statusParts.join(`
|
|
|
1322
1324
|
`;this.addChild(new Markdown(header+this.message.summary,0,0,this.markdownTheme,{color:text=>theme.fg("customMessageText",text)}))}else this.addChild(new Text(theme.fg("customMessageText","Branch summary (")+theme.fg("dim",keyText("app.tools.expand"))+theme.fg("customMessageText"," to expand)"),0,0))}};var CompactionSummaryMessageComponent=class extends Box{expanded=!1;message;markdownTheme;constructor(message,markdownTheme=getMarkdownTheme()){super(1,1,t=>theme.bg("customMessageBg",t)),this.message=message,this.markdownTheme=markdownTheme,this.updateDisplay()}setExpanded(expanded){this.expanded=expanded,this.updateDisplay()}invalidate(){super.invalidate(),this.updateDisplay()}updateDisplay(){this.clear();let tokenStr=this.message.tokensBefore.toLocaleString(),label=theme.fg("customMessageLabel","\x1B[1m[compaction]\x1B[22m");if(this.addChild(new Text(label,0,0)),this.addChild(new Spacer(1)),this.expanded){let header=`**Compacted from ${tokenStr} tokens**
|
|
1323
1325
|
|
|
1324
1326
|
`;this.addChild(new Markdown(header+this.message.summary,0,0,this.markdownTheme,{color:text=>theme.fg("customMessageText",text)}))}else this.addChild(new Text(theme.fg("customMessageText",`Compacted from ${tokenStr} tokens (`)+theme.fg("dim",keyText("app.tools.expand"))+theme.fg("customMessageText"," to expand)"),0,0))}};var CustomEditor=class extends Editor{keybindings;actionHandlers=new Map;onEscape;onCtrlD;onPasteImage;constructor(tui,theme2,keybindings,options){super(tui,theme2,options),this.keybindings=keybindings}onAction(action,handler){this.actionHandlers.set(action,handler)}handleInput(data){if(this.keybindings.matches(data,"app.clipboard.pasteImage")){this.onPasteImage?.();return}if(this.keybindings.matches(data,"app.interrupt")){if(!this.isShowingAutocomplete()){let handler=this.onEscape??this.actionHandlers.get("app.interrupt");if(handler){handler();return}}super.handleInput(data);return}if(this.keybindings.matches(data,"app.exit")&&this.getText().length===0){let handler=this.onCtrlD??this.actionHandlers.get("app.exit");handler&&handler();return}if(this.keybindings.matches(data,"tui.editor.historyPrevious")||this.keybindings.matches(data,"tui.editor.historyNext")){super.handleInput(data);return}for(let[action,handler]of this.actionHandlers)if(action!=="app.interrupt"&&action!=="app.exit"&&this.keybindings.matches(data,action)){handler();return}super.handleInput(data)}};var CustomMessageComponent=class extends Container{message;customRenderer;box;customComponent;markdownTheme;_expanded=!1;outputPad;constructor(message,customRenderer,markdownTheme=getMarkdownTheme(),outputPad=1){super(),this.message=message,this.customRenderer=customRenderer,this.markdownTheme=markdownTheme,this.outputPad=outputPad,this.addChild(new Spacer(1)),this.box=new Box(1,1,t=>theme.bg("customMessageBg",t)),this.rebuild()}setExpanded(expanded){this._expanded!==expanded&&(this._expanded=expanded,this.rebuild())}setOutputPad(outputPad){this.outputPad!==outputPad&&(this.outputPad=outputPad,this.rebuild())}invalidate(){super.invalidate(),this.rebuild()}rebuild(){if(this.customComponent&&(this.removeChild(this.customComponent),this.customComponent=void 0),this.removeChild(this.box),this.customRenderer)try{let component=this.customRenderer(this.message,{expanded:this._expanded,outputPad:this.outputPad},theme);if(component){this.customComponent=component,this.addChild(component);return}}catch{}this.addChild(this.box),this.box.clear();let label=theme.fg("customMessageLabel",`\x1B[1m[${this.message.customType}]\x1B[22m`);this.box.addChild(new Text(label,0,0)),this.box.addChild(new Spacer(1));let text;typeof this.message.content=="string"?text=this.message.content:text=this.message.content.filter(c2=>c2.type==="text").map(c2=>c2.text).join(`
|
|
1325
|
-
`),this.box.addChild(new Markdown(text,0,0,this.markdownTheme,{color:text2=>theme.fg("customMessageText",text2)}))}};import{isAbsolute as isAbsolute12,relative as relative10,resolve as resolve20,sep as sep13}from"node:path";function areExperimentalFeaturesEnabled(){let configuredValue=process.env.AGENT_FORGE_EXPERIMENTAL;return configuredValue===void 0?process.env.PI_EXPERIMENTAL==="1":configuredValue==="1"}function sanitizeStatusText(text){return text.replace(/[\r\n\t]/g," ").replace(/ +/g," ").trim()}function formatTokens(count){return count<1e3?count.toString():count<1e4?`${(count/1e3).toFixed(1)}k`:count<1e6?`${Math.round(count/1e3)}k`:count<1e7?`${(count/1e6).toFixed(1)}M`:`${Math.round(count/1e6)}M`}function formatCwdForFooter(cwd,home){if(!home)return cwd;let resolvedCwd=resolve20(cwd),resolvedHome=resolve20(home),relativeToHome=relative10(resolvedHome,resolvedCwd);return relativeToHome===""||relativeToHome!==".."&&!relativeToHome.startsWith(`..${sep13}`)&&!isAbsolute12(relativeToHome)?relativeToHome===""?"~":`~${sep13}${relativeToHome}`:cwd}var FooterComponent=class{autoCompactEnabled=!0;session;footerData;constructor(session,footerData){this.session=session,this.footerData=footerData}setSession(session){this.session=session}get facade(){return createCodingAgentFacade(this.session)}setAutoCompactEnabled(enabled){this.autoCompactEnabled=enabled}invalidate(){}dispose(){}render(width){let state2=this.facade.getState(),usageTotals=createUsageTotals(),latestCacheHitRate,goalTitle,todoDone=0,todoTotal=0;for(let entry of this.facade.getEntries())if(entry.type==="message"&&entry.message.role==="assistant"){addUsageToTotals(usageTotals,entry.message.usage);let latestPromptTokens=entry.message.usage.input+entry.message.usage.cacheRead+entry.message.usage.cacheWrite;latestCacheHitRate=latestPromptTokens>0?entry.message.usage.cacheRead/latestPromptTokens*100:void 0}else if(entry.type==="message"&&entry.message.role==="toolResult"&&entry.message.usage)addUsageToTotals(usageTotals,entry.message.usage);else if((entry.type==="branch_summary"||entry.type==="compaction")&&entry.usage)addUsageToTotals(usageTotals,entry.usage);else if(entry.type==="custom"&&entry.customType==="goal.state"){let goals=entry.data?.goals,current=Array.isArray(goals)?goals.at(-1):void 0;current&&typeof current.title=="string"&&(goalTitle=current.title)}else if(entry.type==="custom"&&entry.customType==="todo.state"){let todos=entry.data?.todos;Array.isArray(todos)&&(todoDone=todos.filter(item=>item?.status==="done").length,todoTotal=todos.length)}let contextUsage=this.facade.getContextUsage(),contextWindow=contextUsage?.contextWindow??state2.model?.contextWindow??0,contextPercentValue=contextUsage?.percent??0,contextPercent=contextUsage?.percent!==null?contextPercentValue.toFixed(1):"?",pwd=formatCwdForFooter(this.facade.getCwd(),process.env.HOME||process.env.USERPROFILE),branch=this.footerData.getGitBranch();branch&&(pwd=`${pwd} (${branch})`);let sessionName=this.facade.getSessionName();sessionName&&(pwd=`${pwd} \u2022 ${sessionName}`);let statsParts=[];usageTotals.input&&statsParts.push(`\u2191${formatTokens(usageTotals.input)}`),usageTotals.output&&statsParts.push(`\u2193${formatTokens(usageTotals.output)}`),usageTotals.cacheRead&&statsParts.push(`R${formatTokens(usageTotals.cacheRead)}`),usageTotals.cacheWrite&&statsParts.push(`W${formatTokens(usageTotals.cacheWrite)}`),(usageTotals.cacheRead>0||usageTotals.cacheWrite>0)&&latestCacheHitRate!==void 0&&statsParts.push(`CH${latestCacheHitRate.toFixed(1)}%`);let usingSubscription=state2.model?state2.model.provider==="kimi-coding"||this.facade.isUsingSubscription(state2.model.provider):!1;if(usageTotals.cost||usingSubscription){let costStr=`$${usageTotals.cost.toFixed(3)}${usingSubscription?" (sub)":""}`;statsParts.push(costStr)}let contextPercentStr,autoIndicator=this.autoCompactEnabled?" (auto)":"",contextPercentDisplay=contextPercent==="?"?`?/${formatTokens(contextWindow)}${autoIndicator}`:`${contextPercent}%/${formatTokens(contextWindow)}${autoIndicator}`;contextPercentValue>90?contextPercentStr=theme.fg("error",contextPercentDisplay):contextPercentValue>70?contextPercentStr=theme.fg("warning",contextPercentDisplay):contextPercentStr=contextPercentDisplay,statsParts.push(contextPercentStr),areExperimentalFeaturesEnabled()&&statsParts.push(`${theme.fg("dim","\u2022")} ${theme.bold(theme.fg("warning","xp"))}`);let statsLeft=statsParts.join(" "),modelName=state2.model?.id||"no-model",statsLeftWidth=visibleWidth(statsLeft);statsLeftWidth>width&&(statsLeft=truncateToWidth(statsLeft,width,"..."),statsLeftWidth=visibleWidth(statsLeft));let minPadding=2,rightSideWithoutProvider=modelName;if(state2.model?.reasoning){let thinkingLevel=state2.thinkingLevel||"off";rightSideWithoutProvider=thinkingLevel==="off"?`${modelName} \u2022 thinking off`:`${modelName} \u2022 ${thinkingLevel}`}let rightSide=rightSideWithoutProvider;this.footerData.getAvailableProviderCount()>1&&state2.model&&(rightSide=`(${state2.model.provider}) ${rightSideWithoutProvider}`,statsLeftWidth+minPadding+visibleWidth(rightSide)>width&&(rightSide=rightSideWithoutProvider));let rightSideWidth=visibleWidth(rightSide),totalNeeded=statsLeftWidth+minPadding+rightSideWidth,statsLine;if(totalNeeded<=width){let padding=" ".repeat(width-statsLeftWidth-rightSideWidth);statsLine=statsLeft+padding+rightSide}else{let availableForRight=width-statsLeftWidth-minPadding;if(availableForRight>0){let truncatedRight=truncateToWidth(rightSide,availableForRight,""),truncatedRightWidth=visibleWidth(truncatedRight),padding=" ".repeat(Math.max(0,width-statsLeftWidth-truncatedRightWidth));statsLine=statsLeft+padding+truncatedRight}else statsLine=statsLeft}let dimStatsLeft=theme.fg("dim",statsLeft),remainder=statsLine.slice(statsLeft.length),dimRemainder=theme.fg("dim",remainder),lines=[truncateToWidth(theme.fg("dim",pwd),width,theme.fg("dim","...")),dimStatsLeft+dimRemainder];if(goalTitle!==void 0){let goalParts=[`goal: ${goalTitle}`];todoTotal>0&&goalParts.push(`todo ${todoDone}/${todoTotal}`);let goalLine=theme.fg("dim",sanitizeStatusText(goalParts.join(" \u2022 ")));lines.push(truncateToWidth(goalLine,width,theme.fg("dim","...")))}return lines}};var SUBMENU_SELECT_LIST_LAYOUT={minPrimaryColumnWidth:12,maxPrimaryColumnWidth:32},SelectSubmenu=class extends Container{selectList;listChildIndex;allOptions;listLayout;searchInput;onSelectCb;onCancelCb;onSelectionChangeCb;constructor(title,description,options,currentValue,onSelect,onCancel,onSelectionChange,submenuOptions){super(),this.allOptions=options,this.listLayout=submenuOptions?.layout??SUBMENU_SELECT_LIST_LAYOUT,this.onSelectCb=onSelect,this.onCancelCb=onCancel,this.onSelectionChangeCb=onSelectionChange,this.addChild(new Text(theme.bold(theme.fg("accent",title)),0,0)),description&&(this.addChild(new Spacer(1)),this.addChild(new Text(theme.fg("muted",description),0,0))),submenuOptions?.searchable&&(this.addChild(new Spacer(1)),this.searchInput=new Input,this.searchInput.onSubmit=()=>{this.selectList.handleInput("\r")},this.addChild(this.searchInput)),this.addChild(new Spacer(1)),this.selectList=this.buildSelectList(options,currentValue),this.listChildIndex=this.children.length,this.addChild(this.selectList),this.addChild(new Spacer(1));let hint=submenuOptions?.searchable?" Type to filter \xB7 Enter to select \xB7 Esc to go back":" Enter to select \xB7 Esc to go back";this.addChild(new Text(theme.fg("dim",hint),0,0))}buildSelectList(options,preselect){let list=new SelectList(options,Math.min(options.length,10),getSelectListTheme(),this.listLayout),idx=options.findIndex(o=>o.value===preselect);if(idx!==-1&&list.setSelectedIndex(idx),list.onSelect=item=>this.onSelectCb(item.value),list.onCancel=this.onCancelCb,this.onSelectionChangeCb){let cb=this.onSelectionChangeCb;list.onSelectionChange=item=>cb(item.value)}return list}applyFilter(query){let filtered=query?fuzzyFilter(this.allOptions,query,item=>`${item.label} ${item.description??""}`):this.allOptions,newList=this.buildSelectList(filtered,"");this.children[this.listChildIndex]=newList,this.selectList=newList}handleInput(data){if(this.searchInput){let kb=getKeybindings();kb.matches(data,"tui.select.up")||kb.matches(data,"tui.select.down")||kb.matches(data,"tui.select.confirm")||kb.matches(data,"tui.select.cancel")?this.selectList.handleInput(data):(this.searchInput.handleInput(data),this.applyFilter(this.searchInput.getValue()))}else this.selectList.handleInput(data)}},SteppedSubmenu=class extends Container{steps;onComplete;onCancel;opts;activeComponent;context;constructor(steps,onComplete,onCancel,opts={}){super(),this.steps=steps,this.onComplete=onComplete,this.onCancel=onCancel,this.opts=opts,this.context={...opts.initialContext??{}},this.activeComponent=this.buildStep(opts.startAtStep??0)}buildStep(stepIndex){let step=this.steps[stepIndex],total=this.steps.length,stepLabel=total>1?`Step ${stepIndex+1}/${total} \xB7 `:"",title=typeof step.title=="function"?step.title(this.context):step.title,desc=typeof step.description=="function"?step.description(this.context):step.description,items=step.options(this.context),preselect=step.preselect?.(this.context)??"";return new SelectSubmenu(title,`${stepLabel}${desc}`,items,preselect,value=>{this.context[step.key]=value,stepIndex<total-1?this.activeComponent=this.buildStep(stepIndex+1):(this.onComplete({...this.context}),this.opts.loop?(this.context={},this.activeComponent=this.buildStep(0)):this.onCancel())},()=>{stepIndex>0?(delete this.context[step.key],this.activeComponent=this.buildStep(stepIndex-1)):this.onCancel()},void 0,step.searchable||step.layout?{searchable:step.searchable,layout:step.layout}:void 0)}render(width){return this.activeComponent.render(width)}handleInput(data){this.activeComponent.handleInput?.(data)}invalidate(){this.activeComponent.invalidate?.()}};var MODEL_PICKER_LAYOUT={minPrimaryColumnWidth:12,maxPrimaryColumnWidth:46},THINKING_DESCRIPTIONS={off:"No reasoning",minimal:"Very brief reasoning (~1k tokens)",low:"Light reasoning (~2k tokens)",medium:"Moderate reasoning (~8k tokens)",high:"Deep reasoning (~16k tokens)",xhigh:"Extra-high reasoning (~32k tokens)",max:"Maximum reasoning"},WarningSettingsSubmenu=class extends Container{settingsList;state;constructor(warnings,onChange,onCancel){super(),this.state={...warnings};let items=[{id:"anthropic-extra-usage",label:"Anthropic extra usage",description:"Warn when Anthropic subscription auth may use paid extra usage",currentValue:this.state.anthropicExtraUsage??!0?"true":"false",values:["true","false"]}];this.settingsList=new SettingsList(items,Math.min(items.length,10),getSettingsListTheme(),(id,newValue)=>{id==="anthropic-extra-usage"&&(this.state={...this.state,anthropicExtraUsage:newValue==="true"},onChange({...this.state}))},onCancel),this.addChild(this.settingsList)}handleInput(data){this.settingsList.handleInput(data)}},CLEAR_OVERRIDE_VALUE="__clear__";function modelSettingKey(model){return`${model.provider}/${model.id}`}function modelDisplayLabel(model){return`${model.id} [${model.provider}]`}function modelThinkingOverridesSummary(overrides){let count=Object.keys(overrides).length;return count===0?"none":`${count} configured`}function modelItemLabel(model){return`${model.id} ${theme.fg("muted",`[${model.provider}]`)}`}function themeItems(availableThemes){return availableThemes.map(name=>({value:name,label:name}))}var AUTOMATIC_THEME_VALUE="/";function singleModeThemeItems(availableThemes){return[{value:AUTOMATIC_THEME_VALUE,label:"Automatic",description:"Use separate themes for light and dark terminal appearance"},...themeItems(availableThemes)]}function preferredTheme(availableThemes,preferred,fallback){return preferred&&availableThemes.includes(preferred)?preferred:availableThemes.includes(fallback)?fallback:availableThemes[0]??fallback}function defaultAutomaticThemes(currentThemeSetting,availableThemes){let autoTheme=parseAutoThemeSetting(currentThemeSetting);if(autoTheme)return autoTheme;let currentFixedTheme=currentThemeSetting.includes("/")?void 0:currentThemeSetting,themeName=preferredTheme(availableThemes,currentFixedTheme,"dark");return{lightTheme:themeName,darkTheme:themeName}}var ThemeSubmenu=class extends Container{inputComponent;callbacks;availableThemes;terminalTheme;onDone;originalThemeSetting;mode;singleTheme;lightTheme;darkTheme;constructor(currentThemeSetting,terminalTheme,availableThemes,callbacks,onDone){super(),this.callbacks=callbacks,this.availableThemes=availableThemes,this.terminalTheme=terminalTheme,this.onDone=onDone,this.originalThemeSetting=currentThemeSetting;let autoTheme=parseAutoThemeSetting(currentThemeSetting),automaticThemes=defaultAutomaticThemes(currentThemeSetting,availableThemes),fixedTheme=autoTheme||currentThemeSetting.includes("/")?void 0:currentThemeSetting;this.mode=autoTheme?"automatic":"single",this.lightTheme=automaticThemes.lightTheme,this.darkTheme=automaticThemes.darkTheme,this.singleTheme=preferredTheme(availableThemes,fixedTheme??(autoTheme?this.getActiveAutomaticTheme():void 0),"dark"),this.mode==="automatic"?this.showAutomaticMenu():this.showSingleMenu()}handleInput(data){this.inputComponent?.handleInput?.(data)}setContent(renderComponent,inputComponent=renderComponent){this.clear(),this.addChild(renderComponent),this.inputComponent=inputComponent}showSingleMenu(){this.mode="single";let menu=new SelectSubmenu("Theme","Select a theme, or choose Automatic to follow terminal appearance.",singleModeThemeItems(this.availableThemes),this.singleTheme,value=>{if(value===AUTOMATIC_THEME_VALUE){this.mode="automatic",this.callbacks.onThemePreview?.(this.getThemeSetting()),this.showAutomaticMenu();return}this.singleTheme=value,this.apply(value)},()=>this.cancel(),value=>{this.callbacks.onThemePreview?.(value===AUTOMATIC_THEME_VALUE?this.getAutomaticThemeSetting():value)});this.setContent(menu)}showAutomaticMenu(){this.mode="automatic";let content=new Container;content.addChild(new Text(theme.bold(theme.fg("accent","Automatic Theme")),0,0)),content.addChild(new Spacer(1)),content.addChild(new Text(theme.fg("muted","Choose themes for terminal light and dark appearance."),0,0)),content.addChild(new Text(theme.fg("muted","Light/dark detection requires terminal support."),0,0)),content.addChild(new Spacer(1));let items=[{id:"light-theme",label:"Light theme",description:"Theme to use in automatic mode when the terminal is light",currentValue:this.lightTheme,submenu:(currentValue,done)=>this.createThemeSelect("Light Theme","Select the theme to use for light terminal appearance",currentValue,done,value=>{this.lightTheme=value,this.callbacks.onThemePreview?.(this.getThemeSetting()),done(value)})},{id:"dark-theme",label:"Dark theme",description:"Theme to use in automatic mode when the terminal is dark",currentValue:this.darkTheme,submenu:(currentValue,done)=>this.createThemeSelect("Dark Theme","Select the theme to use for dark terminal appearance",currentValue,done,value=>{this.darkTheme=value,this.callbacks.onThemePreview?.(this.getThemeSetting()),done(value)})},{id:"apply",label:"Apply",description:"Save and go back",currentValue:"save and go back",values:["save and go back"]},{id:"single-mode",label:"Change mode",description:"Switch to one theme for light and dark",currentValue:"switch to single theme",values:["switch to single theme"]}],settingsList=new SettingsList(items,Math.min(items.length,10),getSettingsListTheme(),id=>{switch(id){case"single-mode":this.mode="single",this.singleTheme=this.getActiveAutomaticTheme(),this.callbacks.onThemePreview?.(this.singleTheme),this.showSingleMenu();break;case"apply":this.apply(this.getAutomaticThemeSetting());break}},()=>this.cancel());content.addChild(settingsList),this.setContent(content,settingsList)}createThemeSelect(title,description,currentValue,done,onSelect){return new SelectSubmenu(title,description,themeItems(this.availableThemes),currentValue,onSelect,()=>{this.callbacks.onThemePreview?.(this.getThemeSetting()),done()},value=>this.callbacks.onThemePreview?.(value))}getThemeSetting(){return this.mode==="automatic"?this.getAutomaticThemeSetting():this.singleTheme}getActiveAutomaticTheme(){return this.terminalTheme==="light"?this.lightTheme:this.darkTheme}getAutomaticThemeSetting(){return`${this.lightTheme}/${this.darkTheme}`}apply(themeSetting){this.onDone(themeSetting)}cancel(){this.callbacks.onThemePreview?.(this.originalThemeSetting),this.onDone()}},SettingsSelectorComponent=class extends Container{settingsList;constructor(config,callbacks){super();let supportsImages=getCapabilities().images,followUpKey=keyDisplayText("app.message.followUp"),cycleThinkingKey=keyDisplayText("app.thinking.cycle"),currentWarnings={...config.warnings},currentModelThinkingLevels={...config.modelThinkingLevels},defaultModelByValue=new Map(config.availableDefaultModels.map(model=>[modelSettingKey(model),model])),currentDefaultModelKey=defaultModelByValue.has(config.defaultModel)?config.defaultModel:void 0,currentModelKey=config.currentModel?modelSettingKey(config.currentModel):void 0,items=[{id:"autocompact",label:"Auto-compact",description:"Automatically compact context when it gets too large",currentValue:config.autoCompact?"true":"false",values:["true","false"]},{id:"steering-mode",label:"Steering mode",description:"Enter while streaming queues steering messages. 'one-at-a-time': deliver one, wait for response. 'all': deliver all at once.",currentValue:config.steeringMode,values:["one-at-a-time","all"]},{id:"follow-up-mode",label:"Follow-up mode",description:`${followUpKey} queues follow-up messages until agent stops. 'one-at-a-time': deliver one, wait for response. 'all': deliver all at once.`,currentValue:config.followUpMode,values:["one-at-a-time","all"]},{id:"transport",label:"Transport",description:"Preferred transport for providers that support multiple transports",currentValue:config.transport,values:["sse","websocket","websocket-cached","auto"]},{id:"http-idle-timeout",label:"HTTP idle timeout",description:"Maximum idle gap while waiting for HTTP headers or body chunks. Disable for local models that pause longer than five minutes.",currentValue:formatHttpIdleTimeoutMs(config.httpIdleTimeoutMs),values:HTTP_IDLE_TIMEOUT_CHOICES.map(choice=>choice.label)},{id:"hide-thinking",label:"Hide thinking",description:"Hide thinking blocks in assistant responses",currentValue:config.hideThinkingBlock?"true":"false",values:["true","false"]},{id:"mermaid-rendering",label:"Mermaid diagrams",description:"Render Mermaid code blocks as Unicode diagrams",currentValue:config.mermaidRenderingMode,values:["off","final","streaming"]},{id:"cache-miss-notices",label:"Cache miss notices",description:"Show transcript notices for cache costs and provider recovery diagnostics",currentValue:config.showCacheMissNotices?"true":"false",values:["true","false"]},{id:"collapse-changelog",label:"Collapse changelog",description:"Show condensed changelog after updates",currentValue:config.collapseChangelog?"true":"false",values:["true","false"]},{id:"quiet-startup",label:"Quiet startup",description:"Disable verbose printing at startup",currentValue:config.quietStartup?"true":"false",values:["true","false"]},{id:"double-escape-action",label:"Double-escape action",description:"Action when pressing Escape twice with empty editor",currentValue:config.doubleEscapeAction,values:["tree","fork","none"]},{id:"tree-filter-mode",label:"Tree filter mode",description:"Default filter when opening /tree",currentValue:config.treeFilterMode,values:["default","no-tools","user-only","labeled-only","all"]},{id:"warnings",label:"Warnings",description:"Enable or disable individual warnings",currentValue:"configure",submenu:(_currentValue,done)=>new WarningSettingsSubmenu(currentWarnings,warnings=>{currentWarnings=warnings,callbacks.onWarningsChange(warnings)},()=>done())},{id:"model-thinking",label:"Default thinking level per model",description:`Override the default thinking level for specific models. ${cycleThinkingKey} cycles in-session.`,currentValue:modelThinkingOverridesSummary(currentModelThinkingLevels),submenu:(_currentValue,done)=>{let steps=[{key:"model",title:"Per-Model Thinking Level",description:"Select a model to configure",options:()=>{let items2=[...config.availableDefaultModels].sort((a,b2)=>{let aKey=modelSettingKey(a),bKey=modelSettingKey(b2);return aKey===currentModelKey?-1:bKey===currentModelKey?1:aKey===currentDefaultModelKey?-1:bKey===currentDefaultModelKey?1:a.provider.localeCompare(b2.provider)}).map(model=>{let key=modelSettingKey(model),override=currentModelThinkingLevels[key];return{value:key,label:modelItemLabel(model),description:override??void 0}});return items2.length===0&&items2.push({value:"__none__",label:"No models available",description:"Log in to a provider or configure an API key first"}),items2},preselect:()=>currentModelKey??currentDefaultModelKey,searchable:!0,layout:MODEL_PICKER_LAYOUT},{key:"level",title:ctx=>{let m2=defaultModelByValue.get(ctx.model);return`Thinking Level for ${m2?modelDisplayLabel(m2):ctx.model}`},description:"Select default thinking level for this model",options:ctx=>{let model=defaultModelByValue.get(ctx.model);if(!model)return[];let items2=(model.reasoning?getSupportedThinkingLevels(model):["off"]).map(level=>({value:level,label:level,description:THINKING_DESCRIPTIONS[level]}));return currentModelThinkingLevels[ctx.model]!==void 0&&items2.push({value:CLEAR_OVERRIDE_VALUE,label:"(clear override)",description:`Revert to global default (${config.thinkingLevel})`}),items2},preselect:ctx=>currentModelThinkingLevels[ctx.model]}],summary=()=>modelThinkingOverridesSummary(currentModelThinkingLevels);return new SteppedSubmenu(steps,selections=>{let model=defaultModelByValue.get(selections.model);model&&(selections.level===CLEAR_OVERRIDE_VALUE?(callbacks.onModelThinkingLevelRemove(model.provider,model.id),delete currentModelThinkingLevels[selections.model]):(callbacks.onModelThinkingLevelChange(model.provider,model.id,selections.level),currentModelThinkingLevels[selections.model]=selections.level))},()=>{done(summary())},{loop:!0})}},{id:"tui-mode",label:"TUI mode",description:"Interface layout; fullscreen mode is experimental",currentValue:config.tuiMode,values:["regular","fullscreen"]},{id:"fullscreen-exit-output",label:"Fullscreen exit output",description:"Print the transcript or only a session resume hint when exiting fullscreen mode",currentValue:config.fullscreenExitOutput,values:["transcript","resume-hint"]},{id:"fullscreen-scrollbar",label:"Fullscreen scrollbar",description:"Scrollbar behavior in fullscreen mode; has no effect in regular mode",currentValue:config.fullscreenScrollbar,values:["auto","always","hidden"]},{id:"fullscreen-copy-on-select",label:"Fullscreen copy on select",description:"Automatically copy selected text in fullscreen mode; disable to copy selections with Ctrl+X",currentValue:config.fullscreenCopyOnSelect?"true":"false",values:["true","false"]},{id:"theme",label:"Theme",description:"Color theme for the interface",currentValue:config.currentTheme,submenu:(currentValue,done)=>new ThemeSubmenu(currentValue,config.terminalTheme,config.availableThemes,callbacks,done)}];supportsImages&&(items.splice(1,0,{id:"show-images",label:"Show images",description:"Render images inline in terminal",currentValue:config.showImages?"true":"false",values:["true","false"]}),items.splice(2,0,{id:"image-width-cells",label:"Image width",description:"Preferred inline image width in terminal cells",currentValue:String(config.imageWidthCells),values:["60","80","120"]})),items.splice(supportsImages?3:1,0,{id:"auto-resize-images",label:"Auto-resize images",description:"Resize large images to 2000x2000 max for better model compatibility",currentValue:config.autoResizeImages?"true":"false",values:["true","false"]});let autoResizeIndex=items.findIndex(item=>item.id==="auto-resize-images");items.splice(autoResizeIndex+1,0,{id:"block-images",label:"Block images",description:"Prevent images from being sent to LLM providers",currentValue:config.blockImages?"true":"false",values:["true","false"]});let blockImagesIndex=items.findIndex(item=>item.id==="block-images");items.splice(blockImagesIndex+1,0,{id:"skill-commands",label:"Skill commands",description:"Register skills as /skill:name commands",currentValue:config.enableSkillCommands?"true":"false",values:["true","false"]});let skillCommandsIndex=items.findIndex(item=>item.id==="skill-commands");items.splice(skillCommandsIndex+1,0,{id:"show-hardware-cursor",label:"Show hardware cursor",description:"Show the terminal cursor while still positioning it for IME support",currentValue:config.showHardwareCursor?"true":"false",values:["true","false"]});let hardwareCursorIndex=items.findIndex(item=>item.id==="show-hardware-cursor");items.splice(hardwareCursorIndex+1,0,{id:"editor-padding",label:"Editor padding",description:"Horizontal padding for input editor (0-3)",currentValue:String(config.editorPaddingX),values:["0","1","2","3"]});let editorPaddingIndex=items.findIndex(item=>item.id==="editor-padding");items.splice(editorPaddingIndex+1,0,{id:"output-padding",label:"Output padding",description:"Horizontal padding for user messages, assistant messages, and thinking",currentValue:String(config.outputPad),values:["0","1"]});let outputPaddingIndex=items.findIndex(item=>item.id==="output-padding");items.splice(outputPaddingIndex+1,0,{id:"autocomplete-max-visible",label:"Autocomplete max items",description:"Max visible items in autocomplete dropdown (3-20)",currentValue:String(config.autocompleteMaxVisible),values:["3","5","7","10","15","20"]});let autocompleteIndex=items.findIndex(item=>item.id==="autocomplete-max-visible");items.splice(autocompleteIndex+1,0,{id:"clear-on-shrink",label:"Clear on shrink",description:"Clear empty rows when content shrinks (may cause flicker)",currentValue:config.clearOnShrink?"true":"false",values:["true","false"]});let clearOnShrinkIndex=items.findIndex(item=>item.id==="clear-on-shrink");items.splice(clearOnShrinkIndex+1,0,{id:"terminal-progress",label:"Terminal progress",description:"Show OSC 9;4 progress indicators in the terminal tab bar",currentValue:config.showTerminalProgress?"true":"false",values:["true","false"]}),this.addChild(new DynamicBorder),this.settingsList=new SettingsList(items,10,getSettingsListTheme(),(id,newValue)=>{switch(id){case"autocompact":callbacks.onAutoCompactChange(newValue==="true");break;case"show-images":callbacks.onShowImagesChange(newValue==="true");break;case"image-width-cells":callbacks.onImageWidthCellsChange(parseInt(newValue,10));break;case"auto-resize-images":callbacks.onAutoResizeImagesChange(newValue==="true");break;case"block-images":callbacks.onBlockImagesChange(newValue==="true");break;case"skill-commands":callbacks.onEnableSkillCommandsChange(newValue==="true");break;case"steering-mode":callbacks.onSteeringModeChange(newValue);break;case"follow-up-mode":callbacks.onFollowUpModeChange(newValue);break;case"transport":callbacks.onTransportChange(newValue);break;case"http-idle-timeout":{let choice=HTTP_IDLE_TIMEOUT_CHOICES.find(item=>item.label===newValue);choice&&callbacks.onHttpIdleTimeoutMsChange(choice.timeoutMs);break}case"hide-thinking":callbacks.onHideThinkingBlockChange(newValue==="true");break;case"mermaid-rendering":callbacks.onMermaidRenderingModeChange(newValue);break;case"cache-miss-notices":callbacks.onShowCacheMissNoticesChange(newValue==="true");break;case"collapse-changelog":callbacks.onCollapseChangelogChange(newValue==="true");break;case"quiet-startup":callbacks.onQuietStartupChange(newValue==="true");break;case"double-escape-action":callbacks.onDoubleEscapeActionChange(newValue);break;case"tree-filter-mode":callbacks.onTreeFilterModeChange(newValue);break;case"show-hardware-cursor":callbacks.onShowHardwareCursorChange(newValue==="true");break;case"editor-padding":callbacks.onEditorPaddingXChange(parseInt(newValue,10));break;case"output-padding":callbacks.onOutputPadChange(newValue==="0"?0:1);break;case"autocomplete-max-visible":callbacks.onAutocompleteMaxVisibleChange(parseInt(newValue,10));break;case"clear-on-shrink":callbacks.onClearOnShrinkChange(newValue==="true");break;case"terminal-progress":callbacks.onShowTerminalProgressChange(newValue==="true");break;case"tui-mode":callbacks.onTuiModeChange(newValue);break;case"fullscreen-exit-output":callbacks.onFullscreenExitOutputChange(newValue);break;case"fullscreen-scrollbar":callbacks.onFullscreenScrollbarChange(newValue);break;case"fullscreen-copy-on-select":callbacks.onFullscreenCopyOnSelectChange(newValue==="true");break;case"theme":callbacks.onThemeChange(newValue);break}},callbacks.onCancel,{enableSearch:!0}),this.addChild(this.settingsList),this.addChild(new DynamicBorder)}getSettingsList(){return this.settingsList}};var SkillInvocationMessageComponent=class extends Box{expanded=!1;skillBlock;markdownTheme;constructor(skillBlock,markdownTheme=getMarkdownTheme()){super(1,1,t=>theme.bg("customMessageBg",t)),this.skillBlock=skillBlock,this.markdownTheme=markdownTheme,this.updateDisplay()}setExpanded(expanded){this.expanded=expanded,this.updateDisplay()}invalidate(){super.invalidate(),this.updateDisplay()}updateDisplay(){if(this.clear(),this.expanded){let label=theme.fg("customMessageLabel","\x1B[1m[skill]\x1B[22m");this.addChild(new Text(label,0,0));let header=`**${this.skillBlock.name}**
|
|
1327
|
+
`),this.box.addChild(new Markdown(text,0,0,this.markdownTheme,{color:text2=>theme.fg("customMessageText",text2)}))}};import{isAbsolute as isAbsolute12,relative as relative10,resolve as resolve20,sep as sep13}from"node:path";function areExperimentalFeaturesEnabled(){let configuredValue=process.env.AGENT_FORGE_EXPERIMENTAL;return configuredValue===void 0?process.env.PI_EXPERIMENTAL==="1":configuredValue==="1"}function sanitizeStatusText(text){return text.replace(/[\r\n\t]/g," ").replace(/ +/g," ").trim()}function formatTokens(count){return count<1e3?count.toString():count<1e4?`${(count/1e3).toFixed(1)}k`:count<1e6?`${Math.round(count/1e3)}k`:count<1e7?`${(count/1e6).toFixed(1)}M`:`${Math.round(count/1e6)}M`}function formatCwdForFooter(cwd,home){if(!home)return cwd;let resolvedCwd=resolve20(cwd),resolvedHome=resolve20(home),relativeToHome=relative10(resolvedHome,resolvedCwd);return relativeToHome===""||relativeToHome!==".."&&!relativeToHome.startsWith(`..${sep13}`)&&!isAbsolute12(relativeToHome)?relativeToHome===""?"~":`~${sep13}${relativeToHome}`:cwd}function summarizeWorkflowState(state2){let workflows=state2?.workflows,records=Array.isArray(workflows)?workflows:[],record=[...records].reverse().find(item=>item?.status==="draft"||item?.status==="running")??records.at(-1);if(record===void 0||typeof record.title!="string")return;let stages=Array.isArray(record.runtime)?record.runtime:[],done=stages.filter(stage=>stage?.status==="completed"||stage?.status==="skipped").length,activeCount=stages.filter(stage=>stage?.status==="active").length,parts=[`wf: ${record.title} ${done}/${stages.length}`];return activeCount>=2&&parts.push(`\u25B6${activeCount}`),stages.some(stage=>stage?.status==="awaiting_review")&&parts.push("\u23F8"),Array.isArray(record.diagnostics)&&record.diagnostics.length>0&&parts.push("\u26A0"),record.status==="failed"&&parts.push("\u2717"),parts.join(" ")}var FooterComponent=class{autoCompactEnabled=!0;session;footerData;constructor(session,footerData){this.session=session,this.footerData=footerData}setSession(session){this.session=session}get facade(){return createCodingAgentFacade(this.session)}setAutoCompactEnabled(enabled){this.autoCompactEnabled=enabled}invalidate(){}dispose(){}render(width){let state2=this.facade.getState(),usageTotals=createUsageTotals(),latestCacheHitRate,goalTitle,todoDone=0,todoTotal=0,workflowState;for(let entry of this.facade.getEntries())if(entry.type==="message"&&entry.message.role==="assistant"){addUsageToTotals(usageTotals,entry.message.usage);let latestPromptTokens=entry.message.usage.input+entry.message.usage.cacheRead+entry.message.usage.cacheWrite;latestCacheHitRate=latestPromptTokens>0?entry.message.usage.cacheRead/latestPromptTokens*100:void 0}else if(entry.type==="message"&&entry.message.role==="toolResult"&&entry.message.usage)addUsageToTotals(usageTotals,entry.message.usage);else if((entry.type==="branch_summary"||entry.type==="compaction")&&entry.usage)addUsageToTotals(usageTotals,entry.usage);else if(entry.type==="custom"&&entry.customType==="goal.state"){let goals=entry.data?.goals,current=Array.isArray(goals)?goals.at(-1):void 0;current&&typeof current.title=="string"&&(goalTitle=current.title)}else if(entry.type==="custom"&&entry.customType==="todo.state"){let todos=entry.data?.todos;Array.isArray(todos)&&(todoDone=todos.filter(item=>item?.status==="done").length,todoTotal=todos.length)}else entry.type==="custom"&&entry.customType==="workflow.state"&&(workflowState=entry.data);let contextUsage=this.facade.getContextUsage(),contextWindow=contextUsage?.contextWindow??state2.model?.contextWindow??0,contextPercentValue=contextUsage?.percent??0,contextPercent=contextUsage?.percent!==null?contextPercentValue.toFixed(1):"?",pwd=formatCwdForFooter(this.facade.getCwd(),process.env.HOME||process.env.USERPROFILE),branch=this.footerData.getGitBranch();branch&&(pwd=`${pwd} (${branch})`);let sessionName=this.facade.getSessionName();sessionName&&(pwd=`${pwd} \u2022 ${sessionName}`);let statsParts=[];usageTotals.input&&statsParts.push(`\u2191${formatTokens(usageTotals.input)}`),usageTotals.output&&statsParts.push(`\u2193${formatTokens(usageTotals.output)}`),usageTotals.cacheRead&&statsParts.push(`R${formatTokens(usageTotals.cacheRead)}`),usageTotals.cacheWrite&&statsParts.push(`W${formatTokens(usageTotals.cacheWrite)}`),(usageTotals.cacheRead>0||usageTotals.cacheWrite>0)&&latestCacheHitRate!==void 0&&statsParts.push(`CH${latestCacheHitRate.toFixed(1)}%`);let usingSubscription=state2.model?state2.model.provider==="kimi-coding"||this.facade.isUsingSubscription(state2.model.provider):!1;if(usageTotals.cost||usingSubscription){let costStr=`$${usageTotals.cost.toFixed(3)}${usingSubscription?" (sub)":""}`;statsParts.push(costStr)}let contextPercentStr,autoIndicator=this.autoCompactEnabled?" (auto)":"",contextPercentDisplay=contextPercent==="?"?`?/${formatTokens(contextWindow)}${autoIndicator}`:`${contextPercent}%/${formatTokens(contextWindow)}${autoIndicator}`;contextPercentValue>90?contextPercentStr=theme.fg("error",contextPercentDisplay):contextPercentValue>70?contextPercentStr=theme.fg("warning",contextPercentDisplay):contextPercentStr=contextPercentDisplay,statsParts.push(contextPercentStr),areExperimentalFeaturesEnabled()&&statsParts.push(`${theme.fg("dim","\u2022")} ${theme.bold(theme.fg("warning","xp"))}`);let statsLeft=statsParts.join(" "),modelName=state2.model?.id||"no-model",statsLeftWidth=visibleWidth(statsLeft);statsLeftWidth>width&&(statsLeft=truncateToWidth(statsLeft,width,"..."),statsLeftWidth=visibleWidth(statsLeft));let minPadding=2,rightSideWithoutProvider=modelName;if(state2.model?.reasoning){let thinkingLevel=state2.thinkingLevel||"off";rightSideWithoutProvider=thinkingLevel==="off"?`${modelName} \u2022 thinking off`:`${modelName} \u2022 ${thinkingLevel}`}let rightSide=rightSideWithoutProvider;this.footerData.getAvailableProviderCount()>1&&state2.model&&(rightSide=`(${state2.model.provider}) ${rightSideWithoutProvider}`,statsLeftWidth+minPadding+visibleWidth(rightSide)>width&&(rightSide=rightSideWithoutProvider));let rightSideWidth=visibleWidth(rightSide),totalNeeded=statsLeftWidth+minPadding+rightSideWidth,statsLine;if(totalNeeded<=width){let padding=" ".repeat(width-statsLeftWidth-rightSideWidth);statsLine=statsLeft+padding+rightSide}else{let availableForRight=width-statsLeftWidth-minPadding;if(availableForRight>0){let truncatedRight=truncateToWidth(rightSide,availableForRight,""),truncatedRightWidth=visibleWidth(truncatedRight),padding=" ".repeat(Math.max(0,width-statsLeftWidth-truncatedRightWidth));statsLine=statsLeft+padding+truncatedRight}else statsLine=statsLeft}let dimStatsLeft=theme.fg("dim",statsLeft),remainder=statsLine.slice(statsLeft.length),dimRemainder=theme.fg("dim",remainder),lines=[truncateToWidth(theme.fg("dim",pwd),width,theme.fg("dim","...")),dimStatsLeft+dimRemainder];if(goalTitle!==void 0){let goalParts=[`goal: ${goalTitle}`];todoTotal>0&&goalParts.push(`todo ${todoDone}/${todoTotal}`);let goalLine=theme.fg("dim",sanitizeStatusText(goalParts.join(" \u2022 ")));lines.push(truncateToWidth(goalLine,width,theme.fg("dim","...")))}let workflowSummary=summarizeWorkflowState(workflowState);if(workflowSummary!==void 0){let workflowLine=theme.fg("dim",sanitizeStatusText(workflowSummary));lines.push(truncateToWidth(workflowLine,width,theme.fg("dim","...")))}return lines}};var SUBMENU_SELECT_LIST_LAYOUT={minPrimaryColumnWidth:12,maxPrimaryColumnWidth:32},SelectSubmenu=class extends Container{selectList;listChildIndex;allOptions;listLayout;searchInput;onSelectCb;onCancelCb;onSelectionChangeCb;constructor(title,description,options,currentValue,onSelect,onCancel,onSelectionChange,submenuOptions){super(),this.allOptions=options,this.listLayout=submenuOptions?.layout??SUBMENU_SELECT_LIST_LAYOUT,this.onSelectCb=onSelect,this.onCancelCb=onCancel,this.onSelectionChangeCb=onSelectionChange,this.addChild(new Text(theme.bold(theme.fg("accent",title)),0,0)),description&&(this.addChild(new Spacer(1)),this.addChild(new Text(theme.fg("muted",description),0,0))),submenuOptions?.searchable&&(this.addChild(new Spacer(1)),this.searchInput=new Input,this.searchInput.onSubmit=()=>{this.selectList.handleInput("\r")},this.addChild(this.searchInput)),this.addChild(new Spacer(1)),this.selectList=this.buildSelectList(options,currentValue),this.listChildIndex=this.children.length,this.addChild(this.selectList),this.addChild(new Spacer(1));let hint=submenuOptions?.searchable?" Type to filter \xB7 Enter to select \xB7 Esc to go back":" Enter to select \xB7 Esc to go back";this.addChild(new Text(theme.fg("dim",hint),0,0))}buildSelectList(options,preselect){let list=new SelectList(options,Math.min(options.length,10),getSelectListTheme(),this.listLayout),idx=options.findIndex(o=>o.value===preselect);if(idx!==-1&&list.setSelectedIndex(idx),list.onSelect=item=>this.onSelectCb(item.value),list.onCancel=this.onCancelCb,this.onSelectionChangeCb){let cb=this.onSelectionChangeCb;list.onSelectionChange=item=>cb(item.value)}return list}applyFilter(query){let filtered=query?fuzzyFilter(this.allOptions,query,item=>`${item.label} ${item.description??""}`):this.allOptions,newList=this.buildSelectList(filtered,"");this.children[this.listChildIndex]=newList,this.selectList=newList}handleInput(data){if(this.searchInput){let kb=getKeybindings();kb.matches(data,"tui.select.up")||kb.matches(data,"tui.select.down")||kb.matches(data,"tui.select.confirm")||kb.matches(data,"tui.select.cancel")?this.selectList.handleInput(data):(this.searchInput.handleInput(data),this.applyFilter(this.searchInput.getValue()))}else this.selectList.handleInput(data)}},SteppedSubmenu=class extends Container{steps;onComplete;onCancel;opts;activeComponent;context;constructor(steps,onComplete,onCancel,opts={}){super(),this.steps=steps,this.onComplete=onComplete,this.onCancel=onCancel,this.opts=opts,this.context={...opts.initialContext??{}},this.activeComponent=this.buildStep(opts.startAtStep??0)}buildStep(stepIndex){let step=this.steps[stepIndex],total=this.steps.length,stepLabel=total>1?`Step ${stepIndex+1}/${total} \xB7 `:"",title=typeof step.title=="function"?step.title(this.context):step.title,desc=typeof step.description=="function"?step.description(this.context):step.description,items=step.options(this.context),preselect=step.preselect?.(this.context)??"";return new SelectSubmenu(title,`${stepLabel}${desc}`,items,preselect,value=>{this.context[step.key]=value,stepIndex<total-1?this.activeComponent=this.buildStep(stepIndex+1):(this.onComplete({...this.context}),this.opts.loop?(this.context={},this.activeComponent=this.buildStep(0)):this.onCancel())},()=>{stepIndex>0?(delete this.context[step.key],this.activeComponent=this.buildStep(stepIndex-1)):this.onCancel()},void 0,step.searchable||step.layout?{searchable:step.searchable,layout:step.layout}:void 0)}render(width){return this.activeComponent.render(width)}handleInput(data){this.activeComponent.handleInput?.(data)}invalidate(){this.activeComponent.invalidate?.()}};var MODEL_PICKER_LAYOUT={minPrimaryColumnWidth:12,maxPrimaryColumnWidth:46},THINKING_DESCRIPTIONS={off:"No reasoning",minimal:"Very brief reasoning (~1k tokens)",low:"Light reasoning (~2k tokens)",medium:"Moderate reasoning (~8k tokens)",high:"Deep reasoning (~16k tokens)",xhigh:"Extra-high reasoning (~32k tokens)",max:"Maximum reasoning"},WarningSettingsSubmenu=class extends Container{settingsList;state;constructor(warnings,onChange,onCancel){super(),this.state={...warnings};let items=[{id:"anthropic-extra-usage",label:"Anthropic extra usage",description:"Warn when Anthropic subscription auth may use paid extra usage",currentValue:this.state.anthropicExtraUsage??!0?"true":"false",values:["true","false"]}];this.settingsList=new SettingsList(items,Math.min(items.length,10),getSettingsListTheme(),(id,newValue)=>{id==="anthropic-extra-usage"&&(this.state={...this.state,anthropicExtraUsage:newValue==="true"},onChange({...this.state}))},onCancel),this.addChild(this.settingsList)}handleInput(data){this.settingsList.handleInput(data)}},CLEAR_OVERRIDE_VALUE="__clear__";function modelSettingKey(model){return`${model.provider}/${model.id}`}function modelDisplayLabel(model){return`${model.id} [${model.provider}]`}function modelThinkingOverridesSummary(overrides){let count=Object.keys(overrides).length;return count===0?"none":`${count} configured`}function modelItemLabel(model){return`${model.id} ${theme.fg("muted",`[${model.provider}]`)}`}function themeItems(availableThemes){return availableThemes.map(name=>({value:name,label:name}))}var AUTOMATIC_THEME_VALUE="/";function singleModeThemeItems(availableThemes){return[{value:AUTOMATIC_THEME_VALUE,label:"Automatic",description:"Use separate themes for light and dark terminal appearance"},...themeItems(availableThemes)]}function preferredTheme(availableThemes,preferred,fallback){return preferred&&availableThemes.includes(preferred)?preferred:availableThemes.includes(fallback)?fallback:availableThemes[0]??fallback}function defaultAutomaticThemes(currentThemeSetting,availableThemes){let autoTheme=parseAutoThemeSetting(currentThemeSetting);if(autoTheme)return autoTheme;let currentFixedTheme=currentThemeSetting.includes("/")?void 0:currentThemeSetting,themeName=preferredTheme(availableThemes,currentFixedTheme,"dark");return{lightTheme:themeName,darkTheme:themeName}}var ThemeSubmenu=class extends Container{inputComponent;callbacks;availableThemes;terminalTheme;onDone;originalThemeSetting;mode;singleTheme;lightTheme;darkTheme;constructor(currentThemeSetting,terminalTheme,availableThemes,callbacks,onDone){super(),this.callbacks=callbacks,this.availableThemes=availableThemes,this.terminalTheme=terminalTheme,this.onDone=onDone,this.originalThemeSetting=currentThemeSetting;let autoTheme=parseAutoThemeSetting(currentThemeSetting),automaticThemes=defaultAutomaticThemes(currentThemeSetting,availableThemes),fixedTheme=autoTheme||currentThemeSetting.includes("/")?void 0:currentThemeSetting;this.mode=autoTheme?"automatic":"single",this.lightTheme=automaticThemes.lightTheme,this.darkTheme=automaticThemes.darkTheme,this.singleTheme=preferredTheme(availableThemes,fixedTheme??(autoTheme?this.getActiveAutomaticTheme():void 0),"dark"),this.mode==="automatic"?this.showAutomaticMenu():this.showSingleMenu()}handleInput(data){this.inputComponent?.handleInput?.(data)}setContent(renderComponent,inputComponent=renderComponent){this.clear(),this.addChild(renderComponent),this.inputComponent=inputComponent}showSingleMenu(){this.mode="single";let menu=new SelectSubmenu("Theme","Select a theme, or choose Automatic to follow terminal appearance.",singleModeThemeItems(this.availableThemes),this.singleTheme,value=>{if(value===AUTOMATIC_THEME_VALUE){this.mode="automatic",this.callbacks.onThemePreview?.(this.getThemeSetting()),this.showAutomaticMenu();return}this.singleTheme=value,this.apply(value)},()=>this.cancel(),value=>{this.callbacks.onThemePreview?.(value===AUTOMATIC_THEME_VALUE?this.getAutomaticThemeSetting():value)});this.setContent(menu)}showAutomaticMenu(){this.mode="automatic";let content=new Container;content.addChild(new Text(theme.bold(theme.fg("accent","Automatic Theme")),0,0)),content.addChild(new Spacer(1)),content.addChild(new Text(theme.fg("muted","Choose themes for terminal light and dark appearance."),0,0)),content.addChild(new Text(theme.fg("muted","Light/dark detection requires terminal support."),0,0)),content.addChild(new Spacer(1));let items=[{id:"light-theme",label:"Light theme",description:"Theme to use in automatic mode when the terminal is light",currentValue:this.lightTheme,submenu:(currentValue,done)=>this.createThemeSelect("Light Theme","Select the theme to use for light terminal appearance",currentValue,done,value=>{this.lightTheme=value,this.callbacks.onThemePreview?.(this.getThemeSetting()),done(value)})},{id:"dark-theme",label:"Dark theme",description:"Theme to use in automatic mode when the terminal is dark",currentValue:this.darkTheme,submenu:(currentValue,done)=>this.createThemeSelect("Dark Theme","Select the theme to use for dark terminal appearance",currentValue,done,value=>{this.darkTheme=value,this.callbacks.onThemePreview?.(this.getThemeSetting()),done(value)})},{id:"apply",label:"Apply",description:"Save and go back",currentValue:"save and go back",values:["save and go back"]},{id:"single-mode",label:"Change mode",description:"Switch to one theme for light and dark",currentValue:"switch to single theme",values:["switch to single theme"]}],settingsList=new SettingsList(items,Math.min(items.length,10),getSettingsListTheme(),id=>{switch(id){case"single-mode":this.mode="single",this.singleTheme=this.getActiveAutomaticTheme(),this.callbacks.onThemePreview?.(this.singleTheme),this.showSingleMenu();break;case"apply":this.apply(this.getAutomaticThemeSetting());break}},()=>this.cancel());content.addChild(settingsList),this.setContent(content,settingsList)}createThemeSelect(title,description,currentValue,done,onSelect){return new SelectSubmenu(title,description,themeItems(this.availableThemes),currentValue,onSelect,()=>{this.callbacks.onThemePreview?.(this.getThemeSetting()),done()},value=>this.callbacks.onThemePreview?.(value))}getThemeSetting(){return this.mode==="automatic"?this.getAutomaticThemeSetting():this.singleTheme}getActiveAutomaticTheme(){return this.terminalTheme==="light"?this.lightTheme:this.darkTheme}getAutomaticThemeSetting(){return`${this.lightTheme}/${this.darkTheme}`}apply(themeSetting){this.onDone(themeSetting)}cancel(){this.callbacks.onThemePreview?.(this.originalThemeSetting),this.onDone()}},SettingsSelectorComponent=class extends Container{settingsList;constructor(config,callbacks){super();let supportsImages=getCapabilities().images,followUpKey=keyDisplayText("app.message.followUp"),cycleThinkingKey=keyDisplayText("app.thinking.cycle"),currentWarnings={...config.warnings},currentModelThinkingLevels={...config.modelThinkingLevels},defaultModelByValue=new Map(config.availableDefaultModels.map(model=>[modelSettingKey(model),model])),currentDefaultModelKey=defaultModelByValue.has(config.defaultModel)?config.defaultModel:void 0,currentModelKey=config.currentModel?modelSettingKey(config.currentModel):void 0,items=[{id:"autocompact",label:"Auto-compact",description:"Automatically compact context when it gets too large",currentValue:config.autoCompact?"true":"false",values:["true","false"]},{id:"steering-mode",label:"Steering mode",description:"Enter while streaming queues steering messages. 'one-at-a-time': deliver one, wait for response. 'all': deliver all at once.",currentValue:config.steeringMode,values:["one-at-a-time","all"]},{id:"follow-up-mode",label:"Follow-up mode",description:`${followUpKey} queues follow-up messages until agent stops. 'one-at-a-time': deliver one, wait for response. 'all': deliver all at once.`,currentValue:config.followUpMode,values:["one-at-a-time","all"]},{id:"transport",label:"Transport",description:"Preferred transport for providers that support multiple transports",currentValue:config.transport,values:["sse","websocket","websocket-cached","auto"]},{id:"http-idle-timeout",label:"HTTP idle timeout",description:"Maximum idle gap while waiting for HTTP headers or body chunks. Disable for local models that pause longer than five minutes.",currentValue:formatHttpIdleTimeoutMs(config.httpIdleTimeoutMs),values:HTTP_IDLE_TIMEOUT_CHOICES.map(choice=>choice.label)},{id:"hide-thinking",label:"Hide thinking",description:"Hide thinking blocks in assistant responses",currentValue:config.hideThinkingBlock?"true":"false",values:["true","false"]},{id:"mermaid-rendering",label:"Mermaid diagrams",description:"Render Mermaid code blocks as Unicode diagrams",currentValue:config.mermaidRenderingMode,values:["off","final","streaming"]},{id:"cache-miss-notices",label:"Cache miss notices",description:"Show transcript notices for cache costs and provider recovery diagnostics",currentValue:config.showCacheMissNotices?"true":"false",values:["true","false"]},{id:"collapse-changelog",label:"Collapse changelog",description:"Show condensed changelog after updates",currentValue:config.collapseChangelog?"true":"false",values:["true","false"]},{id:"quiet-startup",label:"Quiet startup",description:"Disable verbose printing at startup",currentValue:config.quietStartup?"true":"false",values:["true","false"]},{id:"double-escape-action",label:"Double-escape action",description:"Action when pressing Escape twice with empty editor",currentValue:config.doubleEscapeAction,values:["tree","fork","none"]},{id:"tree-filter-mode",label:"Tree filter mode",description:"Default filter when opening /tree",currentValue:config.treeFilterMode,values:["default","no-tools","user-only","labeled-only","all"]},{id:"warnings",label:"Warnings",description:"Enable or disable individual warnings",currentValue:"configure",submenu:(_currentValue,done)=>new WarningSettingsSubmenu(currentWarnings,warnings=>{currentWarnings=warnings,callbacks.onWarningsChange(warnings)},()=>done())},{id:"model-thinking",label:"Default thinking level per model",description:`Override the default thinking level for specific models. ${cycleThinkingKey} cycles in-session.`,currentValue:modelThinkingOverridesSummary(currentModelThinkingLevels),submenu:(_currentValue,done)=>{let steps=[{key:"model",title:"Per-Model Thinking Level",description:"Select a model to configure",options:()=>{let items2=[...config.availableDefaultModels].sort((a,b2)=>{let aKey=modelSettingKey(a),bKey=modelSettingKey(b2);return aKey===currentModelKey?-1:bKey===currentModelKey?1:aKey===currentDefaultModelKey?-1:bKey===currentDefaultModelKey?1:a.provider.localeCompare(b2.provider)}).map(model=>{let key=modelSettingKey(model),override=currentModelThinkingLevels[key];return{value:key,label:modelItemLabel(model),description:override??void 0}});return items2.length===0&&items2.push({value:"__none__",label:"No models available",description:"Log in to a provider or configure an API key first"}),items2},preselect:()=>currentModelKey??currentDefaultModelKey,searchable:!0,layout:MODEL_PICKER_LAYOUT},{key:"level",title:ctx=>{let m2=defaultModelByValue.get(ctx.model);return`Thinking Level for ${m2?modelDisplayLabel(m2):ctx.model}`},description:"Select default thinking level for this model",options:ctx=>{let model=defaultModelByValue.get(ctx.model);if(!model)return[];let items2=(model.reasoning?getSupportedThinkingLevels(model):["off"]).map(level=>({value:level,label:level,description:THINKING_DESCRIPTIONS[level]}));return currentModelThinkingLevels[ctx.model]!==void 0&&items2.push({value:CLEAR_OVERRIDE_VALUE,label:"(clear override)",description:`Revert to global default (${config.thinkingLevel})`}),items2},preselect:ctx=>currentModelThinkingLevels[ctx.model]}],summary=()=>modelThinkingOverridesSummary(currentModelThinkingLevels);return new SteppedSubmenu(steps,selections=>{let model=defaultModelByValue.get(selections.model);model&&(selections.level===CLEAR_OVERRIDE_VALUE?(callbacks.onModelThinkingLevelRemove(model.provider,model.id),delete currentModelThinkingLevels[selections.model]):(callbacks.onModelThinkingLevelChange(model.provider,model.id,selections.level),currentModelThinkingLevels[selections.model]=selections.level))},()=>{done(summary())},{loop:!0})}},{id:"tui-mode",label:"TUI mode",description:"Interface layout; fullscreen mode is experimental",currentValue:config.tuiMode,values:["regular","fullscreen"]},{id:"fullscreen-exit-output",label:"Fullscreen exit output",description:"Print the transcript or only a session resume hint when exiting fullscreen mode",currentValue:config.fullscreenExitOutput,values:["transcript","resume-hint"]},{id:"fullscreen-scrollbar",label:"Fullscreen scrollbar",description:"Scrollbar behavior in fullscreen mode; has no effect in regular mode",currentValue:config.fullscreenScrollbar,values:["auto","always","hidden"]},{id:"fullscreen-copy-on-select",label:"Fullscreen copy on select",description:"Automatically copy selected text in fullscreen mode; disable to copy selections with Ctrl+X",currentValue:config.fullscreenCopyOnSelect?"true":"false",values:["true","false"]},{id:"theme",label:"Theme",description:"Color theme for the interface",currentValue:config.currentTheme,submenu:(currentValue,done)=>new ThemeSubmenu(currentValue,config.terminalTheme,config.availableThemes,callbacks,done)}];supportsImages&&(items.splice(1,0,{id:"show-images",label:"Show images",description:"Render images inline in terminal",currentValue:config.showImages?"true":"false",values:["true","false"]}),items.splice(2,0,{id:"image-width-cells",label:"Image width",description:"Preferred inline image width in terminal cells",currentValue:String(config.imageWidthCells),values:["60","80","120"]})),items.splice(supportsImages?3:1,0,{id:"auto-resize-images",label:"Auto-resize images",description:"Resize large images to 2000x2000 max for better model compatibility",currentValue:config.autoResizeImages?"true":"false",values:["true","false"]});let autoResizeIndex=items.findIndex(item=>item.id==="auto-resize-images");items.splice(autoResizeIndex+1,0,{id:"block-images",label:"Block images",description:"Prevent images from being sent to LLM providers",currentValue:config.blockImages?"true":"false",values:["true","false"]});let blockImagesIndex=items.findIndex(item=>item.id==="block-images");items.splice(blockImagesIndex+1,0,{id:"skill-commands",label:"Skill commands",description:"Register skills as /skill:name commands",currentValue:config.enableSkillCommands?"true":"false",values:["true","false"]});let skillCommandsIndex=items.findIndex(item=>item.id==="skill-commands");items.splice(skillCommandsIndex+1,0,{id:"show-hardware-cursor",label:"Show hardware cursor",description:"Show the terminal cursor while still positioning it for IME support",currentValue:config.showHardwareCursor?"true":"false",values:["true","false"]});let hardwareCursorIndex=items.findIndex(item=>item.id==="show-hardware-cursor");items.splice(hardwareCursorIndex+1,0,{id:"editor-padding",label:"Editor padding",description:"Horizontal padding for input editor (0-3)",currentValue:String(config.editorPaddingX),values:["0","1","2","3"]});let editorPaddingIndex=items.findIndex(item=>item.id==="editor-padding");items.splice(editorPaddingIndex+1,0,{id:"output-padding",label:"Output padding",description:"Horizontal padding for user messages, assistant messages, and thinking",currentValue:String(config.outputPad),values:["0","1"]});let outputPaddingIndex=items.findIndex(item=>item.id==="output-padding");items.splice(outputPaddingIndex+1,0,{id:"autocomplete-max-visible",label:"Autocomplete max items",description:"Max visible items in autocomplete dropdown (3-20)",currentValue:String(config.autocompleteMaxVisible),values:["3","5","7","10","15","20"]});let autocompleteIndex=items.findIndex(item=>item.id==="autocomplete-max-visible");items.splice(autocompleteIndex+1,0,{id:"clear-on-shrink",label:"Clear on shrink",description:"Clear empty rows when content shrinks (may cause flicker)",currentValue:config.clearOnShrink?"true":"false",values:["true","false"]});let clearOnShrinkIndex=items.findIndex(item=>item.id==="clear-on-shrink");items.splice(clearOnShrinkIndex+1,0,{id:"terminal-progress",label:"Terminal progress",description:"Show OSC 9;4 progress indicators in the terminal tab bar",currentValue:config.showTerminalProgress?"true":"false",values:["true","false"]}),this.addChild(new DynamicBorder),this.settingsList=new SettingsList(items,10,getSettingsListTheme(),(id,newValue)=>{switch(id){case"autocompact":callbacks.onAutoCompactChange(newValue==="true");break;case"show-images":callbacks.onShowImagesChange(newValue==="true");break;case"image-width-cells":callbacks.onImageWidthCellsChange(parseInt(newValue,10));break;case"auto-resize-images":callbacks.onAutoResizeImagesChange(newValue==="true");break;case"block-images":callbacks.onBlockImagesChange(newValue==="true");break;case"skill-commands":callbacks.onEnableSkillCommandsChange(newValue==="true");break;case"steering-mode":callbacks.onSteeringModeChange(newValue);break;case"follow-up-mode":callbacks.onFollowUpModeChange(newValue);break;case"transport":callbacks.onTransportChange(newValue);break;case"http-idle-timeout":{let choice=HTTP_IDLE_TIMEOUT_CHOICES.find(item=>item.label===newValue);choice&&callbacks.onHttpIdleTimeoutMsChange(choice.timeoutMs);break}case"hide-thinking":callbacks.onHideThinkingBlockChange(newValue==="true");break;case"mermaid-rendering":callbacks.onMermaidRenderingModeChange(newValue);break;case"cache-miss-notices":callbacks.onShowCacheMissNoticesChange(newValue==="true");break;case"collapse-changelog":callbacks.onCollapseChangelogChange(newValue==="true");break;case"quiet-startup":callbacks.onQuietStartupChange(newValue==="true");break;case"double-escape-action":callbacks.onDoubleEscapeActionChange(newValue);break;case"tree-filter-mode":callbacks.onTreeFilterModeChange(newValue);break;case"show-hardware-cursor":callbacks.onShowHardwareCursorChange(newValue==="true");break;case"editor-padding":callbacks.onEditorPaddingXChange(parseInt(newValue,10));break;case"output-padding":callbacks.onOutputPadChange(newValue==="0"?0:1);break;case"autocomplete-max-visible":callbacks.onAutocompleteMaxVisibleChange(parseInt(newValue,10));break;case"clear-on-shrink":callbacks.onClearOnShrinkChange(newValue==="true");break;case"terminal-progress":callbacks.onShowTerminalProgressChange(newValue==="true");break;case"tui-mode":callbacks.onTuiModeChange(newValue);break;case"fullscreen-exit-output":callbacks.onFullscreenExitOutputChange(newValue);break;case"fullscreen-scrollbar":callbacks.onFullscreenScrollbarChange(newValue);break;case"fullscreen-copy-on-select":callbacks.onFullscreenCopyOnSelectChange(newValue==="true");break;case"theme":callbacks.onThemeChange(newValue);break}},callbacks.onCancel,{enableSearch:!0}),this.addChild(this.settingsList),this.addChild(new DynamicBorder)}getSettingsList(){return this.settingsList}};var SkillInvocationMessageComponent=class extends Box{expanded=!1;skillBlock;markdownTheme;constructor(skillBlock,markdownTheme=getMarkdownTheme()){super(1,1,t=>theme.bg("customMessageBg",t)),this.skillBlock=skillBlock,this.markdownTheme=markdownTheme,this.updateDisplay()}setExpanded(expanded){this.expanded=expanded,this.updateDisplay()}invalidate(){super.invalidate(),this.updateDisplay()}updateDisplay(){if(this.clear(),this.expanded){let label=theme.fg("customMessageLabel","\x1B[1m[skill]\x1B[22m");this.addChild(new Text(label,0,0));let header=`**${this.skillBlock.name}**
|
|
1326
1328
|
|
|
1327
1329
|
`;this.addChild(new Markdown(header+this.skillBlock.content,0,0,this.markdownTheme,{color:text=>theme.fg("customMessageText",text)}))}else{let line=theme.fg("customMessageLabel","\x1B[1m[skill]\x1B[22m ")+theme.fg("customMessageText",this.skillBlock.name)+theme.fg("dim",` (${keyText("app.tools.expand")} to expand)`);this.addChild(new Text(line,0,0))}}};var FALLBACK_PREVIEW_LINES=10,ToolExecutionComponent=class extends Container{contentBox;contentText;selfRenderContainer;callRendererComponent;resultRendererComponent;rendererState={};imageComponents=[];imageSpacers=[];toolName;toolCallId;args;expanded=!1;showImages;imageWidthCells;isPartial=!0;toolDefinition;builtInToolDefinition;ui;cwd;executionStarted=!1;argsComplete=!1;result;convertedImages=new Map;hideComponent=!1;constructor(toolName,toolCallId,args,options={},toolDefinition,ui,cwd){super(),this.toolName=toolName,this.toolCallId=toolCallId,this.args=args,this.toolDefinition=toolDefinition,this.builtInToolDefinition=createAllToolDefinitions(cwd)[toolName],this.showImages=options.showImages??!0,this.imageWidthCells=options.imageWidthCells??60,this.ui=ui,this.cwd=cwd,this.addChild(new Spacer(1)),this.contentBox=new Box(1,1,text=>theme.bg("toolPendingBg",text)),this.contentText=new Text("",1,1,text=>theme.bg("toolPendingBg",text)),this.selfRenderContainer=new Container,this.hasRendererDefinition()?this.addChild(this.getRenderShell()==="self"?this.selfRenderContainer:this.contentBox):this.addChild(this.contentText),this.updateDisplay()}getCallRenderer(){return this.builtInToolDefinition?this.toolDefinition?this.toolDefinition.renderCall??this.builtInToolDefinition.renderCall:this.builtInToolDefinition.renderCall:this.toolDefinition?.renderCall}getResultRenderer(){return this.builtInToolDefinition?this.toolDefinition?this.toolDefinition.renderResult??this.builtInToolDefinition.renderResult:this.builtInToolDefinition.renderResult:this.toolDefinition?.renderResult}hasRendererDefinition(){return this.builtInToolDefinition!==void 0||this.toolDefinition!==void 0}getRenderShell(){return this.builtInToolDefinition?this.toolDefinition?this.toolDefinition.renderShell??this.builtInToolDefinition.renderShell??"default":this.builtInToolDefinition.renderShell??"default":this.toolDefinition?.renderShell??"default"}getRenderContext(lastComponent){return{args:this.args,toolCallId:this.toolCallId,invalidate:()=>{this.invalidate(),this.ui.requestRender()},lastComponent,state:this.rendererState,cwd:this.cwd,executionStarted:this.executionStarted,argsComplete:this.argsComplete,isPartial:this.isPartial,expanded:this.expanded,showImages:this.showImages,isError:this.result?.isError??!1}}createCallFallback(){return new Text(theme.fg("toolTitle",theme.bold(this.toolName)),0,0)}createResultFallback(){let output=this.getTextOutput();if(!output)return;let lines=output.split(`
|
|
1328
1330
|
`),displayLines=this.expanded?lines:lines.slice(0,FALLBACK_PREVIEW_LINES),remaining=lines.length-displayLines.length,text=displayLines.map(line=>theme.fg("toolOutput",line)).join(`
|
package/dist/bundle/cli.js
CHANGED
|
@@ -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-
|
|
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));
|