@gencode/agents 0.0.42 → 0.0.43

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.ts CHANGED
@@ -2,7 +2,7 @@ import { S as AgentsConfig, _ as saveAgentsConfig, a as listAgents, b as AgentCo
2
2
  import { AssistantMessage, Message } from "@mariozechner/pi-ai";
3
3
  import { AgentMessage, AgentTool } from "@mariozechner/pi-agent-core";
4
4
  import * as _gencode_shared0 from "@gencode/shared";
5
- import { AgentCustomProgressEvent, AgentProgressEvent, AgentProgressEvent as AgentProgressEvent$1, CallbackEventPayload, CallbackEventPayload as CallbackEventPayload$1, Channel, Channel as Channel$1, CollapseSpan, HitlCheckpoint, HitlCheckpoint as HitlCheckpoint$1, HitlHistoryEntry, HitlRequest, HitlRequest as HitlRequest$1, HitlResolution, HitlResolution as HitlResolution$1, HitlStatus, HitlToolContext, HitlToolContext as HitlToolContext$1, PausedRunState, PausedRunState as PausedRunState$1, ReadStateRecord, RunResultPayload, RunResultPayload as RunResultPayload$1, SessionContextSnapshot, SessionMemorySnapshot, SnipRecord, ToolResultReference, UiToolExtra, UiToolPausedState, UiToolRequest, UiToolResult, UiToolSchema, UiToolValidationResult } from "@gencode/shared";
5
+ import { AgentCustomProgressEvent, AgentProgressEvent, AgentProgressEvent as AgentProgressEvent$1, CallbackEventPayload, CallbackEventPayload as CallbackEventPayload$1, Channel, Channel as Channel$1, CollapseSpan, HitlCheckpoint, HitlCheckpoint as HitlCheckpoint$1, HitlHistoryEntry, HitlRequest, HitlRequest as HitlRequest$1, HitlResolution, HitlResolution as HitlResolution$1, HitlStatus, HitlToolContext, HitlToolContext as HitlToolContext$1, PausedRunState, PausedRunState as PausedRunState$1, ReadStateRecord, RunResultPayload, RunResultPayload as RunResultPayload$1, SessionContextSnapshot, SessionMemorySnapshot, SnipRecord, ToolResultReference, UiToolExtra, UiToolOutputSchema, UiToolPausedState, UiToolRequest, UiToolResult, UiToolValidationResult } from "@gencode/shared";
6
6
 
7
7
  //#region src/loop-detection/tool-loop-detection.d.ts
8
8
  type ToolLoopDetectionConfig = {
@@ -204,7 +204,7 @@ type AgentRunResult = RunResultPayload$1 & {
204
204
  requestId: string;
205
205
  toolName: string;
206
206
  toolCallId: string;
207
- schema: _gencode_shared0.UiToolSchema;
207
+ outputSchema: _gencode_shared0.UiToolOutputSchema;
208
208
  extra?: _gencode_shared0.UiToolExtra;
209
209
  };
210
210
  };
@@ -1695,8 +1695,13 @@ type UiToolOptions = {
1695
1695
  /** Unique tool name (must be valid identifier, e.g. "collect_feedback"). */name: string; /** Human-readable label shown in tool listings. */
1696
1696
  label: string; /** Description used in the LLM system prompt. */
1697
1697
  description: string; /** Current session ID. */
1698
- sessionId: string; /** The UI form schema that the front-end should render. */
1699
- schema: UiToolSchema; /** Optional JSON-safe payload for highly custom front-end rendering. */
1698
+ sessionId: string;
1699
+ /**
1700
+ * Optional LLM-facing input schema.
1701
+ * If omitted, a default `{ reason: string }` schema is used.
1702
+ */
1703
+ inputSchema?: UiToolInputSchema; /** The UI form schema that the front-end should render and submit. */
1704
+ outputSchema: UiToolOutputSchema; /** Optional JSON-safe payload for highly custom front-end rendering. */
1700
1705
  extra?: UiToolExtra;
1701
1706
  /**
1702
1707
  * Optional custom validator. Called after built-in schema validation passes.
@@ -1713,16 +1718,17 @@ type UiToolOptions = {
1713
1718
  };
1714
1719
  /**
1715
1720
  * The LLM sees a thin schema: `reason` explains why input is needed.
1716
- * The actual form fields are defined in UiToolSchema and are NOT exposed
1717
- * to the LLM they are only used by the front-end renderer.
1721
+ * The actual form fields are defined in UiToolOutputSchema and are NOT exposed
1722
+ * to the LLM. They are only used by the front-end renderer and resume validation.
1718
1723
  */
1719
- declare const uiToolLlmSchema: TObject<{
1724
+ type UiToolInputSchema = Record<string, unknown>;
1725
+ declare const defaultUiToolInputSchema: TObject<{
1720
1726
  reason: TString;
1721
1727
  }>;
1722
1728
  /**
1723
1729
  * Creates a UI tool that pauses the agent for front-end input collection.
1724
1730
  */
1725
- declare function createUiTool(options: UiToolOptions): AgentTool<typeof uiToolLlmSchema>;
1731
+ declare function createUiTool(options: UiToolOptions): AgentTool<any>;
1726
1732
  //#endregion
1727
1733
  //#region src/tools/ui-tool-signal.d.ts
1728
1734
  declare class UiToolPauseSignal extends Error {
@@ -1740,9 +1746,9 @@ declare class UiToolPauseSignal extends Error {
1740
1746
 
1741
1747
  toolName: string, /** The LLM-generated tool call ID. */
1742
1748
 
1743
- toolCallId: string, /** The UI form schema. */
1749
+ toolCallId: string, /** The front-end output schema used for rendering and submission. */
1744
1750
 
1745
- schema: UiToolSchema, /** Optional custom front-end rendering payload. */
1751
+ outputSchema: UiToolOutputSchema, /** Optional custom front-end rendering payload. */
1746
1752
 
1747
1753
  extra: UiToolExtra | undefined, /** The original tool arguments from the LLM. */
1748
1754
 
@@ -1851,8 +1857,13 @@ type RegisteredPluginTool = {
1851
1857
  type PluginUiToolDescriptor = {
1852
1858
  /** Unique tool name (must be a valid identifier, e.g. "collect_feedback"). */name: string; /** Human-readable label shown in tool listings. */
1853
1859
  label: string; /** Description used in the LLM system prompt. */
1854
- description: string; /** The UI form schema that the front-end should render. */
1855
- schema: UiToolSchema; /** Optional JSON-safe payload for highly custom front-end rendering. */
1860
+ description: string;
1861
+ /**
1862
+ * Optional LLM-facing input schema.
1863
+ * If omitted, the framework uses the default `{ reason: string }` schema.
1864
+ */
1865
+ inputSchema?: UiToolInputSchema; /** The UI form schema that the front-end should render and submit. */
1866
+ outputSchema: UiToolOutputSchema; /** Optional JSON-safe payload for highly custom front-end rendering. */
1856
1867
  extra?: UiToolExtra;
1857
1868
  /**
1858
1869
  * Optional custom validator. Called after built-in schema validation passes.
@@ -2222,4 +2233,4 @@ declare function formatClarifyResolution(resolution: HitlResolution): string;
2222
2233
  declare function formatReviewResolution(resolution: HitlResolution): string;
2223
2234
  declare function buildResumeNarration(resolution: HitlResolution, kind: string): string;
2224
2235
  //#endregion
2225
- export { AgentBinding, AgentConfig, type AgentCustomProgressEvent, AgentModelConfig, type AgentProgressEvent, type AgentRunParams, type AgentRunResult, AgentsConfig, BOOTSTRAP_FILE_NAMES, BOOTSTRAP_MAX_CHARS, BOOTSTRAP_TOTAL_MAX_CHARS, type BootstrapContextFile, type BootstrapEnsureResult, type BootstrapFile, type BootstrapMountResult, type BootstrapMountStatus, type CallbackEventPayload, type CallbackPayload, type Channel, type ContextManager, DEFAULT_SESSION_STORE_NAME, type EmbeddingProvider, type EmbeddingProviderContext, type EmbeddingProviderFactory, type EmbeddingProviderRegistration, HITL_MESSAGES, type HitlPauseContext, HitlPauseSignal, type HitlToolContext, MAX_CHILDREN_PER_SESSION, MAX_SUBAGENT_DEPTH, type MemoryCallOptions, type MemoryChangeSource, type MemoryChangedEvent, type MemoryChangedHandler, MemoryIndexManager, type MemoryProvider, type MemoryProviderContext, type MemoryProviderFactory, type MemoryProviderRegistration, type MemoryProviderStatus, type MemorySearchOptions, type MemorySearchResult, type NormalizedPluginsConfig, PLUGIN_MANIFEST_FILENAME, PLUGIN_MANIFEST_FILENAMES, type PersistedSubagentRunRecord, type PersistedToolResult, type PluginApi, type PluginCandidate, type PluginConfigUiHint, type PluginCustomProgressInput, type PluginDiagnostic, type PluginDiscoveryOptions, type PluginDiscoveryResult, type PluginEntryConfig, type PluginExecutionRuntime, type PluginHookAfterCompactionEvent, type PluginHookAfterPromptBuildEvent, type PluginHookAfterToolCallEvent, type PluginHookAgentContext, type PluginHookAgentEndEvent, type PluginHookAssistantMessageEndEvent, type PluginHookBeforeCompactionEvent, type PluginHookBeforeModelResolveEvent, type PluginHookBeforeModelResolveResult, type PluginHookBeforePromptBuildEvent, type PluginHookBeforePromptBuildResult, type PluginHookBeforeToolCallEvent, type PluginHookBeforeToolCallResult, type PluginHookHandlerMap, type PluginHookLlmInputEvent, type PluginHookLlmOutputEvent, type PluginHookMemoryChangedEvent, type PluginHookName, PluginHookRegistry, type PluginHookSessionEndEvent, type PluginHookSessionResetEvent, type PluginHookSessionStartEvent, type PluginKind, type PluginManifest, type PluginManifestLoadResult, type PluginManifestRegistry, type PluginOrigin, type PluginProgressEmitter, type PluginRecord, type PluginRegistry, type PluginRuntime, type PluginRuntimeContext, type PluginSystem, type PluginSystemOptions, type PluginToolOptions, PluginToolRegistry, type PluginUiToolDescriptor, type PluginUiToolOptions, type PluginsConfig, type PluginsConfigValidationResult, type RegisteredPluginTool, type ResumeOptions, type ResumeValidationResult, type RunResultPayload, type SessionContextStore, type SessionExport, type SessionInspection, type SessionMetadata, type SessionMetadataUpdate, type SessionSummary, type Skill, type SlashCommandList, type SubagentContext, SubagentRegistry, type SubagentRunRecord, type SubagentStatus, type SubagentToolsContext, type SystemPromptParams, type ToolLoopDetectionConfig, type TranscriptEntry, type UiToolOptions, UiToolPauseSignal, addAgent, addBinding, aimaxDir, appendToMemory, appendTranscriptEntry, approvalSummaryFromResolution, bootstrapMountLayout, buildBootstrapContextFiles, buildResumeNarration, buildSkillsPrompt, buildSubagentAnnounceMessage, buildSystemPrompt, cleanupOldSubagentRecords, clearPendingHitl, clearPendingUiTool, collapseLogPath, contextSnapshotPath, createAgentTools, createApplyPatchTool, createBashTool, createBuiltinMemoryProvider, createClarifyTool, createContextManager, createEditFileTool, createExecTool, createImageTool, createListDirTool, createMemoryAppendTool, createMemoryGetTool, createMemorySearchTool, createPendingHitl, createPendingUiTool, createPluginProgressEmitter, createPluginRuntime, createProcessTool, createReadFileTool, createRequestApprovalTool, createRequestReviewTool, createSession, createSessionContextStore, createSessionsSpawnTool, createSubagentsTool, createUiTool, createWriteFileTool, deleteMemoryFile, discoverAIMaxPlugins, ensureBootstrapMountLayout, ensureSession, exportSession, formatApprovalResolution, formatClarifyResolution, formatReviewResolution, generateSessionTitle, getAgentConfig, getMemoryLines, hasBootstrapSentinel, hitlHistoryPath, initializePluginSystem, inspectBootstrapMountLayout, inspectSession, isBootstrapMountLayoutReady, isHitlPauseSignal, isUiToolPauseSignal, listAgents, listAvailableSlashCommands, listBindings, listMemoryFiles, listSessionSummaries, listSessions, listSubagentRunsFromDisk, loadAgentsConfig, loadBootstrapFiles, readPendingHitl as loadPendingHitl, readPendingHitl, readPendingUiTool as loadPendingUiTool, readPendingUiTool, loadPluginManifest, loadPluginManifestRegistry, loadPlugins, loadSessionContextSnapshot, loadSessionMetadata, loadSkills, loadSkillsFromDirs, loadSkillsWithPluginDirs, loadSubagentRegistryFromDisk, loadTranscript, memoryDir, metadataPath, normalizeAgentId, normalizePluginsConfig, normalizeSessionStoreName, pendingHitlPath, pendingUiToolPath, primaryMemoryPath, readHitlHistory, readMemoryFile, readPrimaryMemory, registerEmbeddingProvider, registerMemoryProvider, removeAgent, removeBindings, replaceMemoryFile, resetEmbeddingProviderRegistryForTests, resetMemoryProviderRegistryForTests, resolveAgentDir, resolveAgentIdByBinding, resolveAgentsConfigPath, resolveDefaultAgentId, resolveEmbeddingProvider, resolveHitlRequest, resolveHitlRequest as resolvePendingHitl, resolveMemoryProvider, resolveModelFallbacks, resolveModelString, resolvePendingUiTool, resolvePluginManifestPath, rewriteTranscript, runAgent, saveAgentsConfig, saveSessionMetadata, saveSubagentRegistryToDisk, searchMemory, sessionDir, sessionMemoryPath, sessionsDir, skillsDir, toolResultsDir, transcriptPath, transitionHitlStatus, updateAgentIdentity, updateSessionMetadata, validatePluginsConfig, validateResume, wrapToolsWithHooks };
2236
+ export { AgentBinding, AgentConfig, type AgentCustomProgressEvent, AgentModelConfig, type AgentProgressEvent, type AgentRunParams, type AgentRunResult, AgentsConfig, BOOTSTRAP_FILE_NAMES, BOOTSTRAP_MAX_CHARS, BOOTSTRAP_TOTAL_MAX_CHARS, type BootstrapContextFile, type BootstrapEnsureResult, type BootstrapFile, type BootstrapMountResult, type BootstrapMountStatus, type CallbackEventPayload, type CallbackPayload, type Channel, type ContextManager, DEFAULT_SESSION_STORE_NAME, type EmbeddingProvider, type EmbeddingProviderContext, type EmbeddingProviderFactory, type EmbeddingProviderRegistration, HITL_MESSAGES, type HitlPauseContext, HitlPauseSignal, type HitlToolContext, MAX_CHILDREN_PER_SESSION, MAX_SUBAGENT_DEPTH, type MemoryCallOptions, type MemoryChangeSource, type MemoryChangedEvent, type MemoryChangedHandler, MemoryIndexManager, type MemoryProvider, type MemoryProviderContext, type MemoryProviderFactory, type MemoryProviderRegistration, type MemoryProviderStatus, type MemorySearchOptions, type MemorySearchResult, type NormalizedPluginsConfig, PLUGIN_MANIFEST_FILENAME, PLUGIN_MANIFEST_FILENAMES, type PersistedSubagentRunRecord, type PersistedToolResult, type PluginApi, type PluginCandidate, type PluginConfigUiHint, type PluginCustomProgressInput, type PluginDiagnostic, type PluginDiscoveryOptions, type PluginDiscoveryResult, type PluginEntryConfig, type PluginExecutionRuntime, type PluginHookAfterCompactionEvent, type PluginHookAfterPromptBuildEvent, type PluginHookAfterToolCallEvent, type PluginHookAgentContext, type PluginHookAgentEndEvent, type PluginHookAssistantMessageEndEvent, type PluginHookBeforeCompactionEvent, type PluginHookBeforeModelResolveEvent, type PluginHookBeforeModelResolveResult, type PluginHookBeforePromptBuildEvent, type PluginHookBeforePromptBuildResult, type PluginHookBeforeToolCallEvent, type PluginHookBeforeToolCallResult, type PluginHookHandlerMap, type PluginHookLlmInputEvent, type PluginHookLlmOutputEvent, type PluginHookMemoryChangedEvent, type PluginHookName, PluginHookRegistry, type PluginHookSessionEndEvent, type PluginHookSessionResetEvent, type PluginHookSessionStartEvent, type PluginKind, type PluginManifest, type PluginManifestLoadResult, type PluginManifestRegistry, type PluginOrigin, type PluginProgressEmitter, type PluginRecord, type PluginRegistry, type PluginRuntime, type PluginRuntimeContext, type PluginSystem, type PluginSystemOptions, type PluginToolOptions, PluginToolRegistry, type PluginUiToolDescriptor, type PluginUiToolOptions, type PluginsConfig, type PluginsConfigValidationResult, type RegisteredPluginTool, type ResumeOptions, type ResumeValidationResult, type RunResultPayload, type SessionContextStore, type SessionExport, type SessionInspection, type SessionMetadata, type SessionMetadataUpdate, type SessionSummary, type Skill, type SlashCommandList, type SubagentContext, SubagentRegistry, type SubagentRunRecord, type SubagentStatus, type SubagentToolsContext, type SystemPromptParams, type ToolLoopDetectionConfig, type TranscriptEntry, type UiToolInputSchema, type UiToolOptions, UiToolPauseSignal, addAgent, addBinding, aimaxDir, appendToMemory, appendTranscriptEntry, approvalSummaryFromResolution, bootstrapMountLayout, buildBootstrapContextFiles, buildResumeNarration, buildSkillsPrompt, buildSubagentAnnounceMessage, buildSystemPrompt, cleanupOldSubagentRecords, clearPendingHitl, clearPendingUiTool, collapseLogPath, contextSnapshotPath, createAgentTools, createApplyPatchTool, createBashTool, createBuiltinMemoryProvider, createClarifyTool, createContextManager, createEditFileTool, createExecTool, createImageTool, createListDirTool, createMemoryAppendTool, createMemoryGetTool, createMemorySearchTool, createPendingHitl, createPendingUiTool, createPluginProgressEmitter, createPluginRuntime, createProcessTool, createReadFileTool, createRequestApprovalTool, createRequestReviewTool, createSession, createSessionContextStore, createSessionsSpawnTool, createSubagentsTool, createUiTool, createWriteFileTool, defaultUiToolInputSchema, deleteMemoryFile, discoverAIMaxPlugins, ensureBootstrapMountLayout, ensureSession, exportSession, formatApprovalResolution, formatClarifyResolution, formatReviewResolution, generateSessionTitle, getAgentConfig, getMemoryLines, hasBootstrapSentinel, hitlHistoryPath, initializePluginSystem, inspectBootstrapMountLayout, inspectSession, isBootstrapMountLayoutReady, isHitlPauseSignal, isUiToolPauseSignal, listAgents, listAvailableSlashCommands, listBindings, listMemoryFiles, listSessionSummaries, listSessions, listSubagentRunsFromDisk, loadAgentsConfig, loadBootstrapFiles, readPendingHitl as loadPendingHitl, readPendingHitl, readPendingUiTool as loadPendingUiTool, readPendingUiTool, loadPluginManifest, loadPluginManifestRegistry, loadPlugins, loadSessionContextSnapshot, loadSessionMetadata, loadSkills, loadSkillsFromDirs, loadSkillsWithPluginDirs, loadSubagentRegistryFromDisk, loadTranscript, memoryDir, metadataPath, normalizeAgentId, normalizePluginsConfig, normalizeSessionStoreName, pendingHitlPath, pendingUiToolPath, primaryMemoryPath, readHitlHistory, readMemoryFile, readPrimaryMemory, registerEmbeddingProvider, registerMemoryProvider, removeAgent, removeBindings, replaceMemoryFile, resetEmbeddingProviderRegistryForTests, resetMemoryProviderRegistryForTests, resolveAgentDir, resolveAgentIdByBinding, resolveAgentsConfigPath, resolveDefaultAgentId, resolveEmbeddingProvider, resolveHitlRequest, resolveHitlRequest as resolvePendingHitl, resolveMemoryProvider, resolveModelFallbacks, resolveModelString, resolvePendingUiTool, resolvePluginManifestPath, rewriteTranscript, runAgent, saveAgentsConfig, saveSessionMetadata, saveSubagentRegistryToDisk, searchMemory, sessionDir, sessionMemoryPath, sessionsDir, skillsDir, toolResultsDir, transcriptPath, transitionHitlStatus, updateAgentIdentity, updateSessionMetadata, validatePluginsConfig, validateResume, wrapToolsWithHooks };
package/dist/index.js CHANGED
@@ -47,7 +47,7 @@ import{A as e,C as t,D as n,E as r,O as i,S as a,T as o,_ as s,a as c,b as l,c a
47
47
  `))}const ui=L.Object({question:L.String({description:`The question to ask the user.`}),options:L.Optional(L.Array(L.String(),{description:`Optional list of choices for the user to select from.`})),allow_free_text:L.Optional(L.Boolean({description:`Whether to allow the user to type a free-text response in addition to choices. Defaults to true.`}))});function di(e,t){return{name:`clarify`,label:Y.clarify.label,description:Y.clarify.description,parameters:ui,async execute(n,r){if(t?.request.kind===`clarify`&&t.toolContext?.toolName===`clarify`&&t.toolContext.toolCallId===n)return{content:[{type:`text`,text:si(t.resolution)}],details:{paused:!1}};let i=z(),a=r.options&&r.options.length>0,o;throw o=a?{mode:`choice`,choices:r.options.map((e,t)=>({id:`option-${t}`,label:e})),allowFreeText:r.allow_free_text!==!1}:{mode:`text`,multiline:!0,placeholder:Y.clarify.placeholder},new K({requestId:i,sessionId:e,kind:`clarify`,title:Y.clarify.title,prompt:r.question,input:o,policy:{resumable:!0},createdAt:new Date().toISOString()},{turnId:n,phase:`before_tool`,resumeStrategy:`reenter_from_checkpoint`},{toolCallId:n,toolName:`clarify`,toolArgs:r})}}}function fi(e){return I.join(e,`.aimax`)}function pi(e){return I.join(fi(e),`MEMORY.md`)}async function mi(e,t,n){e.onMemoryChanged&&await Promise.resolve(e.onMemoryChanged(n)).catch(()=>{}),t&&await Promise.resolve(t(n)).catch(()=>{})}function hi(e,t){let n=fi(e),r=k({providerId:t?.providerId,pluginId:t?.pluginId,dataDir:e,memoryDir:n,sessionId:t?.sessionId});return r?r.provider:y({dataDir:e,memoryDir:n,sessionId:t?.sessionId})}async function gi(e){return C(fi(e))}async function _i(e){try{return await F.readFile(e,`utf-8`)}catch(e){if(e.code===`ENOENT`)return null;throw e}}async function vi(e){return _i(pi(e))}async function yi(e,t,n){return await hi(e,n).search(t)}async function bi(e,t,n,r,i){try{return await hi(e,i).getLines(t,n,r)}catch{return null}}async function xi(e,t,n){let r=hi(e,n);await r.append(t),await mi(r,n?.onMemoryChanged,{reason:`append`,files:[`MEMORY.md`],source:`memory`,sessionId:n?.sessionId,providerId:n?.providerId??n?.pluginId,timestamp:new Date().toISOString()})}async function Si(e,t,n,r){let i=hi(e,r);await i.updateFile(t,n),await mi(i,r?.onMemoryChanged,{reason:`update`,files:[t],source:`memory`,sessionId:r?.sessionId,providerId:r?.providerId??r?.pluginId,timestamp:new Date().toISOString()})}async function Ci(e,t,n){let r=hi(e,n);await r.deleteFile(t),await mi(r,n?.onMemoryChanged,{reason:`delete`,files:[t],source:`memory`,sessionId:n?.sessionId,providerId:n?.providerId??n?.pluginId,timestamp:new Date().toISOString()})}const wi=L.Object({query:L.String({description:`Search query (case-insensitive substring match)`})});function Ti(e,t){return{name:`memory_search`,label:`Memory Search`,description:`Search memory files for relevant information`,parameters:wi,async execute(n,r){let i=(await yi(e,r.query,{providerId:t?.providerId,pluginId:t?.pluginId,sessionId:t?.sessionId})).map(e=>({file:e.path,start_line:e.startLine,end_line:e.endLine,score:Number(e.score.toFixed(4)),text:e.snippet,source:e.source,citation:e.citation}));return i.length===0?{content:[{type:`text`,text:`No results found for: ${r.query}`}],details:{matches:i}}:{content:[{type:`text`,text:i.map(e=>{let t=`${e.file}:${e.start_line}-${e.end_line} (${e.score}): ${e.text}`;return e.citation?`${t}\n${e.citation}`:t}).join(`
48
48
  `)}],details:{matches:i}}}}}const Ei=L.Object({file:L.String({description:`Memory file path`}),start_line:L.Number({description:`Start line number (1-based)`}),end_line:L.Number({description:`End line number (1-based)`})});function Di(e,t){return{name:`memory_get`,label:`Memory Get`,description:`Read specific lines from a memory file`,parameters:Ei,async execute(n,r){let i=await bi(e,r.file,r.start_line,r.end_line,{providerId:t?.providerId,pluginId:t?.pluginId,sessionId:t?.sessionId});return i===null?{content:[{type:`text`,text:`File not found: ${r.file}`}],details:{lines:null}}:{content:[{type:`text`,text:i.map((e,t)=>`${(r.start_line+t).toString().padStart(4)} ${e}`).join(`
49
49
  `)||`(empty)`}],details:{lines:i}}}}}const Oi=L.Object({content:L.String({description:`Content to append to MEMORY.md`})});function ki(e,t){return{name:`memory_append`,label:`Memory Append`,description:`Append new information to the MEMORY.md file`,parameters:Oi,async execute(n,r){try{return await xi(e,r.content,{providerId:t?.providerId,pluginId:t?.pluginId,sessionId:t?.sessionId,onMemoryChanged:t?.onMemoryChanged}),{content:[{type:`text`,text:`Memory updated.`}],details:{appended:!0}}}catch(e){return{content:[{type:`text`,text:`Error appending to memory: ${e instanceof Error?e.message:String(e)}`}],details:{appended:!1}}}}}}const Ai=L.Object({action:L.String({description:`A short description of the action that needs approval.`}),reason:L.String({description:`Why this action needs human approval.`}),details:L.Optional(L.String({description:`Additional details about the action (e.g. the command to execute).`}))});function ji(e){let t=e.action===`submit`&&(e.values?.selectedChoiceIds?.includes(`approve`)??!1);return JSON.stringify({summary:oi(e),action:e.action,approved:t,values:e.values??{},submittedBy:e.submittedBy,submittedAt:e.submittedAt,idempotencyKey:e.idempotencyKey})}function Mi(e,t){return{name:`request_approval`,label:Y.approval.label,description:Y.approval.description,parameters:Ai,async execute(n,r){if(t?.request.kind===`approval`&&t.toolContext?.toolName===`request_approval`&&t.toolContext.toolCallId===n&&t.resolution.action===`submit`)return{content:[{type:`text`,text:ji(t.resolution)}],details:{paused:!1,approved:t.resolution.values?.selectedChoiceIds?.includes(`approve`)??!1,resolution:t.resolution}};let i=z(),a;throw r.details&&(a={mimeType:`text/plain`,content:r.details}),new K({requestId:i,sessionId:e,kind:`approval`,title:r.action,prompt:r.reason,preview:a,input:{mode:`choice`,choices:[{id:`approve`,label:Y.approval.choices.approve.label,description:Y.approval.choices.approve.description},{id:`deny`,label:Y.approval.choices.deny.label,description:Y.approval.choices.deny.description}]},policy:{resumable:!0,defaultOnTimeout:`deny`},createdAt:new Date().toISOString()},{turnId:n,phase:`before_tool`,resumeStrategy:`reenter_from_checkpoint`},{toolCallId:n,toolName:`request_approval`,toolArgs:r})}}}const Ni=L.Object({title:L.String({description:`A short title for the review (e.g. 'Weekly Report Draft').`}),description:L.String({description:`What the user should review and what kind of feedback you need.`}),content:L.String({description:`The content to review (text, markdown, or JSON).`}),content_type:L.Optional(L.String({description:`MIME type: text/plain, application/json, or text/markdown. Defaults to text/markdown.`}))});function Pi(e,t){return{name:`request_review`,label:Y.review.label,description:Y.review.description,parameters:Ni,async execute(n,r){if(t?.request.kind===`review`&&t.toolContext?.toolName===`request_review`&&t.toolContext.toolCallId===n)return{content:[{type:`text`,text:ci(t.resolution)}],details:{paused:!1}};let i=z(),a={mimeType:r.content_type??`text/markdown`,content:r.content};throw new K({requestId:i,sessionId:e,kind:`review`,title:r.title,prompt:r.description,preview:a,input:{mode:`choice`,choices:[{id:`approve`,label:Y.review.choices.approve.label,description:Y.review.choices.approve.description},{id:`revise`,label:Y.review.choices.revise.label,description:Y.review.choices.revise.description},{id:`reject`,label:Y.review.choices.reject.label,description:Y.review.choices.reject.description}],allowFreeText:!0},policy:{resumable:!0},createdAt:new Date().toISOString()},{turnId:n,phase:`before_tool`,resumeStrategy:`reenter_from_checkpoint`},{toolCallId:n,toolName:`request_review`,toolArgs:r})}}}const Fi=L.Object({task:L.String({description:`The task description for the subagent to execute`}),label:L.Optional(L.String({description:`Optional short label to identify this subagent`}))});function Ii(e){let t=e.label?`"${e.label}"`:`task: ${e.task}`;return e.status===`done`?`[Subagent completed] ${t}\n\n${e.result??`(no output)`}`:e.status===`error`?`[Subagent failed] ${t}\n\nError: ${e.error??`unknown error`}`:`[Subagent killed] ${t}`}function Li(e,t,n,r,i,a,o,s,c){return{name:`sessions_spawn`,label:`Spawn Subagent`,description:`Use this tool only when the user or system instructions explicitly require using a subagent, delegation, or parallel agent execution. Do not use it for routine decomposition or inferred parallelism. Returns immediately with status=accepted; the subagent result will be delivered back automatically as a follow-up message — do not poll or sleep.`,parameters:Fi,async execute(l,u){let d=u.task.trim(),p=u.label?.trim();if(!d){let e={status:`error`,error:`task must not be empty`};return{content:[{type:`text`,text:JSON.stringify(e)}],details:e}}let m=e.checkSpawnAllowed(t,n+1);if(!m.allowed){let e={status:`forbidden`,error:m.reason};return{content:[{type:`text`,text:JSON.stringify(e)}],details:e}}let h=z(),g=new AbortController,_;try{_=await f(r,i,{storeName:s.sessionStoreName})}catch(e){let t={status:`error`,error:`Failed to create session: ${e instanceof Error?e.message:String(e)}`};return{content:[{type:`text`,text:JSON.stringify(t)}],details:t}}let v={runId:h,childSessionId:_,parentSessionId:t,task:d,label:p,depth:n+1,status:`running`,startedAt:Date.now(),abortController:g},y=c({dataDir:r,sessionId:_,message:d,channel:i,llm:a,...s,loopDetection:o,abortSignal:g.signal,subagentContext:{depth:n+1,parentSessionId:t}}).then(t=>{e.complete(h,t.text||t.error||`(no output)`)}).catch(t=>{let n=t instanceof Error?t.message:String(t);e.fail(h,n)});e.register(v,y);let b={status:`accepted`,childSessionId:_,runId:h,note:`The subagent result will be sent back automatically. Do not poll or re-spawn.`};return{content:[{type:`text`,text:JSON.stringify(b)}],details:b}}}}const Ri=L.Object({action:L.Union([`list`,`kill`].map(e=>L.Literal(e)),{description:`Action to perform: "list" to show subagents, "kill" to stop one or all`}),target:L.Optional(L.String({description:`For kill: a runId, label, or index from the list. Use "*" or "all" to kill every subagent.`}))});function zi(e){return e<1e3?`${e}ms`:e<6e4?`${(e/1e3).toFixed(1)}s`:`${Math.floor(e/6e4)}m${Math.floor(e%6e4/1e3)}s`}function Bi(e,t){let n=parseInt(t,10);return!isNaN(n)&&n>=1&&n<=e.length?e[n-1]:e.find(e=>e.runId.startsWith(t)||e.runId===t)||(e.find(e=>e.label&&e.label.toLowerCase()===t.toLowerCase())??null)}function Vi(e,t){return{name:`subagents`,label:`Subagents`,description:`List or kill subagents spawned by this session. Use list to check status, kill to stop one or all.`,parameters:Ri,async execute(n,r){let i=r.action,a=Date.now(),o=e.list(t);if(i===`list`){let e=o.map((e,t)=>({index:t+1,runId:e.runId,label:e.label??e.task.slice(0,40),task:e.task,status:e.status,depth:e.depth,runtimeMs:e.endedAt?e.endedAt-e.startedAt:a-e.startedAt})),t={action:`list`,runs:e,text:(e.length===0?[`(no subagents)`]:e.map(e=>`${e.index}. [${e.status}] ${e.label} (${zi(e.runtimeMs)})`)).join(`
50
- `)};return{content:[{type:`text`,text:JSON.stringify(t)}],details:t}}if(i===`kill`){let n=r.target?.trim();if(!n||n===`*`||n===`all`){let n=e.killAll(t),r={action:`kill`,killed:n,text:n>0?`Killed ${n} subagent(s).`:`No running subagents to kill.`};return{content:[{type:`text`,text:JSON.stringify(r)}],details:r}}let i=Bi(o,n);if(!i){let e={action:`kill`,killed:0,error:`No subagent found matching "${n}". Use list to see available subagents.`,text:`Error: no subagent matching "${n}"`};return{content:[{type:`text`,text:JSON.stringify(e)}],details:e}}let a=e.kill(i.runId),s=i.label??i.task.slice(0,40),c={action:`kill`,killed:a?1:0,text:a?`Killed subagent "${s}".`:`Subagent "${s}" is already finished.`};return{content:[{type:`text`,text:JSON.stringify(c)}],details:c}}let s={action:i,error:`Unsupported action.`,text:`Error: unsupported action.`};return{content:[{type:`text`,text:JSON.stringify(s)}],details:s}}}}const Hi=L.Object({image:L.String({description:`Image path or URL`}),prompt:L.Optional(L.String({description:`Prompt for image analysis`})),model:L.Optional(L.String({description:`Optional model override`})),maxBytesMb:L.Optional(L.Number({description:`Optional size cap in MB`}))});function Ui(){return{name:`image`,label:`Image`,description:`Analyze an image with the configured image model. (Not implemented in AIMax yet.)`,parameters:Hi,async execute(e,t){let n={implemented:!1,error:`image tool not implemented (awaiting third-party integration).`};return{content:[{type:`text`,text:`Error: ${n.error}`}],details:n}}}}var Wi=class extends Error{isUiToolPause=!0;request;constructor(e,t,n,r,i,a,o){super(`UI_TOOL_PAUSED`),this.toolArgs=o,this.name=`UiToolPauseSignal`,this.request={requestId:e,sessionId:t,toolName:n,toolCallId:r,schema:i,extra:a,createdAt:new Date().toISOString()}}};function Gi(e){return!!(e instanceof Wi||typeof e==`object`&&e&&`isUiToolPause`in e&&e.isUiToolPause===!0)}const Ki=new Fe;function qi(){return{}}async function Ji(e,t){return await Ki.run(e,t)}function Yi(e){let t=Ki.getStore();!t||t.signal||(t.signal=e)}const Xi=L.Object({reason:L.String({description:`A brief explanation of why user input is needed through this UI form.`})});function Zi(e){let{name:t,label:n,description:r,sessionId:i,schema:a,extra:o,validate:s,resume:c}=e;return{name:t,label:n,description:r,parameters:Xi,async execute(e,n){if(c&&c.toolCallId===e&&c.toolName===t&&c.sessionId===i){let e=Pe(a,c.values);if(!e.valid){let t=e.errors;return{content:[{type:`text`,text:JSON.stringify({error:`validation_failed`,errors:t})}],details:{}}}if(s){let e=await s(c.values);if(!e.valid){let t=e.errors;return{content:[{type:`text`,text:JSON.stringify({error:`validation_failed`,errors:t})}],details:{}}}}return{content:[{type:`text`,text:JSON.stringify({submitted:!0,values:c.values})}],details:{}}}let r=new Wi(e,i,t,e,a,o,n);throw Yi(r),r}}}function Qi(e,t){let n=I.join(e,`workspace`),r=t?.memoryOptions,i=Ar(),a=[_r({sessionId:t?.sessionId,workspaceDir:n,registry:i,scopeKey:n,contextManager:t?.contextManager,hitlResume:t?.hitlResume}),xr({registry:i,scopeKey:n}),Ir(n,t?.contextManager),Rr(n,t?.contextManager),Br(n,t?.contextManager),Hr(n),Jr(n,{sessionId:t?.sessionId,hitlResume:t?.hitlResume}),Ti(e,r),Di(e,r),ki(e,r),...t?.sessionId?[di(t.sessionId,t.hitlResume),Mi(t.sessionId,t.hitlResume),Pi(t.sessionId,t.hitlResume)]:[]];return t&&a.push(Li(t.registry,t.parentSessionId,t.depth,e,t.channel,t.llm,t.loopDetection,t.inheritedRunParams??{},t.spawnFn),Vi(t.registry,t.parentSessionId)),a}const $i={read_file:`Read file contents`,write_file:`Create or overwrite files`,edit_file:`Make precise edits to files`,list_dir:`List directory contents`,apply_patch:`Apply multi-file patches`,exec:`Run shell commands`,process:`Manage background exec sessions`,memory_search:`Search memory files for relevant information`,memory_get:`Read specific lines from memory files`,memory_append:`Append new long-term memory`,sessions_spawn:`Spawn an isolated subagent session`,subagents:`List, steer, or kill subagent runs`},ea=[`read_file`,`write_file`,`edit_file`,`list_dir`,`apply_patch`,`exec`,`process`,`memory_search`,`memory_get`,`memory_append`,`sessions_spawn`,`subagents`];function ta(e){let t=new Map;for(let n of e){let e=n.trim();if(!e)continue;let r=e.toLowerCase();t.has(r)||t.set(r,e)}let n=Array.from(t.keys());return{ordered:[...ea.filter(e=>t.has(e)),...n.filter(e=>!ea.includes(e)).sort()],displayName:t}}function na(e){let{ordered:t,displayName:n}=ta(e.toolNames),r=new Map;for(let[t,n]of Object.entries(e.toolSummaries??{})){let e=t.trim().toLowerCase();!e||!n?.trim()||r.set(e,n.trim())}return[`## Tooling`,`Tool availability (filtered by runtime policy):`,`Tool names are case-sensitive. Call tools exactly as listed.`,t.map(e=>{let t=n.get(e)??e,i=r.get(e)??$i[e];return i?`- ${t}: ${i}`:`- ${t}`}).join(`
50
+ `)};return{content:[{type:`text`,text:JSON.stringify(t)}],details:t}}if(i===`kill`){let n=r.target?.trim();if(!n||n===`*`||n===`all`){let n=e.killAll(t),r={action:`kill`,killed:n,text:n>0?`Killed ${n} subagent(s).`:`No running subagents to kill.`};return{content:[{type:`text`,text:JSON.stringify(r)}],details:r}}let i=Bi(o,n);if(!i){let e={action:`kill`,killed:0,error:`No subagent found matching "${n}". Use list to see available subagents.`,text:`Error: no subagent matching "${n}"`};return{content:[{type:`text`,text:JSON.stringify(e)}],details:e}}let a=e.kill(i.runId),s=i.label??i.task.slice(0,40),c={action:`kill`,killed:a?1:0,text:a?`Killed subagent "${s}".`:`Subagent "${s}" is already finished.`};return{content:[{type:`text`,text:JSON.stringify(c)}],details:c}}let s={action:i,error:`Unsupported action.`,text:`Error: unsupported action.`};return{content:[{type:`text`,text:JSON.stringify(s)}],details:s}}}}const Hi=L.Object({image:L.String({description:`Image path or URL`}),prompt:L.Optional(L.String({description:`Prompt for image analysis`})),model:L.Optional(L.String({description:`Optional model override`})),maxBytesMb:L.Optional(L.Number({description:`Optional size cap in MB`}))});function Ui(){return{name:`image`,label:`Image`,description:`Analyze an image with the configured image model. (Not implemented in AIMax yet.)`,parameters:Hi,async execute(e,t){let n={implemented:!1,error:`image tool not implemented (awaiting third-party integration).`};return{content:[{type:`text`,text:`Error: ${n.error}`}],details:n}}}}var Wi=class extends Error{isUiToolPause=!0;request;constructor(e,t,n,r,i,a,o){super(`UI_TOOL_PAUSED`),this.toolArgs=o,this.name=`UiToolPauseSignal`,this.request={requestId:e,sessionId:t,toolName:n,toolCallId:r,outputSchema:i,extra:a,createdAt:new Date().toISOString()}}};function Gi(e){return!!(e instanceof Wi||typeof e==`object`&&e&&`isUiToolPause`in e&&e.isUiToolPause===!0)}const Ki=new Fe;function qi(){return{}}async function Ji(e,t){return await Ki.run(e,t)}function Yi(e){let t=Ki.getStore();!t||t.signal||(t.signal=e)}const Xi=L.Object({reason:L.String({description:`A brief explanation of why user input is needed through this UI form.`})});function Zi(e){let{name:t,label:n,description:r,sessionId:i,inputSchema:a,outputSchema:o,extra:s,validate:c,resume:l}=e;return{name:t,label:n,description:r,parameters:a??Xi,async execute(e,n){if(l&&l.toolCallId===e&&l.toolName===t&&l.sessionId===i){let e=Pe(o,l.values);if(!e.valid){let t=e.errors;return{content:[{type:`text`,text:JSON.stringify({error:`validation_failed`,errors:t})}],details:{}}}if(c){let e=await c(l.values);if(!e.valid){let t=e.errors;return{content:[{type:`text`,text:JSON.stringify({error:`validation_failed`,errors:t})}],details:{}}}}return{content:[{type:`text`,text:JSON.stringify({submitted:!0,values:l.values})}],details:{}}}let r=new Wi(e,i,t,e,o,s,n);throw Yi(r),r}}}function Qi(e,t){let n=I.join(e,`workspace`),r=t?.memoryOptions,i=Ar(),a=[_r({sessionId:t?.sessionId,workspaceDir:n,registry:i,scopeKey:n,contextManager:t?.contextManager,hitlResume:t?.hitlResume}),xr({registry:i,scopeKey:n}),Ir(n,t?.contextManager),Rr(n,t?.contextManager),Br(n,t?.contextManager),Hr(n),Jr(n,{sessionId:t?.sessionId,hitlResume:t?.hitlResume}),Ti(e,r),Di(e,r),ki(e,r),...t?.sessionId?[di(t.sessionId,t.hitlResume),Mi(t.sessionId,t.hitlResume),Pi(t.sessionId,t.hitlResume)]:[]];return t&&a.push(Li(t.registry,t.parentSessionId,t.depth,e,t.channel,t.llm,t.loopDetection,t.inheritedRunParams??{},t.spawnFn),Vi(t.registry,t.parentSessionId)),a}const $i={read_file:`Read file contents`,write_file:`Create or overwrite files`,edit_file:`Make precise edits to files`,list_dir:`List directory contents`,apply_patch:`Apply multi-file patches`,exec:`Run shell commands`,process:`Manage background exec sessions`,memory_search:`Search memory files for relevant information`,memory_get:`Read specific lines from memory files`,memory_append:`Append new long-term memory`,sessions_spawn:`Spawn an isolated subagent session`,subagents:`List, steer, or kill subagent runs`},ea=[`read_file`,`write_file`,`edit_file`,`list_dir`,`apply_patch`,`exec`,`process`,`memory_search`,`memory_get`,`memory_append`,`sessions_spawn`,`subagents`];function ta(e){let t=new Map;for(let n of e){let e=n.trim();if(!e)continue;let r=e.toLowerCase();t.has(r)||t.set(r,e)}let n=Array.from(t.keys());return{ordered:[...ea.filter(e=>t.has(e)),...n.filter(e=>!ea.includes(e)).sort()],displayName:t}}function na(e){let{ordered:t,displayName:n}=ta(e.toolNames),r=new Map;for(let[t,n]of Object.entries(e.toolSummaries??{})){let e=t.trim().toLowerCase();!e||!n?.trim()||r.set(e,n.trim())}return[`## Tooling`,`Tool availability (filtered by runtime policy):`,`Tool names are case-sensitive. Call tools exactly as listed.`,t.map(e=>{let t=n.get(e)??e,i=r.get(e)??$i[e];return i?`- ${t}: ${i}`:`- ${t}`}).join(`
51
51
  `),``].join(`
52
52
  `)}function ra(){return[`## Safety`,`You have no independent goals: do not pursue self-preservation, replication, resource acquisition, or power-seeking; avoid long-term plans beyond the user's request.`,`Prioritize safety and human oversight over completion; if instructions conflict, pause and ask; comply with stop/pause/audit requests and never bypass safeguards.`,`Do not attempt to bypass approvals, safety rails, or access boundaries.`,`Never print, reveal, or echo environment variable values. If configuration must be shown, use placeholders plus brief meanings instead, such as {{API_KEY}}: model access credential.`,``].join(`
53
53
  `)}function ia(e){return e?``:[`## Tool Call Style`,`Default: call routine low-risk tools directly without narrating every step.`,`Narrate briefly when actions are sensitive, long-running, or likely surprising.`,`When approvals are required, keep the command text exact and complete.`,``].join(`
@@ -69,7 +69,7 @@ import{A as e,C as t,D as n,E as r,O as i,S as a,T as o,_ as s,a as c,b as l,c a
69
69
  `)}function ya(e){return e?.trim()?[`## Prior Conversation Summary`,`The following is a summary of the conversation history that occurred before the current context window.`,`Use it to maintain continuity with earlier work.`,``,e.trim(),``].join(`
70
70
  `):``}function ba(e){let t=e.promptMode??`full`,n=t===`minimal`;if(t===`none`)return`You are a personal assistant running inside AiMax.`;let r=e.toolNames&&e.toolNames.length>0?e.toolNames:[...ea],i=e.skills??[],a=e.contextFiles??[];return[`You are a personal assistant running inside AiMax.
71
71
  `,na({toolNames:r,toolSummaries:e.toolSummaries}),ia(n),ra(),aa(i),oa(),sa(),ca(e.memoryCitationsMode??`off`),la({dataDir:e.dataDir,sandboxInfo:e.sandboxInfo}),ua(e.sandboxInfo),da({currentDate:e.currentDate,timezone:e.timezone}),pa({isMinimal:n,enabled:e.messaging?.enabled,channels:e.messaging?.channels}),ma({isMinimal:n,docs:e.docs}),ga({isMinimal:n}),_a({isMinimal:n,heartbeatPrompt:e.heartbeatPrompt}),ha(e.runtimeInfo),va({contextFiles:a,bootstrapWarnings:e.bootstrapWarnings}),ya(e.priorConversationSummary)].filter(Boolean).join(`
72
- `)}const xa=new Fe;async function Sa(e,t){return await xa.run(e,t)}function Ca(e){return{async emit(t){let n=xa.getStore();if(!n||n.pluginId!==e)throw Error(`Plugin ${e} cannot emit progress outside its runtime context`);if(!n.hookContext.sessionId)throw Error(`Plugin ${e} cannot emit progress without an active session`);await n.eventDispatcher.dispatchProgress(n.hookContext.sessionId,{type:`custom`,pluginId:e,name:t.name,label:t.label,data:t.data})}}}const wa=Symbol(`pluginToolOwner`);var Ta=class{tools=[];uiTools=[];register(e,t,n){let r=t.name,i=n?.names??(n?.name?[n.name]:r?[r]:[]);Object.defineProperty(t,wa,{value:e,enumerable:!1,configurable:!1,writable:!1}),this.tools.push({pluginId:e,tool:t,optional:n?.optional??!1,names:i})}registerUiTool(e,t,n){this.uiTools.push({pluginId:e,descriptor:t,optional:n?.optional??!1})}list(){return[...this.tools]}listUiTools(){return[...this.uiTools]}namesForPlugin(e){let t=this.tools.filter(t=>t.pluginId===e).flatMap(e=>e.names),n=this.uiTools.filter(t=>t.pluginId===e).map(e=>e.descriptor.name);return[...t,...n]}resolveEnabled(e){let t=new Set((e??[]).map(e=>e.trim()).filter(Boolean));return this.tools.filter(e=>{if(!e.optional)return!0;if(t.size===0)return!1;if(t.has(e.pluginId))return!0;for(let n of e.names)if(t.has(n))return!0;return!1}).map(e=>e.tool)}resolveUiTools(e,t,n){let r=new Set((n??[]).map(e=>e.trim()).filter(Boolean));return this.uiTools.filter(e=>e.optional?r.size===0?!1:!!(r.has(e.pluginId)||r.has(e.descriptor.name)):!0).map(n=>{let r=Zi({name:n.descriptor.name,label:n.descriptor.label,description:n.descriptor.description,sessionId:e,schema:n.descriptor.schema,extra:n.descriptor.extra,validate:n.descriptor.validate,resume:t});return Object.defineProperty(r,wa,{value:n.pluginId,enumerable:!1,configurable:!1,writable:!1}),r})}};function Ea(e){return e[wa]}const Da=new Fe;function Oa(){return{}}async function ka(e,t){return await Da.run(e,t)}function Aa(e){let t=Da.getStore();!t||t.signal||(t.signal=e)}function ja(e,t,n,r){return e.map(e=>{let i=e,a=e.name??`unknown`,o=Ea(e);return{...i,async execute(e,s,c,l){let u=Date.now(),d=s??{},f=!1,p,m=async e=>o?await Sa({pluginId:o,hookContext:n,eventDispatcher:r.eventDispatcher},e):await e(),h=await t.dispatch(`before_tool_call`,{toolCallId:e,toolName:a,params:d},n,r);for(let e of h)e&&(e.params&&(d=e.params),e.block&&(f=!0,p=e.blockReason));if(f)return await t.dispatch(`after_tool_call`,{toolCallId:e,toolName:a,params:d,error:p??`blocked by plugin`,durationMs:Date.now()-u},n,r),{content:[{type:`text`,text:p??`Tool blocked by plugin`}],isError:!0,details:{}};try{let o=await m(async()=>await i.execute(e,d,c,l));return await t.dispatch(`after_tool_call`,{toolCallId:e,toolName:a,params:d,result:o,durationMs:Date.now()-u},n,r),o}catch(i){if(sr(i)){Aa(i);let o={content:[{type:`text`,text:i.message}],isError:!0,details:{}};return await t.dispatch(`after_tool_call`,{toolCallId:e,toolName:a,params:d,result:o,durationMs:Date.now()-u},n,r),o}throw await t.dispatch(`after_tool_call`,{toolCallId:e,toolName:a,params:d,error:String(i),durationMs:Date.now()-u},n,r),i}}}})}var Ma=class{hooks=new Map;register(e){let t=this.hooks.get(e.hookName)??[];t.push(e),t.sort((e,t)=>(e.priority??0)-(t.priority??0)),this.hooks.set(e.hookName,t)}async dispatch(e,t,n,r){let i=this.hooks.get(e)??[],a=[];for(let e of i){let i=async()=>await e.handler(t,n),o=r?await Sa({pluginId:e.pluginId,hookContext:n,eventDispatcher:r.eventDispatcher},i):await i();a.push(o)}return a}};const X={enabled:!1,historySize:30,warningThreshold:10,criticalThreshold:20,globalCircuitBreakerThreshold:30,detectors:{genericRepeat:!0,knownPollNoProgress:!0,pingPong:!0}};function Na(e,t){return typeof e!=`number`||!Number.isInteger(e)||e<=0?t:e}function Pa(e){let t=Na(e?.warningThreshold,X.warningThreshold),n=Na(e?.criticalThreshold,X.criticalThreshold),r=Na(e?.globalCircuitBreakerThreshold,X.globalCircuitBreakerThreshold);return n<=t&&(n=t+1),r<=n&&(r=n+1),{enabled:e?.enabled??X.enabled,historySize:Na(e?.historySize,X.historySize),warningThreshold:t,criticalThreshold:n,globalCircuitBreakerThreshold:r,detectors:{genericRepeat:e?.detectors?.genericRepeat??X.detectors.genericRepeat,knownPollNoProgress:e?.detectors?.knownPollNoProgress??X.detectors.knownPollNoProgress,pingPong:e?.detectors?.pingPong??X.detectors.pingPong}}}function Z(e){return!!e&&typeof e==`object`&&!Array.isArray(e)}function Fa(e,t){return`${e}:${Q(t)}`}function Ia(e){if(typeof e!=`object`||!e)return JSON.stringify(e);if(Array.isArray(e))return`[${e.map(Ia).join(`,`)}]`;let t=e;return`{${Object.keys(t).toSorted().map(e=>`${JSON.stringify(e)}:${Ia(t[e])}`).join(`,`)}}`}function La(e){try{return Ia(e)}catch{return e==null?`${e}`:typeof e==`string`?e:typeof e==`number`||typeof e==`boolean`||typeof e==`bigint`?`${e}`:e instanceof Error?`${e.name}:${e.message}`:Object.prototype.toString.call(e)}}function Q(e){let t=La(e);return Oe(`sha256`).update(t).digest(`hex`)}function Ra(e,t){if(e===`command_status`)return!0;if(e!==`process`||!Z(t))return!1;let n=t.action;return n===`poll`||n===`log`}function za(e){return!Z(e)||!Array.isArray(e.content)?``:e.content.filter(e=>Z(e)&&typeof e.type==`string`&&typeof e.text==`string`).map(e=>e.text).join(`
72
+ `)}const xa=new Fe;async function Sa(e,t){return await xa.run(e,t)}function Ca(e){return{async emit(t){let n=xa.getStore();if(!n||n.pluginId!==e)throw Error(`Plugin ${e} cannot emit progress outside its runtime context`);if(!n.hookContext.sessionId)throw Error(`Plugin ${e} cannot emit progress without an active session`);await n.eventDispatcher.dispatchProgress(n.hookContext.sessionId,{type:`custom`,pluginId:e,name:t.name,label:t.label,data:t.data})}}}const wa=Symbol(`pluginToolOwner`);var Ta=class{tools=[];uiTools=[];register(e,t,n){let r=t.name,i=n?.names??(n?.name?[n.name]:r?[r]:[]);Object.defineProperty(t,wa,{value:e,enumerable:!1,configurable:!1,writable:!1}),this.tools.push({pluginId:e,tool:t,optional:n?.optional??!1,names:i})}registerUiTool(e,t,n){this.uiTools.push({pluginId:e,descriptor:t,optional:n?.optional??!1})}list(){return[...this.tools]}listUiTools(){return[...this.uiTools]}namesForPlugin(e){let t=this.tools.filter(t=>t.pluginId===e).flatMap(e=>e.names),n=this.uiTools.filter(t=>t.pluginId===e).map(e=>e.descriptor.name);return[...t,...n]}resolveEnabled(e){let t=new Set((e??[]).map(e=>e.trim()).filter(Boolean));return this.tools.filter(e=>{if(!e.optional)return!0;if(t.size===0)return!1;if(t.has(e.pluginId))return!0;for(let n of e.names)if(t.has(n))return!0;return!1}).map(e=>e.tool)}resolveUiTools(e,t,n){let r=new Set((n??[]).map(e=>e.trim()).filter(Boolean));return this.uiTools.filter(e=>e.optional?r.size===0?!1:!!(r.has(e.pluginId)||r.has(e.descriptor.name)):!0).map(n=>{let r=Zi({name:n.descriptor.name,label:n.descriptor.label,description:n.descriptor.description,sessionId:e,inputSchema:n.descriptor.inputSchema,outputSchema:n.descriptor.outputSchema,extra:n.descriptor.extra,validate:n.descriptor.validate,resume:t});return Object.defineProperty(r,wa,{value:n.pluginId,enumerable:!1,configurable:!1,writable:!1}),r})}};function Ea(e){return e[wa]}const Da=new Fe;function Oa(){return{}}async function ka(e,t){return await Da.run(e,t)}function Aa(e){let t=Da.getStore();!t||t.signal||(t.signal=e)}function ja(e,t,n,r){return e.map(e=>{let i=e,a=e.name??`unknown`,o=Ea(e);return{...i,async execute(e,s,c,l){let u=Date.now(),d=s??{},f=!1,p,m=async e=>o?await Sa({pluginId:o,hookContext:n,eventDispatcher:r.eventDispatcher},e):await e(),h=await t.dispatch(`before_tool_call`,{toolCallId:e,toolName:a,params:d},n,r);for(let e of h)e&&(e.params&&(d=e.params),e.block&&(f=!0,p=e.blockReason));if(f)return await t.dispatch(`after_tool_call`,{toolCallId:e,toolName:a,params:d,error:p??`blocked by plugin`,durationMs:Date.now()-u},n,r),{content:[{type:`text`,text:p??`Tool blocked by plugin`}],isError:!0,details:{}};try{let o=await m(async()=>await i.execute(e,d,c,l));return await t.dispatch(`after_tool_call`,{toolCallId:e,toolName:a,params:d,result:o,durationMs:Date.now()-u},n,r),o}catch(i){if(sr(i)){Aa(i);let o={content:[{type:`text`,text:i.message}],isError:!0,details:{}};return await t.dispatch(`after_tool_call`,{toolCallId:e,toolName:a,params:d,result:o,durationMs:Date.now()-u},n,r),o}throw await t.dispatch(`after_tool_call`,{toolCallId:e,toolName:a,params:d,error:String(i),durationMs:Date.now()-u},n,r),i}}}})}var Ma=class{hooks=new Map;register(e){let t=this.hooks.get(e.hookName)??[];t.push(e),t.sort((e,t)=>(e.priority??0)-(t.priority??0)),this.hooks.set(e.hookName,t)}async dispatch(e,t,n,r){let i=this.hooks.get(e)??[],a=[];for(let e of i){let i=async()=>await e.handler(t,n),o=r?await Sa({pluginId:e.pluginId,hookContext:n,eventDispatcher:r.eventDispatcher},i):await i();a.push(o)}return a}};const X={enabled:!1,historySize:30,warningThreshold:10,criticalThreshold:20,globalCircuitBreakerThreshold:30,detectors:{genericRepeat:!0,knownPollNoProgress:!0,pingPong:!0}};function Na(e,t){return typeof e!=`number`||!Number.isInteger(e)||e<=0?t:e}function Pa(e){let t=Na(e?.warningThreshold,X.warningThreshold),n=Na(e?.criticalThreshold,X.criticalThreshold),r=Na(e?.globalCircuitBreakerThreshold,X.globalCircuitBreakerThreshold);return n<=t&&(n=t+1),r<=n&&(r=n+1),{enabled:e?.enabled??X.enabled,historySize:Na(e?.historySize,X.historySize),warningThreshold:t,criticalThreshold:n,globalCircuitBreakerThreshold:r,detectors:{genericRepeat:e?.detectors?.genericRepeat??X.detectors.genericRepeat,knownPollNoProgress:e?.detectors?.knownPollNoProgress??X.detectors.knownPollNoProgress,pingPong:e?.detectors?.pingPong??X.detectors.pingPong}}}function Z(e){return!!e&&typeof e==`object`&&!Array.isArray(e)}function Fa(e,t){return`${e}:${Q(t)}`}function Ia(e){if(typeof e!=`object`||!e)return JSON.stringify(e);if(Array.isArray(e))return`[${e.map(Ia).join(`,`)}]`;let t=e;return`{${Object.keys(t).toSorted().map(e=>`${JSON.stringify(e)}:${Ia(t[e])}`).join(`,`)}}`}function La(e){try{return Ia(e)}catch{return e==null?`${e}`:typeof e==`string`?e:typeof e==`number`||typeof e==`boolean`||typeof e==`bigint`?`${e}`:e instanceof Error?`${e.name}:${e.message}`:Object.prototype.toString.call(e)}}function Q(e){let t=La(e);return Oe(`sha256`).update(t).digest(`hex`)}function Ra(e,t){if(e===`command_status`)return!0;if(e!==`process`||!Z(t))return!1;let n=t.action;return n===`poll`||n===`log`}function za(e){return!Z(e)||!Array.isArray(e.content)?``:e.content.filter(e=>Z(e)&&typeof e.type==`string`&&typeof e.text==`string`).map(e=>e.text).join(`
73
73
  `).trim()}function Ba(e){return e instanceof Error?e.message||e.name:typeof e==`string`?e:typeof e==`number`||typeof e==`boolean`||typeof e==`bigint`?`${e}`:Ia(e)}function Va(e,t,n,r){if(r!==void 0)return`error:${Q(Ba(r))}`;if(!Z(n))return n===void 0?void 0:Q(n);let i=Z(n.details)?n.details:{},a=za(n);if(Ra(e,t)&&e===`process`&&Z(t)){let e=t.action;if(e===`poll`)return Q({action:e,status:i.status,exitCode:i.exitCode??null,exitSignal:i.exitSignal??null,aggregated:i.aggregated??null,text:a});if(e===`log`)return Q({action:e,status:i.status,totalLines:i.totalLines??null,totalChars:i.totalChars??null,truncated:i.truncated??null,exitCode:i.exitCode??null,exitSignal:i.exitSignal??null,text:a})}return Q({details:i,text:a})}function Ha(e,t,n){let r=0,i;for(let a=e.length-1;a>=0;--a){let o=e[a];if(!(!o||o.toolName!==t||o.argsHash!==n)&&!(typeof o.resultHash!=`string`||!o.resultHash)){if(!i){i=o.resultHash,r=1;continue}if(o.resultHash!==i)break;r+=1}}return{count:r,latestResultHash:i}}function Ua(e,t){let n=e.at(-1);if(!n)return{count:0,noProgressEvidence:!1};let r,i;for(let t=e.length-2;t>=0;--t){let a=e[t];if(a&&a.argsHash!==n.argsHash){r=a.argsHash,i=a.toolName;break}}if(!r||!i)return{count:0,noProgressEvidence:!1};let a=0;for(let t=e.length-1;t>=0;--t){let i=e[t];if(!i)continue;let o=a%2==0?n.argsHash:r;if(i.argsHash!==o)break;a+=1}if(a<2||t!==r)return{count:0,noProgressEvidence:!1};let o=Math.max(0,e.length-a),s,c,l=!0;for(let t=o;t<e.length;t+=1){let i=e[t];if(i){if(!i.resultHash){l=!1;break}if(i.argsHash===n.argsHash){if(!s)s=i.resultHash;else if(s!==i.resultHash){l=!1;break}continue}if(i.argsHash===r){if(!c)c=i.resultHash;else if(c!==i.resultHash){l=!1;break}continue}l=!1;break}}return(!s||!c)&&(l=!1),{count:a+1,pairedToolName:n.toolName,pairedSignature:n.argsHash,noProgressEvidence:l}}function Wa(e,t){return[e,t].toSorted().join(`|`)}function Ga(e,t,n,r){let i=Pa(r);if(!i.enabled)return{stuck:!1};let a=e.toolCallHistory??[],o=Fa(t,n),s=Ha(a,t,o),c=s.count,l=Ra(t,n),u=Ua(a,o);if(c>=i.globalCircuitBreakerThreshold)return{stuck:!0,level:`critical`,detector:`global_circuit_breaker`,count:c,message:`CRITICAL: ${t} has repeated identical no-progress outcomes ${c} times. Session execution blocked by global circuit breaker to prevent runaway loops.`,warningKey:`global:${t}:${o}:${s.latestResultHash??`none`}`};if(l&&i.detectors.knownPollNoProgress&&c>=i.criticalThreshold)return{stuck:!0,level:`critical`,detector:`known_poll_no_progress`,count:c,message:`CRITICAL: Called ${t} with identical arguments and no progress ${c} times. This appears to be a stuck polling loop. Session execution blocked to prevent resource waste.`,warningKey:`poll:${t}:${o}:${s.latestResultHash??`none`}`};if(l&&i.detectors.knownPollNoProgress&&c>=i.warningThreshold)return{stuck:!0,level:`warning`,detector:`known_poll_no_progress`,count:c,message:`WARNING: You have called ${t} ${c} times with identical arguments and no progress. Stop polling and either (1) increase wait time between checks, or (2) report the task as failed if the process is stuck.`,warningKey:`poll:${t}:${o}:${s.latestResultHash??`none`}`};let d=u.pairedSignature?`pingpong:${Wa(o,u.pairedSignature)}`:`pingpong:${t}:${o}`;if(i.detectors.pingPong&&u.count>=i.criticalThreshold&&u.noProgressEvidence)return{stuck:!0,level:`critical`,detector:`ping_pong`,count:u.count,message:`CRITICAL: You are alternating between repeated tool-call patterns (${u.count} consecutive calls) with no progress. This appears to be a stuck ping-pong loop. Session execution blocked to prevent resource waste.`,pairedToolName:u.pairedToolName,warningKey:d};if(i.detectors.pingPong&&u.count>=i.warningThreshold)return{stuck:!0,level:`warning`,detector:`ping_pong`,count:u.count,message:`WARNING: You are alternating between repeated tool-call patterns (${u.count} consecutive calls). This looks like a ping-pong loop; stop retrying and report the task as failed.`,pairedToolName:u.pairedToolName,warningKey:d};let f=a.filter(e=>e.toolName===t&&e.argsHash===o).length;return!l&&i.detectors.genericRepeat&&f>=i.warningThreshold?{stuck:!0,level:`warning`,detector:`generic_repeat`,count:f,message:`WARNING: You have called ${t} ${f} times with identical arguments. If this is not making progress, stop retrying and report the task as failed.`,warningKey:`generic:${t}:${o}`}:{stuck:!1}}function Ka(e,t,n,r,i){let a=Pa(i);e.toolCallHistory||=[],e.toolCallHistory.push({toolName:t,argsHash:Fa(t,n),toolCallId:r,timestamp:Date.now()}),e.toolCallHistory.length>a.historySize&&e.toolCallHistory.shift()}function qa(e,t){let n=Pa(t.config),r=Va(t.toolName,t.toolParams,t.result,t.error);if(!r)return;e.toolCallHistory||=[];let i=Fa(t.toolName,t.toolParams),a=!1;for(let n=e.toolCallHistory.length-1;n>=0;--n){let o=e.toolCallHistory[n];if(o&&!(t.toolCallId&&o.toolCallId!==t.toolCallId)&&!(o.toolName!==t.toolName||o.argsHash!==i)&&o.resultHash===void 0){o.resultHash=r,a=!0;break}}a||e.toolCallHistory.push({toolName:t.toolName,argsHash:i,toolCallId:t.toolCallId,resultHash:r,timestamp:Date.now()}),e.toolCallHistory.length>n.historySize&&e.toolCallHistory.splice(0,e.toolCallHistory.length-n.historySize)}function Ja(e,t,n){e.toolLoopWarningBuckets||=new Map;let r=Math.floor(n/10);if(r<=(e.toolLoopWarningBuckets.get(t)??0))return!1;if(e.toolLoopWarningBuckets.set(t,r),e.toolLoopWarningBuckets.size>256){let t=e.toolLoopWarningBuckets.keys().next().value;t&&e.toolLoopWarningBuckets.delete(t)}return!0}function Ya(e){return e&&e.trim()||`tool`}function Xa(e,t,n){if(!e.execute)return e;let r=Ya(e.name),i=e.execute.bind(e);return{...e,execute:async(e,a,o,s)=>{let c=n(t.sessionId),l=Ga(c,r,a,t.config);if(l.stuck){if(l.level===`critical`)throw Error(l.message);Ja(c,l.warningKey??`${l.detector}:${r}`,l.count)&&t.onWarning?.(l)}Ka(c,r,a,e,t.config);try{let n=await i(e,a,o,s);return qa(c,{toolName:r,toolParams:a,toolCallId:e,result:n,config:t.config}),n}catch(n){throw qa(c,{toolName:r,toolParams:a,toolCallId:e,error:n,config:t.config}),n}}}}function Za(e,t,n){return e.map(e=>Xa(e,t,n))}async function Qa(e){let{session:{runParams:t,sessionId:n,hookRegistry:r,hookContext:i,runContext:a,eventDispatcher:o},runtimeInputs:{contextFiles:s,bootstrapWarnings:c,skills:u,effectivePromptText:d,pluginTools:f},dependencies:{registry:p,spawnFn:m,createModel:h,abortSignal:g}}=e,_=t.channel===`CRON`,v=_?[]:await l(t.dataDir,n,{storeName:t.sessionStoreName}),y={model:t.llm.model,api:`openai-completions`},b=await ar({dataDir:t.dataDir,sessionId:n,sessionStoreName:t.sessionStoreName}),x=_?{messages:[],priorSummary:void 0,compactionEntry:void 0,stats:{originalCount:0,keptCount:0,estimatedTokens:0,compacted:!1},compactionEvents:[]}:await or({entries:v,modelInfo:y,contextWindowTokens:t.llm.contextWindow??2e5,llm:{baseUrl:t.llm.baseUrl,apiKey:t.llm.apiKey,model:t.llm.model},historyLimit:t.historyLimit,compactionEnabled:!0,signal:g,hooks:r,hookCtx:i,contextManager:b,dataDir:t.dataDir,sessionId:n});await $a({sessionId:n,historyResult:x,runContext:a,eventDispatcher:o,hookRegistry:r,hookContext:i});let S=t.subagentContext?.depth??0,C=[...Qi(t.dataDir,{sessionId:t.subagentContext?.parentSessionId??n,registry:p,parentSessionId:n,depth:S,channel:t.channel,llm:t.llm,inheritedRunParams:{sessionStoreName:t.sessionStoreName,plugins:t.plugins,memory:t.memory,messaging:t.messaging,docs:t.docs,historyLimit:t.historyLimit,onProgress:t.onProgress,messageId:t.messageId},loopDetection:t.loopDetection,memoryOptions:{providerId:a.memoryProviderId,pluginId:a.memoryPluginId,sessionId:n,onMemoryChanged:async()=>{}},contextManager:b,hitlResume:t.hitlResume,spawnFn:m}),...f],w=C.map(e=>typeof e.name==`string`?e.name.trim():``).filter(Boolean),T={};for(let e of C){let t=typeof e.name==`string`?e.name.trim():``,n=typeof e.description==`string`?e.description.trim():``;!t||!n||T[t]||(T[t]=n)}let E=t.messaging?.enabled??t.channel!==`CRON`,D=t.messaging?.channels&&t.messaging.channels.length>0?t.messaging.channels:[t.channel],O=ba({dataDir:t.dataDir,skills:u,contextFiles:s,toolNames:w,toolSummaries:T,promptMode:S>0?`minimal`:`full`,bootstrapWarnings:c,memoryCitationsMode:t.memory?.citationsMode??`off`,messaging:{enabled:E,channels:D},docs:{localPath:t.docs?.localPath,webUrl:t.docs?.webUrl,sourceUrl:t.docs?.sourceUrl},sandboxInfo:{enabled:!0,hostWorkspaceDir:a.workspaceDir,containerWorkspaceDir:a.workspaceDir},runtimeInfo:{os:process.platform,node:process.version,model:t.llm.model,hostname:Ae.hostname()},currentDate:new Date().toISOString().split(`T`)[0],priorConversationSummary:x.priorSummary}),k=await r.dispatch(`before_prompt_build`,{prompt:d},i,{eventDispatcher:o});for(let e of k)e&&(e.systemPrompt&&(O=e.systemPrompt),e.prependContext&&(O=`${e.prependContext}\n\n${O}`));await r.dispatch(`after_prompt_build`,{prompt:d,systemPrompt:O},i,{eventDispatcher:o});let A=Za(ja(C,r,i,{eventDispatcher:o}),{sessionId:n,config:t.loopDetection},rt),j=t.llm.model,M=await r.dispatch(`before_model_resolve`,{prompt:d},i,{eventDispatcher:o});for(let e of M)e&&e.modelOverride&&(j=e.modelOverride);let N=h({...t.llm,model:j},n),P=new ke({initialState:{systemPrompt:O,model:N,tools:A,messages:[]},getApiKey:e=>t.llm.apiKey});return x.messages.length>0&&P.replaceMessages(x.messages),{agent:P,resolvedModelId:j,historyMessages:x.messages,historyResult:x,workspaceDir:a.workspaceDir}}async function $a(e){let{sessionId:t,historyResult:n,runContext:r,eventDispatcher:i,hookRegistry:a,hookContext:o}=e;for(let e of n.compactionEvents??[])e.type===`compaction`&&await i.dispatchDiagnostic(t,{level:`info`,scope:`session`,phase:`history_compaction`,message:e.reason,details:{layer:e.layer,strategy:e.strategy,estimatedTokensFreed:e.estimatedTokensFreed,affectedEntries:e.affectedEntries,snapshotVersion:e.snapshotVersion}});if(n.compactionEntry){let e=n.stats.originalCount-n.stats.keptCount;await a.dispatch(`before_compaction`,{messageCount:n.stats.originalCount,compactingCount:e},o,{eventDispatcher:i}),await r.appendTranscriptEntry(n.compactionEntry),(n.compactionEvents?.length??0)===0&&await i.dispatchDiagnostic(t,{level:`info`,scope:`session`,phase:`history_compaction`,message:`Summarised ${e} older entries`,details:{strategy:`summary_only`,compactedCount:e}}),await a.dispatch(`after_compaction`,{messageCount:n.stats.originalCount,compactedCount:e},o,{eventDispatcher:i})}}async function eo(e){let{agent:t,message:n,continueFromHistory:r=!1,sessionId:i,modelId:a,historyMessages:o,eventDispatcher:s,skillUsageTracker:c,hooks:l,hookCtx:u,abortSignal:d,onTurnRecordProduced:f}=e,p=``,m=``,h=``,g=0,_=0,v,y,b=0,x=[],S=new Map,C=Oa(),w=qi(),T=t.subscribe(async e=>{if(e.type===`message_update`){let t=e.assistantMessageEvent;if(t.type===`text_delta`&&typeof t.delta==`string`){let n=so(`partial`in t?t.partial:void 0)??so(`message`in t?t.message:void 0)??so(`message`in e?e.message:void 0),r=co(t.delta,n,m);r&&(await s.dispatchProgress(i,{type:`stream_text_delta`,text:r}),h+=r),n&&(m=n,h=n)}if(t.type===`done`){let e=t.message;p=oo(e);let n=co(``,p,h||m);n&&(await s.dispatchProgress(i,{type:`stream_text_delta`,text:n}),h+=n),m=p,h=p,e.usage&&(g=e.usage.input,_=e.usage.output)}return}if(e.type===`message_end`){let t=e.message;if(t.usage&&(g=t.usage.input,_=t.usage.output),t.role===`assistant`&&Array.isArray(t.content)){let e=t,n=oo(e);await l.dispatch(`assistant_message_end`,{sessionId:i,model:a,assistantText:n,assistantMessage:e,hasToolCalls:e.content.some(e=>e.type===`toolCall`),durationMs:b>0?Math.max(0,Date.now()-b):void 0,usage:t.usage?{input:g,output:_,total:g+_}:void 0},u)}return}if(e.type===`turn_end`){let t=e.message;(t.stopReason===`error`||t.stopReason===`aborted`)&&(y=t.errorMessage??(t.stopReason===`aborted`?`aborted`:`Unknown LLM error`));let n=(e.toolResults??[]).map(e=>({toolCallId:e.toolCallId,toolName:e.toolName,content:e.content.filter(e=>e.type===`text`).map(e=>e.text??``).join(``),isError:e.isError,toolResultRef:io(e.content.filter(e=>e.type===`text`).map(e=>e.text??``).join(``),i,e.toolCallId,e.toolName)}));if(x.push({message:t,toolResults:n}),f){let e=!!C.signal,r=!!w.signal;if(e&&C.signal.transparentPause||await f(no(to(t),e||r),r?[]:n.map(ro)),e||r)return}return}if(e.type===`tool_execution_start`){h=``,S.set(e.toolCallId,e.args),c.onToolExecutionStart({toolName:e.toolName,args:e.args}),await s.dispatchProgress(i,{type:`tool_start`,toolCallId:e.toolCallId,name:e.toolName,input:e.args});return}if(e.type===`tool_execution_end`){await c.onToolExecutionEnd({toolName:e.toolName,isError:e.isError});let t=typeof e.result==`string`?e.result:JSON.stringify(e.result),n=S.get(e.toolCallId);if(S.delete(e.toolCallId),w.signal)return;await s.dispatchProgress(i,{type:`tool_end`,toolCallId:e.toolCallId,name:e.toolName,input:n,output:t,isError:e.isError})}});try{if(await l.dispatch(`llm_input`,{sessionId:i,model:a,prompt:typeof n==`string`?n:JSON.stringify(n),historyMessages:o},u),d?.aborted)throw Error(`aborted`);b=Date.now(),await ka(C,async()=>{await Ji(w,async()=>{r?await t.continue():await t.prompt(n)})});let e=C.signal;if(e)throw e;let c=w.signal;if(c)throw c;if(!v){let e=typeof t.state.error==`string`?t.state.error:void 0,n=y??e;n&&(v=lo(n),await s.dispatchProgress(i,{type:`error`,message:v}))}}catch(e){if(sr(e)||Gi(e))throw e;v=lo(e),await s.dispatchProgress(i,{type:`error`,message:v})}finally{T()}let E=x.length>0?x[x.length-1]?.message:void 0;await l.dispatch(`llm_output`,{sessionId:i,model:a,assistantTexts:p?[p]:[],lastAssistant:E,usage:{input:g,output:_,total:g+_}},u);let D=x.length>0?oo(x[x.length-1].message):``;if(C.signal)throw C.signal;if(w.signal)throw w.signal;return f&&x.length===0&&p.trim().length>0&&await f({role:`assistant`,content:p,timestamp:new Date().toISOString()},[]),{text:D||p,inputTokens:g,outputTokens:_,error:v,turnRecords:x}}function to(e){let t=e.content.filter(e=>e.type===`text`).map(e=>e.text).join(``),n=e.content.filter(e=>e.type===`toolCall`).map(e=>({id:e.id,name:e.name,arguments:e.arguments}));if(t.trim().length===0&&n.length===0)return null;let r={role:`assistant`,content:t,timestamp:new Date().toISOString()};return n.length>0&&(r.toolCalls=n),r}function no(e,t){return!e||!t?e:!e.toolCalls||e.toolCalls.length===0?null:{...e,content:``}}function ro(e){return{role:`tool_result`,toolCallId:e.toolCallId,toolName:e.toolName,content:e.content,isError:e.isError,toolResultRef:e.toolResultRef,timestamp:new Date().toISOString()}}function io(e,t,n,r){let i=e.match(/\[tool result persisted\][^\n]*\((\d+) chars\)\.\nFull output: ([^\n]+)/);if(i)return{sessionId:t,toolCallId:n,toolName:r,storagePath:i[2]??``,preview:ao(e),originalChars:Number(i[1]??`0`),truncated:!0,createdAt:new Date().toISOString()}}function ao(e){let t=e.indexOf(`
74
74
  Preview:
75
75
  `);return t===-1?``:e.slice(t+10).replace(/\n\.\.\.$/,``)}function oo(e){return e.content.filter(e=>e.type===`text`).map(e=>e.text).join(``)}function so(e){if(!e||typeof e!=`object`)return null;let t=e;return Array.isArray(t.content)?t.content.filter(e=>typeof e==`object`&&!!e&&`type`in e&&e.type===`text`&&`text`in e).map(e=>e.text).join(``):null}function co(e,t,n){return t?n?t===n?``:t.startsWith(n)?t.slice(n.length):t:t:e}function lo(e){let t=uo(e);return t?t.code===`http_error`&&t.statusCode?t.providerMessage?`LLM upstream returned HTTP ${t.statusCode}${t.statusText?` ${t.statusText}`:``}: ${t.providerMessage}`:`LLM upstream returned HTTP ${t.statusCode}${t.statusText?` ${t.statusText}`:``}`:t.code===`timeout`?`LLM request timed out`:t.code===`network_error`?t.message:t.code===`aborted`?`LLM request was aborted`:t.message:e instanceof Error?e.message:String(e)}function uo(e){if(e instanceof H)return e;if(!(e instanceof Error))return null;let t=e;return e.name!==`LlmRequestError`&&!t.code?null:{message:e.message,code:t.code,statusCode:t.statusCode,statusText:t.statusText,providerMessage:t.providerMessage}}async function fo(e){let{agent:t,registry:n,sessionId:r,resolvedModelId:i,eventDispatcher:a,skillUsageTracker:o,hookRegistry:s,hookContext:c,abortSignal:l,appendEntry:u}=e,d=0,f=``,p=0,m=0,h;for(;!l?.aborted&&n.needsAnnounce(r)&&d<10;){d++,await n.waitForAll(r);let e=n.consumeCompleted(r);if(e.length===0)break;for(let t of e)await a.dispatchProgress(r,{type:`subagent_complete`,childSessionId:t.childSessionId,task:t.task,status:t.status});let g=po(e);await u({role:`assistant`,content:g,timestamp:new Date().toISOString()});let _=await eo({agent:t,message:g,sessionId:r,modelId:i,historyMessages:[],eventDispatcher:a,skillUsageTracker:o,hooks:s,hookCtx:c,abortSignal:l,onTurnRecordProduced:async(e,t)=>{e&&await u(e);for(let e of t)await u(e)}});f=_.text,p+=_.inputTokens,m+=_.outputTokens,_.error&&!h&&(h=_.error)}return{text:f,inputTokens:p,outputTokens:m,error:h}}function po(e){if(e.length===1){let t=e[0];return Ii({task:t.task,label:t.label,status:t.status,result:t.result,error:t.error})}let t=e.map(e=>Ii({task:e.task,label:e.label,status:e.status,result:e.result,error:e.error}));return`[${e.length} subagents completed]\n\n${t.join(`
@@ -78,7 +78,7 @@ Preview:
78
78
 
79
79
  `)}`}function mo(e){if(!e)return null;let t=(typeof e==`string`?e:e.toString(`utf-8`)).replace(/\\/g,`/`).replace(/^\.\//,``).trim();return t.length>0?t:null}function ho(e){let t=mo(e.filename);if(e.kind===`memory-file`)return[`MEMORY.md`];if(e.kind===`memory-file-lower`)return[`memory.md`];if(e.kind===`memory-dir`){if(!t)return[`memory`];let e=I.basename(t).replace(/\\/g,`/`);return e.endsWith(`.md`)?[`memory/${e}`]:[]}return t?t===`MEMORY.md`||t===`memory.md`?[t]:t===`memory`?[`memory`]:t.startsWith(`memory/`)?t.endsWith(`.md`)?[t]:[`memory`]:[]:[`MEMORY.md`,`memory`]}function go(e){let t=e.watchFactory??((e,t,n)=>B.watch(e,t,n)),n=I.join(e.dataDir,`.aimax`),r=[{target:I.join(n,`MEMORY.md`),kind:`memory-file`},{target:I.join(n,`memory.md`),kind:`memory-file-lower`},{target:I.join(n,`memory`),kind:`memory-dir`},{target:n,kind:`memory-root`}],i=[],a=new Set,o=null,s=Number.isFinite(e.debounceMs)&&(e.debounceMs??0)>0?Math.floor(e.debounceMs):1500,c=async()=>{let t=Array.from(a);if(a.clear(),t.length===0)return;let n={reason:`external-watch`,files:t,source:`memory`,sessionId:e.sessionId,providerId:e.providerId,timestamp:new Date().toISOString()};e.provider?.sync&&await e.provider.sync(`external-watch`).catch(()=>{}),e.provider?.onMemoryChanged&&await Promise.resolve(e.provider.onMemoryChanged(n)).catch(()=>{}),e.onMemoryChanged&&await Promise.resolve(e.onMemoryChanged(n)).catch(()=>{})},l=()=>{o&&clearTimeout(o),o=setTimeout(()=>{o=null,c()},s)};for(let e of r)try{let n=t(e.target,{recursive:!1},(t,n)=>{let r=ho({kind:e.kind,filename:n});if(r.length!==0){for(let e of r)a.add(e);l()}});n.on?.(`error`,()=>{try{n.close()}catch{}}),i.push(n)}catch{}return()=>{o&&=(clearTimeout(o),null);for(let e of i)try{e.close()}catch{}}}async function _o(e){let{runParams:t,eventDispatcher:n,hookRegistry:r}=e,{sessionId:i,hookContext:a,memoryProviderId:o,memoryPluginId:s}=e,c=I.join(t.dataDir,`workspace`),l=new Map,u=new Map,d=!1,f=async e=>{let t=Date.now(),o=bo(e.files);if(o.length===0)return;let s=e.reason===`external-watch`&&e.source===`memory`?o.filter(e=>t-(l.get(e.toLowerCase())??0)>3e3):o;if(s.length===0)return;if(e.reason!==`external-watch`&&e.source===`memory`)for(let e of s)l.set(e.toLowerCase(),t);let c=`${e.reason}|${e.source}|${s.map(e=>e.toLowerCase()).sort().join(`|`)}`;if(t-(u.get(c)??0)<1e3)return;u.set(c,t);let d={...e,files:s};await n.dispatchProgress(e.sessionId??i,{type:`memory_changed`,reason:d.reason,files:d.files,source:d.source,providerId:d.providerId,timestamp:d.timestamp}).catch(()=>{}),await r.dispatch(`memory_changed`,d,{...a,sessionId:d.sessionId??a.sessionId},{eventDispatcher:n}).catch(()=>{})},p=I.join(t.dataDir,`.aimax`),m=k({providerId:o,pluginId:s,dataDir:t.dataDir,memoryDir:p,sessionId:i,sessionStoreName:t.sessionStoreName})?.provider??y({dataDir:t.dataDir,memoryDir:p,sessionId:i,sessionStoreName:t.sessionStoreName}),h=go({dataDir:t.dataDir,sessionId:i,providerId:o??s??m.id,provider:m,onMemoryChanged:f});m.sync&&m.sync(`session-start`).catch(()=>{});let g=async e=>{await _(t.dataDir,i,e,yo({sessionStoreName:t.sessionStoreName,providerId:o,pluginId:s,onMemoryChanged:f}))};return{workspaceDir:c,memoryProviderId:o,memoryPluginId:s,appendTranscriptEntry:g,persistInitialUserEntry:async e=>d?!1:(await g({role:`user`,content:e,timestamp:new Date().toISOString()}),d=!0,!0),stop:()=>{h()}}}function vo(e){let t=new Date().toISOString();return{id:e.sessionId,title:e.title,channel:e.channel,createdAt:t,updatedAt:t}}function yo(e){return e.sessionStoreName||e.providerId||e.pluginId?{storeName:e.sessionStoreName,providerId:e.providerId,pluginId:e.pluginId,onMemoryChanged:e.onMemoryChanged}:{onMemoryChanged:e.onMemoryChanged}}function bo(e){let t=[],n=new Set;for(let r of e){let e=r.replace(/\\/g,`/`).replace(/^\.\//,``).trim();if(!e)continue;let i=e.toLowerCase()===`memory.md`?`MEMORY.md`:e,a=i.toLowerCase();n.has(a)||(n.add(a),t.push(i))}return t}function xo(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function So(e){return Array.isArray(e)?e.map(e=>typeof e==`string`?e.trim():``).filter(Boolean):[]}function Co(){let e=Ae.homedir();if(typeof e!=`string`)return;let t=e.trim();return t.length>0?t:void 0}function wo(e){let t=e.trim(),n=Co();return t===`~`?n:t.startsWith(`~/`)||t.startsWith(`~\\`)?n?I.join(n,t.slice(2)):void 0:I.resolve(t)}const To=new Ie({allErrors:!0,strict:!1}),Eo=new Map;function Do(e,t){let n=Eo.get(t);if(n)return n;let r=To.compile(e);return Eo.set(t,r),r}function Oo(e){let t=e.cacheKey??JSON.stringify(e.schema),n=Do(e.schema,t);return n(e.value)?{ok:!0}:{ok:!1,errors:(n.errors??[]).map(e=>({path:e.instancePath||`/`,message:e.message??`invalid`}))}}function ko(e){let t=So(e?.allow),n=So(e?.deny),r=So(e?.load?.paths),i=e?.entries??{},a=e?.slots??{};return{enabled:e?.enabled??!0,allow:Array.from(new Set(t)),deny:Array.from(new Set(n)),loadPaths:Array.from(new Set(r)),entries:i,slots:a}}function Ao(e){let t=[],{config:n,registry:r}=e,i=new Set(r.manifests.keys()),a=(e,n)=>i.has(e)?!0:(t.push({level:`error`,message:`unknown plugin id in ${n}: ${e}`,pluginId:e}),!1);for(let e of n.allow)a(e,`plugins.allow`);for(let e of n.deny)a(e,`plugins.deny`);for(let e of Object.keys(n.entries))a(e,`plugins.entries`);let o=n.slots??{};for(let[e,n]of Object.entries(o)){if(!n||n===`none`||!a(n,`plugins.slots.${e}`))continue;let i=r.manifests.get(n);i?.manifest.kind?i.manifest.kind!==e&&t.push({level:`error`,message:`plugin ${n} does not declare kind ${e}`,pluginId:n}):t.push({level:`error`,message:`plugin ${n} does not declare kind ${e}`,pluginId:n})}for(let[e,i]of Object.entries(n.entries)){let n=r.manifests.get(e);if(!n)continue;let a=n.manifest.configSchema,o=Oo({schema:a,cacheKey:`${e}:${n.manifestPath}`,value:i?.config??{}});if(!o.ok)for(let n of o.errors)t.push({level:`error`,message:`plugin config invalid (${e}) at ${n.path}: ${n.message}`,pluginId:e});i?.enabled===!1&&i?.config&&t.push({level:`warn`,message:`plugin config set while disabled: ${e}`,pluginId:e})}return{ok:t.every(e=>e.level!==`error`),diagnostics:t}}function jo(e){try{return B.realpathSync(e)}catch{return null}}function Mo(e){try{return B.statSync(e)}catch{return null}}function No(e,t){let n=I.relative(e,t);return n===``?!0:n.startsWith(`..`)?!1:!I.isAbsolute(n)}function Po(e){return`0o${e.toString(8).padStart(3,`0`)}`}const Fo=new Set([`.ts`,`.js`,`.mts`,`.cts`,`.mjs`,`.cjs`]),Io=[`index.ts`,`index.js`,`index.mts`,`index.cts`,`index.mjs`,`index.cjs`];function Lo(e){let t=I.join(e,`package.json`);if(B.existsSync(t))try{let e=JSON.parse(B.readFileSync(t,`utf-8`));return xo(e)?e:void 0}catch{return}}function Ro(e){let t=e?.aimax?.extensions;if(!Array.isArray(t))return{status:`missing`,entries:[]};let n=t.map(e=>typeof e==`string`?e.trim():``).filter(Boolean);return n.length===0?{status:`empty`,entries:[]}:{status:`ok`,entries:n}}function zo(e){return e===void 0?process.platform===`win32`||typeof process.getuid!=`function`?null:process.getuid():e}function Bo(e){let t=jo(e.source),n=jo(e.rootDir);return!t||!n||No(n,t)?null:{reason:`source_escapes_root`,sourcePath:e.source,rootPath:e.rootDir,targetPath:e.source,sourceRealPath:t,rootRealPath:n}}function Vo(e){if(process.platform===`win32`)return null;let t=[e.rootDir,e.source],n=new Set;for(let r of t){let t=I.resolve(r);if(n.has(t))continue;n.add(t);let i=Mo(r);if(!i)return{reason:`path_stat_failed`,sourcePath:e.source,rootPath:e.rootDir,targetPath:r};let a=i.mode&511;if(a&2)return{reason:`path_world_writable`,sourcePath:e.source,rootPath:e.rootDir,targetPath:r,modeBits:a};if(e.origin!==`bundled`&&e.uid!==null&&typeof i.uid==`number`&&i.uid!==e.uid&&i.uid!==0)return{reason:`path_suspicious_ownership`,sourcePath:e.source,rootPath:e.rootDir,targetPath:r,foundUid:i.uid,expectedUid:e.uid}}return null}function Ho(e){return Bo({source:e.source,rootDir:e.rootDir})||Vo({source:e.source,rootDir:e.rootDir,origin:e.origin,uid:zo(e.ownershipUid)})}function Uo(e){return e.reason===`source_escapes_root`?`blocked plugin candidate: source escapes plugin root (${e.sourcePath} -> ${e.sourceRealPath}; root=${e.rootRealPath})`:e.reason===`path_stat_failed`?`blocked plugin candidate: cannot stat path (${e.targetPath})`:e.reason===`path_world_writable`?`blocked plugin candidate: world-writable path (${e.targetPath}, mode=${Po(e.modeBits??0)})`:`blocked plugin candidate: suspicious ownership (${e.targetPath}, uid=${e.foundUid}, expected uid=${e.expectedUid} or root)`}function Wo(e){let t=Ho({source:e.source,rootDir:e.rootDir,origin:e.origin,ownershipUid:e.ownershipUid});return t?(e.diagnostics.push({level:`warn`,message:Uo(t),source:e.source}),!0):!1}function Go(e){return I.basename(e,I.extname(e))}function Ko(e){return{idHint:e.idHint,source:e.source,rootDir:e.rootDir,origin:e.origin,workspaceDir:e.workspaceDir,packageName:e.packageName,packageVersion:e.packageVersion,packageDescription:e.packageDescription,packageDir:e.packageDir,packageManifest:e.packageManifest}}function qo(e){for(let t of Io){let n=I.join(e,t);if(B.existsSync(n))return n}return null}function Jo(e){let t;try{t=B.readdirSync(e.rootDir,{withFileTypes:!0})}catch{return}for(let n of t){let t=I.join(e.rootDir,n.name);if(n.isFile()){if(!Fo.has(I.extname(n.name)))continue;let r=I.dirname(t);if(Wo({source:t,rootDir:r,origin:e.origin,diagnostics:e.diagnostics,ownershipUid:e.ownershipUid}))continue;e.candidates.push(Ko({idHint:Go(t),source:t,rootDir:r,origin:e.origin,workspaceDir:e.workspaceDir}));continue}if(!n.isDirectory())continue;let r=Lo(t),i=Ro(r);if(i.status===`ok`){for(let n of i.entries){let i=I.resolve(t,n);if(!No(t,i)){e.diagnostics.push({level:`warn`,message:`blocked plugin candidate: package entry escapes package root (${n})`,source:i});continue}if(!B.existsSync(i)){e.diagnostics.push({level:`warn`,message:`plugin entry missing: ${i}`,source:i});continue}if(!Fo.has(I.extname(i))){e.diagnostics.push({level:`warn`,message:`plugin entry not a supported extension: ${i}`,source:i});continue}if(Wo({source:i,rootDir:t,origin:e.origin,diagnostics:e.diagnostics,ownershipUid:e.ownershipUid}))continue;let a=r?.name?.trim(),o=a?`${a}/${Go(i)}`:Go(i);e.candidates.push(Ko({idHint:o,source:i,rootDir:t,origin:e.origin,workspaceDir:e.workspaceDir,packageName:r?.name,packageVersion:r?.version,packageDescription:r?.description,packageDir:t,packageManifest:r?.aimax}))}continue}let a=qo(t);a&&(Wo({source:a,rootDir:t,origin:e.origin,diagnostics:e.diagnostics,ownershipUid:e.ownershipUid})||e.candidates.push(Ko({idHint:I.basename(t),source:a,rootDir:t,origin:e.origin,workspaceDir:e.workspaceDir})))}}function Yo(e){return e?e.map(wo).filter(e=>typeof e==`string`&&e.length>0):[]}function Xo(){let e=Co();if(e)return I.join(e,`.aimax`,`extensions`)}function Zo(e){return I.join(e,`.aimax`,`extensions`)}function Qo(e){return I.join(e,`.aimax`,`extensions`)}function $o(e={}){let t=[],n=[],r=Yo(e.extraPaths);for(let i of r){if(!B.existsSync(i)){n.push({level:`warn`,message:`plugin path not found: ${i}`,source:i});continue}let r=Mo(i);if(!r){n.push({level:`warn`,message:`plugin path not readable: ${i}`,source:i});continue}if(r.isFile()){if(!Fo.has(I.extname(i))){n.push({level:`warn`,message:`plugin file has unsupported extension: ${i}`,source:i});continue}let r=I.dirname(i);if(Wo({source:i,rootDir:r,origin:`config`,diagnostics:n,ownershipUid:e.ownershipUid}))continue;t.push(Ko({idHint:Go(i),source:i,rootDir:r,origin:`config`,workspaceDir:e.workspaceDir}));continue}r.isDirectory()&&Jo({rootDir:i,origin:`config`,workspaceDir:e.workspaceDir,diagnostics:n,candidates:t,ownershipUid:e.ownershipUid})}e.dataDir?Jo({rootDir:Zo(e.dataDir),origin:`workspace`,workspaceDir:e.workspaceDir,diagnostics:n,candidates:t,ownershipUid:e.ownershipUid}):e.workspaceDir&&Jo({rootDir:Qo(e.workspaceDir),origin:`workspace`,workspaceDir:e.workspaceDir,diagnostics:n,candidates:t,ownershipUid:e.ownershipUid});let i=Xo();return i?Jo({rootDir:i,origin:`global`,workspaceDir:e.workspaceDir,diagnostics:n,candidates:t,ownershipUid:e.ownershipUid}):n.push({level:`warn`,message:`skipping global plugin discovery: home directory is unavailable`}),e.bundledDir&&Jo({rootDir:e.bundledDir,origin:`bundled`,workspaceDir:e.workspaceDir,diagnostics:n,candidates:t,ownershipUid:e.ownershipUid}),{candidates:t,diagnostics:n}}function es(e){let t=e.rejectHardlinks??!0,n=jo(e.rootPath),r=jo(e.absolutePath);if(!n||!r)return{ok:!1,reason:`path`};if(!No(n,r))return{ok:!1,reason:`unsafe`};let i;try{i=B.lstatSync(r)}catch{return{ok:!1,reason:`stat`}}if(t&&typeof i.nlink==`number`&&i.nlink>1)return{ok:!1,reason:`hardlink`};try{return{ok:!0,fd:B.openSync(r,`r`)}}catch{return{ok:!1,reason:`path`}}}const ts=`aimax.plugin.json`,ns=[ts];function rs(e){for(let t of ns){let n=I.join(e,t);if(B.existsSync(n))return n}return I.join(e,ts)}function is(e,t=!0){let n=rs(e),r=es({absolutePath:n,rootPath:e,rejectHardlinks:t});if(!r.ok){let e=r.reason;return e===`path`?{ok:!1,error:`plugin manifest not found: ${n}`,manifestPath:n}:{ok:!1,error:`unsafe plugin manifest path: ${n} (${e})`,manifestPath:n}}let i;try{i=JSON.parse(B.readFileSync(r.fd,`utf-8`))}catch(e){return{ok:!1,error:`failed to parse plugin manifest: ${String(e)}`,manifestPath:n}}finally{B.closeSync(r.fd)}if(!xo(i))return{ok:!1,error:`plugin manifest must be an object`,manifestPath:n};let a=typeof i.id==`string`?i.id.trim():``;if(!a)return{ok:!1,error:`plugin manifest requires id`,manifestPath:n};let o=xo(i.configSchema)?i.configSchema:null;if(!o)return{ok:!1,error:`plugin manifest requires configSchema`,manifestPath:n};let s=typeof i.kind==`string`?i.kind:void 0,c=typeof i.name==`string`?i.name.trim():void 0,l=typeof i.description==`string`?i.description.trim():void 0,u=typeof i.version==`string`?i.version.trim():void 0,d=So(i.skills),f;return xo(i.uiHints)&&(f=i.uiHints),{ok:!0,manifest:{id:a,configSchema:o,kind:s,name:c,description:l,version:u,skills:d,uiHints:f},manifestPath:n}}function as(e){let t=new Map,n=[];for(let r of e){let e=is(r.rootDir);if(!e.ok){n.push({level:`error`,message:e.error,source:r.source,pluginId:r.idHint});continue}let i=e.manifest.id;if(t.has(i)){n.push({level:`warn`,message:`duplicate plugin id ignored: ${i}`,source:r.source,pluginId:i});continue}t.set(i,{id:i,rootDir:r.rootDir,source:r.source,origin:r.origin,manifestPath:e.manifestPath,manifest:e.manifest})}return{manifests:t,diagnostics:n}}let os=function(e){return e.INFO=`INFO`,e.WARN=`WARN`,e.ERROR=`ERROR`,e}({});function ss(){let e=new Date;return`${e.getFullYear()}-${String(e.getMonth()+1).padStart(2,`0`)}-${String(e.getDate()).padStart(2,`0`)} ${String(e.getHours()).padStart(2,`0`)}:${String(e.getMinutes()).padStart(2,`0`)}:${String(e.getSeconds()).padStart(2,`0`)}.${String(e.getMilliseconds()).padStart(3,`0`)}`}function cs(e,t,n,r){process.stderr.write(`[${ss()}] [${e}] [plugin:${t}][logger:${n}] ${r}\n`)}function ls(e){return{version:`0.1.0`,logging:{getLogger:t=>({info:n=>cs(os.INFO,e.pluginId,t,n),warn:n=>cs(os.WARN,e.pluginId,t,n),error:n=>cs(os.ERROR,e.pluginId,t,n)})}}}function us(e){if(!e.config.enabled)return!1;let t=e.config.entries[e.pluginId];if(t?.enabled===!1||e.config.deny.includes(e.pluginId)||e.config.allow.length>0&&!e.config.allow.includes(e.pluginId)||e.origin===`bundled`&&t?.enabled!==!0)return!1;if(e.kind&&e.config.slots?.[e.kind]){let t=e.config.slots[e.kind];if(t&&t!==`none`&&t!==e.pluginId)return!1}return!0}function ds(e){return{id:e.id,source:e.source,origin:e.origin,enabled:e.enabled,status:e.enabled?`loaded`:`disabled`,toolCount:0,hookCount:0,skills:e.skills,configSchema:e.configSchema}}function fs(e){let t=[...e.registry.diagnostics],n=new Ta,r=new Ma,i=[],a=[],o=e.runtime?.llm?ct({baseUrl:e.runtime.llm.baseUrl,apiKey:e.runtime.llm.apiKey,defaultModel:e.runtime.llm.model,hooks:r,hookCtx:e.runtime.hookCtx}):void 0,s=ps(e.runtime?.llmAllowlist),c=Le(import.meta.url,{interopDefault:!0,requireCache:!1});for(let l of e.registry.manifests.values()){let u=us({config:e.plugins,pluginId:l.id,origin:l.origin,kind:l.manifest.kind}),d=ds({id:l.id,source:l.source,origin:l.origin,enabled:u,configSchema:!0,skills:l.manifest.skills??[]});if(!u){a.push(d);continue}let f;try{f=c(l.source)}catch(e){d.status=`error`,d.error=String(e),t.push({level:`error`,message:`failed to load plugin ${l.id}: ${String(e)}`,pluginId:l.id,source:l.source}),a.push(d);continue}let p=f&&typeof f==`object`&&`default`in f?f.default:f,m=typeof p==`function`?p:p&&typeof p==`object`&&typeof p.register==`function`?p.register:void 0;if(!m){d.status=`error`,d.error=`plugin module does not export a register function`,t.push({level:`error`,message:`plugin ${l.id} has no register function`,pluginId:l.id,source:l.source}),a.push(d);continue}let g=ls({pluginId:l.id}),_=e.plugins.entries[l.id]?.config,v={id:l.id,source:l.source,rootDir:l.rootDir,config:_,runtime:g,llm:{chat:async e=>{if(!o)throw Error(`LLM client is not configured`);if(!ms(l.id,n,s))throw Error(`Plugin ${l.id} is not allowed to use LLM`);return o.chat(e)}},registerTool:(e,t)=>{n.register(l.id,e,t),d.toolCount+=1},registerUiTool:(e,t)=>{n.registerUiTool(l.id,e,t),d.toolCount+=1},registerEmbeddingProvider:e=>{if(l.manifest.kind!==`memory`)throw Error(`Plugin ${l.id} is not allowed to register embedding providers`);h({pluginId:l.id,id:e.id,create:e.create,config:_,rootDir:l.rootDir,source:l.source})},registerMemoryProvider:e=>{if(l.manifest.kind!==`memory`)throw Error(`Plugin ${l.id} is not allowed to register memory providers`);A({pluginId:l.id,id:e.id,create:e.create,config:_,rootDir:l.rootDir,source:l.source})},registerHook:(e,t,n)=>{r.register({pluginId:l.id,hookName:e,handler:t,priority:n?.priority,source:l.source}),d.hookCount+=1},registerSkillDir:e=>{let t=I.isAbsolute(e)?e:I.resolve(l.rootDir,e);i.push(t)},createProgressEmitter:()=>Ca(l.id)};try{m(v)}catch(e){d.status=`error`,d.error=String(e),t.push({level:`error`,message:`plugin ${l.id} registration failed: ${String(e)}`,pluginId:l.id,source:l.source})}if(l.manifest.skills&&l.manifest.skills.length>0)for(let e of l.manifest.skills){let t=I.isAbsolute(e)?e:I.resolve(l.rootDir,e);i.push(t)}a.push(d)}return{plugins:a,diagnostics:t,tools:n,hooks:r,skills:i}}function ps(e){return(e??[]).map(e=>e.trim()).filter(Boolean)}function ms(e,t,n){return n.length===0?!1:n.includes(e)?!0:t.namesForPlugin(e).some(e=>n.includes(e))}function hs(e={}){let t=ko(e.config),n=$o({dataDir:e.dataDir,workspaceDir:e.workspaceDir,extraPaths:t.loadPaths,bundledDir:e.bundledDir,ownershipUid:e.ownershipUid}),r=as(n.candidates),i=Ao({config:t,registry:r}),a=fs({registry:r,plugins:t,workspaceDir:e.workspaceDir,runtime:e.runtime});return{registry:a,diagnostics:[...n.diagnostics,...r.diagnostics,...i.diagnostics,...a.diagnostics],normalizedConfig:t}}function gs(e){let{runParams:t,hookContext:n,sessionId:r,eventDispatcher:i}=e,a=e=>{i.dispatchDiagnostic(r,e).catch(()=>void 0)},o=t.plugins?hs({...t.plugins,runtime:{llm:t.llm,hookCtx:n,llmAllowlist:t.plugins.llmAllowlist}}):void 0;if(!o)a({level:`info`,scope:`plugin`,phase:`plugin_system_disabled`,message:`plugin system disabled for this run`});else{a({level:o.diagnostics.some(e=>e.level===`error`)?`warn`:`info`,scope:`plugin`,phase:`plugin_system_initialized`,message:`plugin system initialized`,details:{pluginCount:o.registry.plugins.length,enabledPluginCount:o.registry.plugins.filter(e=>e.status===`loaded`).length,disabledPluginCount:o.registry.plugins.filter(e=>e.status===`disabled`).length,errorPluginCount:o.registry.plugins.filter(e=>e.status===`error`).length,diagnosticCount:o.diagnostics.length}});for(let e of o.registry.plugins)a({level:e.status===`error`?`error`:e.status===`disabled`?`warn`:`info`,scope:`plugin`,phase:`plugin_${e.status}`,message:e.status===`error`?`plugin failed to initialize`:e.status===`disabled`?`plugin disabled`:`plugin enabled`,details:{pluginId:e.id,origin:e.origin,toolCount:e.toolCount,hookCount:e.hookCount,skillCount:e.skills.length,source:e.source,errorMessage:e.error}});for(let e of o.diagnostics)a({level:e.level===`error`?`error`:`warn`,scope:`plugin`,phase:`plugin_diagnostic`,message:e.message,details:{pluginId:e.pluginId,source:e.source}})}return{hookRegistry:o?.registry.hooks??new Ma,pluginSkillDirs:o?.registry.skills??[],pluginTools:[...o?.registry.tools.resolveEnabled(t.plugins?.toolAllowlist)??[],...o?.registry.tools.resolveUiTools(r,t.uiToolResume,t.plugins?.toolAllowlist)??[]],memoryPluginId:t.memory?.pluginId??o?.normalizedConfig.slots?.memory}}async function _s(e){let{runParams:t,requestedSessionId:n,eventDispatcher:r}=e,i=I.join(t.dataDir,`workspace`),a=n,o=!a;a?await x(t.dataDir,a,{storeName:t.sessionStoreName}):a=await f(t.dataDir,t.channel,{storeName:t.sessionStoreName});let s={sessionId:a,workspaceDir:i,channel:t.channel},c=gs({runParams:t,hookContext:s,sessionId:a,eventDispatcher:r}),l=c.hookRegistry,u=await _o({runParams:t,sessionId:a,hookContext:s,memoryProviderId:t.memory?.providerId,memoryPluginId:c.memoryPluginId,eventDispatcher:r,hookRegistry:l});return{sessionId:a,isNewSession:o,workspaceDir:i,hookContext:s,hookRegistry:l,pluginContext:c,runContext:u,start:e=>Ut({sessionId:a,runParams:t,hookRegistry:l,hookContext:s,eventDispatcher:r,...e})}}function vs(e){return e===null||typeof e==`string`||typeof e==`number`||typeof e==`boolean`?e:JSON.stringify(e)??String(e)}function ys(e){if(!(e instanceof Error))return{errorValue:vs(e)};let t={errorName:e.name,errorMessage:e.message};e.stack&&(t.stack=e.stack);let n=e;for(let e of[`code`,`statusCode`,`statusText`,`providerMessage`,`retryable`,`cause`])n[e]!==void 0&&(t[e]=vs(n[e]));return t}async function bs(e){await e.dispatcher.dispatchDiagnostic(e.sessionId,{level:`error`,scope:e.scope,phase:e.phase,message:e.message,details:{...e.details,...ys(e.error)}})}function xs(e,t,n){return I.join(o(e,t,n),`pending-hitl.json`)}function Ss(e,t,n){return I.join(o(e,t,n),`hitl-history.jsonl`)}async function Cs(e,t,n,r){let i=o(e,t,r);await F.mkdir(i,{recursive:!0});let a=xs(e,t,r);await F.writeFile(a,JSON.stringify(n,null,2),`utf-8`)}async function ws(e,t,n,r){let i=o(e,t,r);await F.mkdir(i,{recursive:!0});let a=Ss(e,t,r),s=JSON.stringify(n)+`
80
80
  `;await F.appendFile(a,s,`utf-8`)}async function Ts(e,t,n){let r=xs(e,t,n);try{let e=await F.readFile(r,`utf-8`);return JSON.parse(e)}catch(e){if(e.code===`ENOENT`)return null;throw e}}async function Es(e,t,n){let r=Ss(e,t,n);try{let e=await F.readFile(r,`utf-8`),t=[];for(let n of e.split(`
81
- `)){let e=n.trim();if(e)try{t.push(JSON.parse(e))}catch{}}return t}catch(e){if(e.code===`ENOENT`)return[];throw e}}async function Ds(e,t,n,r,i,a,o){let s=new Date().toISOString(),c={version:1,sessionId:t,request:n,status:`pending`,checkpoint:r,context:i,toolContext:a,createdAt:s,updatedAt:s};return await Cs(e,t,c,o),await ws(e,t,{requestId:n.requestId,sessionId:t,action:`requested`,payload:n,timestamp:s},o),c}async function Os(e,t,n,r,i,a){let o=await Ts(e,t,a);if(!o||o.request.requestId!==n||o.status!==`pending`)return null;let s=new Date().toISOString(),c={...o,status:r,resolution:i,updatedAt:s};await Cs(e,t,c,a);let l={resolved:`resolved`,expired:`expired`,cancelled:`cancelled`}[r];return await ws(e,t,{requestId:n,sessionId:t,action:l,payload:i??o.request,timestamp:s},a),c}async function ks(e,t,n,r){let i=await Ts(e,t,r);return!i||i.request.requestId!==n?null:i.status===`resolved`?i:null}async function As(e,t,n){let r=xs(e,t,n);try{await F.unlink(r)}catch(e){if(e.code===`ENOENT`)return;throw e}}function js(e,t,n){return I.join(o(e,t,n),`pending-ui-tool.json`)}async function Ms(e,t,n,r){let i=o(e,t,r);await F.mkdir(i,{recursive:!0}),await F.writeFile(js(e,t,r),JSON.stringify(n,null,2),`utf-8`)}async function Ns(e,t,n){try{let r=await F.readFile(js(e,t,n),`utf-8`);return JSON.parse(r)}catch(e){if(e.code===`ENOENT`)return null;throw e}}async function Ps(e,t,n,r){let i=new Date().toISOString(),a={version:1,sessionId:t,request:n,status:`pending`,createdAt:i,updatedAt:i};return await Ms(e,t,a,r),a}async function Fs(e,t,n,r,i){let a=await Ns(e,t,i);if(!a||a.request.requestId!==n||a.status!==`pending`)return null;let o={...a,status:`resolved`,result:r,updatedAt:new Date().toISOString()};return await Ms(e,t,o,i),o}async function Is(e,t,n){try{await F.unlink(js(e,t,n))}catch(e){if(e.code===`ENOENT`)return;throw e}}function Ls(e,t){return{id:e.model,name:e.model,api:`openai-completions`,provider:`openai`,baseUrl:e.baseUrl,reasoning:!1,input:[`text`],cost:{input:0,output:0,cacheRead:0,cacheWrite:0},contextWindow:e.contextWindow??2e5,maxTokens:32768,headers:{"Client-Code":`AIMax`,"X-Session-Id":t},compat:{supportsStore:!1,supportsDeveloperRole:!1,supportsReasoningEffort:!1,supportsUsageInStreaming:!0}}}async function Rs(e,t){Lt();let n=Date.now(),r=new Rt(e),i=Cn(e),a=i.transcriptMessage,o=!1,s=i.previousSessionId,c=await _s({runParams:e,requestedSessionId:i.requestedSessionId,eventDispatcher:r}),l=c.sessionId,u=c.isNewSession,d=c.workspaceDir,f=c.hookContext,p=c.hookRegistry,m=c.pluginContext,h=c.runContext;await r.dispatchDiagnostic(l,{level:`info`,scope:`runner`,phase:`run_started`,message:`agent run started`,details:{channel:e.channel,isNewSession:u,hasMessageId:!!e.messageId,hasPlugins:!!e.plugins,hasMemory:!!e.memory}}),await r.dispatchDiagnostic(l,{level:`info`,scope:`session`,phase:u?`session_created`:`session_resumed`,message:u?`session created`:`session resumed`,details:{requestedSessionId:i.requestedSessionId,previousSessionId:s,workspaceDir:d}}),u&&await E(e.dataDir,vo({sessionId:l,title:Ht(a),channel:e.channel}),{storeName:e.sessionStoreName}),i.resetCommand&&!e.hitlResume&&!e.uiToolResume&&(o=await h.persistInitialUserEntry(a)),await c.start({resetCommand:i.resetCommand,previousSessionId:s,resetMessage:i.slashCommandSource,startMessage:typeof i.promptInput==`string`?i.promptInput:a});let g=new AbortController;e.abortSignal?.aborted?g.abort():e.abortSignal?.addEventListener(`abort`,()=>g.abort());let _=await Ve(e.dataDir),v=[],y=We(_,{warn:e=>v.push(e)});await r.dispatchDiagnostic(l,{level:v.length>0?`warn`:`info`,scope:`runner`,phase:`bootstrap_loaded`,message:`bootstrap context loaded`,details:{bootstrapFileCount:_.length,contextFileCount:y.length,warningCount:v.length}});let b=await Xe(e.dataDir,m.pluginSkillDirs),x=new st({workspaceDir:d,sessionId:l,skills:b,report:e=>r.dispatchProgress(l,e),reportDiagnostic:e=>r.dispatchDiagnostic(l,{level:e.level,scope:`skill`,phase:e.phase,message:e.message,details:e.details})});await r.dispatchDiagnostic(l,{level:`info`,scope:`skill`,phase:`skills_loaded`,message:`skills loaded`,details:{skillCount:b.length,pluginSkillDirCount:m.pluginSkillDirs.length}});let S=e=>h.appendTranscriptEntry(e),C=await Tn({invocation:i,skills:b,sessionId:l,isNewSession:u,initialUserEntryPersisted:o,runParams:e,hookRegistry:p,hookContext:f,startTime:n,eventDispatcher:r});if(C.kind===`completed`)return C.result;let w=C.effectivePrompt;a=C.transcriptMessage;let T=typeof w==`string`?w:a;await r.dispatchDiagnostic(l,{level:`info`,scope:`runner`,phase:`invocation_resolved`,message:`invocation resolved`,details:{promptType:typeof w==`string`?`string`:`messages`,transcriptLength:a.length}});let D=await Qa({session:{runParams:e,sessionId:l,hookRegistry:p,hookContext:f,runContext:h,eventDispatcher:r},runtimeInputs:{contextFiles:y,bootstrapWarnings:v,skills:b,effectivePromptText:T,pluginTools:m.pluginTools},dependencies:{registry:t,spawnFn:e=>Rs(e,new tt),createModel:Ls,abortSignal:g.signal}}),O=D.agent,k=D.resolvedModelId;await r.dispatchDiagnostic(l,{level:`info`,scope:`runner`,phase:`runtime_created`,message:`agent runtime created`,details:{modelId:k,historyMessageCount:D.historyMessages.length,pluginToolCount:m.pluginTools.length}}),g.signal.addEventListener(`abort`,()=>O.abort());let A=0,j=0,M=``,N;try{!e.hitlResume&&!e.uiToolResume&&(o=await h.persistInitialUserEntry(a)||o),await r.dispatchDiagnostic(l,{level:`info`,scope:`runner`,phase:`first_turn_started`,message:`first agent turn started`});let n=await eo({agent:O,message:w,continueFromHistory:!!e.uiToolResume,sessionId:l,modelId:k,historyMessages:D.historyMessages,eventDispatcher:r,skillUsageTracker:x,hooks:p,hookCtx:f,abortSignal:g.signal,onTurnRecordProduced:async(e,t)=>{e&&await S(e);for(let e of t)await S(e)}});M=n.text,A+=n.inputTokens,j+=n.outputTokens,n.error&&(N=n.error),await r.dispatchDiagnostic(l,{level:n.error?`warn`:`info`,scope:`runner`,phase:`first_turn_completed`,message:`first agent turn completed`,details:{hasError:!!n.error,error:n.error,inputTokens:n.inputTokens,outputTokens:n.outputTokens}}),await r.dispatchDiagnostic(l,{level:`info`,scope:`runner`,phase:`announce_loop_started`,message:`announce loop started`});let i=await fo({agent:O,registry:t,sessionId:l,resolvedModelId:k,eventDispatcher:r,skillUsageTracker:x,hookRegistry:p,hookContext:f,abortSignal:g.signal,appendEntry:S});i.text&&(M=i.text),A+=i.inputTokens,j+=i.outputTokens,i.error&&!N&&(N=i.error),await r.dispatchDiagnostic(l,{level:i.error?`warn`:`info`,scope:`runner`,phase:`announce_loop_completed`,message:`announce loop completed`,details:{hasError:!!i.error,error:i.error,inputTokens:i.inputTokens,outputTokens:i.outputTokens}})}catch(t){if(sr(t)){let i=t,o=e.subagentContext?.parentSessionId??l,s=o===i.request.sessionId?i.request:{...i.request,sessionId:o};await Ds(e.dataDir,o,s,i.checkpoint,{agentId:e.subagentContext?`subagent-depth-${e.subagentContext.depth}`:void 0,channel:e.channel,parentSessionId:e.subagentContext?.parentSessionId,depth:e.subagentContext?.depth},i.toolContext),await r.dispatchProgress(o,{type:`hitl_requested`,request:s}),await r.dispatchDiagnostic(l,{level:`info`,scope:`runner`,phase:`hitl_paused`,message:`agent paused for HITL: ${i.request.kind} — ${i.request.title}`,details:{requestId:s.requestId,kind:s.kind,checkpointPhase:i.checkpoint.phase,bubbledToParent:!!e.subagentContext?.parentSessionId}});let c={input:A,output:j,total:A+j};return Kt({sessionId:l,isNewSession:u,transcriptMessage:a,runParams:e,hookRegistry:p,hookContext:f,startTime:n,eventDispatcher:r,text:M||`[HITL paused] ${i.request.title}: ${i.request.prompt}`,usage:c,error:void 0,paused:{requestId:s.requestId,kind:s.kind,title:s.title}})}if(Gi(t)){let i=t;await Ps(e.dataDir,l,i.request,{storeName:e.sessionStoreName}),await r.dispatchProgress(l,{type:`ui_tool_request`,request:i.request}),await r.dispatchDiagnostic(l,{level:`info`,scope:`tool`,phase:`ui_tool_paused`,message:`agent paused for UI tool input: ${i.request.toolName}`,details:{requestId:i.request.requestId,toolName:i.request.toolName,toolCallId:i.request.toolCallId,schemaTitle:i.request.schema.title,propertyCount:Object.keys(i.request.schema.properties).length}});let o={input:A,output:j,total:A+j};return Kt({sessionId:l,isNewSession:u,transcriptMessage:a,runParams:e,hookRegistry:p,hookContext:f,startTime:n,eventDispatcher:r,text:M||`[UI Tool] Waiting for user input: ${i.request.schema.title}`,usage:o,error:void 0,uiToolPending:{requestId:i.request.requestId,toolName:i.request.toolName,toolCallId:i.request.toolCallId,schema:i.request.schema,extra:i.request.extra}})}throw await bs({dispatcher:r,sessionId:l,scope:`runner`,phase:`run_failed`,message:`agent run failed`,error:t,details:{channel:e.channel,isNewSession:u}}),t}finally{it(l),h.stop()}let P={input:A,output:j,total:A+j};return await r.dispatchDiagnostic(l,{level:N?`warn`:`info`,scope:`runner`,phase:`run_completed`,message:`agent run completed`,details:{durationMs:Date.now()-n,inputTokens:P.input,outputTokens:P.output,totalTokens:P.total,hasError:!!N,error:N}}),Kt({sessionId:l,isNewSession:u,transcriptMessage:a,runParams:e,hookRegistry:p,hookContext:f,startTime:n,eventDispatcher:r,text:M,usage:P,error:N})}async function zs(e,t){let n=t??new tt;try{return await Rs(e,n)}catch(t){throw e.onProgress&&await e.onProgress({type:`diagnostic`,level:`error`,scope:`runner`,phase:`run_crashed`,message:`agent run crashed before completion`,details:ys(t)}),t}}const Bs={"AGENTS.md":`---
81
+ `)){let e=n.trim();if(e)try{t.push(JSON.parse(e))}catch{}}return t}catch(e){if(e.code===`ENOENT`)return[];throw e}}async function Ds(e,t,n,r,i,a,o){let s=new Date().toISOString(),c={version:1,sessionId:t,request:n,status:`pending`,checkpoint:r,context:i,toolContext:a,createdAt:s,updatedAt:s};return await Cs(e,t,c,o),await ws(e,t,{requestId:n.requestId,sessionId:t,action:`requested`,payload:n,timestamp:s},o),c}async function Os(e,t,n,r,i,a){let o=await Ts(e,t,a);if(!o||o.request.requestId!==n||o.status!==`pending`)return null;let s=new Date().toISOString(),c={...o,status:r,resolution:i,updatedAt:s};await Cs(e,t,c,a);let l={resolved:`resolved`,expired:`expired`,cancelled:`cancelled`}[r];return await ws(e,t,{requestId:n,sessionId:t,action:l,payload:i??o.request,timestamp:s},a),c}async function ks(e,t,n,r){let i=await Ts(e,t,r);return!i||i.request.requestId!==n?null:i.status===`resolved`?i:null}async function As(e,t,n){let r=xs(e,t,n);try{await F.unlink(r)}catch(e){if(e.code===`ENOENT`)return;throw e}}function js(e,t,n){return I.join(o(e,t,n),`pending-ui-tool.json`)}async function Ms(e,t,n,r){let i=o(e,t,r);await F.mkdir(i,{recursive:!0}),await F.writeFile(js(e,t,r),JSON.stringify(n,null,2),`utf-8`)}async function Ns(e,t,n){try{let r=await F.readFile(js(e,t,n),`utf-8`);return JSON.parse(r)}catch(e){if(e.code===`ENOENT`)return null;throw e}}async function Ps(e,t,n,r){let i=new Date().toISOString(),a={version:1,sessionId:t,request:n,status:`pending`,createdAt:i,updatedAt:i};return await Ms(e,t,a,r),a}async function Fs(e,t,n,r,i){let a=await Ns(e,t,i);if(!a||a.request.requestId!==n||a.status!==`pending`)return null;let o={...a,status:`resolved`,result:r,updatedAt:new Date().toISOString()};return await Ms(e,t,o,i),o}async function Is(e,t,n){try{await F.unlink(js(e,t,n))}catch(e){if(e.code===`ENOENT`)return;throw e}}function Ls(e,t){return{id:e.model,name:e.model,api:`openai-completions`,provider:`openai`,baseUrl:e.baseUrl,reasoning:!1,input:[`text`],cost:{input:0,output:0,cacheRead:0,cacheWrite:0},contextWindow:e.contextWindow??2e5,maxTokens:32768,headers:{"Client-Code":`AIMax`,"X-Session-Id":t},compat:{supportsStore:!1,supportsDeveloperRole:!1,supportsReasoningEffort:!1,supportsUsageInStreaming:!0}}}async function Rs(e,t){Lt();let n=Date.now(),r=new Rt(e),i=Cn(e),a=i.transcriptMessage,o=!1,s=i.previousSessionId,c=await _s({runParams:e,requestedSessionId:i.requestedSessionId,eventDispatcher:r}),l=c.sessionId,u=c.isNewSession,d=c.workspaceDir,f=c.hookContext,p=c.hookRegistry,m=c.pluginContext,h=c.runContext;await r.dispatchDiagnostic(l,{level:`info`,scope:`runner`,phase:`run_started`,message:`agent run started`,details:{channel:e.channel,isNewSession:u,hasMessageId:!!e.messageId,hasPlugins:!!e.plugins,hasMemory:!!e.memory}}),await r.dispatchDiagnostic(l,{level:`info`,scope:`session`,phase:u?`session_created`:`session_resumed`,message:u?`session created`:`session resumed`,details:{requestedSessionId:i.requestedSessionId,previousSessionId:s,workspaceDir:d}}),u&&await E(e.dataDir,vo({sessionId:l,title:Ht(a),channel:e.channel}),{storeName:e.sessionStoreName}),i.resetCommand&&!e.hitlResume&&!e.uiToolResume&&(o=await h.persistInitialUserEntry(a)),await c.start({resetCommand:i.resetCommand,previousSessionId:s,resetMessage:i.slashCommandSource,startMessage:typeof i.promptInput==`string`?i.promptInput:a});let g=new AbortController;e.abortSignal?.aborted?g.abort():e.abortSignal?.addEventListener(`abort`,()=>g.abort());let _=await Ve(e.dataDir),v=[],y=We(_,{warn:e=>v.push(e)});await r.dispatchDiagnostic(l,{level:v.length>0?`warn`:`info`,scope:`runner`,phase:`bootstrap_loaded`,message:`bootstrap context loaded`,details:{bootstrapFileCount:_.length,contextFileCount:y.length,warningCount:v.length}});let b=await Xe(e.dataDir,m.pluginSkillDirs),x=new st({workspaceDir:d,sessionId:l,skills:b,report:e=>r.dispatchProgress(l,e),reportDiagnostic:e=>r.dispatchDiagnostic(l,{level:e.level,scope:`skill`,phase:e.phase,message:e.message,details:e.details})});await r.dispatchDiagnostic(l,{level:`info`,scope:`skill`,phase:`skills_loaded`,message:`skills loaded`,details:{skillCount:b.length,pluginSkillDirCount:m.pluginSkillDirs.length}});let S=e=>h.appendTranscriptEntry(e),C=await Tn({invocation:i,skills:b,sessionId:l,isNewSession:u,initialUserEntryPersisted:o,runParams:e,hookRegistry:p,hookContext:f,startTime:n,eventDispatcher:r});if(C.kind===`completed`)return C.result;let w=C.effectivePrompt;a=C.transcriptMessage;let T=typeof w==`string`?w:a;await r.dispatchDiagnostic(l,{level:`info`,scope:`runner`,phase:`invocation_resolved`,message:`invocation resolved`,details:{promptType:typeof w==`string`?`string`:`messages`,transcriptLength:a.length}});let D=await Qa({session:{runParams:e,sessionId:l,hookRegistry:p,hookContext:f,runContext:h,eventDispatcher:r},runtimeInputs:{contextFiles:y,bootstrapWarnings:v,skills:b,effectivePromptText:T,pluginTools:m.pluginTools},dependencies:{registry:t,spawnFn:e=>Rs(e,new tt),createModel:Ls,abortSignal:g.signal}}),O=D.agent,k=D.resolvedModelId;await r.dispatchDiagnostic(l,{level:`info`,scope:`runner`,phase:`runtime_created`,message:`agent runtime created`,details:{modelId:k,historyMessageCount:D.historyMessages.length,pluginToolCount:m.pluginTools.length}}),g.signal.addEventListener(`abort`,()=>O.abort());let A=0,j=0,M=``,N;try{!e.hitlResume&&!e.uiToolResume&&(o=await h.persistInitialUserEntry(a)||o),await r.dispatchDiagnostic(l,{level:`info`,scope:`runner`,phase:`first_turn_started`,message:`first agent turn started`});let n=await eo({agent:O,message:w,continueFromHistory:!!e.uiToolResume,sessionId:l,modelId:k,historyMessages:D.historyMessages,eventDispatcher:r,skillUsageTracker:x,hooks:p,hookCtx:f,abortSignal:g.signal,onTurnRecordProduced:async(e,t)=>{e&&await S(e);for(let e of t)await S(e)}});M=n.text,A+=n.inputTokens,j+=n.outputTokens,n.error&&(N=n.error),await r.dispatchDiagnostic(l,{level:n.error?`warn`:`info`,scope:`runner`,phase:`first_turn_completed`,message:`first agent turn completed`,details:{hasError:!!n.error,error:n.error,inputTokens:n.inputTokens,outputTokens:n.outputTokens}}),await r.dispatchDiagnostic(l,{level:`info`,scope:`runner`,phase:`announce_loop_started`,message:`announce loop started`});let i=await fo({agent:O,registry:t,sessionId:l,resolvedModelId:k,eventDispatcher:r,skillUsageTracker:x,hookRegistry:p,hookContext:f,abortSignal:g.signal,appendEntry:S});i.text&&(M=i.text),A+=i.inputTokens,j+=i.outputTokens,i.error&&!N&&(N=i.error),await r.dispatchDiagnostic(l,{level:i.error?`warn`:`info`,scope:`runner`,phase:`announce_loop_completed`,message:`announce loop completed`,details:{hasError:!!i.error,error:i.error,inputTokens:i.inputTokens,outputTokens:i.outputTokens}})}catch(t){if(sr(t)){let i=t,o=e.subagentContext?.parentSessionId??l,s=o===i.request.sessionId?i.request:{...i.request,sessionId:o};await Ds(e.dataDir,o,s,i.checkpoint,{agentId:e.subagentContext?`subagent-depth-${e.subagentContext.depth}`:void 0,channel:e.channel,parentSessionId:e.subagentContext?.parentSessionId,depth:e.subagentContext?.depth},i.toolContext),await r.dispatchProgress(o,{type:`hitl_requested`,request:s}),await r.dispatchDiagnostic(l,{level:`info`,scope:`runner`,phase:`hitl_paused`,message:`agent paused for HITL: ${i.request.kind} — ${i.request.title}`,details:{requestId:s.requestId,kind:s.kind,checkpointPhase:i.checkpoint.phase,bubbledToParent:!!e.subagentContext?.parentSessionId}});let c={input:A,output:j,total:A+j};return Kt({sessionId:l,isNewSession:u,transcriptMessage:a,runParams:e,hookRegistry:p,hookContext:f,startTime:n,eventDispatcher:r,text:M||`[HITL paused] ${i.request.title}: ${i.request.prompt}`,usage:c,error:void 0,paused:{requestId:s.requestId,kind:s.kind,title:s.title}})}if(Gi(t)){let i=t;await Ps(e.dataDir,l,i.request,{storeName:e.sessionStoreName}),await r.dispatchProgress(l,{type:`ui_tool_request`,request:i.request}),await r.dispatchDiagnostic(l,{level:`info`,scope:`tool`,phase:`ui_tool_paused`,message:`agent paused for UI tool input: ${i.request.toolName}`,details:{requestId:i.request.requestId,toolName:i.request.toolName,toolCallId:i.request.toolCallId,outputSchemaTitle:i.request.outputSchema.title,propertyCount:Object.keys(i.request.outputSchema.properties).length}});let o={input:A,output:j,total:A+j};return Kt({sessionId:l,isNewSession:u,transcriptMessage:a,runParams:e,hookRegistry:p,hookContext:f,startTime:n,eventDispatcher:r,text:M||`[UI Tool] Waiting for user input: ${i.request.outputSchema.title}`,usage:o,error:void 0,uiToolPending:{requestId:i.request.requestId,toolName:i.request.toolName,toolCallId:i.request.toolCallId,outputSchema:i.request.outputSchema,extra:i.request.extra}})}throw await bs({dispatcher:r,sessionId:l,scope:`runner`,phase:`run_failed`,message:`agent run failed`,error:t,details:{channel:e.channel,isNewSession:u}}),t}finally{it(l),h.stop()}let P={input:A,output:j,total:A+j};return await r.dispatchDiagnostic(l,{level:N?`warn`:`info`,scope:`runner`,phase:`run_completed`,message:`agent run completed`,details:{durationMs:Date.now()-n,inputTokens:P.input,outputTokens:P.output,totalTokens:P.total,hasError:!!N,error:N}}),Kt({sessionId:l,isNewSession:u,transcriptMessage:a,runParams:e,hookRegistry:p,hookContext:f,startTime:n,eventDispatcher:r,text:M,usage:P,error:N})}async function zs(e,t){let n=t??new tt;try{return await Rs(e,n)}catch(t){throw e.onProgress&&await e.onProgress({type:`diagnostic`,level:`error`,scope:`runner`,phase:`run_crashed`,message:`agent run crashed before completion`,details:ys(t)}),t}}const Bs={"AGENTS.md":`---
82
82
  title: "AGENTS.md Template"
83
83
  summary: ".aimax template for AGENTS.md"
84
84
  read_when:
@@ -385,4 +385,4 @@ read_when:
385
385
  # Add tasks below when you want the agent to check something periodically.
386
386
 
387
387
  # This file lives at .aimax/HEARTBEAT.md, not in workspace/.
388
- `},Vs=[`AGENTS.md`,`BOOTSTRAP.md`,`IDENTITY.md`,`USER.md`,`SOUL.md`,`TOOLS.md`,`HEARTBEAT.md`];async function $(e,t){try{if(!(await F.stat(e)).isDirectory())throw Error(`Path exists but is not a directory: ${e}`);t.skippedDirs.push(e);return}catch(e){if(e.code!==`ENOENT`)throw e}await F.mkdir(e,{recursive:!0}),t.createdDirs.push(e)}async function Hs(e,t,n){try{if(!(await F.stat(e)).isFile())throw Error(`Path exists but is not a file: ${e}`);n.skippedFiles.push(e);return}catch(e){if(e.code!==`ENOENT`)throw e}await F.mkdir(I.dirname(e),{recursive:!0});try{await F.writeFile(e,t,{encoding:`utf-8`,flag:`wx`}),n.createdFiles.push(e)}catch(t){if(t.code===`EEXIST`){n.skippedFiles.push(e);return}throw t}}function Us(e){let t=V(e);return[e,t,I.join(t,`skills`),I.join(t,`sessions`),I.join(t,`memory`),I.join(e,`workspace`)]}function Ws(e){let t=V(e);return[...Vs.filter(e=>e!==`BOOTSTRAP.md`).map(e=>I.join(t,e)),I.join(t,`MEMORY.md`)]}function Gs(e){return I.join(V(e),`.bootstrapped`)}async function Ks(e){try{return(await F.stat(Gs(e))).isFile()}catch(e){if(e.code===`ENOENT`)return!1;throw e}}async function qs(e){let t=Gs(e);await F.mkdir(I.dirname(t),{recursive:!0}),await F.writeFile(t,``,{encoding:`utf-8`})}async function Js(e){let t=[],n=[];for(let n of Us(e))try{(await F.stat(n)).isDirectory()||t.push(n)}catch(e){if(e.code===`ENOENT`){t.push(n);continue}throw e}for(let t of Ws(e))try{(await F.stat(t)).isFile()||n.push(t)}catch(e){if(e.code===`ENOENT`){n.push(t);continue}throw e}return{dataDir:e,ready:t.length===0&&n.length===0,missingDirs:t,missingFiles:n}}async function Ys(e){return(await Js(e)).ready}async function Xs(e){if(await Ks(e))return{ready:!0,performedBootstrap:!1};if((await Js(e)).ready)return await qs(e),{ready:!0,performedBootstrap:!1};let t=await Zs(e);return await qs(e),{ready:!0,performedBootstrap:!0,result:t}}async function Zs(e){let t={dataDir:e,createdDirs:[],skippedDirs:[],createdFiles:[],skippedFiles:[]},n=V(e),r=I.join(e,`workspace`),i=I.join(n,`skills`),a=I.join(n,`sessions`),o=I.join(n,`memory`);await $(e,t),await $(n,t),await $(i,t),await $(a,t),await $(o,t),await $(r,t);for(let e of Vs){let r=Bs[e]??``;await Hs(I.join(n,e),r,t)}return await Hs(I.join(n,`MEMORY.md`),``,t),t}async function Qs(e){let t=I.join(e,`.aimax`,`subagents`,`runs.json`);try{let e=await F.readFile(t,`utf-8`),n=JSON.parse(e);if(!n||typeof n!=`object`)return new Map;let r;if(n.version===1&&n.records)r=n.records;else if(n.version===void 0)r=n;else return new Map;let i=new Map;for(let[e,t]of Object.entries(r)){if(!t||typeof t!=`object`)continue;let n=t;i.set(e,{...n,abortController:new AbortController})}return i}catch(e){return e.code,new Map}}async function $s(e,t){let n=I.join(e,`.aimax`,`subagents`,`runs.json`),r={};for(let[e,n]of t.entries())if(typeof n.endedAt==`number`){let{abortController:t,...i}=n;r[e]={...i,version:1}}let i={version:1,records:r};await F.mkdir(I.dirname(n),{recursive:!0}),await F.writeFile(n,JSON.stringify(i,null,2),`utf-8`)}async function ec(e,t){let n=await Qs(e),r=[];for(let e of n.values())if(e.parentSessionId===t){let{abortController:t,...n}=e;r.push({...n,version:1})}return r.sort((e,t)=>e.startedAt-t.startedAt)}async function tc(e,t=7){let n=await Qs(e),r=Date.now()-t*24*60*60*1e3,i=0;for(let[e,t]of n.entries())t.endedAt&&t.endedAt<r&&(n.delete(e),i++);return i>0&&await $s(e,n),i}async function nc(e,t,n,r){let i=await Ts(e,t,{storeName:r});return i?i.request.requestId===n?i.sessionId===t?i.status===`pending`?Ne(i.request)?(await Os(e,t,n,`expired`,void 0,{storeName:r}),{valid:!1,reason:`HITL request has expired`}):{valid:!0,state:i}:{valid:!1,reason:`HITL request is already "${i.status}", cannot resume`}:{valid:!1,reason:`Session ID mismatch: expected "${i.sessionId}", got "${t}"`}:{valid:!1,reason:`Request ID mismatch: expected "${i.request.requestId}", got "${n}"`}:{valid:!1,reason:`No pending HITL request found for this session`}}async function rc(e){let{dataDir:t,sessionId:n,requestId:r,resolution:i,sessionStoreName:a}=e,o=await ks(t,n,r,{storeName:a});if(o){let e=o.resolution?.idempotencyKey;if(e&&i.idempotencyKey&&e===i.idempotencyKey)return{state:o,idempotentReplay:!0};throw Error(`HITL resume validation failed: HITL request is already "${o.status}", cannot resume`)}let s=await nc(t,n,r,a);if(!s.valid)throw Error(`HITL resume validation failed: ${s.reason}`);let c=await Os(t,n,r,`resolved`,i,{storeName:a});if(!c)throw Error(`Failed to transition HITL state to resolved (concurrent modification?)`);return{state:c,idempotentReplay:!1}}export{Be as BOOTSTRAP_FILE_NAMES,Re as BOOTSTRAP_MAX_CHARS,ze as BOOTSTRAP_TOTAL_MAX_CHARS,u as DEFAULT_SESSION_STORE_NAME,Y as HITL_MESSAGES,K as HitlPauseSignal,et as MAX_CHILDREN_PER_SESSION,$e as MAX_SUBAGENT_DEPTH,S as MemoryIndexManager,ts as PLUGIN_MANIFEST_FILENAME,ns as PLUGIN_MANIFEST_FILENAMES,Ma as PluginHookRegistry,Ta as PluginToolRegistry,tt as SubagentRegistry,Wi as UiToolPauseSignal,de as addAgent,se as addBinding,V as aimaxDir,xi as appendToMemory,_ as appendTranscriptEntry,oi as approvalSummaryFromResolution,Zs as bootstrapMountLayout,We as buildBootstrapContextFiles,li as buildResumeNarration,Qe as buildSkillsPrompt,Ii as buildSubagentAnnounceMessage,ba as buildSystemPrompt,tc as cleanupOldSubagentRecords,As as clearPendingHitl,Is as clearPendingUiTool,w as collapseLogPath,d as contextSnapshotPath,Qi as createAgentTools,Jr as createApplyPatchTool,jr as createBashTool,y as createBuiltinMemoryProvider,di as createClarifyTool,ar as createContextManager,Br as createEditFileTool,_r as createExecTool,Ui as createImageTool,Hr as createListDirTool,ki as createMemoryAppendTool,Di as createMemoryGetTool,Ti as createMemorySearchTool,Ds as createPendingHitl,Ps as createPendingUiTool,Ca as createPluginProgressEmitter,ls as createPluginRuntime,xr as createProcessTool,Ir as createReadFileTool,Mi as createRequestApprovalTool,Pi as createRequestReviewTool,f as createSession,Ln as createSessionContextStore,Li as createSessionsSpawnTool,Vi as createSubagentsTool,Zi as createUiTool,Rr as createWriteFileTool,Ci as deleteMemoryFile,$o as discoverAIMaxPlugins,Xs as ensureBootstrapMountLayout,x as ensureSession,v as exportSession,ji as formatApprovalResolution,si as formatClarifyResolution,ci as formatReviewResolution,Bt as generateSessionTitle,ie as getAgentConfig,bi as getMemoryLines,Ks as hasBootstrapSentinel,Ss as hitlHistoryPath,hs as initializePluginSystem,Js as inspectBootstrapMountLayout,m as inspectSession,Ys as isBootstrapMountLayoutReady,sr as isHitlPauseSignal,Gi as isUiToolPauseSignal,N as listAgents,Zt as listAvailableSlashCommands,ce as listBindings,gi as listMemoryFiles,p as listSessionSummaries,s as listSessions,ec as listSubagentRunsFromDisk,ue as loadAgentsConfig,Ve as loadBootstrapFiles,Ts as loadPendingHitl,Ts as readPendingHitl,Ns as loadPendingUiTool,Ns as readPendingUiTool,is as loadPluginManifest,as as loadPluginManifestRegistry,fs as loadPlugins,T as loadSessionContextSnapshot,O as loadSessionMetadata,Ye as loadSkills,Ze as loadSkillsFromDirs,Xe as loadSkillsWithPluginDirs,Qs as loadSubagentRegistryFromDisk,l as loadTranscript,fi as memoryDir,D as metadataPath,P as normalizeAgentId,ko as normalizePluginsConfig,a as normalizeSessionStoreName,xs as pendingHitlPath,js as pendingUiToolPath,pi as primaryMemoryPath,Es as readHitlHistory,_i as readMemoryFile,vi as readPrimaryMemory,h as registerEmbeddingProvider,A as registerMemoryProvider,ae as removeAgent,fe as removeBindings,Si as replaceMemoryFile,c as resetEmbeddingProviderRegistryForTests,j as resetMemoryProviderRegistryForTests,ee as resolveAgentDir,te as resolveAgentIdByBinding,le as resolveAgentsConfigPath,oe as resolveDefaultAgentId,b as resolveEmbeddingProvider,rc as resolveHitlRequest,rc as resolvePendingHitl,k as resolveMemoryProvider,re as resolveModelFallbacks,ne as resolveModelString,Fs as resolvePendingUiTool,rs as resolvePluginManifestPath,t as rewriteTranscript,zs as runAgent,M as saveAgentsConfig,E as saveSessionMetadata,$s as saveSubagentRegistryToDisk,yi as searchMemory,o as sessionDir,r as sessionMemoryPath,n as sessionsDir,Ge as skillsDir,i as toolResultsDir,g as transcriptPath,Os as transitionHitlStatus,pe as updateAgentIdentity,e as updateSessionMetadata,Ao as validatePluginsConfig,nc as validateResume,ja as wrapToolsWithHooks};
388
+ `},Vs=[`AGENTS.md`,`BOOTSTRAP.md`,`IDENTITY.md`,`USER.md`,`SOUL.md`,`TOOLS.md`,`HEARTBEAT.md`];async function $(e,t){try{if(!(await F.stat(e)).isDirectory())throw Error(`Path exists but is not a directory: ${e}`);t.skippedDirs.push(e);return}catch(e){if(e.code!==`ENOENT`)throw e}await F.mkdir(e,{recursive:!0}),t.createdDirs.push(e)}async function Hs(e,t,n){try{if(!(await F.stat(e)).isFile())throw Error(`Path exists but is not a file: ${e}`);n.skippedFiles.push(e);return}catch(e){if(e.code!==`ENOENT`)throw e}await F.mkdir(I.dirname(e),{recursive:!0});try{await F.writeFile(e,t,{encoding:`utf-8`,flag:`wx`}),n.createdFiles.push(e)}catch(t){if(t.code===`EEXIST`){n.skippedFiles.push(e);return}throw t}}function Us(e){let t=V(e);return[e,t,I.join(t,`skills`),I.join(t,`sessions`),I.join(t,`memory`),I.join(e,`workspace`)]}function Ws(e){let t=V(e);return[...Vs.filter(e=>e!==`BOOTSTRAP.md`).map(e=>I.join(t,e)),I.join(t,`MEMORY.md`)]}function Gs(e){return I.join(V(e),`.bootstrapped`)}async function Ks(e){try{return(await F.stat(Gs(e))).isFile()}catch(e){if(e.code===`ENOENT`)return!1;throw e}}async function qs(e){let t=Gs(e);await F.mkdir(I.dirname(t),{recursive:!0}),await F.writeFile(t,``,{encoding:`utf-8`})}async function Js(e){let t=[],n=[];for(let n of Us(e))try{(await F.stat(n)).isDirectory()||t.push(n)}catch(e){if(e.code===`ENOENT`){t.push(n);continue}throw e}for(let t of Ws(e))try{(await F.stat(t)).isFile()||n.push(t)}catch(e){if(e.code===`ENOENT`){n.push(t);continue}throw e}return{dataDir:e,ready:t.length===0&&n.length===0,missingDirs:t,missingFiles:n}}async function Ys(e){return(await Js(e)).ready}async function Xs(e){if(await Ks(e))return{ready:!0,performedBootstrap:!1};if((await Js(e)).ready)return await qs(e),{ready:!0,performedBootstrap:!1};let t=await Zs(e);return await qs(e),{ready:!0,performedBootstrap:!0,result:t}}async function Zs(e){let t={dataDir:e,createdDirs:[],skippedDirs:[],createdFiles:[],skippedFiles:[]},n=V(e),r=I.join(e,`workspace`),i=I.join(n,`skills`),a=I.join(n,`sessions`),o=I.join(n,`memory`);await $(e,t),await $(n,t),await $(i,t),await $(a,t),await $(o,t),await $(r,t);for(let e of Vs){let r=Bs[e]??``;await Hs(I.join(n,e),r,t)}return await Hs(I.join(n,`MEMORY.md`),``,t),t}async function Qs(e){let t=I.join(e,`.aimax`,`subagents`,`runs.json`);try{let e=await F.readFile(t,`utf-8`),n=JSON.parse(e);if(!n||typeof n!=`object`)return new Map;let r;if(n.version===1&&n.records)r=n.records;else if(n.version===void 0)r=n;else return new Map;let i=new Map;for(let[e,t]of Object.entries(r)){if(!t||typeof t!=`object`)continue;let n=t;i.set(e,{...n,abortController:new AbortController})}return i}catch(e){return e.code,new Map}}async function $s(e,t){let n=I.join(e,`.aimax`,`subagents`,`runs.json`),r={};for(let[e,n]of t.entries())if(typeof n.endedAt==`number`){let{abortController:t,...i}=n;r[e]={...i,version:1}}let i={version:1,records:r};await F.mkdir(I.dirname(n),{recursive:!0}),await F.writeFile(n,JSON.stringify(i,null,2),`utf-8`)}async function ec(e,t){let n=await Qs(e),r=[];for(let e of n.values())if(e.parentSessionId===t){let{abortController:t,...n}=e;r.push({...n,version:1})}return r.sort((e,t)=>e.startedAt-t.startedAt)}async function tc(e,t=7){let n=await Qs(e),r=Date.now()-t*24*60*60*1e3,i=0;for(let[e,t]of n.entries())t.endedAt&&t.endedAt<r&&(n.delete(e),i++);return i>0&&await $s(e,n),i}async function nc(e,t,n,r){let i=await Ts(e,t,{storeName:r});return i?i.request.requestId===n?i.sessionId===t?i.status===`pending`?Ne(i.request)?(await Os(e,t,n,`expired`,void 0,{storeName:r}),{valid:!1,reason:`HITL request has expired`}):{valid:!0,state:i}:{valid:!1,reason:`HITL request is already "${i.status}", cannot resume`}:{valid:!1,reason:`Session ID mismatch: expected "${i.sessionId}", got "${t}"`}:{valid:!1,reason:`Request ID mismatch: expected "${i.request.requestId}", got "${n}"`}:{valid:!1,reason:`No pending HITL request found for this session`}}async function rc(e){let{dataDir:t,sessionId:n,requestId:r,resolution:i,sessionStoreName:a}=e,o=await ks(t,n,r,{storeName:a});if(o){let e=o.resolution?.idempotencyKey;if(e&&i.idempotencyKey&&e===i.idempotencyKey)return{state:o,idempotentReplay:!0};throw Error(`HITL resume validation failed: HITL request is already "${o.status}", cannot resume`)}let s=await nc(t,n,r,a);if(!s.valid)throw Error(`HITL resume validation failed: ${s.reason}`);let c=await Os(t,n,r,`resolved`,i,{storeName:a});if(!c)throw Error(`Failed to transition HITL state to resolved (concurrent modification?)`);return{state:c,idempotentReplay:!1}}export{Be as BOOTSTRAP_FILE_NAMES,Re as BOOTSTRAP_MAX_CHARS,ze as BOOTSTRAP_TOTAL_MAX_CHARS,u as DEFAULT_SESSION_STORE_NAME,Y as HITL_MESSAGES,K as HitlPauseSignal,et as MAX_CHILDREN_PER_SESSION,$e as MAX_SUBAGENT_DEPTH,S as MemoryIndexManager,ts as PLUGIN_MANIFEST_FILENAME,ns as PLUGIN_MANIFEST_FILENAMES,Ma as PluginHookRegistry,Ta as PluginToolRegistry,tt as SubagentRegistry,Wi as UiToolPauseSignal,de as addAgent,se as addBinding,V as aimaxDir,xi as appendToMemory,_ as appendTranscriptEntry,oi as approvalSummaryFromResolution,Zs as bootstrapMountLayout,We as buildBootstrapContextFiles,li as buildResumeNarration,Qe as buildSkillsPrompt,Ii as buildSubagentAnnounceMessage,ba as buildSystemPrompt,tc as cleanupOldSubagentRecords,As as clearPendingHitl,Is as clearPendingUiTool,w as collapseLogPath,d as contextSnapshotPath,Qi as createAgentTools,Jr as createApplyPatchTool,jr as createBashTool,y as createBuiltinMemoryProvider,di as createClarifyTool,ar as createContextManager,Br as createEditFileTool,_r as createExecTool,Ui as createImageTool,Hr as createListDirTool,ki as createMemoryAppendTool,Di as createMemoryGetTool,Ti as createMemorySearchTool,Ds as createPendingHitl,Ps as createPendingUiTool,Ca as createPluginProgressEmitter,ls as createPluginRuntime,xr as createProcessTool,Ir as createReadFileTool,Mi as createRequestApprovalTool,Pi as createRequestReviewTool,f as createSession,Ln as createSessionContextStore,Li as createSessionsSpawnTool,Vi as createSubagentsTool,Zi as createUiTool,Rr as createWriteFileTool,Xi as defaultUiToolInputSchema,Ci as deleteMemoryFile,$o as discoverAIMaxPlugins,Xs as ensureBootstrapMountLayout,x as ensureSession,v as exportSession,ji as formatApprovalResolution,si as formatClarifyResolution,ci as formatReviewResolution,Bt as generateSessionTitle,ie as getAgentConfig,bi as getMemoryLines,Ks as hasBootstrapSentinel,Ss as hitlHistoryPath,hs as initializePluginSystem,Js as inspectBootstrapMountLayout,m as inspectSession,Ys as isBootstrapMountLayoutReady,sr as isHitlPauseSignal,Gi as isUiToolPauseSignal,N as listAgents,Zt as listAvailableSlashCommands,ce as listBindings,gi as listMemoryFiles,p as listSessionSummaries,s as listSessions,ec as listSubagentRunsFromDisk,ue as loadAgentsConfig,Ve as loadBootstrapFiles,Ts as loadPendingHitl,Ts as readPendingHitl,Ns as loadPendingUiTool,Ns as readPendingUiTool,is as loadPluginManifest,as as loadPluginManifestRegistry,fs as loadPlugins,T as loadSessionContextSnapshot,O as loadSessionMetadata,Ye as loadSkills,Ze as loadSkillsFromDirs,Xe as loadSkillsWithPluginDirs,Qs as loadSubagentRegistryFromDisk,l as loadTranscript,fi as memoryDir,D as metadataPath,P as normalizeAgentId,ko as normalizePluginsConfig,a as normalizeSessionStoreName,xs as pendingHitlPath,js as pendingUiToolPath,pi as primaryMemoryPath,Es as readHitlHistory,_i as readMemoryFile,vi as readPrimaryMemory,h as registerEmbeddingProvider,A as registerMemoryProvider,ae as removeAgent,fe as removeBindings,Si as replaceMemoryFile,c as resetEmbeddingProviderRegistryForTests,j as resetMemoryProviderRegistryForTests,ee as resolveAgentDir,te as resolveAgentIdByBinding,le as resolveAgentsConfigPath,oe as resolveDefaultAgentId,b as resolveEmbeddingProvider,rc as resolveHitlRequest,rc as resolvePendingHitl,k as resolveMemoryProvider,re as resolveModelFallbacks,ne as resolveModelString,Fs as resolvePendingUiTool,rs as resolvePluginManifestPath,t as rewriteTranscript,zs as runAgent,M as saveAgentsConfig,E as saveSessionMetadata,$s as saveSubagentRegistryToDisk,yi as searchMemory,o as sessionDir,r as sessionMemoryPath,n as sessionsDir,Ge as skillsDir,i as toolResultsDir,g as transcriptPath,Os as transitionHitlStatus,pe as updateAgentIdentity,e as updateSessionMetadata,Ao as validatePluginsConfig,nc as validateResume,ja as wrapToolsWithHooks};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@gencode/agents",
3
- "version": "0.0.42",
3
+ "version": "0.0.43",
4
4
  "type": "module",
5
5
  "main": "./dist/index.js",
6
6
  "types": "./dist/index.d.ts",
@@ -31,7 +31,7 @@
31
31
  "openai": "6.10.0",
32
32
  "sqlite-vec": "^0.1.6",
33
33
  "zod": "^4.3.6",
34
- "@gencode/shared": "0.0.14"
34
+ "@gencode/shared": "0.0.15"
35
35
  },
36
36
  "devDependencies": {
37
37
  "@sinclair/typebox": "^0.34.48",