@astralyn/pi 0.87.3 → 0.87.4

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.
@@ -1,2 +1,2 @@
1
1
  import { createRequire as __piCreateRequire } from "node:module"; const require = __piCreateRequire(import.meta.url);
2
- import{ShowImagesSelectorComponent,ThemeSelectorComponent}from"./chunks/chunk-MJ45I4SM.js";import{AgentSession,AgentSessionRuntime,ArminComponent,AssistantMessageComponent,BackgroundService,BashExecutionComponent,BorderedLoader,BranchSummaryMessageComponent,CONFIG_DIR_NAME,CURRENT_SESSION_VERSION,CompactionSummaryMessageComponent,CredentialSynchronizationError,CustomEditor,CustomMessageComponent,DEFAULT_COMPACTION_SETTINGS,DEFAULT_MAX_BYTES,DEFAULT_MAX_LINES,DefaultPackageManager,DefaultResourceLoader,DynamicBorder,ExtensionEditorComponent,ExtensionInputComponent,ExtensionRunner,ExtensionSelectorComponent,FooterComponent,InteractiveMode,LoginDialogComponent,ModelRegistry,ModelRuntime,ModelSelectorComponent,OAuthSelectorComponent,ProjectTrustStore,RpcClient,SessionManager,SessionSelectorComponent,SettingsManager,SettingsSelectorComponent,SkillInvocationMessageComponent,Theme,ThinkingSelectorComponent,ToolExecutionComponent,TreeSelectorComponent,UserMessageComponent,UserMessageSelectorComponent,VERSION,buildContextEntries,buildSessionContext,buildSessionProjection,calculateContextTokens,collectEntriesForBranchSummary,compact,convertToLlm,convertToPng,copyToClipboard,createAgentSession,createAgentSessionFromServices,createAgentSessionRuntime,createAgentSessionServices,createBashTool,createBashToolDefinition,createCodingTools,createEditTool,createEditToolDefinition,createEventBus,createExtensionRuntime,createFindTool,createFindToolDefinition,createGrepTool,createGrepToolDefinition,createLocalBashOperations,createLocalPowerShellOperations,createLsTool,createLsToolDefinition,createPowerShellTool,createPowerShellToolDefinition,createReadOnlyTools,createReadTool,createReadToolDefinition,createSyntheticSourceInfo,createWriteTool,createWriteToolDefinition,defineTool,detectSupportedImageMimeTypeFromFile,discoverAndLoadExtensions,estimateTokens,findCutPoint,findTurnStartIndex,formatDimensionNote,formatSize,formatSkillsForPrompt,generateBranchSummary,generateDiffString,generateSummary,generateSummaryWithUsage,generateUnifiedPatch,getAgentDir,getDocsPath,getExamplesPath,getLanguageFromPath,getLastAssistantUsage,getLatestCompactionEntry,getMarkdownTheme,getPackageDir,getPowerShellConfig,getReadmePath,getSelectListTheme,getSettingsListTheme,getShellConfig,hasTrustRequiringProjectResources,highlightCode,initTheme,isBashToolResult,isEditToolResult,isFindToolResult,isGrepToolResult,isLsToolResult,isPowerShellToolResult,isReadToolResult,isToolCallEventType,isWriteToolResult,keyHint,keyText,loadProjectContextFiles,loadSkills,loadSkillsFromDir,main,migrateSessionEntries,parseArgs,parseFrontmatter,parseSessionEntries,parseSkillBlock,prepareBranchEntries,rawKeyHint,readStoredCredential,renderDiff,resizeImage,resolveCliModel,resolveModelScopeWithDiagnostics,runPrintMode,runRpcMode,serializeConversation,sessionEntryToContextMessages,shouldCompact,stripFrontmatter,truncateHead,truncateLine,truncateTail,truncateToVisualLines,withFileMutationQueue,wrapRegisteredTool,wrapRegisteredTools}from"./chunks/chunk-TYOQD6VQ.js";import"./chunks/chunk-JEIV47WR.js";import"./chunks/chunk-5FDOJRDS.js";import"./chunks/chunk-5B3S5DVL.js";import"./chunks/chunk-2IO5GDBS.js";import"./chunks/chunk-JI4WGISU.js";import"./chunks/chunk-4L3WN2XY.js";export{AgentSession,AgentSessionRuntime,ArminComponent,AssistantMessageComponent,BackgroundService,BashExecutionComponent,BorderedLoader,BranchSummaryMessageComponent,CONFIG_DIR_NAME,CURRENT_SESSION_VERSION,CompactionSummaryMessageComponent,CredentialSynchronizationError,CustomEditor,CustomMessageComponent,DEFAULT_COMPACTION_SETTINGS,DEFAULT_MAX_BYTES,DEFAULT_MAX_LINES,DefaultPackageManager,DefaultResourceLoader,DynamicBorder,ExtensionEditorComponent,ExtensionInputComponent,ExtensionRunner,ExtensionSelectorComponent,FooterComponent,InteractiveMode,LoginDialogComponent,ModelRegistry,ModelRuntime,ModelSelectorComponent,OAuthSelectorComponent,ProjectTrustStore,RpcClient,SessionManager,SessionSelectorComponent,SettingsManager,SettingsSelectorComponent,ShowImagesSelectorComponent,SkillInvocationMessageComponent,Theme,ThemeSelectorComponent,ThinkingSelectorComponent,ToolExecutionComponent,TreeSelectorComponent,UserMessageComponent,UserMessageSelectorComponent,VERSION,buildContextEntries,buildSessionContext,buildSessionProjection,calculateContextTokens,collectEntriesForBranchSummary,compact,convertToLlm,convertToPng,copyToClipboard,createAgentSession,createAgentSessionFromServices,createAgentSessionRuntime,createAgentSessionServices,createBashTool,createBashToolDefinition,createCodingTools,createEditTool,createEditToolDefinition,createEventBus,createExtensionRuntime,createFindTool,createFindToolDefinition,createGrepTool,createGrepToolDefinition,createLocalBashOperations,createLocalPowerShellOperations,createLsTool,createLsToolDefinition,createPowerShellTool,createPowerShellToolDefinition,createReadOnlyTools,createReadTool,createReadToolDefinition,createSyntheticSourceInfo,createWriteTool,createWriteToolDefinition,defineTool,detectSupportedImageMimeTypeFromFile,discoverAndLoadExtensions,estimateTokens,findCutPoint,findTurnStartIndex,formatDimensionNote,formatSize,formatSkillsForPrompt,generateBranchSummary,generateDiffString,generateSummary,generateSummaryWithUsage,generateUnifiedPatch,getAgentDir,getDocsPath,getExamplesPath,getLanguageFromPath,getLastAssistantUsage,getLatestCompactionEntry,getMarkdownTheme,getPackageDir,getPowerShellConfig,getReadmePath,getSelectListTheme,getSettingsListTheme,getShellConfig,hasTrustRequiringProjectResources,highlightCode,initTheme,isBashToolResult,isEditToolResult,isFindToolResult,isGrepToolResult,isLsToolResult,isPowerShellToolResult,isReadToolResult,isToolCallEventType,isWriteToolResult,keyHint,keyText,loadProjectContextFiles,loadSkills,loadSkillsFromDir,main,migrateSessionEntries,parseArgs,parseFrontmatter,parseSessionEntries,parseSkillBlock,prepareBranchEntries,rawKeyHint,readStoredCredential,renderDiff,resizeImage,resolveCliModel,resolveModelScopeWithDiagnostics,runPrintMode,runRpcMode,serializeConversation,sessionEntryToContextMessages,shouldCompact,stripFrontmatter,truncateHead,truncateLine,truncateTail,truncateToVisualLines,withFileMutationQueue,wrapRegisteredTool,wrapRegisteredTools};
2
+ import{ShowImagesSelectorComponent,ThemeSelectorComponent}from"./chunks/chunk-ANT4TSUE.js";import{AgentSession,AgentSessionRuntime,ArminComponent,AssistantMessageComponent,BackgroundService,BashExecutionComponent,BorderedLoader,BranchSummaryMessageComponent,CONFIG_DIR_NAME,CURRENT_SESSION_VERSION,CompactionSummaryMessageComponent,CredentialSynchronizationError,CustomEditor,CustomMessageComponent,DEFAULT_COMPACTION_SETTINGS,DEFAULT_MAX_BYTES,DEFAULT_MAX_LINES,DefaultPackageManager,DefaultResourceLoader,DynamicBorder,ExtensionEditorComponent,ExtensionInputComponent,ExtensionRunner,ExtensionSelectorComponent,FooterComponent,InteractiveMode,LoginDialogComponent,ModelRegistry,ModelRuntime,ModelSelectorComponent,OAuthSelectorComponent,ProjectTrustStore,RpcClient,SessionManager,SessionSelectorComponent,SettingsManager,SettingsSelectorComponent,SkillInvocationMessageComponent,Theme,ThinkingSelectorComponent,ToolExecutionComponent,TreeSelectorComponent,UserMessageComponent,UserMessageSelectorComponent,VERSION,buildContextEntries,buildSessionContext,buildSessionProjection,calculateContextTokens,collectEntriesForBranchSummary,compact,convertToLlm,convertToPng,copyToClipboard,createAgentSession,createAgentSessionFromServices,createAgentSessionRuntime,createAgentSessionServices,createBashTool,createBashToolDefinition,createCodingTools,createEditTool,createEditToolDefinition,createEventBus,createExtensionRuntime,createFindTool,createFindToolDefinition,createGrepTool,createGrepToolDefinition,createLocalBashOperations,createLocalPowerShellOperations,createLsTool,createLsToolDefinition,createPowerShellTool,createPowerShellToolDefinition,createReadOnlyTools,createReadTool,createReadToolDefinition,createSyntheticSourceInfo,createWriteTool,createWriteToolDefinition,defineTool,detectSupportedImageMimeTypeFromFile,discoverAndLoadExtensions,estimateTokens,findCutPoint,findTurnStartIndex,formatDimensionNote,formatSize,formatSkillsForPrompt,generateBranchSummary,generateDiffString,generateSummary,generateSummaryWithUsage,generateUnifiedPatch,getAgentDir,getDocsPath,getExamplesPath,getLanguageFromPath,getLastAssistantUsage,getLatestCompactionEntry,getMarkdownTheme,getPackageDir,getPowerShellConfig,getReadmePath,getSelectListTheme,getSettingsListTheme,getShellConfig,hasTrustRequiringProjectResources,highlightCode,initTheme,isBashToolResult,isEditToolResult,isFindToolResult,isGrepToolResult,isLsToolResult,isPowerShellToolResult,isReadToolResult,isToolCallEventType,isWriteToolResult,keyHint,keyText,loadProjectContextFiles,loadSkills,loadSkillsFromDir,main,migrateSessionEntries,parseArgs,parseFrontmatter,parseSessionEntries,parseSkillBlock,prepareBranchEntries,rawKeyHint,readStoredCredential,renderDiff,resizeImage,resolveCliModel,resolveModelScopeWithDiagnostics,runPrintMode,runRpcMode,serializeConversation,sessionEntryToContextMessages,shouldCompact,stripFrontmatter,truncateHead,truncateLine,truncateTail,truncateToVisualLines,withFileMutationQueue,wrapRegisteredTool,wrapRegisteredTools}from"./chunks/chunk-CUDKRZ2V.js";import"./chunks/chunk-JEIV47WR.js";import"./chunks/chunk-5FDOJRDS.js";import"./chunks/chunk-5B3S5DVL.js";import"./chunks/chunk-2IO5GDBS.js";import"./chunks/chunk-JI4WGISU.js";import"./chunks/chunk-4L3WN2XY.js";export{AgentSession,AgentSessionRuntime,ArminComponent,AssistantMessageComponent,BackgroundService,BashExecutionComponent,BorderedLoader,BranchSummaryMessageComponent,CONFIG_DIR_NAME,CURRENT_SESSION_VERSION,CompactionSummaryMessageComponent,CredentialSynchronizationError,CustomEditor,CustomMessageComponent,DEFAULT_COMPACTION_SETTINGS,DEFAULT_MAX_BYTES,DEFAULT_MAX_LINES,DefaultPackageManager,DefaultResourceLoader,DynamicBorder,ExtensionEditorComponent,ExtensionInputComponent,ExtensionRunner,ExtensionSelectorComponent,FooterComponent,InteractiveMode,LoginDialogComponent,ModelRegistry,ModelRuntime,ModelSelectorComponent,OAuthSelectorComponent,ProjectTrustStore,RpcClient,SessionManager,SessionSelectorComponent,SettingsManager,SettingsSelectorComponent,ShowImagesSelectorComponent,SkillInvocationMessageComponent,Theme,ThemeSelectorComponent,ThinkingSelectorComponent,ToolExecutionComponent,TreeSelectorComponent,UserMessageComponent,UserMessageSelectorComponent,VERSION,buildContextEntries,buildSessionContext,buildSessionProjection,calculateContextTokens,collectEntriesForBranchSummary,compact,convertToLlm,convertToPng,copyToClipboard,createAgentSession,createAgentSessionFromServices,createAgentSessionRuntime,createAgentSessionServices,createBashTool,createBashToolDefinition,createCodingTools,createEditTool,createEditToolDefinition,createEventBus,createExtensionRuntime,createFindTool,createFindToolDefinition,createGrepTool,createGrepToolDefinition,createLocalBashOperations,createLocalPowerShellOperations,createLsTool,createLsToolDefinition,createPowerShellTool,createPowerShellToolDefinition,createReadOnlyTools,createReadTool,createReadToolDefinition,createSyntheticSourceInfo,createWriteTool,createWriteToolDefinition,defineTool,detectSupportedImageMimeTypeFromFile,discoverAndLoadExtensions,estimateTokens,findCutPoint,findTurnStartIndex,formatDimensionNote,formatSize,formatSkillsForPrompt,generateBranchSummary,generateDiffString,generateSummary,generateSummaryWithUsage,generateUnifiedPatch,getAgentDir,getDocsPath,getExamplesPath,getLanguageFromPath,getLastAssistantUsage,getLatestCompactionEntry,getMarkdownTheme,getPackageDir,getPowerShellConfig,getReadmePath,getSelectListTheme,getSettingsListTheme,getShellConfig,hasTrustRequiringProjectResources,highlightCode,initTheme,isBashToolResult,isEditToolResult,isFindToolResult,isGrepToolResult,isLsToolResult,isPowerShellToolResult,isReadToolResult,isToolCallEventType,isWriteToolResult,keyHint,keyText,loadProjectContextFiles,loadSkills,loadSkillsFromDir,main,migrateSessionEntries,parseArgs,parseFrontmatter,parseSessionEntries,parseSkillBlock,prepareBranchEntries,rawKeyHint,readStoredCredential,renderDiff,resizeImage,resolveCliModel,resolveModelScopeWithDiagnostics,runPrintMode,runRpcMode,serializeConversation,sessionEntryToContextMessages,shouldCompact,stripFrontmatter,truncateHead,truncateLine,truncateTail,truncateToVisualLines,withFileMutationQueue,wrapRegisteredTool,wrapRegisteredTools};
@@ -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-TYOQD6VQ.js";import"./chunks/chunk-JEIV47WR.js";import"./chunks/chunk-5FDOJRDS.js";import"./chunks/chunk-5B3S5DVL.js";import"./chunks/chunk-2IO5GDBS.js";import"./chunks/chunk-JI4WGISU.js";import"./chunks/chunk-4L3WN2XY.js";process.title=`${APP_NAME}-rpc`;process.env.PI_CODING_AGENT="true";process.env.AI_AGENT="pi";process.emitWarning=(()=>{});configureHttpDispatcher();main(["--mode","rpc",...process.argv.slice(2)]);
3
+ import{APP_NAME,configureHttpDispatcher,main}from"./chunks/chunk-CUDKRZ2V.js";import"./chunks/chunk-JEIV47WR.js";import"./chunks/chunk-5FDOJRDS.js";import"./chunks/chunk-5B3S5DVL.js";import"./chunks/chunk-2IO5GDBS.js";import"./chunks/chunk-JI4WGISU.js";import"./chunks/chunk-4L3WN2XY.js";process.title=`${APP_NAME}-rpc`;process.env.PI_CODING_AGENT="true";process.env.AI_AGENT="pi";process.emitWarning=(()=>{});configureHttpDispatcher();main(["--mode","rpc",...process.argv.slice(2)]);
@@ -1 +1 @@
1
- {"version":3,"file":"service.d.ts","sourceRoot":"","sources":["../../../src/core/background/service.ts"],"names":[],"mappings":"AAMA,OAAO,EAEN,KAAK,iBAAiB,EAEtB,KAAK,mBAAmB,EAExB,KAAK,cAAc,EACnB,KAAK,wBAAwB,EAC7B,KAAK,cAAc,EACnB,KAAK,qBAAqB,EAG1B,MAAM,YAAY,CAAC;AAmDpB,0FAA0F;AAC1F,qBAAa,iBAAkB,YAAW,iBAAiB;IAC1D,OAAO,CAAC,QAAQ,CAAC,OAAO,CAAkC;IAC1D,OAAO,CAAC,QAAQ,CAAC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E,EAAE,MAAM,GAAG,MAAM,IAAI;IAa3B,KAAK,IAAI,MAAM,IAAI;IAWnB,oBAAoB,IAAI,cAAc,EAAE;IAOxC;;;OAGG;IACH,OAAO,CAAC,SAAS;IAajB,iBAAiB,CAAC,EAAE,EAAE,MAAM,GAAG,OAAO;IAQtC,aAAa,CAAC,EAAE,EAAE,MAAM,GAAG,IAAI;IAO/B,mBAAmB,CAAC,EAAE,EAAE,MAAM,GAAG,IAAI;IAQrC,KAAK,IAAI,IAAI;IAaP,QAAQ,CAAC,OAAO,SAAO,GAAG,OAAO,CAAC,IAAI,CAAC;IAKvC,mBAAmB,CAAC,SAAS,EAAE,WAAW,CAAC,MAAM,CAAC,GAAG,OAAO,CAAC,IAAI,CAAC;YAe1D,KAAK;IAcnB,OAAO,CAAC,QAAQ;IAIhB,OAAO,CAAC,aAAa;IAoBrB,0FAA0F;IAC1F,OAAO,CAAC,cAAc;IAMtB,OAAO,CAAC,IAAI;IAqBZ,OAAO,CAAC,IAAI;CAWZ"}
@@ -2,7 +2,7 @@ import { randomUUID } from "node:crypto";
2
2
  import { parseBackgroundHistory } from "./history.js";
3
3
  import { BACKGROUND_TITLE_BYTES, boundedResult, boundText, finiteLimit, readOutputSlice, sliceText } from "./output.js";
4
4
  import { readBackgroundProjection } from "./presentation.js";
5
- import { BackgroundExecutionError, isForegroundShellTask, SUBAGENT_BACKGROUND_REJECTION, } from "./types.js";
5
+ import { BackgroundExecutionError, BackgroundLookupError, isForegroundShellTask, SUBAGENT_BACKGROUND_REJECTION, } from "./types.js";
6
6
  function errorText(error) {
7
7
  try {
8
8
  return boundText(error instanceof Error ? error.message : String(error), 4096);
@@ -356,8 +356,9 @@ export class BackgroundService {
356
356
  if (exact)
357
357
  return exact;
358
358
  const matches = [...this.records.values()].filter(({ task }) => task.id.startsWith(id) || task.id.slice(task.kind.length + 1).startsWith(id));
359
- if (!id || matches.length !== 1)
360
- throw new Error(matches.length > 1 ? "Ambiguous background task ID" : "Unknown background task ID");
359
+ if (!id || matches.length !== 1) {
360
+ throw new BackgroundLookupError(matches.length > 1 ? "ambiguous" : "unknown", matches.map((record) => this.snapshot(record)));
361
+ }
361
362
  return matches[0];
362
363
  }
363
364
  get(id) {
@@ -1 +1 @@
1
- {"version":3,"file":"service.js","sourceRoot":"","sources":["../../../src/core/background/service.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AAGzC,OAAO,EAAE,sBAAsB,EAAE,MAAM,cAAc,CAAC;AACtD,OAAO,EAAE,sBAAsB,EAAE,aAAa,EAAE,SAAS,EAAE,WAAW,EAAE,eAAe,EAAE,SAAS,EAAE,MAAM,aAAa,CAAC;AACxH,OAAO,EAAE,wBAAwB,EAAE,MAAM,mBAAmB,CAAC;AAC7D,OAAO,EAKN,wBAAwB,EAKxB,qBAAqB,EACrB,6BAA6B,GAC7B,MAAM,YAAY,CAAC;AAuBpB,SAAS,SAAS,CAAC,KAAc;IAChC,IAAI,CAAC;QACJ,OAAO,SAAS,CAAC,KAAK,YAAY,KAAK,CAAC,CAAC,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC,CAAC,MAAM,CAAC,KAAK,CAAC,EAAE,IAAI,CAAC,CAAC;IAChF,CAAC;IAAC,MAAM,CAAC;QACR,OAAO,iDAAiD,CAAC;IAC1D,CAAC;AACF,CAAC;AAED,SAAS,WAAW,CAAC,IAAoB,EAAE,MAAgC,EAAE,SAAS,GAAG,KAAK;IAC7F,MAAM,OAAO,GAAG,aAAa,CAAC,MAAM,CAAC,CAAC;IACtC,IAAI,CAAC,MAAM,GAAG,OAAO,CAAC;IACtB,IAAI,CAAC,eAAe;QACnB,SAAS;YACT,OAAO,CAAC,OAAO,CAAC,MAAM,KAAK,MAAM,CAAC,OAAO,CAAC,MAAM;YAChD,OAAO,CAAC,OAAO,CAAC,IAAI,CAAC,CAAC,KAAK,EAAE,KAAK,EAAE,EAAE;gBACrC,MAAM,QAAQ,GAAG,MAAM,CAAC,OA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CAAC,IAAI,CAAC,KAAK,KAAK,CAAC,CAAC;YACzG,KAAK,CAAC,IAAI,CAAC,CAAC,IAAI,EAAE,KAAK,EAAE,EAAE,CAAC,CAAC,IAAI,CAAC,IAAI,CAAC,OAAO,IAAI,CAAC,CAAC,GAAG,CAAC,KAAK,CAAC,IAAI,CAAC,OAAO,IAAI,CAAC,CAAC,CAAC,CAAC;YAClF,OAAO,CAAC,IAAI,CAAC,GAAG,KAAK,CAAC,KAAK,CAAC,CAAC,EAAE,IAAI,CAAC,GAAG,CAAC,CAAC,EAAE,KAAK,CAAC,MAAM,GAAG,IAAI,CAAC,UAAU,CAAC,CAAC,CAAC,CAAC;QAC9E,CAAC;QACD,KAAK,MAAM,MAAM,IAAI,OAAO,EAAE,CAAC;YAC9B,IAAI,CAAC,OAAO,CAAC,MAAM,CAAC,MAAM,CAAC,IAAI,CAAC,EAAE,CAAC,CAAC;YACpC,IAAI,CAAC,aAAa,CAAC,MAAM,CAAC,CAAC;QAC5B,CAAC;IACF,CAAC;IAEO,IAAI;QACX,IAAI,IAAI,CAAC,MAAM;YAAE,OAAO;QACxB,KAAK,MAAM,QAAQ,IAAI,CAAC,GAAG,IAAI,CAAC,SAAS,CAAC,EAAE,CAAC;YAC5C,IAAI,IAAI,CAAC,MAAM;gBAAE,MAAM;YACvB,IAAI,CAAC;gBACJ,QAAQ,EAAE,CAAC;YACZ,CAAC;YAAC,MAAM,CAAC;gBACR,iDAAiD;YAClD,CAAC;QACF,CAAC;IACF,CAAC;CACD","sourcesContent":["import { randomUUID } from \"node:crypto\";\nimport type { AgentToolResult } from \"@earendil-works/pi-agent-core\";\nimport type { Usage } from \"@earendil-works/pi-ai/compat\";\nimport { parseBackgroundHistory } from \"./history.ts\";\nimport { BACKGROUND_TITLE_BYTES, boundedResult, boundText, finiteLimit, readOutputSlice, sliceText } from \"./output.ts\";\nimport { readBackgroundProjection } from \"./presentation.ts\";\nimport {\n\ttype BackgroundCompletion,\n\ttype BackgroundContext,\n\ttype BackgroundControl,\n\ttype BackgroundExecution,\n\tBackgroundExecutionError,\n\ttype BackgroundRead,\n\ttype BackgroundServiceOptions,\n\ttype BackgroundTask,\n\ttype BackgroundToolOutcome,\n\tisForegroundShellTask,\n\tSUBAGENT_BACKGROUND_REJECTION,\n} from \"./types.ts\";\n\ninterface RecordState {\n\ttask: BackgroundTask;\n\tcontroller: AbortController;\n\taccepted: boolean;\n\thandedOff: boolean;\n\tdetachRequested: boolean;\n\tsettled: boolean;\n\taccounted: boolean;\n\tvisible: boolean;\n\tsuppressed: boolean;\n\tdelivery: \"pending\" | \"claimed\" | \"delivered\";\n\tpins: number;\n\tcleanup?: () => void | Promise<void>;\n\treadError?: string;\n\tpublishedUsage?: Usage;\n\twaiters: Set<() => void>;\n\tremoveParent: () => void;\n\thandoff: () => void;\n\tdone: Promise<void>;\n}\n\nfunction errorText(error: unknown): string {\n\ttry {\n\t\treturn boundText(error instanceof Error ? error.message : String(error), 4096);\n\t} catch {\n\t\treturn \"Background execution failed (unprintable error)\";\n\t}\n}\n\nfunction storeResult(task: BackgroundTask, result: AgentToolResult<unknown>, truncated = false): void {\n\tconst bounded = boundedResult(result);\n\ttask.result = bounded;\n\ttask.resultTruncated =\n\t\ttruncated ||\n\t\tbounded.content.length !== result.content.length ||\n\t\tbounded.content.some((block, index) => {\n\t\t\tconst original = result.content[index];\n\t\t\treturn original?.type !== \"text\" || block.type !== \"text\" || block.text !== original.text;\n\t\t});\n}\n\nfunction oldestTask(tasks: Iterable<BackgroundTask>): BackgroundTask | undefined {\n\tlet oldest: BackgroundTask | undefined;\n\tfor (const task of tasks) {\n\t\tif (!oldest || task.endedAt! < oldest.endedAt!) oldest = task;\n\t}\n\treturn oldest;\n}\n\n/** Session-local supervision. Executors own their processes, workers and output files. */\nexport class BackgroundService implements BackgroundContext {\n\tprivate readonly records = new Map<string, RecordState>();\n\tprivate readonly listeners = new Set<() => void>();\n\tprivate readonly maxActive: number;\n\tprivate readonly maxHistory: number;\n\tprivate readonly maxRetained: number;\n\tprivate configuredEnabled: boolean;\n\tprivate _closed = false;\n\tprivate readonly cleanups = new Set<Promise<void>>();\n\n\tget closed(): boolean {\n\t\treturn this._closed;\n\t}\n\tprivate pauses = 0;\n\n\tprivate readonly options: BackgroundServiceOptions;\n\n\tconstructor(options: BackgroundServiceOptions = {}) {\n\t\tthis.options = options;\n\t\tthis.configuredEnabled = options.enabled ?? false;\n\t\tthis.maxActive = Math.max(1, finiteLimit(options.maxActive, 8, 128));\n\t\tthis.maxHistory = finiteLimit(options.maxHistory, 32, 1024);\n\t\t// Separate foreground shell history, plus the existing history/protected-record allowance.\n\t\tthis.maxRetained = this.maxActive + 2 * Math.max(1, this.maxHistory) + this.maxHistory;\n\t}\n\n\t/**\n\t * Rehydrate terminal version-2 custom data only, newest endedAt in each history\n\t * (later input wins ties). Existing runtime records win ID collisions. No execution, accounting,\n\t * notification, or deletion ownership is restored, including for worker projections.\n\t * The host supplies the current branch; closed services ignore restoration.\n\t */\n\trestoreHistory(records: readonly unknown[]): void {\n\t\tif (this.closed) return;\n\t\t// Restoration must not evict runtime-owned records or run their cleanup callbacks.\n\t\tconst history = this.historyRecords();\n\t\tconst shells = history.filter((record) => isForegroundShellTask(record.task)).length;\n\t\tconst shellCapacity = Math.max(0, this.maxHistory - shells);\n\t\tconst taskCapacity = Math.max(0, this.maxHistory - (history.length - shells));\n\t\tconst capacity = Math.max(\n\t\t\t0,\n\t\t\tMath.min(shellCapacity + taskCapacity, this.maxRetained - this.records.size - this.cleanups.size),\n\t\t);\n\t\tconst newest = new Map<string, BackgroundTask>();\n\t\tfor (const value of records) {\n\t\t\tconst task = parseBackgroundHistory(value);\n\t\t\tif (!task) continue;\n\t\t\tconst existing = this.records.get(task.id);\n\t\t\tif (existing) {\n\t\t\t\tif (existing.settled) existing.visible = true;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (capacity === 0) continue;\n\t\t\tconst previous = newest.get(task.id);\n\t\t\tif (previous && previous.endedAt! > task.endedAt!) continue;\n\t\t\tnewest.delete(task.id);\n\t\t\tconst shell = isForegroundShellTask(task);\n\t\t\tconst limit = shell ? shellCapacity : taskCapacity;\n\t\t\tif (limit === 0) continue;\n\t\t\tnewest.set(task.id, task);\n\t\t\tconst group = [...newest.values()].filter((candidate) => isForegroundShellTask(candidate) === shell);\n\t\t\tif (group.length > limit) newest.delete(oldestTask(group)!.id);\n\t\t\tif (newest.size > capacity) {\n\t\t\t\t// Protected runtime records can leave less room than both histories allow.\n\t\t\t\t// Restore inspectable tasks before hidden foreground shell logs in that case.\n\t\t\t\tconst foreground = [...newest.values()].filter(isForegroundShellTask);\n\t\t\t\tnewest.delete(oldestTask(foreground.length ? foreground : newest.values())!.id);\n\t\t\t}\n\t\t}\n\t\tfor (const task of [...newest.values()].sort((a, b) => a.endedAt! - b.endedAt!)) {\n\t\t\tthis.records.set(task.id, {\n\t\t\t\ttask,\n\t\t\t\tcontroller: new AbortController(),\n\t\t\t\taccepted: false,\n\t\t\t\thandedOff: false,\n\t\t\t\tdetachRequested: false,\n\t\t\t\tsettled: true,\n\t\t\t\taccounted: true,\n\t\t\t\tvisible: true,\n\t\t\t\tsuppressed: true,\n\t\t\t\tdelivery: \"delivered\",\n\t\t\t\tpins: 0,\n\t\t\t\twaiters: new Set(),\n\t\t\t\tremoveParent: () => {},\n\t\t\t\thandoff: () => {},\n\t\t\t\tdone: Promise.resolve(),\n\t\t\t});\n\t\t}\n\t}\n\n\tget enabled(): boolean {\n\t\treturn this.configuredEnabled && !this.closed && this.options.role !== \"subagent\";\n\t}\n\n\tsetEnabled(enabled: boolean): void {\n\t\tthis.configuredEnabled = enabled;\n\t\tthis.emit();\n\t}\n\n\tasync execute<T>(execution: BackgroundExecution<T>): Promise<BackgroundToolOutcome<T>> {\n\t\t// Admission and registration happen synchronously, before invoking user code or awaiting anything.\n\t\tif (this.options.role === \"subagent\") throw new Error(SUBAGENT_BACKGROUND_REJECTION);\n\t\tif (this.closed) throw new Error(\"Background service is closed\");\n\t\tif (!this.enabled) throw new Error(\"Background execution is not available in this host\");\n\t\tif (execution.signal?.aborted) throw execution.signal.reason ?? new Error(\"Execution aborted\");\n\t\tif ([...this.records.values()].filter((record) => !record.settled).length >= this.maxActive) {\n\t\t\tthrow new Error(`Background execution limit reached (${this.maxActive})`);\n\t\t}\n\t\tif (this.records.size + this.cleanups.size >= this.maxRetained) {\n\t\t\tthrow new Error(\n\t\t\t\t\"Background history retention limit reached; deliver pending notifications or release pinned or claimed records\",\n\t\t\t);\n\t\t}\n\t\tconst anchorId = this.options.anchor?.() ?? null;\n\t\tif (anchorId !== null && Buffer.byteLength(anchorId) > 8192)\n\t\t\tthrow new Error(\"Background branch anchor is too large\");\n\t\tconst task: BackgroundTask = {\n\t\t\tid: `${execution.kind}-${randomUUID()}`,\n\t\t\tkind: execution.kind,\n\t\t\ttitle: boundText(execution.title, BACKGROUND_TITLE_BYTES),\n\t\t\ttoolCallId: boundText(execution.toolCallId, 512),\n\t\t\tanchorId,\n\t\t\tmode: execution.background ? \"background\" : \"foreground\",\n\t\t\tstatus: \"queued\",\n\t\t\tstartedAt: Date.now(),\n\t\t\tcommand: execution.command === undefined ? undefined : boundText(execution.command, 8192),\n\t\t\tcommandTruncated:\n\t\t\t\texecution.command === undefined ? undefined : boundText(execution.command, 8192) !== execution.command,\n\t\t\tcwd: execution.cwd === undefined ? undefined : boundText(execution.cwd, 4096),\n\t\t};\n\t\tlet resolveCaller!: (outcome: BackgroundToolOutcome<T>) => void;\n\t\tlet rejectCaller!: (error: unknown) => void;\n\t\tconst caller = new Promise<BackgroundToolOutcome<T>>((resolve, reject) => {\n\t\t\tresolveCaller = resolve;\n\t\t\trejectCaller = reject;\n\t\t});\n\t\tlet resolveDone!: () => void;\n\t\tconst record: RecordState = {\n\t\t\ttask,\n\t\t\tcontroller: new AbortController(),\n\t\t\taccepted: false,\n\t\t\thandedOff: false,\n\t\t\tdetachRequested: execution.background ?? false,\n\t\t\tsettled: false,\n\t\t\taccounted: false,\n\t\t\tvisible: true,\n\t\t\tsuppressed: false,\n\t\t\tdelivery: \"pending\",\n\t\t\tpins: 0,\n\t\t\twaiters: new Set(),\n\t\t\tremoveParent: () => {},\n\t\t\thandoff: () => {\n\t\t\t\tif (\n\t\t\t\t\t!record.accepted ||\n\t\t\t\t\t!record.detachRequested ||\n\t\t\t\t\trecord.settled ||\n\t\t\t\t\trecord.handedOff ||\n\t\t\t\t\tthis.closed ||\n\t\t\t\t\trecord.suppressed ||\n\t\t\t\t\trecord.controller.signal.aborted\n\t\t\t\t)\n\t\t\t\t\treturn;\n\t\t\t\trecord.handedOff = true;\n\t\t\t\ttask.mode = \"background\";\n\t\t\t\trecord.removeParent();\n\t\t\t\tresolveCaller({ kind: \"background\", task: this.snapshot(record) });\n\t\t\t\tthis.emit();\n\t\t\t},\n\t\t\tdone: new Promise<void>((resolve) => {\n\t\t\t\tresolveDone = resolve;\n\t\t\t}),\n\t\t};\n\t\tconst parentSignal = execution.signal;\n\t\tlet onUpdate = execution.background ? undefined : execution.onUpdate;\n\t\tconst parentAbort = () => {\n\t\t\tif (!record.detachRequested || !record.accepted) this.cancel(record);\n\t\t};\n\t\tparentSignal?.addEventListener(\"abort\", parentAbort, { once: true });\n\t\trecord.removeParent = () => {\n\t\t\tparentSignal?.removeEventListener(\"abort\", parentAbort);\n\t\t\tonUpdate = undefined;\n\t\t};\n\t\tthis.records.set(task.id, record);\n\t\tconst control: BackgroundControl<T> = {\n\t\t\tid: task.id,\n\t\t\tsignal: record.controller.signal,\n\t\t\tget mode() {\n\t\t\t\treturn task.mode;\n\t\t\t},\n\t\t\taccept: () => {\n\t\t\t\tif (record.settled || record.accepted || this.closed || record.controller.signal.aborted) return;\n\t\t\t\trecord.accepted = true;\n\t\t\t\tif (task.status === \"queued\") task.status = \"running\";\n\t\t\t\tif (record.detachRequested) record.removeParent();\n\t\t\t\t// Let an already available final result win over a handoff.\n\t\t\t\tqueueMicrotask(() => queueMicrotask(record.handoff));\n\t\t\t\tthis.emit();\n\t\t\t},\n\t\t\tpublish: (result, projection) => {\n\t\t\t\tif (record.settled || this.closed) return;\n\t\t\t\tstoreResult(task, result);\n\t\t\t\tif (result.usage !== undefined) record.publishedUsage = structuredClone(result.usage);\n\t\t\t\tif (projection) task.projection = readBackgroundProjection(projection);\n\t\t\t\tif (!record.detachRequested && !record.handedOff) {\n\t\t\t\t\ttry {\n\t\t\t\t\t\tonUpdate?.(result);\n\t\t\t\t\t} catch {\n\t\t\t\t\t\t/* UI observers cannot stop execution. */\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tthis.emit();\n\t\t\t},\n\t\t\tsetOutputPath: (path, cleanup) => {\n\t\t\t\tif (record.settled) {\n\t\t\t\t\tif (cleanup) throw new Error(\"Background execution has settled\");\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tif (record.cleanup) throw new Error(\"Managed output is already registered\");\n\t\t\t\t// Never truncate a real filesystem path into a different path.\n\t\t\t\tif (Buffer.byteLength(path) > 8192) throw new Error(\"Background output path is too large\");\n\t\t\t\trecord.cleanup = cleanup;\n\t\t\t\ttask.outputPath = path;\n\t\t\t\tthis.emit();\n\t\t\t},\n\t\t};\n\t\tconst finish = (completion: BackgroundCompletion<T> | undefined, error?: unknown) => {\n\t\t\tif (record.settled) return;\n\t\t\trecord.settled = true;\n\t\t\trecord.removeParent();\n\t\t\ttask.endedAt = Date.now();\n\t\t\tconst failed = completion === undefined;\n\t\t\ttask.status =\n\t\t\t\tcompletion?.status ??\n\t\t\t\t(error instanceof BackgroundExecutionError\n\t\t\t\t\t? error.status\n\t\t\t\t\t: record.controller.signal.aborted\n\t\t\t\t\t\t? \"cancelled\"\n\t\t\t\t\t\t: failed\n\t\t\t\t\t\t\t? \"failed\"\n\t\t\t\t\t\t\t: \"completed\");\n\t\t\tif (completion) {\n\t\t\t\tstoreResult(task, completion.result);\n\t\t\t\tif (completion.error !== undefined) task.error = boundText(completion.error, 4096);\n\t\t\t\tif (completion.exitCode !== undefined) task.exitCode = completion.exitCode;\n\t\t\t}\n\t\t\tif (failed) {\n\t\t\t\ttask.error = errorText(error);\n\t\t\t\tstoreResult(\n\t\t\t\t\ttask,\n\t\t\t\t\t{\n\t\t\t\t\t\tcontent: [{ type: \"text\", text: task.error }, ...(task.result?.content ?? [])],\n\t\t\t\t\t\tdetails: task.result?.details,\n\t\t\t\t\t},\n\t\t\t\t\ttask.resultTruncated,\n\t\t\t\t);\n\t\t\t}\n\t\t\tlet settlementWarning: string | undefined;\n\t\t\ttry {\n\t\t\t\tthis.options.onSettled?.(\n\t\t\t\t\tthis.snapshot(record),\n\t\t\t\t\tcompletion?.usage ?? completion?.result.usage ?? record.publishedUsage,\n\t\t\t\t);\n\t\t\t} catch (accountingError) {\n\t\t\t\tconst warning = `Usage settlement failed: ${errorText(accountingError)}`;\n\t\t\t\tsettlementWarning = warning;\n\t\t\t\ttask.error = boundText([task.error, warning].filter(Boolean).join(\"\\n\"), 8192);\n\t\t\t\tstoreResult(\n\t\t\t\t\ttask,\n\t\t\t\t\t{\n\t\t\t\t\t\tcontent: [{ type: \"text\", text: warning }, ...(task.result?.content ?? [])],\n\t\t\t\t\t\tdetails: task.result?.details,\n\t\t\t\t\t},\n\t\t\t\t\ttask.resultTruncated,\n\t\t\t\t);\n\t\t\t}\n\t\t\trecord.publishedUsage = undefined;\n\t\t\trecord.accounted = true;\n\t\t\tif (!record.handedOff) {\n\t\t\t\trecord.delivery = \"delivered\";\n\t\t\t\tif (failed) rejectCaller(error);\n\t\t\t\telse {\n\t\t\t\t\tconst { usage: _usage, ...result } = completion.result;\n\t\t\t\t\tif (settlementWarning) result.content = [{ type: \"text\", text: settlementWarning }, ...result.content];\n\t\t\t\t\tresolveCaller({ kind: \"result\", result, status: task.status, error: task.error });\n\t\t\t\t}\n\t\t\t}\n\t\t\tfor (const waiter of [...record.waiters]) waiter();\n\t\t\tresolveDone();\n\t\t\tthis.trim();\n\t\t\tthis.emit();\n\t\t};\n\t\t// The rejection handler is installed immediately, including for synchronous preflight throws.\n\t\ttry {\n\t\t\tconst running = execution.run(control);\n\t\t\tvoid Promise.resolve(running).then(\n\t\t\t\t(result) => finish(result),\n\t\t\t\t(error: unknown) => finish(undefined, error),\n\t\t\t);\n\t\t} catch (error) {\n\t\t\tfinish(undefined, error);\n\t\t}\n\t\tthis.emit();\n\t\treturn caller;\n\t}\n\n\tdetachForeground(): number {\n\t\tif (!this.enabled) return 0;\n\t\tconst records = [...this.records.values()].filter(\n\t\t\t(record) => !record.settled && !record.detachRequested && !record.controller.signal.aborted,\n\t\t);\n\t\t// Update the whole batch before callbacks/observers can re-enter.\n\t\tfor (const record of records) {\n\t\t\trecord.detachRequested = true;\n\t\t\trecord.task.mode = \"background\";\n\t\t\tif (record.accepted) record.removeParent();\n\t\t}\n\t\tfor (const record of records) record.handoff();\n\t\tif (records.length) this.emit();\n\t\treturn records.length;\n\t}\n\n\tlist(): BackgroundTask[] {\n\t\treturn [...this.records.values()].filter((record) => record.visible).map((record) => this.snapshot(record));\n\t}\n\n\tprivate lookup(id: string): RecordState {\n\t\tconst exact = this.records.get(id);\n\t\tif (exact) return exact;\n\t\tconst matches = [...this.records.values()].filter(\n\t\t\t({ task }) => task.id.startsWith(id) || task.id.slice(task.kind.length + 1).startsWith(id),\n\t\t);\n\t\tif (!id || matches.length !== 1)\n\t\t\tthrow new Error(matches.length > 1 ? \"Ambiguous background task ID\" : \"Unknown background task ID\");\n\t\treturn matches[0]!;\n\t}\n\n\tget(id: string): BackgroundTask {\n\t\treturn this.snapshot(this.lookup(id));\n\t}\n\n\tasync read(\n\t\tid: string,\n\t\toptions: { mode?: \"head\" | \"tail\"; bytes?: number; sinceBytes?: number } = {},\n\t): Promise<BackgroundRead> {\n\t\tconst record = this.lookup(id);\n\t\tconst release = this.pin(record.task.id);\n\t\ttry {\n\t\t\tconst task = this.snapshot(record);\n\t\t\tif (task.outputPath) {\n\t\t\t\ttry {\n\t\t\t\t\treturn { task, ...(await readOutputSlice(task.outputPath, options)) };\n\t\t\t\t} catch (error) {\n\t\t\t\t\treturn {\n\t\t\t\t\t\ttask,\n\t\t\t\t\t\treadError: boundText(`Output could not be read: ${errorText(error)}`, 4096),\n\t\t\t\t\t\t...sliceText(this.resultText(task), options),\n\t\t\t\t\t};\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn { task, readError: record.readError, ...sliceText(this.resultText(task), options) };\n\t\t} finally {\n\t\t\trelease();\n\t\t}\n\t}\n\n\tprivate resultText(task: BackgroundTask): string {\n\t\treturn boundText(\n\t\t\ttask.result?.content\n\t\t\t\t.filter((block) => block.type === \"text\")\n\t\t\t\t.map((block) => block.text)\n\t\t\t\t.join(\"\\n\") ||\n\t\t\t\ttask.projection?.text ||\n\t\t\t\ttask.error ||\n\t\t\t\t\"No output yet.\",\n\t\t);\n\t}\n\n\t/** Observe completion without consuming delivery; the host acknowledges only persisted tool results. */\n\tasync wait(id: string, timeoutMs = 20_000, signal?: AbortSignal): Promise<BackgroundTask> {\n\t\tif (signal?.aborted) throw signal.reason ?? new Error(\"Wait aborted\");\n\t\tconst record = this.lookup(id);\n\t\tif (record.settled) return this.snapshot(record);\n\t\treturn new Promise<BackgroundTask>((resolve, reject) => {\n\t\t\tlet finished = false;\n\t\t\tlet timer: ReturnType<typeof setTimeout> | undefined;\n\t\t\tconst complete = (aborted = false) => {\n\t\t\t\tif (finished) return;\n\t\t\t\tfinished = true;\n\t\t\t\tif (timer !== undefined) clearTimeout(timer);\n\t\t\t\tsignal?.removeEventListener(\"abort\", abort);\n\t\t\t\trecord.waiters.delete(wake);\n\t\t\t\tif (aborted) reject(signal?.reason ?? new Error(\"Wait aborted\"));\n\t\t\t\telse resolve(this.snapshot(record));\n\t\t\t\tthis.trim();\n\t\t\t\tthis.emit();\n\t\t\t};\n\t\t\tconst wake = () => complete();\n\t\t\tconst abort = () => complete(true);\n\t\t\trecord.waiters.add(wake);\n\t\t\tsignal?.addEventListener(\"abort\", abort, { once: true });\n\t\t\ttimer = setTimeout(wake, finiteLimit(timeoutMs, 20_000, 60_000));\n\t\t\tif (this.closed) wake();\n\t\t});\n\t}\n\n\tkill(id: string): boolean {\n\t\treturn this.cancel(this.lookup(id));\n\t}\n\n\tprivate cancel(record: RecordState): boolean {\n\t\tif (record.settled || record.controller.signal.aborted) return false;\n\t\trecord.task.status = \"stopping\";\n\t\trecord.controller.abort();\n\t\tthis.emit();\n\t\treturn true;\n\t}\n\n\tsubscribe(listener: () => void): () => void {\n\t\tif (this.closed) return () => {};\n\t\tthis.listeners.add(listener);\n\t\treturn () => {\n\t\t\tthis.listeners.delete(listener);\n\t\t};\n\t}\n\n\t/**\n\t * Pins defer history eviction and completion delivery, so a live read or a watched row\n\t * never races an automatic notification for the same record. Releasing resumes both, and\n\t * announces the record only when that unblocks a delivery.\n\t */\n\tpin(id: string): () => void {\n\t\tconst record = this.lookup(id);\n\t\trecord.pins++;\n\t\tlet released = false;\n\t\treturn () => {\n\t\t\tif (released) return;\n\t\t\treleased = true;\n\t\t\trecord.pins--;\n\t\t\tthis.trim();\n\t\t\tif (!this.closed && this.pauses === 0 && this.candidate(record)) this.emit();\n\t\t};\n\t}\n\n\tpause(): () => void {\n\t\tthis.pauses++;\n\t\tlet resumed = false;\n\t\treturn () => {\n\t\t\tif (resumed) return;\n\t\t\tresumed = true;\n\t\t\tthis.pauses--;\n\t\t\tthis.emit();\n\t\t};\n\t}\n\n\tpendingNotifications(): BackgroundTask[] {\n\t\tif (this.closed || this.pauses > 0) return [];\n\t\treturn [...this.records.values()]\n\t\t\t.filter((record) => this.candidate(record))\n\t\t\t.map((record) => this.snapshot(record));\n\t}\n\n\t/**\n\t * A pinned record is being read or watched, so its completion is not announced yet:\n\t * a terminal `bg wait` or `bg read` delivers the result as its own tool result instead.\n\t */\n\tprivate candidate(record: RecordState): boolean {\n\t\treturn (\n\t\t\trecord.visible &&\n\t\t\trecord.settled &&\n\t\t\trecord.accounted &&\n\t\t\trecord.handedOff &&\n\t\t\t!record.suppressed &&\n\t\t\trecord.delivery === \"pending\" &&\n\t\t\trecord.waiters.size === 0 &&\n\t\t\trecord.pins === 0\n\t\t);\n\t}\n\n\tclaimNotification(id: string): boolean {\n\t\tif (this.closed || this.pauses > 0) return false;\n\t\tconst record = this.records.get(id);\n\t\tif (!record || !this.candidate(record)) return false;\n\t\trecord.delivery = \"claimed\";\n\t\treturn true;\n\t}\n\n\tmarkDelivered(id: string): void {\n\t\tconst record = this.records.get(id);\n\t\tif (!record) return;\n\t\trecord.delivery = \"delivered\";\n\t\tthis.trim();\n\t}\n\n\treleaseNotification(id: string): void {\n\t\tconst record = this.records.get(id);\n\t\tif (!record || record.delivery !== \"claimed\") return;\n\t\trecord.delivery = \"pending\";\n\t\tthis.trim();\n\t\tthis.emit();\n\t}\n\n\tclose(): void {\n\t\tif (this.closed) return;\n\t\tthis._closed = true;\n\t\tthis.listeners.clear();\n\t\tfor (const record of this.records.values()) {\n\t\t\trecord.suppressed = true;\n\t\t\trecord.removeParent();\n\t\t\tthis.cancel(record);\n\t\t\tfor (const waiter of [...record.waiters]) waiter();\n\t\t}\n\t\tthis.trim();\n\t}\n\n\tasync shutdown(graceMs = 2000): Promise<void> {\n\t\tthis.close();\n\t\tawait this.drain([...this.records.values()], graceMs);\n\t}\n\n\tasync cancelOutsideBranch(ancestors: ReadonlySet<string>): Promise<void> {\n\t\tfor (const record of this.records.values()) {\n\t\t\trecord.visible = record.task.anchorId === null || ancestors.has(record.task.anchorId);\n\t\t\t// Returning to a branch revives its undelivered completions; restored history\n\t\t\t// stays delivered and suppressed.\n\t\t\tif (record.visible && record.delivery === \"pending\") record.suppressed = false;\n\t\t}\n\t\tconst outside = [...this.records.values()].filter((record) => !record.visible);\n\t\tfor (const record of outside) record.suppressed = true;\n\t\tfor (const record of outside) this.cancel(record);\n\t\tthis.trim();\n\t\tthis.emit();\n\t\tawait this.drain(outside, 2000);\n\t}\n\n\tprivate async drain(records: RecordState[], graceMs: number): Promise<void> {\n\t\tlet timer: ReturnType<typeof setTimeout> | undefined;\n\t\ttry {\n\t\t\tawait Promise.race([\n\t\t\t\tPromise.all(records.map((record) => record.done)).then(() => Promise.all(this.cleanups)),\n\t\t\t\tnew Promise<void>((resolve) => {\n\t\t\t\t\ttimer = setTimeout(resolve, finiteLimit(graceMs, 2000, 60_000));\n\t\t\t\t}),\n\t\t\t]);\n\t\t} finally {\n\t\t\tif (timer !== undefined) clearTimeout(timer);\n\t\t}\n\t}\n\n\tprivate snapshot(record: RecordState): BackgroundTask {\n\t\treturn structuredClone(record.task);\n\t}\n\n\tprivate cleanupOutput(record: RecordState): void {\n\t\tif (!record.settled || record.pins || record.waiters.size || !record.cleanup) return;\n\t\tconst cleanup = record.cleanup;\n\t\trecord.cleanup = undefined;\n\t\t// Snapshots retain final bounded text; expired files are never needed to render history.\n\t\trecord.task.outputPath = undefined;\n\t\trecord.readError = \"Output has expired: the managed log was released; showing the stored result.\";\n\t\tconst pending = Promise.resolve()\n\t\t\t.then(cleanup)\n\t\t\t.catch((error: unknown) => {\n\t\t\t\ttry {\n\t\t\t\t\tthis.options.onCleanupError?.(errorText(error));\n\t\t\t\t} catch {\n\t\t\t\t\t/* Cleanup/reporting is best effort, never an unhandled rejection. */\n\t\t\t\t}\n\t\t\t})\n\t\t\t.finally(() => this.cleanups.delete(pending));\n\t\tthis.cleanups.add(pending);\n\t}\n\n\t/** Pending delivery, active reads and pins have their own bounded retention allowance. */\n\tprivate historyRecords(): RecordState[] {\n\t\treturn [...this.records.values()].filter(\n\t\t\t(record) => record.settled && record.delivery === \"delivered\" && !record.pins && !record.waiters.size,\n\t\t);\n\t}\n\n\tprivate trim(): void {\n\t\tif (this.closed) {\n\t\t\tfor (const record of this.records.values()) this.cleanupOutput(record);\n\t\t\treturn;\n\t\t}\n\t\t// Undelivered notifications and claims are never evicted. Admission bounds all retention.\n\t\tconst history = this.historyRecords();\n\t\t// Delivered history can be restored from branch snapshots; hidden rows must\n\t\t// not occupy the current branch's history budget. Pending results stay owned.\n\t\tconst expired = history.filter((record) => !record.visible);\n\t\tfor (const shell of [false, true]) {\n\t\t\tconst group = history.filter((record) => record.visible && isForegroundShellTask(record.task) === shell);\n\t\t\tgroup.sort((left, right) => (left.task.endedAt ?? 0) - (right.task.endedAt ?? 0));\n\t\t\texpired.push(...group.slice(0, Math.max(0, group.length - this.maxHistory)));\n\t\t}\n\t\tfor (const record of expired) {\n\t\t\tthis.records.delete(record.task.id);\n\t\t\tthis.cleanupOutput(record);\n\t\t}\n\t}\n\n\tprivate emit(): void {\n\t\tif (this.closed) return;\n\t\tfor (const listener of [...this.listeners]) {\n\t\t\tif (this.closed) break;\n\t\t\ttry {\n\t\t\t\tlistener();\n\t\t\t} catch {\n\t\t\t\t/* Observers do not own execution or delivery. */\n\t\t\t}\n\t\t}\n\t}\n}\n"]}
1
+ {"version":3,"file":"service.js","sourceRoot":"","sources":["../../../src/core/background/service.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AAGzC,OAAO,EAAE,sBAAsB,EAAE,MAAM,cAAc,CAAC;AACtD,OAAO,EAAE,sBAAsB,EAAE,aAAa,EAAE,SAAS,EAAE,WAAW,EAAE,eAAe,EAAE,SAAS,EAAE,MAAM,aAAa,CAAC;AACxH,OAAO,EAAE,wBAAwB,EAAE,MAAM,mBAAmB,CAAC;AAC7D,OAAO,EAKN,wBAAwB,EACxB,qBAAqB,EAKrB,qBAAqB,EACrB,6BAA6B,GAC7B,MAAM,YAAY,CAAC;AAuBpB,SAAS,SAAS,CAAC,KAAc;IAChC,IAAI,CAAC;QACJ,OAAO,SAAS,CAAC,KAAK,YAAY,KAAK,CAAC,CAAC,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC,CAAC,MAAM,CAAC,KAAK,CAAC,EAAE,IAAI,CAAC,CAAC;IAChF,CAAC;IAAC,MAAM,CAAC;QACR,OAAO,iDAAiD,CAAC;IAC1D,CAAC;AACF,CAAC;AAED,SAAS,WAAW,CAAC,IAAoB,EAAE,MAAgC,EAAE,SAA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5C,IAAI,IAAI,CAAC,MAAM;gBAAE,MAAM;YACvB,IAAI,CAAC;gBACJ,QAAQ,EAAE,CAAC;YACZ,CAAC;YAAC,MAAM,CAAC;gBACR,iDAAiD;YAClD,CAAC;QACF,CAAC;IACF,CAAC;CACD","sourcesContent":["import { randomUUID } from \"node:crypto\";\nimport type { AgentToolResult } from \"@earendil-works/pi-agent-core\";\nimport type { Usage } from \"@earendil-works/pi-ai/compat\";\nimport { parseBackgroundHistory } from \"./history.ts\";\nimport { BACKGROUND_TITLE_BYTES, boundedResult, boundText, finiteLimit, readOutputSlice, sliceText } from \"./output.ts\";\nimport { readBackgroundProjection } from \"./presentation.ts\";\nimport {\n\ttype BackgroundCompletion,\n\ttype BackgroundContext,\n\ttype BackgroundControl,\n\ttype BackgroundExecution,\n\tBackgroundExecutionError,\n\tBackgroundLookupError,\n\ttype BackgroundRead,\n\ttype BackgroundServiceOptions,\n\ttype BackgroundTask,\n\ttype BackgroundToolOutcome,\n\tisForegroundShellTask,\n\tSUBAGENT_BACKGROUND_REJECTION,\n} from \"./types.ts\";\n\ninterface RecordState {\n\ttask: BackgroundTask;\n\tcontroller: AbortController;\n\taccepted: boolean;\n\thandedOff: boolean;\n\tdetachRequested: boolean;\n\tsettled: boolean;\n\taccounted: boolean;\n\tvisible: boolean;\n\tsuppressed: boolean;\n\tdelivery: \"pending\" | \"claimed\" | \"delivered\";\n\tpins: number;\n\tcleanup?: () => void | Promise<void>;\n\treadError?: string;\n\tpublishedUsage?: Usage;\n\twaiters: Set<() => void>;\n\tremoveParent: () => void;\n\thandoff: () => void;\n\tdone: Promise<void>;\n}\n\nfunction errorText(error: unknown): string {\n\ttry {\n\t\treturn boundText(error instanceof Error ? error.message : String(error), 4096);\n\t} catch {\n\t\treturn \"Background execution failed (unprintable error)\";\n\t}\n}\n\nfunction storeResult(task: BackgroundTask, result: AgentToolResult<unknown>, truncated = false): void {\n\tconst bounded = boundedResult(result);\n\ttask.result = bounded;\n\ttask.resultTruncated =\n\t\ttruncated ||\n\t\tbounded.content.length !== result.content.length ||\n\t\tbounded.content.some((block, index) => {\n\t\t\tconst original = result.content[index];\n\t\t\treturn original?.type !== \"text\" || block.type !== \"text\" || block.text !== original.text;\n\t\t});\n}\n\nfunction oldestTask(tasks: Iterable<BackgroundTask>): BackgroundTask | undefined {\n\tlet oldest: BackgroundTask | undefined;\n\tfor (const task of tasks) {\n\t\tif (!oldest || task.endedAt! < oldest.endedAt!) oldest = task;\n\t}\n\treturn oldest;\n}\n\n/** Session-local supervision. Executors own their processes, workers and output files. */\nexport class BackgroundService implements BackgroundContext {\n\tprivate readonly records = new Map<string, RecordState>();\n\tprivate readonly listeners = new Set<() => void>();\n\tprivate readonly maxActive: number;\n\tprivate readonly maxHistory: number;\n\tprivate readonly maxRetained: number;\n\tprivate configuredEnabled: boolean;\n\tprivate _closed = false;\n\tprivate readonly cleanups = new Set<Promise<void>>();\n\n\tget closed(): boolean {\n\t\treturn this._closed;\n\t}\n\tprivate pauses = 0;\n\n\tprivate readonly options: BackgroundServiceOptions;\n\n\tconstructor(options: BackgroundServiceOptions = {}) {\n\t\tthis.options = options;\n\t\tthis.configuredEnabled = options.enabled ?? false;\n\t\tthis.maxActive = Math.max(1, finiteLimit(options.maxActive, 8, 128));\n\t\tthis.maxHistory = finiteLimit(options.maxHistory, 32, 1024);\n\t\t// Separate foreground shell history, plus the existing history/protected-record allowance.\n\t\tthis.maxRetained = this.maxActive + 2 * Math.max(1, this.maxHistory) + this.maxHistory;\n\t}\n\n\t/**\n\t * Rehydrate terminal version-2 custom data only, newest endedAt in each history\n\t * (later input wins ties). Existing runtime records win ID collisions. No execution, accounting,\n\t * notification, or deletion ownership is restored, including for worker projections.\n\t * The host supplies the current branch; closed services ignore restoration.\n\t */\n\trestoreHistory(records: readonly unknown[]): void {\n\t\tif (this.closed) return;\n\t\t// Restoration must not evict runtime-owned records or run their cleanup callbacks.\n\t\tconst history = this.historyRecords();\n\t\tconst shells = history.filter((record) => isForegroundShellTask(record.task)).length;\n\t\tconst shellCapacity = Math.max(0, this.maxHistory - shells);\n\t\tconst taskCapacity = Math.max(0, this.maxHistory - (history.length - shells));\n\t\tconst capacity = Math.max(\n\t\t\t0,\n\t\t\tMath.min(shellCapacity + taskCapacity, this.maxRetained - this.records.size - this.cleanups.size),\n\t\t);\n\t\tconst newest = new Map<string, BackgroundTask>();\n\t\tfor (const value of records) {\n\t\t\tconst task = parseBackgroundHistory(value);\n\t\t\tif (!task) continue;\n\t\t\tconst existing = this.records.get(task.id);\n\t\t\tif (existing) {\n\t\t\t\tif (existing.settled) existing.visible = true;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (capacity === 0) continue;\n\t\t\tconst previous = newest.get(task.id);\n\t\t\tif (previous && previous.endedAt! > task.endedAt!) continue;\n\t\t\tnewest.delete(task.id);\n\t\t\tconst shell = isForegroundShellTask(task);\n\t\t\tconst limit = shell ? shellCapacity : taskCapacity;\n\t\t\tif (limit === 0) continue;\n\t\t\tnewest.set(task.id, task);\n\t\t\tconst group = [...newest.values()].filter((candidate) => isForegroundShellTask(candidate) === shell);\n\t\t\tif (group.length > limit) newest.delete(oldestTask(group)!.id);\n\t\t\tif (newest.size > capacity) {\n\t\t\t\t// Protected runtime records can leave less room than both histories allow.\n\t\t\t\t// Restore inspectable tasks before hidden foreground shell logs in that case.\n\t\t\t\tconst foreground = [...newest.values()].filter(isForegroundShellTask);\n\t\t\t\tnewest.delete(oldestTask(foreground.length ? foreground : newest.values())!.id);\n\t\t\t}\n\t\t}\n\t\tfor (const task of [...newest.values()].sort((a, b) => a.endedAt! - b.endedAt!)) {\n\t\t\tthis.records.set(task.id, {\n\t\t\t\ttask,\n\t\t\t\tcontroller: new AbortController(),\n\t\t\t\taccepted: false,\n\t\t\t\thandedOff: false,\n\t\t\t\tdetachRequested: false,\n\t\t\t\tsettled: true,\n\t\t\t\taccounted: true,\n\t\t\t\tvisible: true,\n\t\t\t\tsuppressed: true,\n\t\t\t\tdelivery: \"delivered\",\n\t\t\t\tpins: 0,\n\t\t\t\twaiters: new Set(),\n\t\t\t\tremoveParent: () => {},\n\t\t\t\thandoff: () => {},\n\t\t\t\tdone: Promise.resolve(),\n\t\t\t});\n\t\t}\n\t}\n\n\tget enabled(): boolean {\n\t\treturn this.configuredEnabled && !this.closed && this.options.role !== \"subagent\";\n\t}\n\n\tsetEnabled(enabled: boolean): void {\n\t\tthis.configuredEnabled = enabled;\n\t\tthis.emit();\n\t}\n\n\tasync execute<T>(execution: BackgroundExecution<T>): Promise<BackgroundToolOutcome<T>> {\n\t\t// Admission and registration happen synchronously, before invoking user code or awaiting anything.\n\t\tif (this.options.role === \"subagent\") throw new Error(SUBAGENT_BACKGROUND_REJECTION);\n\t\tif (this.closed) throw new Error(\"Background service is closed\");\n\t\tif (!this.enabled) throw new Error(\"Background execution is not available in this host\");\n\t\tif (execution.signal?.aborted) throw execution.signal.reason ?? new Error(\"Execution aborted\");\n\t\tif ([...this.records.values()].filter((record) => !record.settled).length >= this.maxActive) {\n\t\t\tthrow new Error(`Background execution limit reached (${this.maxActive})`);\n\t\t}\n\t\tif (this.records.size + this.cleanups.size >= this.maxRetained) {\n\t\t\tthrow new Error(\n\t\t\t\t\"Background history retention limit reached; deliver pending notifications or release pinned or claimed records\",\n\t\t\t);\n\t\t}\n\t\tconst anchorId = this.options.anchor?.() ?? null;\n\t\tif (anchorId !== null && Buffer.byteLength(anchorId) > 8192)\n\t\t\tthrow new Error(\"Background branch anchor is too large\");\n\t\tconst task: BackgroundTask = {\n\t\t\tid: `${execution.kind}-${randomUUID()}`,\n\t\t\tkind: execution.kind,\n\t\t\ttitle: boundText(execution.title, BACKGROUND_TITLE_BYTES),\n\t\t\ttoolCallId: boundText(execution.toolCallId, 512),\n\t\t\tanchorId,\n\t\t\tmode: execution.background ? \"background\" : \"foreground\",\n\t\t\tstatus: \"queued\",\n\t\t\tstartedAt: Date.now(),\n\t\t\tcommand: execution.command === undefined ? undefined : boundText(execution.command, 8192),\n\t\t\tcommandTruncated:\n\t\t\t\texecution.command === undefined ? undefined : boundText(execution.command, 8192) !== execution.command,\n\t\t\tcwd: execution.cwd === undefined ? undefined : boundText(execution.cwd, 4096),\n\t\t};\n\t\tlet resolveCaller!: (outcome: BackgroundToolOutcome<T>) => void;\n\t\tlet rejectCaller!: (error: unknown) => void;\n\t\tconst caller = new Promise<BackgroundToolOutcome<T>>((resolve, reject) => {\n\t\t\tresolveCaller = resolve;\n\t\t\trejectCaller = reject;\n\t\t});\n\t\tlet resolveDone!: () => void;\n\t\tconst record: RecordState = {\n\t\t\ttask,\n\t\t\tcontroller: new AbortController(),\n\t\t\taccepted: false,\n\t\t\thandedOff: false,\n\t\t\tdetachRequested: execution.background ?? false,\n\t\t\tsettled: false,\n\t\t\taccounted: false,\n\t\t\tvisible: true,\n\t\t\tsuppressed: false,\n\t\t\tdelivery: \"pending\",\n\t\t\tpins: 0,\n\t\t\twaiters: new Set(),\n\t\t\tremoveParent: () => {},\n\t\t\thandoff: () => {\n\t\t\t\tif (\n\t\t\t\t\t!record.accepted ||\n\t\t\t\t\t!record.detachRequested ||\n\t\t\t\t\trecord.settled ||\n\t\t\t\t\trecord.handedOff ||\n\t\t\t\t\tthis.closed ||\n\t\t\t\t\trecord.suppressed ||\n\t\t\t\t\trecord.controller.signal.aborted\n\t\t\t\t)\n\t\t\t\t\treturn;\n\t\t\t\trecord.handedOff = true;\n\t\t\t\ttask.mode = \"background\";\n\t\t\t\trecord.removeParent();\n\t\t\t\tresolveCaller({ kind: \"background\", task: this.snapshot(record) });\n\t\t\t\tthis.emit();\n\t\t\t},\n\t\t\tdone: new Promise<void>((resolve) => {\n\t\t\t\tresolveDone = resolve;\n\t\t\t}),\n\t\t};\n\t\tconst parentSignal = execution.signal;\n\t\tlet onUpdate = execution.background ? undefined : execution.onUpdate;\n\t\tconst parentAbort = () => {\n\t\t\tif (!record.detachRequested || !record.accepted) this.cancel(record);\n\t\t};\n\t\tparentSignal?.addEventListener(\"abort\", parentAbort, { once: true });\n\t\trecord.removeParent = () => {\n\t\t\tparentSignal?.removeEventListener(\"abort\", parentAbort);\n\t\t\tonUpdate = undefined;\n\t\t};\n\t\tthis.records.set(task.id, record);\n\t\tconst control: BackgroundControl<T> = {\n\t\t\tid: task.id,\n\t\t\tsignal: record.controller.signal,\n\t\t\tget mode() {\n\t\t\t\treturn task.mode;\n\t\t\t},\n\t\t\taccept: () => {\n\t\t\t\tif (record.settled || record.accepted || this.closed || record.controller.signal.aborted) return;\n\t\t\t\trecord.accepted = true;\n\t\t\t\tif (task.status === \"queued\") task.status = \"running\";\n\t\t\t\tif (record.detachRequested) record.removeParent();\n\t\t\t\t// Let an already available final result win over a handoff.\n\t\t\t\tqueueMicrotask(() => queueMicrotask(record.handoff));\n\t\t\t\tthis.emit();\n\t\t\t},\n\t\t\tpublish: (result, projection) => {\n\t\t\t\tif (record.settled || this.closed) return;\n\t\t\t\tstoreResult(task, result);\n\t\t\t\tif (result.usage !== undefined) record.publishedUsage = structuredClone(result.usage);\n\t\t\t\tif (projection) task.projection = readBackgroundProjection(projection);\n\t\t\t\tif (!record.detachRequested && !record.handedOff) {\n\t\t\t\t\ttry {\n\t\t\t\t\t\tonUpdate?.(result);\n\t\t\t\t\t} catch {\n\t\t\t\t\t\t/* UI observers cannot stop execution. */\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tthis.emit();\n\t\t\t},\n\t\t\tsetOutputPath: (path, cleanup) => {\n\t\t\t\tif (record.settled) {\n\t\t\t\t\tif (cleanup) throw new Error(\"Background execution has settled\");\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tif (record.cleanup) throw new Error(\"Managed output is already registered\");\n\t\t\t\t// Never truncate a real filesystem path into a different path.\n\t\t\t\tif (Buffer.byteLength(path) > 8192) throw new Error(\"Background output path is too large\");\n\t\t\t\trecord.cleanup = cleanup;\n\t\t\t\ttask.outputPath = path;\n\t\t\t\tthis.emit();\n\t\t\t},\n\t\t};\n\t\tconst finish = (completion: BackgroundCompletion<T> | undefined, error?: unknown) => {\n\t\t\tif (record.settled) return;\n\t\t\trecord.settled = true;\n\t\t\trecord.removeParent();\n\t\t\ttask.endedAt = Date.now();\n\t\t\tconst failed = completion === undefined;\n\t\t\ttask.status =\n\t\t\t\tcompletion?.status ??\n\t\t\t\t(error instanceof BackgroundExecutionError\n\t\t\t\t\t? error.status\n\t\t\t\t\t: record.controller.signal.aborted\n\t\t\t\t\t\t? \"cancelled\"\n\t\t\t\t\t\t: failed\n\t\t\t\t\t\t\t? \"failed\"\n\t\t\t\t\t\t\t: \"completed\");\n\t\t\tif (completion) {\n\t\t\t\tstoreResult(task, completion.result);\n\t\t\t\tif (completion.error !== undefined) task.error = boundText(completion.error, 4096);\n\t\t\t\tif (completion.exitCode !== undefined) task.exitCode = completion.exitCode;\n\t\t\t}\n\t\t\tif (failed) {\n\t\t\t\ttask.error = errorText(error);\n\t\t\t\tstoreResult(\n\t\t\t\t\ttask,\n\t\t\t\t\t{\n\t\t\t\t\t\tcontent: [{ type: \"text\", text: task.error }, ...(task.result?.content ?? [])],\n\t\t\t\t\t\tdetails: task.result?.details,\n\t\t\t\t\t},\n\t\t\t\t\ttask.resultTruncated,\n\t\t\t\t);\n\t\t\t}\n\t\t\tlet settlementWarning: string | undefined;\n\t\t\ttry {\n\t\t\t\tthis.options.onSettled?.(\n\t\t\t\t\tthis.snapshot(record),\n\t\t\t\t\tcompletion?.usage ?? completion?.result.usage ?? record.publishedUsage,\n\t\t\t\t);\n\t\t\t} catch (accountingError) {\n\t\t\t\tconst warning = `Usage settlement failed: ${errorText(accountingError)}`;\n\t\t\t\tsettlementWarning = warning;\n\t\t\t\ttask.error = boundText([task.error, warning].filter(Boolean).join(\"\\n\"), 8192);\n\t\t\t\tstoreResult(\n\t\t\t\t\ttask,\n\t\t\t\t\t{\n\t\t\t\t\t\tcontent: [{ type: \"text\", text: warning }, ...(task.result?.content ?? [])],\n\t\t\t\t\t\tdetails: task.result?.details,\n\t\t\t\t\t},\n\t\t\t\t\ttask.resultTruncated,\n\t\t\t\t);\n\t\t\t}\n\t\t\trecord.publishedUsage = undefined;\n\t\t\trecord.accounted = true;\n\t\t\tif (!record.handedOff) {\n\t\t\t\trecord.delivery = \"delivered\";\n\t\t\t\tif (failed) rejectCaller(error);\n\t\t\t\telse {\n\t\t\t\t\tconst { usage: _usage, ...result } = completion.result;\n\t\t\t\t\tif (settlementWarning) result.content = [{ type: \"text\", text: settlementWarning }, ...result.content];\n\t\t\t\t\tresolveCaller({ kind: \"result\", result, status: task.status, error: task.error });\n\t\t\t\t}\n\t\t\t}\n\t\t\tfor (const waiter of [...record.waiters]) waiter();\n\t\t\tresolveDone();\n\t\t\tthis.trim();\n\t\t\tthis.emit();\n\t\t};\n\t\t// The rejection handler is installed immediately, including for synchronous preflight throws.\n\t\ttry {\n\t\t\tconst running = execution.run(control);\n\t\t\tvoid Promise.resolve(running).then(\n\t\t\t\t(result) => finish(result),\n\t\t\t\t(error: unknown) => finish(undefined, error),\n\t\t\t);\n\t\t} catch (error) {\n\t\t\tfinish(undefined, error);\n\t\t}\n\t\tthis.emit();\n\t\treturn caller;\n\t}\n\n\tdetachForeground(): number {\n\t\tif (!this.enabled) return 0;\n\t\tconst records = [...this.records.values()].filter(\n\t\t\t(record) => !record.settled && !record.detachRequested && !record.controller.signal.aborted,\n\t\t);\n\t\t// Update the whole batch before callbacks/observers can re-enter.\n\t\tfor (const record of records) {\n\t\t\trecord.detachRequested = true;\n\t\t\trecord.task.mode = \"background\";\n\t\t\tif (record.accepted) record.removeParent();\n\t\t}\n\t\tfor (const record of records) record.handoff();\n\t\tif (records.length) this.emit();\n\t\treturn records.length;\n\t}\n\n\tlist(): BackgroundTask[] {\n\t\treturn [...this.records.values()].filter((record) => record.visible).map((record) => this.snapshot(record));\n\t}\n\n\tprivate lookup(id: string): RecordState {\n\t\tconst exact = this.records.get(id);\n\t\tif (exact) return exact;\n\t\tconst matches = [...this.records.values()].filter(\n\t\t\t({ task }) => task.id.startsWith(id) || task.id.slice(task.kind.length + 1).startsWith(id),\n\t\t);\n\t\tif (!id || matches.length !== 1) {\n\t\t\tthrow new BackgroundLookupError(\n\t\t\t\tmatches.length > 1 ? \"ambiguous\" : \"unknown\",\n\t\t\t\tmatches.map((record) => this.snapshot(record)),\n\t\t\t);\n\t\t}\n\t\treturn matches[0]!;\n\t}\n\n\tget(id: string): BackgroundTask {\n\t\treturn this.snapshot(this.lookup(id));\n\t}\n\n\tasync read(\n\t\tid: string,\n\t\toptions: { mode?: \"head\" | \"tail\"; bytes?: number; sinceBytes?: number } = {},\n\t): Promise<BackgroundRead> {\n\t\tconst record = this.lookup(id);\n\t\tconst release = this.pin(record.task.id);\n\t\ttry {\n\t\t\tconst task = this.snapshot(record);\n\t\t\tif (task.outputPath) {\n\t\t\t\ttry {\n\t\t\t\t\treturn { task, ...(await readOutputSlice(task.outputPath, options)) };\n\t\t\t\t} catch (error) {\n\t\t\t\t\treturn {\n\t\t\t\t\t\ttask,\n\t\t\t\t\t\treadError: boundText(`Output could not be read: ${errorText(error)}`, 4096),\n\t\t\t\t\t\t...sliceText(this.resultText(task), options),\n\t\t\t\t\t};\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn { task, readError: record.readError, ...sliceText(this.resultText(task), options) };\n\t\t} finally {\n\t\t\trelease();\n\t\t}\n\t}\n\n\tprivate resultText(task: BackgroundTask): string {\n\t\treturn boundText(\n\t\t\ttask.result?.content\n\t\t\t\t.filter((block) => block.type === \"text\")\n\t\t\t\t.map((block) => block.text)\n\t\t\t\t.join(\"\\n\") ||\n\t\t\t\ttask.projection?.text ||\n\t\t\t\ttask.error ||\n\t\t\t\t\"No output yet.\",\n\t\t);\n\t}\n\n\t/** Observe completion without consuming delivery; the host acknowledges only persisted tool results. */\n\tasync wait(id: string, timeoutMs = 20_000, signal?: AbortSignal): Promise<BackgroundTask> {\n\t\tif (signal?.aborted) throw signal.reason ?? new Error(\"Wait aborted\");\n\t\tconst record = this.lookup(id);\n\t\tif (record.settled) return this.snapshot(record);\n\t\treturn new Promise<BackgroundTask>((resolve, reject) => {\n\t\t\tlet finished = false;\n\t\t\tlet timer: ReturnType<typeof setTimeout> | undefined;\n\t\t\tconst complete = (aborted = false) => {\n\t\t\t\tif (finished) return;\n\t\t\t\tfinished = true;\n\t\t\t\tif (timer !== undefined) clearTimeout(timer);\n\t\t\t\tsignal?.removeEventListener(\"abort\", abort);\n\t\t\t\trecord.waiters.delete(wake);\n\t\t\t\tif (aborted) reject(signal?.reason ?? new Error(\"Wait aborted\"));\n\t\t\t\telse resolve(this.snapshot(record));\n\t\t\t\tthis.trim();\n\t\t\t\tthis.emit();\n\t\t\t};\n\t\t\tconst wake = () => complete();\n\t\t\tconst abort = () => complete(true);\n\t\t\trecord.waiters.add(wake);\n\t\t\tsignal?.addEventListener(\"abort\", abort, { once: true });\n\t\t\ttimer = setTimeout(wake, finiteLimit(timeoutMs, 20_000, 60_000));\n\t\t\tif (this.closed) wake();\n\t\t});\n\t}\n\n\tkill(id: string): boolean {\n\t\treturn this.cancel(this.lookup(id));\n\t}\n\n\tprivate cancel(record: RecordState): boolean {\n\t\tif (record.settled || record.controller.signal.aborted) return false;\n\t\trecord.task.status = \"stopping\";\n\t\trecord.controller.abort();\n\t\tthis.emit();\n\t\treturn true;\n\t}\n\n\tsubscribe(listener: () => void): () => void {\n\t\tif (this.closed) return () => {};\n\t\tthis.listeners.add(listener);\n\t\treturn () => {\n\t\t\tthis.listeners.delete(listener);\n\t\t};\n\t}\n\n\t/**\n\t * Pins defer history eviction and completion delivery, so a live read or a watched row\n\t * never races an automatic notification for the same record. Releasing resumes both, and\n\t * announces the record only when that unblocks a delivery.\n\t */\n\tpin(id: string): () => void {\n\t\tconst record = this.lookup(id);\n\t\trecord.pins++;\n\t\tlet released = false;\n\t\treturn () => {\n\t\t\tif (released) return;\n\t\t\treleased = true;\n\t\t\trecord.pins--;\n\t\t\tthis.trim();\n\t\t\tif (!this.closed && this.pauses === 0 && this.candidate(record)) this.emit();\n\t\t};\n\t}\n\n\tpause(): () => void {\n\t\tthis.pauses++;\n\t\tlet resumed = false;\n\t\treturn () => {\n\t\t\tif (resumed) return;\n\t\t\tresumed = true;\n\t\t\tthis.pauses--;\n\t\t\tthis.emit();\n\t\t};\n\t}\n\n\tpendingNotifications(): BackgroundTask[] {\n\t\tif (this.closed || this.pauses > 0) return [];\n\t\treturn [...this.records.values()]\n\t\t\t.filter((record) => this.candidate(record))\n\t\t\t.map((record) => this.snapshot(record));\n\t}\n\n\t/**\n\t * A pinned record is being read or watched, so its completion is not announced yet:\n\t * a terminal `bg wait` or `bg read` delivers the result as its own tool result instead.\n\t */\n\tprivate candidate(record: RecordState): boolean {\n\t\treturn (\n\t\t\trecord.visible &&\n\t\t\trecord.settled &&\n\t\t\trecord.accounted &&\n\t\t\trecord.handedOff &&\n\t\t\t!record.suppressed &&\n\t\t\trecord.delivery === \"pending\" &&\n\t\t\trecord.waiters.size === 0 &&\n\t\t\trecord.pins === 0\n\t\t);\n\t}\n\n\tclaimNotification(id: string): boolean {\n\t\tif (this.closed || this.pauses > 0) return false;\n\t\tconst record = this.records.get(id);\n\t\tif (!record || !this.candidate(record)) return false;\n\t\trecord.delivery = \"claimed\";\n\t\treturn true;\n\t}\n\n\tmarkDelivered(id: string): void {\n\t\tconst record = this.records.get(id);\n\t\tif (!record) return;\n\t\trecord.delivery = \"delivered\";\n\t\tthis.trim();\n\t}\n\n\treleaseNotification(id: string): void {\n\t\tconst record = this.records.get(id);\n\t\tif (!record || record.delivery !== \"claimed\") return;\n\t\trecord.delivery = \"pending\";\n\t\tthis.trim();\n\t\tthis.emit();\n\t}\n\n\tclose(): void {\n\t\tif (this.closed) return;\n\t\tthis._closed = true;\n\t\tthis.listeners.clear();\n\t\tfor (const record of this.records.values()) {\n\t\t\trecord.suppressed = true;\n\t\t\trecord.removeParent();\n\t\t\tthis.cancel(record);\n\t\t\tfor (const waiter of [...record.waiters]) waiter();\n\t\t}\n\t\tthis.trim();\n\t}\n\n\tasync shutdown(graceMs = 2000): Promise<void> {\n\t\tthis.close();\n\t\tawait this.drain([...this.records.values()], graceMs);\n\t}\n\n\tasync cancelOutsideBranch(ancestors: ReadonlySet<string>): Promise<void> {\n\t\tfor (const record of this.records.values()) {\n\t\t\trecord.visible = record.task.anchorId === null || ancestors.has(record.task.anchorId);\n\t\t\t// Returning to a branch revives its undelivered completions; restored history\n\t\t\t// stays delivered and suppressed.\n\t\t\tif (record.visible && record.delivery === \"pending\") record.suppressed = false;\n\t\t}\n\t\tconst outside = [...this.records.values()].filter((record) => !record.visible);\n\t\tfor (const record of outside) record.suppressed = true;\n\t\tfor (const record of outside) this.cancel(record);\n\t\tthis.trim();\n\t\tthis.emit();\n\t\tawait this.drain(outside, 2000);\n\t}\n\n\tprivate async drain(records: RecordState[], graceMs: number): Promise<void> {\n\t\tlet timer: ReturnType<typeof setTimeout> | undefined;\n\t\ttry {\n\t\t\tawait Promise.race([\n\t\t\t\tPromise.all(records.map((record) => record.done)).then(() => Promise.all(this.cleanups)),\n\t\t\t\tnew Promise<void>((resolve) => {\n\t\t\t\t\ttimer = setTimeout(resolve, finiteLimit(graceMs, 2000, 60_000));\n\t\t\t\t}),\n\t\t\t]);\n\t\t} finally {\n\t\t\tif (timer !== undefined) clearTimeout(timer);\n\t\t}\n\t}\n\n\tprivate snapshot(record: RecordState): BackgroundTask {\n\t\treturn structuredClone(record.task);\n\t}\n\n\tprivate cleanupOutput(record: RecordState): void {\n\t\tif (!record.settled || record.pins || record.waiters.size || !record.cleanup) return;\n\t\tconst cleanup = record.cleanup;\n\t\trecord.cleanup = undefined;\n\t\t// Snapshots retain final bounded text; expired files are never needed to render history.\n\t\trecord.task.outputPath = undefined;\n\t\trecord.readError = \"Output has expired: the managed log was released; showing the stored result.\";\n\t\tconst pending = Promise.resolve()\n\t\t\t.then(cleanup)\n\t\t\t.catch((error: unknown) => {\n\t\t\t\ttry {\n\t\t\t\t\tthis.options.onCleanupError?.(errorText(error));\n\t\t\t\t} catch {\n\t\t\t\t\t/* Cleanup/reporting is best effort, never an unhandled rejection. */\n\t\t\t\t}\n\t\t\t})\n\t\t\t.finally(() => this.cleanups.delete(pending));\n\t\tthis.cleanups.add(pending);\n\t}\n\n\t/** Pending delivery, active reads and pins have their own bounded retention allowance. */\n\tprivate historyRecords(): RecordState[] {\n\t\treturn [...this.records.values()].filter(\n\t\t\t(record) => record.settled && record.delivery === \"delivered\" && !record.pins && !record.waiters.size,\n\t\t);\n\t}\n\n\tprivate trim(): void {\n\t\tif (this.closed) {\n\t\t\tfor (const record of this.records.values()) this.cleanupOutput(record);\n\t\t\treturn;\n\t\t}\n\t\t// Undelivered notifications and claims are never evicted. Admission bounds all retention.\n\t\tconst history = this.historyRecords();\n\t\t// Delivered history can be restored from branch snapshots; hidden rows must\n\t\t// not occupy the current branch's history budget. Pending results stay owned.\n\t\tconst expired = history.filter((record) => !record.visible);\n\t\tfor (const shell of [false, true]) {\n\t\t\tconst group = history.filter((record) => record.visible && isForegroundShellTask(record.task) === shell);\n\t\t\tgroup.sort((left, right) => (left.task.endedAt ?? 0) - (right.task.endedAt ?? 0));\n\t\t\texpired.push(...group.slice(0, Math.max(0, group.length - this.maxHistory)));\n\t\t}\n\t\tfor (const record of expired) {\n\t\t\tthis.records.delete(record.task.id);\n\t\t\tthis.cleanupOutput(record);\n\t\t}\n\t}\n\n\tprivate emit(): void {\n\t\tif (this.closed) return;\n\t\tfor (const listener of [...this.listeners]) {\n\t\t\tif (this.closed) break;\n\t\t\ttry {\n\t\t\t\tlistener();\n\t\t\t} catch {\n\t\t\t\t/* Observers do not own execution or delivery. */\n\t\t\t}\n\t\t}\n\t}\n}\n"]}
@@ -174,5 +174,16 @@ export declare class BackgroundExecutionError extends Error {
174
174
  readonly status: BackgroundTerminalStatus;
175
175
  constructor(message: string, status: BackgroundTerminalStatus);
176
176
  }
177
+ /**
178
+ * A failed id lookup, typed so hosts can enrich the message without matching
179
+ * on message text. `matches` snapshots exactly the records the id or prefix
180
+ * resolved against — including records outside the current branch, which
181
+ * list() hides but prefix matching still collides with.
182
+ */
183
+ export declare class BackgroundLookupError extends Error {
184
+ readonly kind: "unknown" | "ambiguous";
185
+ readonly matches: BackgroundTask[];
186
+ constructor(kind: "unknown" | "ambiguous", matches: BackgroundTask[]);
187
+ }
177
188
  export {};
178
189
  //# sourceMappingURL=types.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../../../src/core/background/types.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,+BAA+B,CAAC;AACrE,OAAO,KAAK,EAAE,KAAK,EAAE,MAAM,8BAA8B,CAAC;AAE1D,MAAM,MAAM,cAAc,GAAG,MAAM,GAAG,UAAU,CAAC;AACjD,MAAM,MAAM,cAAc,GAAG,YAAY,GAAG,YAAY,CAAC;AACzD,MAAM,MAAM,wBAAwB,GAAG,WAAW,GAAG,SAAS,GAAG,QAAQ,GAAG,WAAW,GAAG,SAAS,CAAC;AACpG,MAAM,MAAM,gBAAgB,GAAG,QAAQ,GAAG,SAAS,GAAG,UAAU,GAAG,wBAAwB,CAAC;AAE5F,0FAA0F;AAC1F,MAAM,WAAW,cAAc;IAC9B,IAAI,EAAE,MAAM,CAAC;IACb,SAAS,EAAE,OAAO,CAAC;CACnB;AAED,MAAM,WAAW,sBAAsB;IACtC,EAAE,EAAE,MAAM,CAAC;IACX,KAAK,EAAE,MAAM,CAAC;IACd,OAAO,EAAE,MAAM,CAAC;IAChB,WAAW,EAAE,MAAM,CAAC;IACpB,MAAM,EAAE,MAAM,CAAC;IACf,MAAM,EAAE,cAAc,CAAC;IACvB,KAAK,CAAC,EAAE,MAAM,CAAC;CACf;AAED,sFAAsF;AACtF,MAAM,WAAW,gBAAiB,SAAQ,sBAAsB;IAC/D,MAAM,EAAE,MAAM,CAAC;IACf,QAAQ,EAAE,MAAM,CAAC;IACjB,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,KAAK,CAAC,EAAE,MAAM,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,EAAE,gBAAgB,GAAG,OAAO,CAEtE;AAED,uGAAuG;AACvG,wBAAgB,qBAAqB,CAAC,IAAI,EAAE,IAAI,CAAC,cAAc,EAAE,MAAM,GAAG,MAAM,CAAC,GAAG,OAAO,CAE1F;AAED,0FAA0F;AAC1F,qBAAa,wBAAyB,SAAQ,KAAK;IAClD,QAAQ,CAAC,MAAM,EAAE,wBAAwB,CAAC;gBAC9B,OAAO,EAAE,MAAM,EAAE,MAAM,EAAE,wBAAwB;CAK7D;AAED;;;;;GAKG;AACH,qBAAa,qBAAsB,SAAQ,KAAK;IAC/C,QAAQ,CAAC,IAAI,EAAE,SAAS,GAAG,WAAW,CAAC;IACvC,QAAQ,CAAC,OAAO,EAAE,cAAc,EAAE,CAAC;gBACvB,IAAI,EAAE,SAAS,GAAG,WAAW,EAAE,OAAO,EAAE,cAAc,EAAE;CAMpE"}
@@ -14,4 +14,18 @@ export class BackgroundExecutionError extends Error {
14
14
  this.status = status;
15
15
  }
16
16
  }
17
+ /**
18
+ * A failed id lookup, typed so hosts can enrich the message without matching
19
+ * on message text. `matches` snapshots exactly the records the id or prefix
20
+ * resolved against — including records outside the current branch, which
21
+ * list() hides but prefix matching still collides with.
22
+ */
23
+ export class BackgroundLookupError extends Error {
24
+ constructor(kind, matches) {
25
+ super(kind === "ambiguous" ? "Ambiguous background task ID" : "Unknown background task ID");
26
+ this.name = "BackgroundLookupError";
27
+ this.kind = kind;
28
+ this.matches = matches;
29
+ }
30
+ }
17
31
  //# sourceMappingURL=types.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"types.js","sourceRoot":"","sources":["../../../src/core/background/types.ts"],"names":[],"mappings":"AA8KA,MAAM,CAAC,MAAM,6BAA6B,GACzC,gOAAgO,CAAC;AAElO,MAAM,UAAU,oBAAoB,CAAC,MAAwB;IAC5D,OAAO,MAAM,KAAK,QAAQ,IAAI,MAAM,KAAK,SAAS,IAAI,MAAM,KAAK,UAAU,CAAC;AAC7E,CAAC;AAED,uGAAuG;AACvG,MAAM,UAAU,qBAAqB,CAAC,IAA2C;IAChF,OAAO,IAAI,CAAC,IAAI,KAAK,MAAM,IAAI,IAAI,CAAC,IAAI,KAAK,YAAY,CAAC;AAC3D,CAAC;AAED,0FAA0F;AAC1F,MAAM,OAAO,wBAAyB,SAAQ,KAAK;IAElD,YAAY,OAAe,EAAE,MAAgC;QAC5D,KAAK,CAAC,OAAO,CAAC,CAAC;QACf,IAAI,CAAC,IAAI,GAAG,0BAA0B,CAAC;QACvC,IAAI,CAAC,MAAM,GAAG,MAAM,CAAC;IACtB,CAAC;CACD","sourcesContent":["import type { AgentToolResult } from \"@earendil-works/pi-agent-core\";\nimport type { Usage } from \"@earendil-works/pi-ai/compat\";\n\nexport type BackgroundKind = \"bash\" | \"subagent\";\nexport type BackgroundMode = \"foreground\" | \"background\";\nexport type BackgroundTerminalStatus = \"completed\" | \"partial\" | \"failed\" | \"cancelled\" | \"timeout\";\nexport type BackgroundStatus = \"queued\" | \"running\" | \"stopping\" | BackgroundTerminalStatus;\n\n/** A bounded snapshot; truncation is recorded at the source, never inferred from text. */\nexport interface BackgroundText {\n\ttext: string;\n\ttruncated: boolean;\n}\n\nexport interface BackgroundWorkerReport {\n\tid: string;\n\tlabel: string;\n\tprofile: string;\n\tdescription: string;\n\tstatus: string;\n\treport: BackgroundText;\n\terror?: string;\n}\n\n/** A serializable, domain-owned projection. No extension-private renderer imports. */\nexport interface BackgroundWorker extends BackgroundWorkerReport {\n\tprompt: string;\n\tactivity: string;\n\tmodel?: string;\n\tusage?: string;\n}\n\nexport interface BackgroundProjection {\n\ttext?: string;\n\tshell?: { name: string; output: BackgroundText };\n\tworkers?: BackgroundWorker[];\n}\n\ninterface BackgroundCompletionBase {\n\tversion: 1;\n\ttaskId: string;\n\ttitle: string;\n\tstatus: BackgroundTerminalStatus;\n\tstartedAt: number;\n\tendedAt: number;\n\terror?: string;\n}\n\n/** Self-contained completion-message details. No live handles, tool-private details or accounting. */\nexport type BackgroundCompletionSnapshot = BackgroundCompletionBase &\n\t(\n\t\t| {\n\t\t\t\tkind: \"bash\";\n\t\t\t\tshell?: string;\n\t\t\t\tcommand?: BackgroundText;\n\t\t\t\tcwd?: string;\n\t\t\t\toutputPath?: string;\n\t\t\t\t/** Process exit code: a number, or null when signal-reaped. */\n\t\t\t\texitCode?: number | null;\n\t\t\t\toutput: BackgroundText;\n\t\t }\n\t\t| {\n\t\t\t\tkind: \"subagent\";\n\t\t\t\tworkers: BackgroundWorkerReport[];\n\t\t\t\t/** Plain fallback when an executor has no worker projection. */\n\t\t\t\toutput?: BackgroundText;\n\t\t }\n\t);\n\nexport interface BackgroundTask {\n\tid: string;\n\tkind: BackgroundKind;\n\ttitle: string;\n\ttoolCallId: string;\n\tanchorId: string | null;\n\tmode: BackgroundMode;\n\tstatus: BackgroundStatus;\n\tstartedAt: number;\n\tendedAt?: number;\n\tcommand?: string;\n\tcommandTruncated?: boolean;\n\tcwd?: string;\n\t/** Process exit code (bash): a number, or null when signal-reaped. Absent while running or unreported. */\n\texitCode?: number | null;\n\toutputPath?: string;\n\tprojection?: BackgroundProjection;\n\tresult?: AgentToolResult<unknown>;\n\tresultTruncated?: boolean;\n\terror?: string;\n}\n\nexport interface BackgroundCompletion<T> {\n\tresult: AgentToolResult<T>;\n\tstatus?: BackgroundTerminalStatus;\n\t/** Terminal diagnostic, stored independently of log slices and bounded to 4096 bytes. */\n\terror?: string;\n\t/** Process exit code (bash): a number, or null when signal-reaped. */\n\texitCode?: number | null;\n\t/** Authoritative cumulative usage; overrides result.usage and any published snapshot. */\n\tusage?: Usage;\n}\n\nexport interface BackgroundControl<T> {\n\treadonly id: string;\n\treadonly signal: AbortSignal;\n\treadonly mode: BackgroundMode;\n\t/** Accept only after whole-invocation preflight; required before returning a handoff. */\n\taccept(): void;\n\t/**\n\t * result.usage is a cumulative snapshot, never a delta. The most recent explicitly\n\t * published usage is settled once on rejection (never inferred from details).\n\t * Final completion.usage, then completion.result.usage, override that snapshot.\n\t */\n\tpublish(result: AgentToolResult<T>, projection?: BackgroundProjection): void;\n\t/** Register once; cleanup must own only this exclusively-created file and close its writer first. */\n\tsetOutputPath(path: string, cleanup?: () => void | Promise<void>): void;\n}\n\nexport interface BackgroundExecution<T> {\n\tkind: BackgroundKind;\n\ttitle: string;\n\ttoolCallId: string;\n\tcommand?: string;\n\tcwd?: string;\n\tbackground?: boolean;\n\tsignal?: AbortSignal;\n\tonUpdate?: (result: AgentToolResult<T>) => void;\n\trun(control: BackgroundControl<T>): Promise<BackgroundCompletion<T>>;\n}\n\nexport type BackgroundToolOutcome<T> =\n\t| { kind: \"result\"; result: AgentToolResult<T>; status?: BackgroundTerminalStatus; error?: string }\n\t| { kind: \"background\"; task: BackgroundTask };\n\nexport interface BackgroundRead {\n\ttask: BackgroundTask;\n\ttext: string;\n\t/** Bounded log-read/expiry diagnostic, independent of text slicing and byte offsets. */\n\treadError?: string;\n\ttotalBytes: number;\n\ttruncated: boolean;\n\tfromByte?: number;\n}\n\n/** Session-bound public capability. Captured instances close on runtime replacement. */\nexport interface BackgroundContext {\n\treadonly enabled: boolean;\n\treadonly closed?: boolean;\n\texecute<T>(execution: BackgroundExecution<T>): Promise<BackgroundToolOutcome<T>>;\n\tlist(): BackgroundTask[];\n\tget(id: string): BackgroundTask;\n\tread(id: string, options?: { mode?: \"head\" | \"tail\"; bytes?: number; sinceBytes?: number }): Promise<BackgroundRead>;\n\t/** Observation only: terminal delivery is acknowledged by the host via markDelivered after result persistence. */\n\twait(id: string, timeoutMs?: number, signal?: AbortSignal): Promise<BackgroundTask>;\n\tkill(id: string): boolean;\n\t/** Move every running foreground execution to the background; returns how many moved. */\n\tdetachForeground(): number;\n\tsubscribe(listener: () => void): () => void;\n\tpin(id: string): () => void;\n}\n\nexport interface BackgroundServiceOptions {\n\tenabled?: boolean;\n\trole?: \"main\" | \"subagent\";\n\tanchor?: () => string | null;\n\tmaxActive?: number;\n\t/** Per-history limit: foreground shells and background tasks/all subagents each get this allowance. */\n\tmaxHistory?: number;\n\t/** Best-effort cleanup errors, bounded to 4096 bytes; no retries or execution failure. */\n\tonCleanupError?: (message: string) => void;\n\t/** Synchronous persistence before terminal observers or notifications. */\n\tonSettled?: (task: BackgroundTask, usage: Usage | undefined) => void;\n}\n\nexport const SUBAGENT_BACKGROUND_REJECTION =\n\t\"Background execution is not available inside subagents. Run this command with background: false (or omit background). Only the parent agent or the user can background the entire subagent invocation. No command was started.\";\n\nexport function isBackgroundTerminal(status: BackgroundStatus): boolean {\n\treturn status !== \"queued\" && status !== \"running\" && status !== \"stopping\";\n}\n\n/** Foreground shell logs have their own history; subagent groups remain inspectable in either mode. */\nexport function isForegroundShellTask(task: Pick<BackgroundTask, \"kind\" | \"mode\">): boolean {\n\treturn task.kind === \"bash\" && task.mode === \"foreground\";\n}\n\n/** Preserve the foreground throwing contract without guessing status from output text. */\nexport class BackgroundExecutionError extends Error {\n\treadonly status: BackgroundTerminalStatus;\n\tconstructor(message: string, status: BackgroundTerminalStatus) {\n\t\tsuper(message);\n\t\tthis.name = \"BackgroundExecutionError\";\n\t\tthis.status = status;\n\t}\n}\n"]}
1
+ {"version":3,"file":"types.js","sourceRoot":"","sources":["../../../src/core/background/types.ts"],"names":[],"mappings":"AA8KA,MAAM,CAAC,MAAM,6BAA6B,GACzC,gOAAgO,CAAC;AAElO,MAAM,UAAU,oBAAoB,CAAC,MAAwB;IAC5D,OAAO,MAAM,KAAK,QAAQ,IAAI,MAAM,KAAK,SAAS,IAAI,MAAM,KAAK,UAAU,CAAC;AAC7E,CAAC;AAED,uGAAuG;AACvG,MAAM,UAAU,qBAAqB,CAAC,IAA2C;IAChF,OAAO,IAAI,CAAC,IAAI,KAAK,MAAM,IAAI,IAAI,CAAC,IAAI,KAAK,YAAY,CAAC;AAC3D,CAAC;AAED,0FAA0F;AAC1F,MAAM,OAAO,wBAAyB,SAAQ,KAAK;IAElD,YAAY,OAAe,EAAE,MAAgC;QAC5D,KAAK,CAAC,OAAO,CAAC,CAAC;QACf,IAAI,CAAC,IAAI,GAAG,0BAA0B,CAAC;QACvC,IAAI,CAAC,MAAM,GAAG,MAAM,CAAC;IACtB,CAAC;CACD;AAED;;;;;GAKG;AACH,MAAM,OAAO,qBAAsB,SAAQ,KAAK;IAG/C,YAAY,IAA6B,EAAE,OAAyB;QACnE,KAAK,CAAC,IAAI,KAAK,WAAW,CAAC,CAAC,CAAC,8BAA8B,CAAC,CAAC,CAAC,4BAA4B,CAAC,CAAC;QAC5F,IAAI,CAAC,IAAI,GAAG,uBAAuB,CAAC;QACpC,IAAI,CAAC,IAAI,GAAG,IAAI,CAAC;QACjB,IAAI,CAAC,OAAO,GAAG,OAAO,CAAC;IACxB,CAAC;CACD","sourcesContent":["import type { AgentToolResult } from \"@earendil-works/pi-agent-core\";\nimport type { Usage } from \"@earendil-works/pi-ai/compat\";\n\nexport type BackgroundKind = \"bash\" | \"subagent\";\nexport type BackgroundMode = \"foreground\" | \"background\";\nexport type BackgroundTerminalStatus = \"completed\" | \"partial\" | \"failed\" | \"cancelled\" | \"timeout\";\nexport type BackgroundStatus = \"queued\" | \"running\" | \"stopping\" | BackgroundTerminalStatus;\n\n/** A bounded snapshot; truncation is recorded at the source, never inferred from text. */\nexport interface BackgroundText {\n\ttext: string;\n\ttruncated: boolean;\n}\n\nexport interface BackgroundWorkerReport {\n\tid: string;\n\tlabel: string;\n\tprofile: string;\n\tdescription: string;\n\tstatus: string;\n\treport: BackgroundText;\n\terror?: string;\n}\n\n/** A serializable, domain-owned projection. No extension-private renderer imports. */\nexport interface BackgroundWorker extends BackgroundWorkerReport {\n\tprompt: string;\n\tactivity: string;\n\tmodel?: string;\n\tusage?: string;\n}\n\nexport interface BackgroundProjection {\n\ttext?: string;\n\tshell?: { name: string; output: BackgroundText };\n\tworkers?: BackgroundWorker[];\n}\n\ninterface BackgroundCompletionBase {\n\tversion: 1;\n\ttaskId: string;\n\ttitle: string;\n\tstatus: BackgroundTerminalStatus;\n\tstartedAt: number;\n\tendedAt: number;\n\terror?: string;\n}\n\n/** Self-contained completion-message details. No live handles, tool-private details or accounting. */\nexport type BackgroundCompletionSnapshot = BackgroundCompletionBase &\n\t(\n\t\t| {\n\t\t\t\tkind: \"bash\";\n\t\t\t\tshell?: string;\n\t\t\t\tcommand?: BackgroundText;\n\t\t\t\tcwd?: string;\n\t\t\t\toutputPath?: string;\n\t\t\t\t/** Process exit code: a number, or null when signal-reaped. */\n\t\t\t\texitCode?: number | null;\n\t\t\t\toutput: BackgroundText;\n\t\t }\n\t\t| {\n\t\t\t\tkind: \"subagent\";\n\t\t\t\tworkers: BackgroundWorkerReport[];\n\t\t\t\t/** Plain fallback when an executor has no worker projection. */\n\t\t\t\toutput?: BackgroundText;\n\t\t }\n\t);\n\nexport interface BackgroundTask {\n\tid: string;\n\tkind: BackgroundKind;\n\ttitle: string;\n\ttoolCallId: string;\n\tanchorId: string | null;\n\tmode: BackgroundMode;\n\tstatus: BackgroundStatus;\n\tstartedAt: number;\n\tendedAt?: number;\n\tcommand?: string;\n\tcommandTruncated?: boolean;\n\tcwd?: string;\n\t/** Process exit code (bash): a number, or null when signal-reaped. Absent while running or unreported. */\n\texitCode?: number | null;\n\toutputPath?: string;\n\tprojection?: BackgroundProjection;\n\tresult?: AgentToolResult<unknown>;\n\tresultTruncated?: boolean;\n\terror?: string;\n}\n\nexport interface BackgroundCompletion<T> {\n\tresult: AgentToolResult<T>;\n\tstatus?: BackgroundTerminalStatus;\n\t/** Terminal diagnostic, stored independently of log slices and bounded to 4096 bytes. */\n\terror?: string;\n\t/** Process exit code (bash): a number, or null when signal-reaped. */\n\texitCode?: number | null;\n\t/** Authoritative cumulative usage; overrides result.usage and any published snapshot. */\n\tusage?: Usage;\n}\n\nexport interface BackgroundControl<T> {\n\treadonly id: string;\n\treadonly signal: AbortSignal;\n\treadonly mode: BackgroundMode;\n\t/** Accept only after whole-invocation preflight; required before returning a handoff. */\n\taccept(): void;\n\t/**\n\t * result.usage is a cumulative snapshot, never a delta. The most recent explicitly\n\t * published usage is settled once on rejection (never inferred from details).\n\t * Final completion.usage, then completion.result.usage, override that snapshot.\n\t */\n\tpublish(result: AgentToolResult<T>, projection?: BackgroundProjection): void;\n\t/** Register once; cleanup must own only this exclusively-created file and close its writer first. */\n\tsetOutputPath(path: string, cleanup?: () => void | Promise<void>): void;\n}\n\nexport interface BackgroundExecution<T> {\n\tkind: BackgroundKind;\n\ttitle: string;\n\ttoolCallId: string;\n\tcommand?: string;\n\tcwd?: string;\n\tbackground?: boolean;\n\tsignal?: AbortSignal;\n\tonUpdate?: (result: AgentToolResult<T>) => void;\n\trun(control: BackgroundControl<T>): Promise<BackgroundCompletion<T>>;\n}\n\nexport type BackgroundToolOutcome<T> =\n\t| { kind: \"result\"; result: AgentToolResult<T>; status?: BackgroundTerminalStatus; error?: string }\n\t| { kind: \"background\"; task: BackgroundTask };\n\nexport interface BackgroundRead {\n\ttask: BackgroundTask;\n\ttext: string;\n\t/** Bounded log-read/expiry diagnostic, independent of text slicing and byte offsets. */\n\treadError?: string;\n\ttotalBytes: number;\n\ttruncated: boolean;\n\tfromByte?: number;\n}\n\n/** Session-bound public capability. Captured instances close on runtime replacement. */\nexport interface BackgroundContext {\n\treadonly enabled: boolean;\n\treadonly closed?: boolean;\n\texecute<T>(execution: BackgroundExecution<T>): Promise<BackgroundToolOutcome<T>>;\n\tlist(): BackgroundTask[];\n\tget(id: string): BackgroundTask;\n\tread(id: string, options?: { mode?: \"head\" | \"tail\"; bytes?: number; sinceBytes?: number }): Promise<BackgroundRead>;\n\t/** Observation only: terminal delivery is acknowledged by the host via markDelivered after result persistence. */\n\twait(id: string, timeoutMs?: number, signal?: AbortSignal): Promise<BackgroundTask>;\n\tkill(id: string): boolean;\n\t/** Move every running foreground execution to the background; returns how many moved. */\n\tdetachForeground(): number;\n\tsubscribe(listener: () => void): () => void;\n\tpin(id: string): () => void;\n}\n\nexport interface BackgroundServiceOptions {\n\tenabled?: boolean;\n\trole?: \"main\" | \"subagent\";\n\tanchor?: () => string | null;\n\tmaxActive?: number;\n\t/** Per-history limit: foreground shells and background tasks/all subagents each get this allowance. */\n\tmaxHistory?: number;\n\t/** Best-effort cleanup errors, bounded to 4096 bytes; no retries or execution failure. */\n\tonCleanupError?: (message: string) => void;\n\t/** Synchronous persistence before terminal observers or notifications. */\n\tonSettled?: (task: BackgroundTask, usage: Usage | undefined) => void;\n}\n\nexport const SUBAGENT_BACKGROUND_REJECTION =\n\t\"Background execution is not available inside subagents. Run this command with background: false (or omit background). Only the parent agent or the user can background the entire subagent invocation. No command was started.\";\n\nexport function isBackgroundTerminal(status: BackgroundStatus): boolean {\n\treturn status !== \"queued\" && status !== \"running\" && status !== \"stopping\";\n}\n\n/** Foreground shell logs have their own history; subagent groups remain inspectable in either mode. */\nexport function isForegroundShellTask(task: Pick<BackgroundTask, \"kind\" | \"mode\">): boolean {\n\treturn task.kind === \"bash\" && task.mode === \"foreground\";\n}\n\n/** Preserve the foreground throwing contract without guessing status from output text. */\nexport class BackgroundExecutionError extends Error {\n\treadonly status: BackgroundTerminalStatus;\n\tconstructor(message: string, status: BackgroundTerminalStatus) {\n\t\tsuper(message);\n\t\tthis.name = \"BackgroundExecutionError\";\n\t\tthis.status = status;\n\t}\n}\n\n/**\n * A failed id lookup, typed so hosts can enrich the message without matching\n * on message text. `matches` snapshots exactly the records the id or prefix\n * resolved against — including records outside the current branch, which\n * list() hides but prefix matching still collides with.\n */\nexport class BackgroundLookupError extends Error {\n\treadonly kind: \"unknown\" | \"ambiguous\";\n\treadonly matches: BackgroundTask[];\n\tconstructor(kind: \"unknown\" | \"ambiguous\", matches: BackgroundTask[]) {\n\t\tsuper(kind === \"ambiguous\" ? \"Ambiguous background task ID\" : \"Unknown background task ID\");\n\t\tthis.name = \"BackgroundLookupError\";\n\t\tthis.kind = kind;\n\t\tthis.matches = matches;\n\t}\n}\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"tool-definition-wrapper.d.ts","sourceRoot":"","sources":["../../../src/core/tools/tool-definition-wrapper.ts"],"names":[],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AAM,wBAAwB,CAAC;AAG/E,KAAK,oBAAoB,CAAC,OAAO,SAAS,OAAO,GAAG,OAAO,EAAE,QAAQ,GAAG,OAAO,IAAI,SAAS,CAAC,OAAO,EAAE,QAAQ,CAAC,GAAG;IACjH,SAAS,CAAC,EAAE,MAAM,CAAC;CACnB,CAAC;AAyHF,oEAAoE;AACpE,wBAAgB,kBAAkB,CAAC,OAAO,SAAS,OAAO,EAAE,QAAQ,GAAG,OAAO,EAC7E,UAAU,EAAE,cAAc,CAAC,OAAO,EAAE,QAAQ,CAAC,EAC7C,UAAU,CAAC,EAAE,MAAM,gBAAgB,GACjC,oBAAoB,CAAC,OAAO,EAAE,QAAQ,CAAC,CAazC;AAED,0EAA0E;AAC1E,wBAAgB,mBAAmB,CAClC,WAAW,EAAE,cAAc,CAAC,GAAG,EAAE,GAAG,CAAC,EAAE,EACvC,UAAU,CAAC,EAAE,MAAM,gBAAgB,GACjC,SAAS,CAAC,GAAG,CAAC,EAAE,CAElB;AAED;;;;;GAKG;AACH,wBAAgB,iCAAiC,CAAC,OAAO,SAAS,OAAO,EAAE,QAAQ,EAClF,IAAI,EAAE,oBAAoB,CAAC,OAAO,EAAE,QAAQ,CAAC,GAC3C,cAAc,CAAC,OAAO,EAAE,QAAQ,CAAC,CAYnC"}
@@ -13,7 +13,9 @@ function isRecord(value) {
13
13
  * `additionalProperties: false`, the non-null fields the schema does not
14
14
  * declare, and at every object, the required fields the arguments lack. The
15
15
  * validator's own report says where validation failed; these hints say what
16
- * the legal shape is. Paths use the validator's dotted style
16
+ * the legal shape is. Union variants (`anyOf`, e.g. a nullable field) are
17
+ * walked through so nested shapes still get hints. Paths use the validator's
18
+ * dotted style
17
19
  * (`tasks[0].prompt`). Non-null unknown fields are reported rather than
18
20
  * silently dropped: a field like `prompt_extra` may carry briefing content
19
21
  * the caller intended to send.
@@ -23,6 +25,11 @@ function collectFieldHints(schema, args) {
23
25
  const visit = (node, value, path) => {
24
26
  if (hints.length >= FIELD_HINTS_MAX || !isRecord(node))
25
27
  return;
28
+ if (Array.isArray(node.anyOf)) {
29
+ for (const variant of node.anyOf)
30
+ visit(variant, value, path);
31
+ return;
32
+ }
26
33
  if (node.type === "array" && Array.isArray(value)) {
27
34
  for (let index = 0; index < value.length; index++) {
28
35
  visit(node.items, value[index], `${path}[${index}]`);
@@ -1 +1 @@
1
- {"version":3,"file":"tool-definition-wrapper.js","sourceRoot":"","sources":["../../../src/core/tools/tool-definition-wrapper.ts"],"names":[],"mappings":"AACA,OAAO,EAAmB,qBAAqB,EAAE,MAAM,uBAAuB,CAAC;AAG/E,OAAO,EAAE,YAAY,EAAE,MAAM,eAAe,CAAC;AAM7C,MAAM,yBAAyB,GAAG,2BAA2B,CAAC;AAC9D,MAAM,WAAW,GAAG,YAAY,CAAC;AACjC,MAAM,4BAA4B,GAAG,CAAC,GAAG,IAAI,CAAC;AAC9C,MAAM,4BAA4B,GAAG,EAAE,CAAC;AACxC,MAAM,eAAe,GAAG,EAAE,CAAC;AAE3B,SAAS,QAAQ,CAAC,KAAc;IAC/B,OAAO,KAAK,KAAK,IAAI,IAAI,OAAO,KAAK,KAAK,QAAQ,IAAI,CAAC,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC,CAAC;AAC7E,CAAC;AAED;;;;;;;;;GASG;AACH,SAAS,iBAAiB,CAAC,MAAe,EAAE,IAAa;IACxD,MAAM,KAAK,GAAa,EAAE,CAAC;IAC3B,MAAM,KAAK,GAAG,CAAC,IAAa,EAAE,KAAc,EAAE,IAAY,EAAQ,EAAE;QACnE,IAAI,KAAK,CAAC,MAAM,IAAI,eAAe,IAAI,CAAC,QAAQ,CAAC,IAAI,CAAC;YAAE,OAAO;QAC/D,IAAI,IAAI,CAAC,IAAI,KAAK,OAAO,IAAI,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC,EAAE,CAAC;YACnD,KAAK,IAAI,KAAK,GAAG,CAAC,EAAE,KAAK,GAAG,KAAK,CAAC,MAAM,EAAE,KAAK,EAAE,E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C;AACpF,CAAC;AAED;;;;;GAKG;AACH,MAAM,UAAU,iCAAiC,CAChD,IAA6C;IAE7C,OAAO;QACN,IAAI,EAAE,IAAI,CAAC,IAAI;QACf,KAAK,EAAE,IAAI,CAAC,KAAK;QACjB,WAAW,EAAE,IAAI,CAAC,WAAW;QAC7B,UAAU,EAAE,IAAI,CAAC,UAAU;QAC3B,mBAAmB,EAAE,IAAI,CAAC,mBAAmB;QAC7C,SAAS,EAAE,IAAI,CAAC,SAAS;QACzB,gBAAgB,EAAE,IAAI,CAAC,gBAAgB;QACvC,aAAa,EAAE,IAAI,CAAC,aAAa;QACjC,OAAO,EAAE,KAAK,EAAE,UAAU,EAAE,MAAM,EAAE,MAAM,EAAE,QAAQ,EAAE,EAAE,CAAC,IAAI,CAAC,OAAO,CAAC,UAAU,EAAE,MAAM,EAAE,MAAM,EAAE,QAAQ,CAAC;KAC3G,CAAC;AACH,CAAC","sourcesContent":["import type { AgentTool } from \"@earendil-works/pi-agent-core\";\nimport { type JsonObject, validateToolArguments } from \"@earendil-works/pi-ai\";\nimport type { Static, TSchema } from \"typebox\";\nimport type { ExtensionContext, ToolDefinition } from \"../extensions/types.ts\";\nimport { truncateHead } from \"./truncate.ts\";\n\ntype PresentableAgentTool<TParams extends TSchema = TSchema, TDetails = unknown> = AgentTool<TParams, TDetails> & {\n\ttoolGroup?: string;\n};\n\nconst RECEIVED_ARGUMENTS_MARKER = \"\\n\\nReceived arguments:\\n\";\nconst HINT_MARKER = \"\\n\\nHint: \";\nconst RECEIVED_ARGUMENTS_MAX_BYTES = 2 * 1024;\nconst RECEIVED_ARGUMENTS_MAX_LINES = 40;\nconst FIELD_HINTS_MAX = 10;\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n\treturn value !== null && typeof value === \"object\" && !Array.isArray(value);\n}\n\n/**\n * Walk schema and arguments in sync to name, at every object with\n * `additionalProperties: false`, the non-null fields the schema does not\n * declare, and at every object, the required fields the arguments lack. The\n * validator's own report says where validation failed; these hints say what\n * the legal shape is. Paths use the validator's dotted style\n * (`tasks[0].prompt`). Non-null unknown fields are reported rather than\n * silently dropped: a field like `prompt_extra` may carry briefing content\n * the caller intended to send.\n */\nfunction collectFieldHints(schema: unknown, args: unknown): string[] {\n\tconst hints: string[] = [];\n\tconst visit = (node: unknown, value: unknown, path: string): void => {\n\t\tif (hints.length >= FIELD_HINTS_MAX || !isRecord(node)) return;\n\t\tif (node.type === \"array\" && Array.isArray(value)) {\n\t\t\tfor (let index = 0; index < value.length; index++) {\n\t\t\t\tvisit(node.items, value[index], `${path}[${index}]`);\n\t\t\t}\n\t\t\treturn;\n\t\t}\n\t\tif (node.type !== \"object\" || !isRecord(value)) return;\n\t\tconst properties = isRecord(node.properties) ? node.properties : {};\n\t\tconst fields = Object.keys(properties);\n\t\tconst where = path || \"root\";\n\t\tif (node.additionalProperties === false) {\n\t\t\tfor (const [key, entry] of Object.entries(value)) {\n\t\t\t\tif (entry !== null && !(key in properties) && hints.length < FIELD_HINTS_MAX) {\n\t\t\t\t\tconst subject = path ? `${path}.${key}` : key;\n\t\t\t\t\thints.push(`${subject} is not a field; fields at ${where}: ${fields.join(\", \")}`);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tif (Array.isArray(node.required)) {\n\t\t\tfor (const key of node.required) {\n\t\t\t\tif (typeof key === \"string\" && value[key] === undefined && hints.length < FIELD_HINTS_MAX) {\n\t\t\t\t\tconst subject = path ? `${path}.${key}` : key;\n\t\t\t\t\thints.push(`${subject} is required; fields at ${where}: ${fields.join(\", \")}`);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tfor (const key of fields) {\n\t\t\tif (value[key] !== undefined && value[key] !== null) {\n\t\t\t\tvisit(properties[key], value[key], path ? `${path}.${key}` : key);\n\t\t\t}\n\t\t}\n\t};\n\tvisit(schema, args, \"\");\n\treturn hints;\n}\n\n/**\n * Rebuild pi-ai's validation error so a model can self-correct: the legal\n * fields are named next to each offending one, and the echoed arguments are\n * bounded (a 50KB subagent prompt must not be reflected whole into context).\n * The `Validation failed for tool \"<name>\":` prefix stays intact — the\n * question tool's renderer parses it.\n */\nfunction enrichValidationError(error: unknown, parameters: TSchema, args: unknown): Error {\n\tconst message = error instanceof Error ? error.message : String(error);\n\t// A definition synthesized from an already-wrapped tool enriches on the\n\t// inside; do not stack a second layer of hints on the same failure.\n\tif (message.includes(HINT_MARKER)) return error instanceof Error ? error : new Error(message);\n\tconst hints = collectFieldHints(parameters, args);\n\tconst markerIndex = message.indexOf(RECEIVED_ARGUMENTS_MARKER);\n\tconst head = markerIndex === -1 ? message : message.slice(0, markerIndex);\n\tconst received = markerIndex === -1 ? \"\" : message.slice(markerIndex + RECEIVED_ARGUMENTS_MARKER.length);\n\tlet enriched = hints.length > 0 ? `${head}\\n\\nHint: ${hints.join(\"\\nHint: \")}` : head;\n\tif (markerIndex !== -1) {\n\t\tconst bounded = truncateHead(received, {\n\t\t\tmaxBytes: RECEIVED_ARGUMENTS_MAX_BYTES,\n\t\t\tmaxLines: RECEIVED_ARGUMENTS_MAX_LINES,\n\t\t});\n\t\tenriched += `${RECEIVED_ARGUMENTS_MARKER}${bounded.content}`;\n\t\tif (bounded.truncated) enriched += \"\\n… (arguments truncated)\";\n\t}\n\treturn new Error(enriched);\n}\n\n/**\n * Pre-validate prepared arguments so a validation failure reaches the model\n * with field-level hints. Valid arguments pass through untouched and are\n * validated again by the agent loop as before.\n */\nfunction wrapPrepareArguments<TParams extends TSchema, TDetails>(\n\tdefinition: ToolDefinition<TParams, TDetails>,\n): (raw: unknown) => Static<TParams> {\n\tconst tool = { name: definition.name, description: definition.description, parameters: definition.parameters };\n\treturn (raw: unknown): Static<TParams> => {\n\t\tconst args = definition.prepareArguments ? definition.prepareArguments(raw) : raw;\n\t\ttry {\n\t\t\tvalidateToolArguments(tool, {\n\t\t\t\ttype: \"toolCall\",\n\t\t\t\tid: \"\",\n\t\t\t\tname: definition.name,\n\t\t\t\targuments: args as JsonObject,\n\t\t\t});\n\t\t} catch (error) {\n\t\t\tthrow enrichValidationError(error, definition.parameters, args);\n\t\t}\n\t\treturn args as Static<TParams>;\n\t};\n}\n\n/** Wrap a ToolDefinition into an AgentTool for the core runtime. */\nexport function wrapToolDefinition<TParams extends TSchema, TDetails = unknown>(\n\tdefinition: ToolDefinition<TParams, TDetails>,\n\tctxFactory?: () => ExtensionContext,\n): PresentableAgentTool<TParams, TDetails> {\n\treturn {\n\t\tname: definition.name,\n\t\tlabel: definition.label,\n\t\tdescription: definition.description,\n\t\tparameters: definition.parameters,\n\t\tconstrainedSampling: definition.constrainedSampling,\n\t\ttoolGroup: definition.toolGroup,\n\t\tprepareArguments: wrapPrepareArguments(definition),\n\t\texecutionMode: definition.executionMode,\n\t\texecute: (toolCallId, params, signal, onUpdate, ctx?: ExtensionContext) =>\n\t\t\tdefinition.execute(toolCallId, params, signal, onUpdate, ctx ?? (ctxFactory?.() as ExtensionContext)),\n\t};\n}\n\n/** Wrap multiple ToolDefinitions into AgentTools for the core runtime. */\nexport function wrapToolDefinitions(\n\tdefinitions: ToolDefinition<any, any>[],\n\tctxFactory?: () => ExtensionContext,\n): AgentTool<any>[] {\n\treturn definitions.map((definition) => wrapToolDefinition(definition, ctxFactory));\n}\n\n/**\n * Synthesize a minimal ToolDefinition from an AgentTool.\n *\n * This keeps AgentSession's internal registry definition-first even when a caller\n * provides plain AgentTool overrides that do not include prompt metadata or renderers.\n */\nexport function createToolDefinitionFromAgentTool<TParams extends TSchema, TDetails>(\n\ttool: PresentableAgentTool<TParams, TDetails>,\n): ToolDefinition<TParams, TDetails> {\n\treturn {\n\t\tname: tool.name,\n\t\tlabel: tool.label,\n\t\tdescription: tool.description,\n\t\tparameters: tool.parameters,\n\t\tconstrainedSampling: tool.constrainedSampling,\n\t\ttoolGroup: tool.toolGroup,\n\t\tprepareArguments: tool.prepareArguments,\n\t\texecutionMode: tool.executionMode,\n\t\texecute: async (toolCallId, params, signal, onUpdate) => tool.execute(toolCallId, params, signal, onUpdate),\n\t};\n}\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;AACpF,CAAC;AAED;;;;;GAKG;AACH,MAAM,UAAU,iCAAiC,CAChD,IAA6C;IAE7C,OAAO;QACN,IAAI,EAAE,IAAI,CAAC,IAAI;QACf,KAAK,EAAE,IAAI,CAAC,KAAK;QACjB,WAAW,EAAE,IAAI,CAAC,WAAW;QAC7B,UAAU,EAAE,IAAI,CAAC,UAAU;QAC3B,mBAAmB,EAAE,IAAI,CAAC,mBAAmB;QAC7C,SAAS,EAAE,IAAI,CAAC,SAAS;QACzB,gBAAgB,EAAE,IAAI,CAAC,gBAAgB;QACvC,aAAa,EAAE,IAAI,CAAC,aAAa;QACjC,OAAO,EAAE,KAAK,EAAE,UAAU,EAAE,MAAM,EAAE,MAAM,EAAE,QAAQ,EAAE,EAAE,CAAC,IAAI,CAAC,OAAO,CAAC,UAAU,EAAE,MAAM,EAAE,MAAM,EAAE,QAAQ,CAAC;KAC3G,CAAC;AACH,CAAC","sourcesContent":["import type { AgentTool } from \"@earendil-works/pi-agent-core\";\nimport { type JsonObject, validateToolArguments } from \"@earendil-works/pi-ai\";\nimport type { Static, TSchema } from \"typebox\";\nimport type { ExtensionContext, ToolDefinition } from \"../extensions/types.ts\";\nimport { truncateHead } from \"./truncate.ts\";\n\ntype PresentableAgentTool<TParams extends TSchema = TSchema, TDetails = unknown> = AgentTool<TParams, TDetails> & {\n\ttoolGroup?: string;\n};\n\nconst RECEIVED_ARGUMENTS_MARKER = \"\\n\\nReceived arguments:\\n\";\nconst HINT_MARKER = \"\\n\\nHint: \";\nconst RECEIVED_ARGUMENTS_MAX_BYTES = 2 * 1024;\nconst RECEIVED_ARGUMENTS_MAX_LINES = 40;\nconst FIELD_HINTS_MAX = 10;\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n\treturn value !== null && typeof value === \"object\" && !Array.isArray(value);\n}\n\n/**\n * Walk schema and arguments in sync to name, at every object with\n * `additionalProperties: false`, the non-null fields the schema does not\n * declare, and at every object, the required fields the arguments lack. The\n * validator's own report says where validation failed; these hints say what\n * the legal shape is. Union variants (`anyOf`, e.g. a nullable field) are\n * walked through so nested shapes still get hints. Paths use the validator's\n * dotted style\n * (`tasks[0].prompt`). Non-null unknown fields are reported rather than\n * silently dropped: a field like `prompt_extra` may carry briefing content\n * the caller intended to send.\n */\nfunction collectFieldHints(schema: unknown, args: unknown): string[] {\n\tconst hints: string[] = [];\n\tconst visit = (node: unknown, value: unknown, path: string): void => {\n\t\tif (hints.length >= FIELD_HINTS_MAX || !isRecord(node)) return;\n\t\tif (Array.isArray(node.anyOf)) {\n\t\t\tfor (const variant of node.anyOf) visit(variant, value, path);\n\t\t\treturn;\n\t\t}\n\t\tif (node.type === \"array\" && Array.isArray(value)) {\n\t\t\tfor (let index = 0; index < value.length; index++) {\n\t\t\t\tvisit(node.items, value[index], `${path}[${index}]`);\n\t\t\t}\n\t\t\treturn;\n\t\t}\n\t\tif (node.type !== \"object\" || !isRecord(value)) return;\n\t\tconst properties = isRecord(node.properties) ? node.properties : {};\n\t\tconst fields = Object.keys(properties);\n\t\tconst where = path || \"root\";\n\t\tif (node.additionalProperties === false) {\n\t\t\tfor (const [key, entry] of Object.entries(value)) {\n\t\t\t\tif (entry !== null && !(key in properties) && hints.length < FIELD_HINTS_MAX) {\n\t\t\t\t\tconst subject = path ? `${path}.${key}` : key;\n\t\t\t\t\thints.push(`${subject} is not a field; fields at ${where}: ${fields.join(\", \")}`);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tif (Array.isArray(node.required)) {\n\t\t\tfor (const key of node.required) {\n\t\t\t\tif (typeof key === \"string\" && value[key] === undefined && hints.length < FIELD_HINTS_MAX) {\n\t\t\t\t\tconst subject = path ? `${path}.${key}` : key;\n\t\t\t\t\thints.push(`${subject} is required; fields at ${where}: ${fields.join(\", \")}`);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tfor (const key of fields) {\n\t\t\tif (value[key] !== undefined && value[key] !== null) {\n\t\t\t\tvisit(properties[key], value[key], path ? `${path}.${key}` : key);\n\t\t\t}\n\t\t}\n\t};\n\tvisit(schema, args, \"\");\n\treturn hints;\n}\n\n/**\n * Rebuild pi-ai's validation error so a model can self-correct: the legal\n * fields are named next to each offending one, and the echoed arguments are\n * bounded (a 50KB subagent prompt must not be reflected whole into context).\n * The `Validation failed for tool \"<name>\":` prefix stays intact — the\n * question tool's renderer parses it.\n */\nfunction enrichValidationError(error: unknown, parameters: TSchema, args: unknown): Error {\n\tconst message = error instanceof Error ? error.message : String(error);\n\t// A definition synthesized from an already-wrapped tool enriches on the\n\t// inside; do not stack a second layer of hints on the same failure.\n\tif (message.includes(HINT_MARKER)) return error instanceof Error ? error : new Error(message);\n\tconst hints = collectFieldHints(parameters, args);\n\tconst markerIndex = message.indexOf(RECEIVED_ARGUMENTS_MARKER);\n\tconst head = markerIndex === -1 ? message : message.slice(0, markerIndex);\n\tconst received = markerIndex === -1 ? \"\" : message.slice(markerIndex + RECEIVED_ARGUMENTS_MARKER.length);\n\tlet enriched = hints.length > 0 ? `${head}\\n\\nHint: ${hints.join(\"\\nHint: \")}` : head;\n\tif (markerIndex !== -1) {\n\t\tconst bounded = truncateHead(received, {\n\t\t\tmaxBytes: RECEIVED_ARGUMENTS_MAX_BYTES,\n\t\t\tmaxLines: RECEIVED_ARGUMENTS_MAX_LINES,\n\t\t});\n\t\tenriched += `${RECEIVED_ARGUMENTS_MARKER}${bounded.content}`;\n\t\tif (bounded.truncated) enriched += \"\\n… (arguments truncated)\";\n\t}\n\treturn new Error(enriched);\n}\n\n/**\n * Pre-validate prepared arguments so a validation failure reaches the model\n * with field-level hints. Valid arguments pass through untouched and are\n * validated again by the agent loop as before.\n */\nfunction wrapPrepareArguments<TParams extends TSchema, TDetails>(\n\tdefinition: ToolDefinition<TParams, TDetails>,\n): (raw: unknown) => Static<TParams> {\n\tconst tool = { name: definition.name, description: definition.description, parameters: definition.parameters };\n\treturn (raw: unknown): Static<TParams> => {\n\t\tconst args = definition.prepareArguments ? definition.prepareArguments(raw) : raw;\n\t\ttry {\n\t\t\tvalidateToolArguments(tool, {\n\t\t\t\ttype: \"toolCall\",\n\t\t\t\tid: \"\",\n\t\t\t\tname: definition.name,\n\t\t\t\targuments: args as JsonObject,\n\t\t\t});\n\t\t} catch (error) {\n\t\t\tthrow enrichValidationError(error, definition.parameters, args);\n\t\t}\n\t\treturn args as Static<TParams>;\n\t};\n}\n\n/** Wrap a ToolDefinition into an AgentTool for the core runtime. */\nexport function wrapToolDefinition<TParams extends TSchema, TDetails = unknown>(\n\tdefinition: ToolDefinition<TParams, TDetails>,\n\tctxFactory?: () => ExtensionContext,\n): PresentableAgentTool<TParams, TDetails> {\n\treturn {\n\t\tname: definition.name,\n\t\tlabel: definition.label,\n\t\tdescription: definition.description,\n\t\tparameters: definition.parameters,\n\t\tconstrainedSampling: definition.constrainedSampling,\n\t\ttoolGroup: definition.toolGroup,\n\t\tprepareArguments: wrapPrepareArguments(definition),\n\t\texecutionMode: definition.executionMode,\n\t\texecute: (toolCallId, params, signal, onUpdate, ctx?: ExtensionContext) =>\n\t\t\tdefinition.execute(toolCallId, params, signal, onUpdate, ctx ?? (ctxFactory?.() as ExtensionContext)),\n\t};\n}\n\n/** Wrap multiple ToolDefinitions into AgentTools for the core runtime. */\nexport function wrapToolDefinitions(\n\tdefinitions: ToolDefinition<any, any>[],\n\tctxFactory?: () => ExtensionContext,\n): AgentTool<any>[] {\n\treturn definitions.map((definition) => wrapToolDefinition(definition, ctxFactory));\n}\n\n/**\n * Synthesize a minimal ToolDefinition from an AgentTool.\n *\n * This keeps AgentSession's internal registry definition-first even when a caller\n * provides plain AgentTool overrides that do not include prompt metadata or renderers.\n */\nexport function createToolDefinitionFromAgentTool<TParams extends TSchema, TDetails>(\n\ttool: PresentableAgentTool<TParams, TDetails>,\n): ToolDefinition<TParams, TDetails> {\n\treturn {\n\t\tname: tool.name,\n\t\tlabel: tool.label,\n\t\tdescription: tool.description,\n\t\tparameters: tool.parameters,\n\t\tconstrainedSampling: tool.constrainedSampling,\n\t\ttoolGroup: tool.toolGroup,\n\t\tprepareArguments: tool.prepareArguments,\n\t\texecutionMode: tool.executionMode,\n\t\texecute: async (toolCallId, params, signal, onUpdate) => tool.execute(toolCallId, params, signal, onUpdate),\n\t};\n}\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"actions.d.ts","sourceRoot":"","sources":["../../../src/extensions/background/actions.ts"],"names":[],"mappings":"AAEA,OAAO,EACN,KAAK,iBAAiB,EAEtB,KAAK,cAAc,EAEnB,MAAM,gCAAgC,CAAC;AACxC,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,gCAAgC,CAAC;AAItE,OAAO,EAAE,KAAK,OAAO,EAA+D,MAAM,aAAa,CAAC;AAExG,OAAO,KAAK,EAAa,aAAa,EAAE,aAAa,EAAE,aAAa,EAAE,aAAa,EAAE,MAAM,YAAY,CAAC;AAExG,wBAAgB,WAAW,CAAC,IAAI,EAAE,MAAM,GAAG,MAAM,CAEhD;AAID,wBAAgB,gBAAgB,CAAC,IAAI,EAAE,cAAc,EAAE,GAAG,SAAa,GAAG,MAAM,CAE/E;AAuDD,wBAAsB,OAAO,CAAC,UAAU,EAAE,iBAAiB,EAAE,KAAK,EAAE,OAAO,GAAG,OAAO,CAAC,eAAe,CAAC,aAAa,CAAC,CAAC,CAwBpH;AACD,wBAAsB,OAAO,CAC5B,UAAU,EAAE,iBAAiB,EAC7B,KAAK,EAAE,OAAO,EACd,MAAM,CAAC,EAAE,WAAW,GAClB,OAAO,CAAC,eAAe,CAAC,aAAa,CAAC,CAAC,CAwCzC;AACD,wBAAgB,OAAO,CAAC,UAAU,EAAE,iBAAiB,EAAE,KAAK,EAAE,OAAO,GAAG,eAAe,CAAC,aAAa,CAAC,CAoBrG;AACD,wBAAgB,OAAO,CAAC,UAAU,EAAE,iBAAiB,GAAG,eAAe,CAAC,aAAa,CAAC,CA2BrF"}
1
+ {"version":3,"file":"actions.d.ts","sourceRoot":"","sources":["../../../src/extensions/background/actions.ts"],"names":[],"mappings":"AAEA,OAAO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