@gencode/agents 0.0.23 → 0.0.25
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 +108 -96
- package/dist/index.js +54 -53
- package/package.json +1 -1
package/dist/index.d.ts
CHANGED
|
@@ -138,7 +138,8 @@ type AgentRunParamsBase = {
|
|
|
138
138
|
/** vLLM/OpenAI-compatible API base URL */baseUrl: string;
|
|
139
139
|
apiKey: string;
|
|
140
140
|
model: string; /** Context window size; defaults to 200000 */
|
|
141
|
-
contextWindow?: number;
|
|
141
|
+
contextWindow?: number; /** Flash model for lightweight tasks (e.g. title generation) */
|
|
142
|
+
flashModel?: string;
|
|
142
143
|
}; /** In-process progress callback */
|
|
143
144
|
onProgress?: (event: AgentProgressEvent$1) => Promise<void>; /** Execution timeout in milliseconds; defaults to 600000 (10 min) */
|
|
144
145
|
timeoutMs?: number; /** Present when this run is itself a subagent; controls depth limits */
|
|
@@ -313,21 +314,6 @@ declare class SubagentRegistry {
|
|
|
313
314
|
getStatus(runId: string): SubagentStatus | null;
|
|
314
315
|
}
|
|
315
316
|
//#endregion
|
|
316
|
-
//#region src/runner/title.d.ts
|
|
317
|
-
/** Generates a session title by truncating the first user message */
|
|
318
|
-
declare function generateSessionTitle(message: string, maxLength?: number): string;
|
|
319
|
-
//#endregion
|
|
320
|
-
//#region src/runner/runner.d.ts
|
|
321
|
-
/**
|
|
322
|
-
* Runs an agent session end-to-end.
|
|
323
|
-
* Supports multi-agent: subagents spawned via sessions_spawn are automatically
|
|
324
|
-
* awaited and their results announced back to the parent agent.
|
|
325
|
-
*
|
|
326
|
-
* @param params - Run parameters.
|
|
327
|
-
* @param _registryForTesting - Internal: inject a pre-populated registry for unit tests.
|
|
328
|
-
*/
|
|
329
|
-
declare function runAgent(params: AgentRunParams, _registryForTesting?: SubagentRegistry): Promise<AgentRunResult>;
|
|
330
|
-
//#endregion
|
|
331
317
|
//#region src/memory/config.d.ts
|
|
332
318
|
type MemorySearchConfig = {
|
|
333
319
|
chunkTokens: number;
|
|
@@ -544,86 +530,6 @@ type MemoryProvider = {
|
|
|
544
530
|
};
|
|
545
531
|
type MemoryProviderFactory = (ctx: MemoryProviderContext) => MemoryProvider;
|
|
546
532
|
//#endregion
|
|
547
|
-
//#region src/session/session.d.ts
|
|
548
|
-
type SessionMetadata = {
|
|
549
|
-
id: string;
|
|
550
|
-
title: string;
|
|
551
|
-
channel: Channel;
|
|
552
|
-
createdAt: string;
|
|
553
|
-
updatedAt: string;
|
|
554
|
-
};
|
|
555
|
-
type SessionSummary = {
|
|
556
|
-
id: string;
|
|
557
|
-
title: string;
|
|
558
|
-
channel: Channel;
|
|
559
|
-
createdAt: string;
|
|
560
|
-
updatedAt: string;
|
|
561
|
-
};
|
|
562
|
-
type SessionInspection = {
|
|
563
|
-
id: string;
|
|
564
|
-
metadata: SessionMetadata | null;
|
|
565
|
-
transcriptPath: string;
|
|
566
|
-
contextSnapshotPath: string;
|
|
567
|
-
sessionMemoryPath: string;
|
|
568
|
-
collapseLogPath: string;
|
|
569
|
-
toolResultsDir: string;
|
|
570
|
-
transcriptEntryCount: number;
|
|
571
|
-
readStateCount: number;
|
|
572
|
-
toolResultRefCount: number;
|
|
573
|
-
transcriptEntries: TranscriptEntry[];
|
|
574
|
-
context: SessionContextSnapshot;
|
|
575
|
-
};
|
|
576
|
-
type SessionExport = {
|
|
577
|
-
id: string;
|
|
578
|
-
metadata: SessionMetadata | null;
|
|
579
|
-
transcript: TranscriptEntry[];
|
|
580
|
-
context: SessionContextSnapshot;
|
|
581
|
-
paths: {
|
|
582
|
-
transcriptPath: string;
|
|
583
|
-
contextSnapshotPath: string;
|
|
584
|
-
sessionMemoryPath: string;
|
|
585
|
-
collapseLogPath: string;
|
|
586
|
-
toolResultsDir: string;
|
|
587
|
-
};
|
|
588
|
-
};
|
|
589
|
-
/** Resolves the sessions directory path within a data directory */
|
|
590
|
-
declare function sessionsDir(dataDir: string): string;
|
|
591
|
-
/** Resolves the directory for a specific session */
|
|
592
|
-
declare function sessionDir(dataDir: string, sessionId: string): string;
|
|
593
|
-
/** Resolves the transcript file path for a session */
|
|
594
|
-
declare function transcriptPath(dataDir: string, sessionId: string): string;
|
|
595
|
-
/** Resolves the metadata file path for a session */
|
|
596
|
-
declare function metadataPath(dataDir: string, sessionId: string): string;
|
|
597
|
-
/** Resolves the persisted context snapshot path for a session */
|
|
598
|
-
declare function contextSnapshotPath(dataDir: string, sessionId: string): string;
|
|
599
|
-
declare function sessionMemoryPath(dataDir: string, sessionId: string): string;
|
|
600
|
-
declare function collapseLogPath(dataDir: string, sessionId: string): string;
|
|
601
|
-
/** Resolves the persisted tool-results directory for a session */
|
|
602
|
-
declare function toolResultsDir(dataDir: string, sessionId: string): string;
|
|
603
|
-
/** Creates a new session with a generated ID */
|
|
604
|
-
declare function createSession(dataDir: string, channel: Channel): Promise<string>;
|
|
605
|
-
/** Ensures a session directory exists (for resuming an existing session) */
|
|
606
|
-
declare function ensureSession(dataDir: string, sessionId: string): Promise<void>;
|
|
607
|
-
/** Loads all transcript entries from a session */
|
|
608
|
-
declare function loadTranscript(dataDir: string, sessionId: string): Promise<TranscriptEntry[]>;
|
|
609
|
-
/** Appends a single entry to the transcript file */
|
|
610
|
-
declare function appendTranscriptEntry(dataDir: string, sessionId: string, entry: TranscriptEntry, options?: {
|
|
611
|
-
providerId?: string;
|
|
612
|
-
pluginId?: string;
|
|
613
|
-
onMemoryChanged?: MemoryChangedHandler;
|
|
614
|
-
}): Promise<void>;
|
|
615
|
-
/** Lists all session IDs within a data directory */
|
|
616
|
-
declare function listSessions(dataDir: string): Promise<string[]>;
|
|
617
|
-
/** Saves session metadata to disk */
|
|
618
|
-
declare function saveSessionMetadata(dataDir: string, metadata: SessionMetadata): Promise<void>;
|
|
619
|
-
/** Loads session metadata from disk; returns null if not found */
|
|
620
|
-
declare function loadSessionMetadata(dataDir: string, sessionId: string): Promise<SessionMetadata | null>;
|
|
621
|
-
/** Lists all sessions with their metadata summaries, optionally filtered by channel */
|
|
622
|
-
declare function listSessionSummaries(dataDir: string, channel?: Channel): Promise<SessionSummary[]>;
|
|
623
|
-
declare function loadSessionContextSnapshot(dataDir: string, sessionId: string): Promise<SessionContextSnapshot>;
|
|
624
|
-
declare function inspectSession(dataDir: string, sessionId: string): Promise<SessionInspection>;
|
|
625
|
-
declare function exportSession(dataDir: string, sessionId: string): Promise<SessionExport>;
|
|
626
|
-
//#endregion
|
|
627
533
|
//#region src/plugins/hooks.d.ts
|
|
628
534
|
type PluginHookName = "before_model_resolve" | "before_prompt_build" | "after_prompt_build" | "llm_input" | "assistant_message_end" | "llm_output" | "before_tool_call" | "after_tool_call" | "agent_end" | "before_compaction" | "after_compaction" | "session_start" | "session_end" | "session_reset" | "memory_changed";
|
|
629
535
|
type PluginHookAgentContext = {
|
|
@@ -760,6 +666,112 @@ declare class PluginHookRegistry {
|
|
|
760
666
|
dispatch<K extends PluginHookName>(hookName: K, event: Parameters<PluginHookHandlerMap[K]>[0], ctx: Parameters<PluginHookHandlerMap[K]>[1], runtime?: PluginExecutionRuntime): Promise<Array<Awaited<ReturnType<PluginHookHandlerMap[K]>>>>;
|
|
761
667
|
}
|
|
762
668
|
//#endregion
|
|
669
|
+
//#region src/runner/title.d.ts
|
|
670
|
+
type GenerateTitleParams = {
|
|
671
|
+
message: string;
|
|
672
|
+
llm: {
|
|
673
|
+
baseUrl: string;
|
|
674
|
+
apiKey: string;
|
|
675
|
+
model: string;
|
|
676
|
+
flashModel?: string;
|
|
677
|
+
};
|
|
678
|
+
signal?: AbortSignal;
|
|
679
|
+
hooks?: PluginHookRegistry;
|
|
680
|
+
hookCtx?: PluginHookAgentContext;
|
|
681
|
+
};
|
|
682
|
+
declare function generateSessionTitle(params: GenerateTitleParams): Promise<string>;
|
|
683
|
+
//#endregion
|
|
684
|
+
//#region src/runner/runner.d.ts
|
|
685
|
+
/**
|
|
686
|
+
* Runs an agent session end-to-end.
|
|
687
|
+
* Supports multi-agent: subagents spawned via sessions_spawn are automatically
|
|
688
|
+
* awaited and their results announced back to the parent agent.
|
|
689
|
+
*
|
|
690
|
+
* @param params - Run parameters.
|
|
691
|
+
* @param _registryForTesting - Internal: inject a pre-populated registry for unit tests.
|
|
692
|
+
*/
|
|
693
|
+
declare function runAgent(params: AgentRunParams, _registryForTesting?: SubagentRegistry): Promise<AgentRunResult>;
|
|
694
|
+
//#endregion
|
|
695
|
+
//#region src/session/session.d.ts
|
|
696
|
+
type SessionMetadata = {
|
|
697
|
+
id: string;
|
|
698
|
+
title: string;
|
|
699
|
+
channel: Channel;
|
|
700
|
+
createdAt: string;
|
|
701
|
+
updatedAt: string;
|
|
702
|
+
};
|
|
703
|
+
type SessionSummary = {
|
|
704
|
+
id: string;
|
|
705
|
+
title: string;
|
|
706
|
+
channel: Channel;
|
|
707
|
+
createdAt: string;
|
|
708
|
+
updatedAt: string;
|
|
709
|
+
};
|
|
710
|
+
type SessionInspection = {
|
|
711
|
+
id: string;
|
|
712
|
+
metadata: SessionMetadata | null;
|
|
713
|
+
transcriptPath: string;
|
|
714
|
+
contextSnapshotPath: string;
|
|
715
|
+
sessionMemoryPath: string;
|
|
716
|
+
collapseLogPath: string;
|
|
717
|
+
toolResultsDir: string;
|
|
718
|
+
transcriptEntryCount: number;
|
|
719
|
+
readStateCount: number;
|
|
720
|
+
toolResultRefCount: number;
|
|
721
|
+
transcriptEntries: TranscriptEntry[];
|
|
722
|
+
context: SessionContextSnapshot;
|
|
723
|
+
};
|
|
724
|
+
type SessionExport = {
|
|
725
|
+
id: string;
|
|
726
|
+
metadata: SessionMetadata | null;
|
|
727
|
+
transcript: TranscriptEntry[];
|
|
728
|
+
context: SessionContextSnapshot;
|
|
729
|
+
paths: {
|
|
730
|
+
transcriptPath: string;
|
|
731
|
+
contextSnapshotPath: string;
|
|
732
|
+
sessionMemoryPath: string;
|
|
733
|
+
collapseLogPath: string;
|
|
734
|
+
toolResultsDir: string;
|
|
735
|
+
};
|
|
736
|
+
};
|
|
737
|
+
/** Resolves the sessions directory path within a data directory */
|
|
738
|
+
declare function sessionsDir(dataDir: string): string;
|
|
739
|
+
/** Resolves the directory for a specific session */
|
|
740
|
+
declare function sessionDir(dataDir: string, sessionId: string): string;
|
|
741
|
+
/** Resolves the transcript file path for a session */
|
|
742
|
+
declare function transcriptPath(dataDir: string, sessionId: string): string;
|
|
743
|
+
/** Resolves the metadata file path for a session */
|
|
744
|
+
declare function metadataPath(dataDir: string, sessionId: string): string;
|
|
745
|
+
/** Resolves the persisted context snapshot path for a session */
|
|
746
|
+
declare function contextSnapshotPath(dataDir: string, sessionId: string): string;
|
|
747
|
+
declare function sessionMemoryPath(dataDir: string, sessionId: string): string;
|
|
748
|
+
declare function collapseLogPath(dataDir: string, sessionId: string): string;
|
|
749
|
+
/** Resolves the persisted tool-results directory for a session */
|
|
750
|
+
declare function toolResultsDir(dataDir: string, sessionId: string): string;
|
|
751
|
+
/** Creates a new session with a generated ID */
|
|
752
|
+
declare function createSession(dataDir: string, channel: Channel): Promise<string>;
|
|
753
|
+
/** Ensures a session directory exists (for resuming an existing session) */
|
|
754
|
+
declare function ensureSession(dataDir: string, sessionId: string): Promise<void>;
|
|
755
|
+
/** Loads all transcript entries from a session */
|
|
756
|
+
declare function loadTranscript(dataDir: string, sessionId: string): Promise<TranscriptEntry[]>;
|
|
757
|
+
/** Appends a single entry to the transcript file */
|
|
758
|
+
declare function appendTranscriptEntry(dataDir: string, sessionId: string, entry: TranscriptEntry, options?: {
|
|
759
|
+
providerId?: string;
|
|
760
|
+
pluginId?: string;
|
|
761
|
+
onMemoryChanged?: MemoryChangedHandler;
|
|
762
|
+
}): Promise<void>;
|
|
763
|
+
/** Lists all session IDs within a data directory */
|
|
764
|
+
declare function listSessions(dataDir: string): Promise<string[]>;
|
|
765
|
+
/** Saves session metadata to disk */
|
|
766
|
+
declare function saveSessionMetadata(dataDir: string, metadata: SessionMetadata): Promise<void>;
|
|
767
|
+
/** Loads session metadata from disk; returns null if not found */
|
|
768
|
+
declare function loadSessionMetadata(dataDir: string, sessionId: string): Promise<SessionMetadata | null>;
|
|
769
|
+
/** Lists all sessions with their metadata summaries, optionally filtered by channel */
|
|
770
|
+
declare function listSessionSummaries(dataDir: string, channel?: Channel): Promise<SessionSummary[]>;
|
|
771
|
+
declare function loadSessionContextSnapshot(dataDir: string, sessionId: string): Promise<SessionContextSnapshot>;
|
|
772
|
+
declare function inspectSession(dataDir: string, sessionId: string): Promise<SessionInspection>;
|
|
773
|
+
declare function exportSession(dataDir: string, sessionId: string): Promise<SessionExport>;
|
|
774
|
+
//#endregion
|
|
763
775
|
//#region src/context/session-context-store.d.ts
|
|
764
776
|
type PersistedToolResult = {
|
|
765
777
|
content: string;
|
package/dist/index.js
CHANGED
|
@@ -8,72 +8,73 @@ import{C as e,E as t,S as n,T as r,_ as i,a,b as o,c as s,d as c,f as l,g as u,h
|
|
|
8
8
|
|
|
9
9
|
`);t.content?t.content.unshift({type:`text`,text:e}):t.content=[{type:`text`,text:e}]}else{let e=s[0].thinkingSignature;e&&e.length>0&&(t[e]=s.map(e=>e.thinking).join(`
|
|
10
10
|
`))}let c=i.content.filter(e=>e.type===`toolCall`);if(c.length>0){t.tool_calls=c.map(e=>({id:e.id,type:`function`,function:{name:e.name,arguments:JSON.stringify(e.arguments)}}));let e=c.filter(e=>e.thoughtSignature).map(e=>{try{return JSON.parse(e.thoughtSignature)}catch{return null}}).filter(Boolean);e.length>0&&(t.reasoning_details=e)}let l=t.content;if(!(l!=null&&l.length>0)&&!t.tool_calls)continue;r.push(t),o=i.role;continue}if(i.role===`toolResult`){let i=[],s=t;for(;s<a.length&&a[s].role===`toolResult`;s+=1){let t=a[s],o=t.content.filter(e=>e.type===`text`).map(e=>e.text).join(`
|
|
11
|
-
`),c=t.content.some(e=>e.type===`image`),l={role:`tool`,content:L(o.length>0?o:`(see attached image)`),tool_call_id:t.toolCallId};if(n.requiresToolResultName&&t.toolName&&(l.name=t.toolName),r.push(l),c&&e.input.includes(`image`))for(let e of t.content)e.type===`image`&&i.push({type:`image_url`,image_url:{url:`data:${e.mimeType};base64,${e.data}`}})}t=s-1,i.length>0?(n.requiresAssistantAfterToolResult&&r.push({role:`assistant`,content:`I have processed the tool results.`}),r.push({role:`user`,content:[{type:`text`,text:`Attached image(s) from tool result:`},...i]}),o=`user`):o=`toolResult`}}return r}function Dt(e,t){return e.map(e=>({type:`function`,function:{name:e.name,description:e.description,parameters:e.parameters,...t.supportsStrictMode!==!1&&{strict:!1}}}))}function Ot(e){if(e===null)return`stop`;switch(e){case`stop`:return`stop`;case`length`:return`length`;case`function_call`:case`tool_calls`:return`toolUse`;case`error`:case`content_filter`:return`error`;default:throw Error(`Unhandled stop reason: ${e}`)}}function kt(e){let t=e.provider,n=e.baseUrl,r=t===`zai`||n.includes(`api.z.ai`),i=t===`cerebras`||n.includes(`cerebras.ai`)||t===`xai`||n.includes(`api.x.ai`)||t===`mistral`||n.includes(`mistral.ai`)||n.includes(`chutes.ai`)||n.includes(`deepseek.com`)||r||t===`opencode`||n.includes(`opencode.ai`),a=t===`mistral`||n.includes(`mistral.ai`)||n.includes(`chutes.ai`),o=t===`xai`||n.includes(`api.x.ai`),s=t===`mistral`||n.includes(`mistral.ai`);return{supportsStore:!i,supportsDeveloperRole:!i,supportsReasoningEffort:!o&&!r,supportsUsageInStreaming:!0,maxTokensField:a?`max_tokens`:`max_completion_tokens`,requiresToolResultName:s,requiresAssistantAfterToolResult:!1,requiresThinkingAsText:s,requiresMistralToolIds:s,thinkingFormat:r?`zai`:`openai`,openRouterRouting:{},vercelGatewayRouting:{},supportsStrictMode:!0}}function At(e){let t=kt(e);return e.compat?{supportsStore:e.compat.supportsStore??t.supportsStore,supportsDeveloperRole:e.compat.supportsDeveloperRole??t.supportsDeveloperRole,supportsReasoningEffort:e.compat.supportsReasoningEffort??t.supportsReasoningEffort,supportsUsageInStreaming:e.compat.supportsUsageInStreaming??t.supportsUsageInStreaming,maxTokensField:e.compat.maxTokensField??t.maxTokensField,requiresToolResultName:e.compat.requiresToolResultName??t.requiresToolResultName,requiresAssistantAfterToolResult:e.compat.requiresAssistantAfterToolResult??t.requiresAssistantAfterToolResult,requiresThinkingAsText:e.compat.requiresThinkingAsText??t.requiresThinkingAsText,requiresMistralToolIds:e.compat.requiresMistralToolIds??t.requiresMistralToolIds,thinkingFormat:e.compat.thinkingFormat??t.thinkingFormat,openRouterRouting:e.compat.openRouterRouting??{},vercelGatewayRouting:e.compat.vercelGatewayRouting??t.vercelGatewayRouting,supportsStrictMode:e.compat.supportsStrictMode??t.supportsStrictMode}:t}let jt=!1;function Mt(){jt||=(ge(),he({api:`openai-completions`,stream:yt,streamSimple:bt}),!0)}var Nt=class{constructor(e){this.params=e}async dispatchProgress(e,t){let n={...t,sessionId:e,...this.params.messageId?{messageId:this.params.messageId}:{},...this.params.subagentContext?{parentSessionId:this.params.subagentContext.parentSessionId,depth:this.params.subagentContext.depth}:{}};await this.params.onProgress?.(n)}async dispatchDiagnostic(e,t){await this.dispatchProgress(e,{type:`diagnostic`,...t})}};
|
|
12
|
-
`),r=
|
|
13
|
-
`)}}function
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
`):e.
|
|
17
|
-
`);
|
|
11
|
+
`),c=t.content.some(e=>e.type===`image`),l={role:`tool`,content:L(o.length>0?o:`(see attached image)`),tool_call_id:t.toolCallId};if(n.requiresToolResultName&&t.toolName&&(l.name=t.toolName),r.push(l),c&&e.input.includes(`image`))for(let e of t.content)e.type===`image`&&i.push({type:`image_url`,image_url:{url:`data:${e.mimeType};base64,${e.data}`}})}t=s-1,i.length>0?(n.requiresAssistantAfterToolResult&&r.push({role:`assistant`,content:`I have processed the tool results.`}),r.push({role:`user`,content:[{type:`text`,text:`Attached image(s) from tool result:`},...i]}),o=`user`):o=`toolResult`}}return r}function Dt(e,t){return e.map(e=>({type:`function`,function:{name:e.name,description:e.description,parameters:e.parameters,...t.supportsStrictMode!==!1&&{strict:!1}}}))}function Ot(e){if(e===null)return`stop`;switch(e){case`stop`:return`stop`;case`length`:return`length`;case`function_call`:case`tool_calls`:return`toolUse`;case`error`:case`content_filter`:return`error`;default:throw Error(`Unhandled stop reason: ${e}`)}}function kt(e){let t=e.provider,n=e.baseUrl,r=t===`zai`||n.includes(`api.z.ai`),i=t===`cerebras`||n.includes(`cerebras.ai`)||t===`xai`||n.includes(`api.x.ai`)||t===`mistral`||n.includes(`mistral.ai`)||n.includes(`chutes.ai`)||n.includes(`deepseek.com`)||r||t===`opencode`||n.includes(`opencode.ai`),a=t===`mistral`||n.includes(`mistral.ai`)||n.includes(`chutes.ai`),o=t===`xai`||n.includes(`api.x.ai`),s=t===`mistral`||n.includes(`mistral.ai`);return{supportsStore:!i,supportsDeveloperRole:!i,supportsReasoningEffort:!o&&!r,supportsUsageInStreaming:!0,maxTokensField:a?`max_tokens`:`max_completion_tokens`,requiresToolResultName:s,requiresAssistantAfterToolResult:!1,requiresThinkingAsText:s,requiresMistralToolIds:s,thinkingFormat:r?`zai`:`openai`,openRouterRouting:{},vercelGatewayRouting:{},supportsStrictMode:!0}}function At(e){let t=kt(e);return e.compat?{supportsStore:e.compat.supportsStore??t.supportsStore,supportsDeveloperRole:e.compat.supportsDeveloperRole??t.supportsDeveloperRole,supportsReasoningEffort:e.compat.supportsReasoningEffort??t.supportsReasoningEffort,supportsUsageInStreaming:e.compat.supportsUsageInStreaming??t.supportsUsageInStreaming,maxTokensField:e.compat.maxTokensField??t.maxTokensField,requiresToolResultName:e.compat.requiresToolResultName??t.requiresToolResultName,requiresAssistantAfterToolResult:e.compat.requiresAssistantAfterToolResult??t.requiresAssistantAfterToolResult,requiresThinkingAsText:e.compat.requiresThinkingAsText??t.requiresThinkingAsText,requiresMistralToolIds:e.compat.requiresMistralToolIds??t.requiresMistralToolIds,thinkingFormat:e.compat.thinkingFormat??t.thinkingFormat,openRouterRouting:e.compat.openRouterRouting??{},vercelGatewayRouting:e.compat.vercelGatewayRouting??t.vercelGatewayRouting,supportsStrictMode:e.compat.supportsStrictMode??t.supportsStrictMode}:t}let jt=!1;function Mt(){jt||=(ge(),he({api:`openai-completions`,stream:yt,streamSimple:bt}),!0)}var Nt=class{constructor(e){this.params=e}async dispatchProgress(e,t){let n={...t,sessionId:e,...this.params.messageId?{messageId:this.params.messageId}:{},...this.params.subagentContext?{parentSessionId:this.params.subagentContext.parentSessionId,depth:this.params.subagentContext.depth}:{}};await this.params.onProgress?.(n)}async dispatchDiagnostic(e,t){await this.dispatchProgress(e,{type:`diagnostic`,...t})}};const Pt=[`You are a session title generator. Generate a concise title (max 80 chars) for the given user message.`,``,`Rules:`,`- The title should capture the main topic or intent of the message`,`- Keep it short and descriptive`,`- Use the user's language (Chinese for Chinese messages, English for English messages)`,`- Output only the title text — no preamble, no quotes, no extra formatting`].join(`
|
|
12
|
+
`);async function Ft(e){let{message:t,llm:n,signal:r,hooks:i,hookCtx:a}=e,o=t.trim().replace(/\s+/g,` `);if(!o)return`New session`;if(!n.flashModel)return Lt(o);let s=n.flashModel,c=rt({baseUrl:n.baseUrl,apiKey:n.apiKey,defaultModel:s,hooks:i,hookCtx:a});for(let e=1;e<=3;e++)try{let e=(await c.chat({system:Pt,user:o,temperature:0,maxTokens:100,signal:r})).text.trim();if(!e)throw Error(`LLM title generation returned empty content`);return e.length>80?e.slice(0,79)+`…`:e}catch(t){if(t instanceof Error&&t.name===`AbortError`)throw t;e<3&&await It(500*e)}return Lt(o)}function It(e){return new Promise(t=>setTimeout(t,e))}function Lt(e,t=80){let n=e.trim().replace(/\s+/g,` `);return n.length<=t?n:n.slice(0,t-1)+`…`}function Rt(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 zt(e){let t=Rt(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=F.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 Bt(e){let t=e.watchFactory??((e,t,n)=>z.watch(e,t,n)),n=F.join(e.dataDir,`.aimax`),r=[{target:F.join(n,`MEMORY.md`),kind:`memory-file`},{target:F.join(n,`memory.md`),kind:`memory-file-lower`},{target:F.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=zt({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 Vt(e){let{runParams:t,eventDispatcher:n,hookRegistry:r}=e,{sessionId:i,hookContext:a,memoryProviderId:o,memoryPluginId:c}=e,l=F.join(t.dataDir,`workspace`),u=new Map,d=new Map,f=!1,p=async e=>{let t=Date.now(),o=Wt(e.files);if(o.length===0)return;let s=e.reason===`external-watch`&&e.source===`memory`?o.filter(e=>t-(u.get(e.toLowerCase())??0)>3e3):o;if(s.length===0)return;if(e.reason!==`external-watch`&&e.source===`memory`)for(let e of s)u.set(e.toLowerCase(),t);let c=`${e.reason}|${e.source}|${s.map(e=>e.toLowerCase()).sort().join(`|`)}`;if(t-(d.get(c)??0)<1e3)return;d.set(c,t);let l={...e,files:s};await n.dispatchProgress(e.sessionId??i,{type:`memory_changed`,reason:l.reason,files:l.files,source:l.source,providerId:l.providerId,timestamp:l.timestamp}).catch(()=>{}),await r.dispatch(`memory_changed`,l,{...a,sessionId:l.sessionId??a.sessionId},{eventDispatcher:n}).catch(()=>{})},m=F.join(t.dataDir,`.aimax`),g=T({providerId:o,pluginId:c,dataDir:t.dataDir,memoryDir:m,sessionId:i})?.provider??h({dataDir:t.dataDir,memoryDir:m,sessionId:i}),_=Bt({dataDir:t.dataDir,sessionId:i,providerId:o??c??g.id,provider:g,onMemoryChanged:p});g.sync&&g.sync(`session-start`).catch(()=>{});let v=async e=>{await s(t.dataDir,i,e,Ut({providerId:o,pluginId:c,onMemoryChanged:p}))};return{workspaceDir:l,memoryProviderId:o,memoryPluginId:c,appendTranscriptEntry:v,persistInitialUserEntry:async e=>f?!1:(await v({role:`user`,content:e,timestamp:new Date().toISOString()}),f=!0,!0),stop:()=>{_()}}}function Ht(e){let t=new Date().toISOString();return{id:e.sessionId,title:e.title,channel:e.channel,createdAt:t,updatedAt:t}}function Ut(e){return e.providerId||e.pluginId?{providerId:e.providerId,pluginId:e.pluginId,onMemoryChanged:e.onMemoryChanged}:{onMemoryChanged:e.onMemoryChanged}}function Wt(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}async function Gt(e){let{sessionId:t,resetCommand:n,previousSessionId:r,resetMessage:i,startMessage:a,hookRegistry:o,hookContext:s,eventDispatcher:c}=e;n&&i&&await c.dispatchProgress(t,{type:`session_reset`,action:n.action,previousSessionId:r,message:i}),n&&i&&await o.dispatch(`session_reset`,{action:n.action,sessionId:t,previousSessionId:r,message:i},s,{eventDispatcher:c}),await c.dispatchProgress(t,{type:`start`,message:a}),await o.dispatch(`session_start`,{sessionId:t},s,{eventDispatcher:c})}async function Kt(e){let{sessionId:t,result:n,runParams:r,hookRegistry:i,hookContext:a}=e;await i.dispatch(`agent_end`,{success:!n.error,error:n.error,durationMs:n.durationMs},a,{eventDispatcher:e.eventDispatcher});let o=await w(r.dataDir,t);await i.dispatch(`session_end`,{sessionId:t,messageCount:o.length,durationMs:n.durationMs},a,{eventDispatcher:e.eventDispatcher})}async function qt(e){let{replyText:t,sessionId:n,isNewSession:i,transcriptMessage:a,initialUserEntryPersisted:o=!1,runParams:c,hookRegistry:l,hookContext:u,startTime:d,compactionEntry:f,eventDispatcher:p}=e;if(o||await s(c.dataDir,n,{role:`user`,content:a,timestamp:new Date().toISOString()}),f&&await s(c.dataDir,n,f),await s(c.dataDir,n,{role:`assistant`,content:t,timestamp:new Date().toISOString()}),i){let e=a.trim()?a:`New session`;await C(c.dataDir,Ht({sessionId:n,title:await Ft({message:e,llm:c.llm,hooks:l,hookCtx:u}),channel:c.channel}))}let m={sessionId:n,text:t,usage:{input:0,output:0,total:0},durationMs:Date.now()-d,context:{snapshotPath:b(c.dataDir,n),toolResultsDir:r(c.dataDir,n)}};return await Kt({sessionId:n,result:m,runParams:c,hookRegistry:l,hookContext:u,eventDispatcher:p}),m}async function Jt(e){let{sessionId:t,isNewSession:n,transcriptMessage:i,runParams:a,hookRegistry:o,hookContext:s,startTime:c,text:l,usage:u,error:d,paused:f,eventDispatcher:p}=e;n&&await C(a.dataDir,Ht({sessionId:t,title:await Ft({message:i,llm:a.llm,hooks:o,hookCtx:s}),channel:a.channel}));let m={sessionId:t,text:l,usage:u,durationMs:Date.now()-c,error:d,paused:f,context:{snapshotPath:b(a.dataDir,t),toolResultsDir:r(a.dataDir,t)}};return await Kt({sessionId:t,result:m,runParams:a,hookRegistry:o,hookContext:s,eventDispatcher:p}),m}const Yt=[{name:`/help`,description:`显示可用命令`},{name:`/new`,description:`开始新会话`},{name:`/reset`,description:`重置当前会话`},{name:`/compact`,description:`精简会话上下文`},{name:`/skill`,description:`按名称运行技能`}];function Xt(){return Yt.map(e=>({...e}))}function Zt(e){return e.trim().replace(/^\/+/,``).toLowerCase().replace(/[\s_]+/g,`-`)}function Qt(e){let t=new Set,n=[];for(let r of e){let e=Zt(r.name);e&&(t.has(e)||(t.add(e),n.push({name:`/${e}`,description:r.description||`Skill command.`})))}return n}function $t(e){let t=Xt(),n=Qt(e);return{builtin:t,skillCommands:n,all:[...t,...n]}}function en(e){let t=e.trim();if(!t)return``;let n=t.indexOf(`
|
|
13
|
+
`),r=n===-1?t:t.slice(0,n).trim(),i=r.match(/^\/([^\s:]+)\s*:(.*)$/);if(!i)return r;let[,a,o]=i,s=o.trimStart();return s?`/${a} ${s}`:`/${a}`}function tn(e){let t=en(e);if(!t.startsWith(`/`))return null;let n=t.match(/^\/([^\s]+)(?:\s+([\s\S]+))?$/);if(!n)return null;let r=n[1]?.trim().toLowerCase()??``,i=(n[2]??``).trim();return r?{name:r,rest:i}:null}function nn(e){let t=e.trim();if(!t.startsWith(`/`))return null;let n=t.match(/^\/([^\s:]+)\s*:(.*)$/s),r=(n?(()=>{let[,e,t]=n,r=t.trimStart();return r?`/${e} ${r}`:`/${e}`})():t).match(/^\/([^\s@]+)(?:@[^\s]+)?(?:\s+([\s\S]+))?$/);if(!r)return null;let i=r[1]?.trim().toLowerCase()??``;if(i!==`new`&&i!==`reset`)return null;let a=(r[2]??``).trim();return{action:i===`new`?`new`:`reset`,remainder:a}}function rn(e,t){let n=tn(e);if(!n)return{kind:`none`};if(n.name===`help`)return n.rest?{kind:`unknown`,name:n.name,args:n.rest}:{kind:`help`};if(n.name===`compact`)return{kind:`compact`,instructions:n.rest};if(n.name===`new`||n.name===`reset`)return{kind:`reset`,action:n.name===`new`?`new`:`reset`,remainder:n.rest};if(n.name===`skill`){if(!n.rest)return{kind:`unknown`,name:n.name,args:``};let e=n.rest.match(/^([^\s]+)(?:\s+([\s\S]+))?$/);return e?{kind:`skill`,name:Zt(e[1]??``),args:(e[2]??``).trim()}:{kind:`unknown`,name:n.name,args:n.rest}}return new Set(Qt(t).map(e=>e.name.slice(1))).has(n.name)?{kind:`skill-direct`,name:n.name,args:n.rest}:{kind:`unknown`,name:n.name,args:n.rest}}const an=new Set([`/new`,`/reset`,`/compact`]),on=new Set([`/help`]);function sn(e){return e.name===`/compact`?{...e,name:`/compact [instructions]`}:e.name===`/skill`?{...e,name:`/skill <name> [input]`}:e}function cn(e){if(e.length===0)return[];let t=e.map(sn),n=Math.max(25,...t.map(e=>e.name.length));return t.map(e=>` ${e.name.padEnd(n)} ${e.description}`)}function ln(e){let t=$t(e.skills),n=t.builtin.filter(e=>an.has(e.name)),r=t.builtin.filter(e=>e.name===`/skill`),i=t.builtin.filter(e=>on.has(e.name)),a=t.skillCommands.slice(0,4),o=[];return o.push(`帮助`),o.push(``),o.push(`会话命令`),o.push(...cn(n)),o.push(``),o.push(`技能命令`),o.push(...cn(r)),a.length>0?(o.push(...cn(a)),t.skillCommands.length>a.length&&o.push(` ... 还有 ${t.skillCommands.length-a.length} 个`)):o.push(` 未安装技能命令`),o.push(``),o.push(`其他命令`),o.push(...cn(i)),{kind:`reply`,text:o.join(`
|
|
14
|
+
`)}}function un(e,t){let n=t.trim().toLowerCase();return n&&Qt(e).map(e=>e.name.slice(1)).includes(n)?{name:n}:null}function dn(e){let t=un(e.ctx.skills,e.skillName);return t?{kind:`rewrite`,message:[`Use the "${t.name}" skill for this request.`,e.args?`User input:\n${e.args}`:null].filter(e=>!!e).join(`
|
|
15
|
+
|
|
16
|
+
`)}:{kind:`reply`,text:`❌ Skill not found: ${e.skillName}. Use /help to see available skills.`}}function fn(e){let t=rn(e.message,e.skills);return t.kind===`none`?{kind:`pass`,message:e.message}:t.kind===`help`?ln(e):t.kind===`compact`?{kind:`compact`,instructions:t.instructions}:t.kind===`skill`||t.kind===`skill-direct`?dn({ctx:e,skillName:t.name,args:t.args}):t.kind===`unknown`&&t.name===`skill`?{kind:`reply`,text:`Usage: /skill <name> [input]`}:{kind:`pass`,message:e.message}}function U(e){return Math.ceil(e.length/4*1.2)}function pn(e){if(e.role===`user`)return U(e.content);if(e.role===`assistant`){let t=U(e.content);for(let n of e.toolCalls??[])t+=U(n.name)+U(JSON.stringify(n.arguments));return t}let t=e.toolResultRef?[`[tool result persisted] ${e.toolResultRef.toolName} (${e.toolResultRef.originalChars} chars).`,`Full output: ${e.toolResultRef.storagePath}`,e.toolResultRef.preview].filter(Boolean).join(`
|
|
17
|
+
`):e.content;return U(e.toolName)+U(t)}function W(e){return e.reduce((e,t)=>e+pn(t),0)}const mn=[`You are a conversation history summariser. Compress the conversation below into a concise summary.`,``,`MUST PRESERVE:`,`- Active tasks and their current status (including batch progress e.g. '5/17 items done')`,`- The last thing the user requested and what was being done about it`,`- Decisions made and their rationale`,`- TODOs, open questions, and constraints`,`- All opaque identifiers exactly as written: UUIDs, hashes, file paths, URLs, IPs, ports (never shorten or reconstruct them)`,``,`Prioritise recent context over older history.`,`Output only the summary text — no preamble, no headings.`].join(`
|
|
18
|
+
`);async function hn(e){let{entries:t,llm:n,previousSummary:r,instructions:i,signal:a,hooks:o,hookCtx:s}=e,c=_n(t,r,i),l,u=rt({baseUrl:n.baseUrl,apiKey:n.apiKey,defaultModel:n.model,hooks:o,hookCtx:s});for(let e=1;e<=3;e++)try{let e=(await u.chat({system:mn,user:c,temperature:0,maxTokens:2048,signal:a})).text.trim();if(!e)throw Error(`LLM summarisation returned empty content`);return e}catch(t){if(t instanceof Error&&t.name===`AbortError`)throw t;l=t,e<3&&await gn(500*e)}throw l}function gn(e){return new Promise(t=>setTimeout(t,e))}function _n(e,t,n){let r=[];n?.trim()&&r.push(`[Extra instructions]\n${n.trim()}\n`),t?.trim()?(r.push(`[Prior summary]\n${t.trim()}\n`),r.push(`[Conversation to incorporate]`)):r.push(`[Conversation to summarise]`);for(let t of e)if(t.role===`user`)r.push(`User: ${t.content}`);else if(t.role===`assistant`){let e=t.toolCalls&&t.toolCalls.length>0?` [called tools: ${t.toolCalls.map(e=>e.name).join(`, `)}]`:``;r.push(`Assistant:${e} ${t.content}`.trimEnd())}else if(t.role===`tool_result`){let e=t.isError?`error`:`ok`,n=t.toolResultRef?[`[tool result persisted] ${t.toolResultRef.toolName} (${t.toolResultRef.originalChars} chars).`,`Full output: ${t.toolResultRef.storagePath}`,t.toolResultRef.preview.trim()?`Preview:\n${t.toolResultRef.preview.trimEnd()}`:``].filter(Boolean).join(`
|
|
18
19
|
`):t.content,i=n.length>2e3?`${n.slice(0,2e3)}… [truncated]`:n;r.push(`Tool(${t.toolName})[${e}]: ${i}`)}return r.join(`
|
|
19
|
-
`)}function
|
|
20
|
-
`);function
|
|
21
|
-
`)}async function
|
|
20
|
+
`)}function vn(e,t){let n=Math.floor(t*.35),r=0,i=e.length;for(let t=e.length-1;t>=0;t--){let a=pn(e[t]);if(r+a>n)break;r+=a,i=t}return{toKeep:e.slice(i),toSummarise:e.slice(0,i)}}function yn(e){let t=new Set;for(let n of e)if(n.role===`assistant`)for(let e of n.toolCalls??[])t.add(e.id);let n=e.filter(e=>e.role!==`tool_result`||t.has(e.toolCallId));return n.length===e.length?e:n}async function bn(e){let{entries:t,contextWindowTokens:n,llm:r,instructions:i,signal:a,hooks:o,hookCtx:s}=e,c=xn(t),l=c>=0?t[c].content:void 0,u=yn(c>=0?t.slice(c+1):t);if(u.length===0)return{status:`skipped`,reason:`No history to compact.`,estimatedTokens:0};let{toKeep:d,toSummarise:f}=vn(u,n);return f.length===0&&u.length>1&&(f=u.slice(0,u.length-1),d=u.slice(u.length-1)),f.length===0?{status:`skipped`,reason:`Not enough history to compact.`,estimatedTokens:W(u)}:{status:`compacted`,entry:{role:`compaction`,content:await hn({entries:f,llm:r,previousSummary:l,instructions:i,signal:a,hooks:o,hookCtx:s}),keptCount:d.length,droppedCount:f.length,timestamp:new Date().toISOString()},keptCount:d.length,droppedCount:f.length,estimatedTokens:W(d)}}function xn(e){for(let t=e.length-1;t>=0;t--)if(e[t].role===`compaction`)return t;return-1}const Sn=[`✨ 新会话已开启,我们可以重新开始啦~`,``,` 我是爱码Max,你的AI研发助手。你可以这样和我聊:`,` 💻 “用React写一个登录组件”`,` ✏️ “帮我写一个用户中心的PRD”`,` 🧪 “为这个接口设计测试用例”`,` 💬 “解释下什么是微服务”`,``,` 直接说出你的需求就行~`].join(`
|
|
21
|
+
`);function Cn(){return{kind:`reply`,text:Sn}}function wn(){return{kind:`reply`,text:`✅ Session reset.`}}function Tn(e){let t=On(e)?`text`:`messages`,n=t===`text`?e.message:void 0,r=t===`messages`?e.messages:void 0,i=r?kn(r):null,a=n??i?.text,o=a?nn(a):null,s=o?.remainder??``,c=!!(o&&!s),l=o&&s?s:a,u=t===`text`?l??``:o&&s&&r?An(r,s):r;return{inputMode:t,rawMessage:n,promptInput:u,transcriptMessage:t===`text`?c?n:l??``:jn(u),slashCommandSource:a,messageForRun:l,requestedSessionId:o?void 0:e.sessionId,previousSessionId:o?e.sessionId:void 0,resetCommand:o??void 0,resetShortCircuit:c}}function En(e,t){if(e.resetShortCircuit)return{kind:`reset_reply`,action:e.resetCommand?.action??`new`,transcriptMessage:e.transcriptMessage,initialUserEntryPersisted:!0};if(!e.slashCommandSource)return{kind:`run`,effectivePrompt:e.promptInput,transcriptMessage:e.transcriptMessage};let n=fn({message:e.messageForRun??``,skills:t});if(n.kind===`reply`)return{kind:`reply`,replyText:n.text,transcriptMessage:e.transcriptMessage};if(n.kind===`compact`)return{kind:`compact`,transcriptMessage:e.transcriptMessage,instructions:n.instructions,initialUserEntryPersisted:e.resetCommand?!0:void 0};if(n.kind===`rewrite`){let t=e.inputMode===`text`?n.message:An(e.promptInput,n.message);return{kind:`run`,effectivePrompt:t,transcriptMessage:jn(t)}}return{kind:`run`,effectivePrompt:e.inputMode===`text`?e.messageForRun??``:e.promptInput,transcriptMessage:e.inputMode===`text`?e.messageForRun??``:e.transcriptMessage}}async function Dn(e){let t=En(e.invocation,e.skills);if(t.kind===`run`)return{kind:`continue`,effectivePrompt:t.effectivePrompt,transcriptMessage:t.transcriptMessage};if(t.kind===`reset_reply`)return{kind:`completed`,result:await qt({replyText:(t.action===`reset`?wn():Cn()).text,sessionId:e.sessionId,isNewSession:e.isNewSession,transcriptMessage:t.transcriptMessage,initialUserEntryPersisted:t.initialUserEntryPersisted||e.initialUserEntryPersisted,runParams:e.runParams,hookRegistry:e.hookRegistry,hookContext:e.hookContext,startTime:e.startTime,eventDispatcher:e.eventDispatcher})};if(t.kind===`reply`)return{kind:`completed`,result:await qt({replyText:t.replyText,sessionId:e.sessionId,isNewSession:e.isNewSession,transcriptMessage:t.transcriptMessage,initialUserEntryPersisted:t.initialUserEntryPersisted||e.initialUserEntryPersisted,runParams:e.runParams,hookRegistry:e.hookRegistry,hookContext:e.hookContext,startTime:e.startTime,eventDispatcher:e.eventDispatcher})};let n=await bn({entries:e.runParams.channel===`CRON`?[]:await w(e.runParams.dataDir,e.sessionId),contextWindowTokens:e.runParams.llm.contextWindow??2e5,llm:{baseUrl:e.runParams.llm.baseUrl,apiKey:e.runParams.llm.apiKey,model:e.runParams.llm.model},instructions:t.instructions,signal:e.runParams.abortSignal,hooks:e.hookRegistry,hookCtx:e.hookContext});return{kind:`completed`,result:await qt({replyText:n.status===`compacted`?`⚙️ Compacted (kept ${n.keptCount}, dropped ${n.droppedCount}).`:`⚙️ Compaction skipped: ${n.reason}`,sessionId:e.sessionId,isNewSession:e.isNewSession,transcriptMessage:t.transcriptMessage,initialUserEntryPersisted:t.initialUserEntryPersisted||e.initialUserEntryPersisted,runParams:e.runParams,hookRegistry:e.hookRegistry,hookContext:e.hookContext,startTime:e.startTime,compactionEntry:n.status===`compacted`?n.entry:void 0,eventDispatcher:e.eventDispatcher})}}function On(e){return typeof e.message==`string`}function kn(e){for(let t=0;t<e.length;t+=1){let n=e[t];if(n.role!==`user`)continue;if(typeof n.content==`string`)return{index:t,text:n.content};if(!Array.isArray(n.content)||n.content.length===0)return null;let r=n.content[0];return r?.type===`text`&&typeof r.text==`string`?{index:t,text:r.text}:null}return null}function An(e,t){let n=kn(e);return n?e.map((e,r)=>{if(r!==n.index)return e;let i=e;return typeof i.content==`string`?{...e,content:t}:Array.isArray(i.content)&&i.content.length>0?{...e,content:i.content.map((e,n)=>{if(n!==0)return e;let r=e;return r?.type===`text`&&typeof r.text==`string`?{...r,text:t}:e})}:e}):e}function jn(e){return typeof e==`string`?e:JSON.stringify(e)}function Mn(e,t){if(!t||t<=0||e.length===0)return e;let n=0,r=e.length;for(let i=e.length-1;i>=0;i--)if(e[i].role===`user`){if(n++,n>t)return e.slice(r);r=i}return e}const Nn={input:0,output:0,cacheRead:0,cacheWrite:0,totalTokens:0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}};function G(e,t){return e.map(e=>Pn(e,t))}function Pn(e,t){let n=new Date(e.timestamp).getTime();if(Fn(e))return{role:`user`,content:e.content,timestamp:n};if(In(e)){let r=[];e.content&&r.push({type:`text`,text:e.content});for(let t of e.toolCalls??[])r.push({type:`toolCall`,id:t.id,name:t.name,arguments:t.arguments});return{role:`assistant`,content:r,api:t.api,provider:`openai`,model:t.model,usage:Nn,stopReason:`stop`,timestamp:n}}let r=e;return{role:`toolResult`,toolCallId:r.toolCallId,toolName:r.toolName,content:[{type:`text`,text:Ln(r)}],isError:r.isError,timestamp:n}}function Fn(e){return e.role===`user`}function In(e){return e.role===`assistant`}function Ln(e){if(!e.toolResultRef)return e.content;let t=e.toolResultRef.preview.trimEnd(),n=[`[tool result persisted] ${e.toolResultRef.toolName} (${e.toolResultRef.originalChars} chars).`,`Full output: ${e.toolResultRef.storagePath}`];return t&&(n.push(`Preview:`),n.push(t)),n.join(`
|
|
22
|
+
`)}async function Rn(e){let t=Hn(e.dataDir,e.sessionId),n=new Map,r=new Map,i=[],a=[],o=[],s,c=0,l,u,d=await Kn(t);for(let e of d.readStates)n.set(zn(e.path,e.offset,e.limit),e);for(let e of d.toolResults)r.set(e.toolCallId,e);i.push(...d.compaction.budgets),a.push(...d.compaction.snips),o.push(...d.compaction.collapseSpans),s=d.compaction.sessionMemory,c=d.compaction.consecutiveAutocompactFailures,l=d.compaction.lastCompactionAt,u=d.compaction.lastCompactionLayer;let f=async()=>{let e={version:2,updatedAt:new Date().toISOString(),readStates:Array.from(n.values()),toolResults:Array.from(r.values()).slice(-100),compaction:{sessionMemory:s,budgets:i.slice(-200),snips:a.slice(-200),collapseSpans:o.slice(-100),consecutiveAutocompactFailures:c,lastCompactionAt:l,lastCompactionLayer:u}};await P.mkdir(F.dirname(t),{recursive:!0}),await P.writeFile(t,JSON.stringify(e,null,2),`utf-8`)};return{async findReusableRead(e,t,r){let i=zn(e,t,r),a=n.get(i);if(!a)return null;let o=await Wn(e);return o===null||o!==a.lastModifiedMs?(n.delete(i),await f(),null):a},async recordRead(e){let t=new Date().toISOString(),r={path:e.path,offset:e.offset,limit:e.limit,contentHash:Gn(e.content),lineCount:e.lineCount,capturedAt:t,lastModifiedMs:await Wn(e.path)??Date.now()};return n.set(zn(e.path,e.offset,e.limit),r),await f(),r},async invalidatePath(e){let t=!1;for(let[r,i]of n.entries())Bn(i.path)===Bn(e)&&(n.delete(r),t=!0);t&&await f()},async persistToolResult(t){let n=t.thresholdChars??12e3;if(t.content.length<=n)return{content:t.content};let a=t.previewChars??2e3,o=Un(e.dataDir,e.sessionId),s=`${t.toolCallId}.txt`,c=F.join(o,s);await P.mkdir(o,{recursive:!0}),await P.writeFile(c,t.content,`utf-8`);let d=F.relative(e.dataDir,c).split(F.sep).join(`/`),p=Yn(t.content,a),m={sessionId:e.sessionId,toolCallId:t.toolCallId,toolName:t.toolName,storagePath:d,preview:p,originalChars:t.content.length,truncated:!0,createdAt:new Date().toISOString()};return r.set(m.toolCallId,m),i.push({toolCallId:m.toolCallId,toolName:m.toolName,originalChars:t.content.length,storedChars:t.content.length,previewChars:p.length,strategy:`persist`,createdAt:m.createdAt}),l=m.createdAt,u=`L2`,await f(),{content:Jn(m),reference:m}},async recordSnip(e){a.push(e),l=e.createdAt,u=e.reason===`context_dedup`?`L1`:e.reason===`microcompact`?`L4`:`L3`,await f()},async recordCollapse(e){o.push(e),l=e.createdAt,u=e.layer,await f()},async setSessionMemory(t){s=t,await Xn(e.dataDir,e.sessionId,t),await f()},async recordAutocompactResult(e){c=e.failed?c+1:0,l=e.timestamp,u=`L6`,await f()},getSnapshot(){return{version:2,updatedAt:new Date().toISOString(),readStates:Array.from(n.values()),toolResults:Array.from(r.values()).slice(-100),compaction:{sessionMemory:s,budgets:i.slice(-200),snips:a.slice(-200),collapseSpans:o.slice(-100),consecutiveAutocompactFailures:c,lastCompactionAt:l,lastCompactionLayer:u}}}}}function zn(e,t,n){return`${Bn(e)}::${t??``}::${n??``}`}function Bn(e){return F.normalize(e)}function Vn(e,t){return F.join(e,`.aimax`,`sessions`,t)}function Hn(e,t){return F.join(Vn(e,t),`context.json`)}function Un(e,t){return F.join(Vn(e,t),`tool-results`)}async function Wn(e){try{return(await P.stat(e)).mtimeMs}catch{return null}}function Gn(e){return Te(`sha1`).update(e).digest(`hex`)}async function Kn(e){try{let t=await P.readFile(e,`utf-8`),n=JSON.parse(t),r=typeof n.version==`number`?n.version:void 0;return r!==1&&r!==2?qn():{version:2,updatedAt:typeof n.updatedAt==`string`?n.updatedAt:new Date(0).toISOString(),readStates:Array.isArray(n.readStates)?n.readStates:[],toolResults:Array.isArray(n.toolResults)?n.toolResults:[],compaction:{sessionMemory:n.compaction?.sessionMemory,budgets:Array.isArray(n.compaction?.budgets)?n.compaction.budgets:[],snips:Array.isArray(n.compaction?.snips)?n.compaction.snips:[],collapseSpans:Array.isArray(n.compaction?.collapseSpans)?n.compaction.collapseSpans:[],consecutiveAutocompactFailures:typeof n.compaction?.consecutiveAutocompactFailures==`number`?n.compaction.consecutiveAutocompactFailures:0,lastCompactionAt:typeof n.compaction?.lastCompactionAt==`string`?n.compaction.lastCompactionAt:void 0,lastCompactionLayer:n.compaction?.lastCompactionLayer===`L1`||n.compaction?.lastCompactionLayer===`L2`||n.compaction?.lastCompactionLayer===`L3`||n.compaction?.lastCompactionLayer===`L4`||n.compaction?.lastCompactionLayer===`L5`||n.compaction?.lastCompactionLayer===`L6`?n.compaction.lastCompactionLayer:void 0}}}catch{return qn()}}function qn(){return{version:2,updatedAt:new Date(0).toISOString(),readStates:[],toolResults:[],compaction:{budgets:[],snips:[],collapseSpans:[],consecutiveAutocompactFailures:0}}}function Jn(e){let t=e.preview.length<e.originalChars?`
|
|
22
23
|
...`:``;return[`[tool result persisted] ${e.toolName} output was too large (${e.originalChars} chars).`,`Full output: ${e.storagePath}`,``,`Preview:`,e.preview+t].join(`
|
|
23
|
-
`)}function
|
|
24
|
-
`),r=n>t*.5?n:t;return e.slice(0,r)}async function
|
|
25
|
-
`);if(s===n.content){l.push(n);continue}u+=1,d+=Math.max(0,Math.floor((n.content.length-s.length)/4));let f=new Date().toISOString();await o?.recordSnip({toolCallId:n.toolCallId,toolName:n.toolName,originalChars:n.content.length,retainedChars:s.length,reason:a===`microcompact`?`microcompact`:`history_snip`,createdAt:f}),l.push({...n,content:s})}return u>0&&s.push({type:`compaction`,reason:`${a===`snip`?`Snip compacted`:`Microcompacted`} ${u} tool results`,layer:i,strategy:a,estimatedTokensFreed:d,affectedEntries:u,snapshotVersion:2}),
|
|
26
|
-
`);r!==e.content&&(a+=1,o+=Math.max(0,Math.floor((e.content.length-r.length)/4)),await n?.recordSnip({toolCallId:e.toolCallId,toolName:e.toolName,originalChars:e.content.length,retainedChars:r.length,reason:`microcompact`,createdAt:new Date().toISOString()})),s.push({...e,content:r})}return a===0?t:(r.push({type:`compaction`,reason:`Microcompacted ${a} stale tool results`,layer:`L4`,strategy:`microcompact_age`,estimatedTokensFreed:o,affectedEntries:a,snapshotVersion:2}),
|
|
24
|
+
`)}function Yn(e,t){if(e.length<=t)return e;let n=e.slice(0,t).lastIndexOf(`
|
|
25
|
+
`),r=n>t*.5?n:t;return e.slice(0,r)}async function Xn(e,t,n){let r=F.join(Vn(e,t),`session-memory.json`);await P.mkdir(F.dirname(r),{recursive:!0}),await P.writeFile(r,JSON.stringify(n,null,2),`utf-8`)}const Zn=new Set([`read_file`,`list_dir`,`glob`,`grep`,`bash`,`exec`,`web_fetch`,`web_search`]);async function Qn(e){let{entries:t,modelInfo:n,contextWindowTokens:r,llm:i,historyLimit:a,compactionEnabled:o=!0,signal:s,hooks:c,hookCtx:l,contextStore:u,dataDir:d,sessionId:f}=e,p,m=or(t),h=m>=0?t.slice(m+1):t;m>=0&&(p=t[m].content);let g=t.length,_=yn(Mn(h,a)),v=[];u&&(p=await $n({entries:_,existingSummary:p,llm:i,contextStore:u,signal:s,hooks:c,hookCtx:l}));let y=_;if(y=await er({entries:y,maxInlineResults:8,maxChars:1e3,layer:`L3`,strategy:`snip`,contextStore:u,compactionEvents:v}),y=await tr({entries:y,contextStore:u,compactionEvents:v}),y=await nr({entries:y,contextStore:u,compactionEvents:v,dataDir:d,sessionId:f}),!o)return{messages:G(y,n),priorSummary:p,compactionEntry:void 0,stats:{originalCount:g,keptCount:y.length,estimatedTokens:W(y),compacted:!1},compactionEvents:v};let b=sr(r),x=W(y)>=Math.max(1e3,b-13e3),S=u?.getSnapshot(),C=S?.compaction.consecutiveAutocompactFailures??0;if(!x||C>=3)return{messages:G(y,n),priorSummary:p,compactionEntry:void 0,stats:{originalCount:g,keptCount:y.length,estimatedTokens:W(y),compacted:!1},compactionEvents:v};let{toKeep:w,toSummarise:T}=vn(y,b);if(T.length===0)return{messages:G(y,n),priorSummary:p,compactionEntry:void 0,stats:{originalCount:g,keptCount:y.length,estimatedTokens:W(y),compacted:!1},compactionEvents:v};let E=new Date().toISOString();try{let e=S?.compaction.sessionMemory,t=e?.summary?.trim()?e.summary.trim():await hn({entries:T,llm:i,previousSummary:p,signal:s,hooks:c,hookCtx:l}),r={role:`compaction`,content:t,keptCount:w.length,droppedCount:T.length,timestamp:E};return await u?.recordAutocompactResult({layer:`L6`,failed:!1,timestamp:E}),v.push({type:`compaction`,reason:e?.summary?.trim()?`Autocompact replaced ${T.length} entries with session memory`:`Autocompact summarised ${T.length} entries`,layer:`L6`,strategy:e?.summary?.trim()?`session_memory`:`full_summary`,estimatedTokensFreed:Math.max(0,W(T)),affectedEntries:T.length,snapshotVersion:2}),{messages:G(yn(w),n),priorSummary:t,compactionEntry:r,stats:{originalCount:g,keptCount:w.length,estimatedTokens:W(w),compacted:!0},compactionEvents:v}}catch{return await u?.recordAutocompactResult({layer:`L6`,failed:!0,timestamp:E}),{messages:G(y,n),priorSummary:p,compactionEntry:void 0,stats:{originalCount:g,keptCount:y.length,estimatedTokens:W(y),compacted:!1},compactionEvents:[...v,{type:`compaction`,reason:`Autocompact failed and was skipped for this turn`,layer:`L6`,strategy:`circuit_breaker_retry`,snapshotVersion:2}]}}}async function $n(e){let{entries:t,existingSummary:n,llm:r,contextStore:i,signal:a,hooks:o,hookCtx:s}=e,c=W(t),l=i.getSnapshot().compaction.sessionMemory,u=!l&&c>=8e3,d=!!l&&c>=(l?.tokenEstimate??0)+15e3&&ar(t)>=3;if(!u&&!d)return n??l?.summary;let f=await hn({entries:t,llm:r,previousSummary:n??l?.summary,instructions:`Produce a durable session memory for future compaction and resume.`,signal:a,hooks:o,hookCtx:s}),p={version:1,summary:f,generatedAt:new Date().toISOString(),sourceEntryCount:t.length,tokenEstimate:c,trigger:u?`threshold`:`autocompact`};return await i.setSessionMemory(p),f}async function er(e){let{entries:t,maxInlineResults:n,maxChars:r,layer:i,strategy:a,contextStore:o,compactionEvents:s}=e;if(t.filter(ir).length<=n)return t;let c=n,l=[],u=0,d=0;for(let e=t.length-1;e>=0;--e){let n=t[e];if(!ir(n)){l.push(n);continue}if(c>0&&n.content.length<=r){--c,l.push(n);continue}let i=n.toolResultRef?.preview?.trim()||n.content.slice(0,r).trim(),s=[`[${a}] Older tool output condensed for context control.`,`Tool: ${n.toolName}`,i?`Preview:\n${i}`:``].filter(Boolean).join(`
|
|
26
|
+
`);if(s===n.content){l.push(n);continue}u+=1,d+=Math.max(0,Math.floor((n.content.length-s.length)/4));let f=new Date().toISOString();await o?.recordSnip({toolCallId:n.toolCallId,toolName:n.toolName,originalChars:n.content.length,retainedChars:s.length,reason:a===`microcompact`?`microcompact`:`history_snip`,createdAt:f}),l.push({...n,content:s})}return u>0&&s.push({type:`compaction`,reason:`${a===`snip`?`Snip compacted`:`Microcompacted`} ${u} tool results`,layer:i,strategy:a,estimatedTokensFreed:d,affectedEntries:u,snapshotVersion:2}),yn(l.reverse())}async function tr(e){let{entries:t,contextStore:n,compactionEvents:r}=e,i=Date.now()-36e5,a=0,o=0,s=[];for(let e of t){if(!ir(e)){s.push(e);continue}let t=Date.parse(e.timestamp);if(!(t>0&&t<i)){s.push(e);continue}let r=[`[microcompact] Tool output aged out of the hot context window.`,`Tool: ${e.toolName}`,`Preview:\n${e.toolResultRef?.preview?.trim()||e.content.slice(0,400).trim()}`].join(`
|
|
27
|
+
`);r!==e.content&&(a+=1,o+=Math.max(0,Math.floor((e.content.length-r.length)/4)),await n?.recordSnip({toolCallId:e.toolCallId,toolName:e.toolName,originalChars:e.content.length,retainedChars:r.length,reason:`microcompact`,createdAt:new Date().toISOString()})),s.push({...e,content:r})}return a===0?t:(r.push({type:`compaction`,reason:`Microcompacted ${a} stale tool results`,layer:`L4`,strategy:`microcompact_age`,estimatedTokensFreed:o,affectedEntries:a,snapshotVersion:2}),er({entries:s,maxInlineResults:4,maxChars:400,layer:`L4`,strategy:`microcompact`,contextStore:n,compactionEvents:r}))}async function nr(e){let{entries:t,contextStore:n,compactionEvents:r,dataDir:i,sessionId:a}=e,o=t.reduce((e,t,n)=>(t.role===`user`&&e.push(n),e),[]);if(o.length<=2)return t;let s=o[o.length-2]??t.length,c=[],l=0,u=0,d=0;for(;l<t.length;){if(l>=s||t[l]?.role===`user`){c.push(t[l]),l+=1;continue}let e=l;for(;l<s&&t[l]?.role!==`user`;)l+=1;let r=t.slice(e,l),o=r.filter(ir).filter(e=>Zn.has(e.toolName)),f=o.reduce((e,t)=>e+t.content.length,0);if(o.length<3||f<1500){c.push(...r);continue}let p=rr(r,o),m=new Date().toISOString(),h={role:`assistant`,content:p,timestamp:m};c.push(h),u+=r.length,d+=Math.max(0,Math.floor(W(r)-W([h])));let g={id:R(),layer:`L5`,startEntryIndex:e,endEntryIndex:l-1,toolNames:[...new Set(o.map(e=>e.toolName))],summary:p,sourceCount:r.length,estimatedTokensFreed:d,createdAt:m};await n?.recordCollapse(g),i&&a&&await cr(i,a,g)}return u>0&&r.push({type:`compaction`,reason:`Collapsed ${u} historical tool activity entries`,layer:`L5`,strategy:`context_collapse`,estimatedTokensFreed:d,affectedEntries:u,snapshotVersion:2}),c}function rr(e,t){let n=[...new Set(t.map(e=>e.toolName))],r=t.slice(-3).map(e=>`- ${e.toolName}: ${(e.toolResultRef?.preview||e.content).slice(0,180).trim()}`).join(`
|
|
27
28
|
`),i=e.filter(e=>e.role===`assistant`).map(e=>e.content.trim()).filter(Boolean).slice(-2).join(`
|
|
28
29
|
`);return[`[context collapse] ${t.length} tool results across ${n.join(`, `)}`,i?`Assistant checkpoints:\n${i}`:``,r?`Recent tool findings:\n${r}`:``].filter(Boolean).join(`
|
|
29
30
|
|
|
30
|
-
`)}function
|
|
31
|
-
`)}function
|
|
32
|
-
`)}],details:{status:l.status,sessionId:l.sessionId,command:l.command,cwd:l.cwd,exitCode:l.exitCode,exitSignal:l.exitSignal,toolResultRef:m?.reference}}}}}const
|
|
33
|
-
`)}],details:{status:`completed`,sessions:t}}}if(!n.sessionId?.trim())return q(`sessionId is required for this action.`);let i=n.sessionId.trim();if(r===`poll`){let t=await e.registry.wait(i,e.scopeKey,
|
|
34
|
-
`);return{sessionId:e.record.sessionId,status:e.record.status,text:a,totalLines:t.length,totalChars:e.record.output.length,truncated:e.record.outputTruncated,exitCode:e.record.exitCode,exitSignal:e.record.exitSignal}}function
|
|
35
|
-
`),c=Math.max(1,r.offset??1),l=Math.min(
|
|
31
|
+
`)}function ir(e){return e.role===`tool_result`}function ar(e){return e.reduce((e,t)=>e+(t.role===`user`?1:0),0)}function or(e){for(let t=e.length-1;t>=0;--t)if(e[t]?.role===`compaction`)return t;return-1}function sr(e){return Math.max(256,e-Math.min(e/4,2e4))}async function cr(e,t,n){let r=p(e,t);await P.mkdir(F.dirname(r),{recursive:!0}),await P.appendFile(r,`${JSON.stringify(n)}\n`,`utf-8`)}async function lr(e){let t=await Rn(e);return{async getReusableRead(e,n,r){let i=await t.findReusableRead(e,n,r);return i?{reused:!0,lineCount:i.lineCount}:{reused:!1}},async rememberRead(e){await t.recordRead(e)},async invalidateReadPath(e){await t.invalidatePath(e)},persistToolResult(e){return t.persistToolResult(e)},manageHistory(e){return Qn({...e,contextStore:t})},getSnapshot:t.getSnapshot}}async function ur(e){return e.contextManager?e.contextManager.manageHistory({entries:e.entries,modelInfo:e.modelInfo,contextWindowTokens:e.contextWindowTokens,llm:e.llm,historyLimit:e.historyLimit,compactionEnabled:e.compactionEnabled,signal:e.signal,hooks:e.hooks,hookCtx:e.hookCtx,dataDir:e.dataDir,sessionId:e.sessionId}):Qn({entries:e.entries,modelInfo:e.modelInfo,contextWindowTokens:e.contextWindowTokens,llm:e.llm,historyLimit:e.historyLimit,compactionEnabled:e.compactionEnabled,signal:e.signal,hooks:e.hooks,hookCtx:e.hookCtx,dataDir:e.dataDir,sessionId:e.sessionId})}var K=class extends Error{isHitlPause=!0;constructor(e,t,n){super(`HITL_PAUSED`),this.request=e,this.checkpoint=t,this.toolContext=n,this.name=`HitlPauseSignal`}};function dr(e){return!!(e instanceof K||typeof e==`object`&&e&&`isHitlPause`in e&&e.isHitlPause===!0)}const fr=I.Object({command:I.String({description:`Shell command to execute`}),workdir:I.Optional(I.String({description:`Working directory (relative to workspace root)`})),env:I.Optional(I.Record(I.String(),I.String())),timeout:I.Optional(I.Number({description:`Timeout in seconds (default: 1800)`})),yieldMs:I.Optional(I.Number({description:`Wait this many milliseconds before returning running state`})),background:I.Optional(I.Boolean({description:`Return immediately with running session`}))});function pr(e,t,n){return Math.max(t,Math.min(n,e))}function mr(e){return typeof e!=`number`||!Number.isFinite(e)||e<=0?1800:Math.floor(e)}function hr(e){return typeof e!=`number`||!Number.isFinite(e)||e<0?1e4:pr(Math.floor(e),0,12e4)}function gr(e,t){if(!t?.trim())return e;let n=F.isAbsolute(t)?F.normalize(t):F.normalize(F.join(e,t));if(!n.startsWith(e+F.sep)&&n!==e)throw Error(`workdir escapes workspace: ${t}`);return n}function _r(e){let t=e.outputTail.trim();return`${t.length>0?`${t}\n\n`:``}Process is running in the background. sessionId=${e.sessionId}\nUse process(action="poll"|"log", sessionId) to continue.`}function vr(e){return br({stdout:e.stdoutTail,stderr:e.stderrTail,exitCode:e.exitCode,backgroundInfo:``}).join(`
|
|
32
|
+
`)}function yr(e){return e.replace(/^(\s*\n)+/,``).trimEnd()}function br(e){let t=yr(e.stdout),n=e.stderr.trim();if(e.exitCode!==void 0&&e.exitCode!==0){let t=`Exit code: ${e.exitCode===null?`null`:e.exitCode}`;n=n.length>0?`${n}\n${t}`:t}return[t.length>0?t:`(no output)`,n,e.backgroundInfo?.trim()||``].filter(e=>e.length>0)}function xr(e){return/\b(rm|mv|cp|chmod|chown|sudo|git\s+push|kubectl\s+delete|terraform\s+apply|docker\s+rm)\b|[>|]{1,2}\s*[^ ]+/i.test(e)}function Sr(e,t,n){return!e||e.request.kind!==`approval`||e.toolContext?.toolName!==`exec`||e.toolContext.toolCallId!==t||JSON.stringify(e.toolContext.toolArgs)!==JSON.stringify(n)?!1:e.resolution.action===`submit`&&(e.resolution.values?.selectedChoiceIds?.includes(`approve`)??!1)}function Cr(e){return{name:`exec`,label:`Exec`,description:`Execute shell commands with optional background continuation. Use process tool to poll logs and status.`,parameters:fr,async execute(t,n,r){if(!n.command?.trim())return{content:[{type:`text`,text:`Error: command is required.`}],details:{status:`failed`}};if(e.sessionId&&xr(n.command)&&!Sr(e.hitlResume,t,n))throw new K({requestId:R(),sessionId:e.hitlResume?.request.sessionId??e.sessionId,kind:`approval`,title:`Confirm shell command`,prompt:`This command may modify system or workspace state. Approve before execution.`,details:{tool:`exec`,command:n.command,workdir:n.workdir},preview:{mimeType:`text/plain`,content:n.command},input:{mode:`choice`,choices:[{id:`approve`,label:`Approve`},{id:`deny`,label:`Deny`}]},policy:{resumable:!0,defaultOnTimeout:`deny`},createdAt:new Date().toISOString()},{turnId:t,phase:`before_tool`,resumeStrategy:`reenter_from_checkpoint`},{toolCallId:t,toolName:`exec`,toolArgs:n});let i;try{i=gr(e.workspaceDir,n.workdir)}catch(e){return{content:[{type:`text`,text:`Error: ${e instanceof Error?e.message:String(e)}`}],details:{status:`failed`}}}let a=mr(n.timeout),o=e.registry.start({command:n.command,cwd:i,env:n.env,timeoutSec:a,scopeKey:e.scopeKey}),s=n.background===!0,c=typeof n.yieldMs==`number`&&Number.isFinite(n.yieldMs),l=o,u;try{if(!s&&r&&(u=()=>{e.registry.terminate(o.sessionId,e.scopeKey)},r.aborted?u():r.addEventListener(`abort`,u,{once:!0})),!s&&!c){let t=await e.registry.wait(o.sessionId,e.scopeKey,void 0);t&&(l=t)}else if(!s){let t=await e.registry.wait(o.sessionId,e.scopeKey,hr(n.yieldMs));t&&(l=t)}}finally{r&&u&&r.removeEventListener(`abort`,u)}if(l.status===`running`)return{content:[{type:`text`,text:_r(l)}],details:{status:`running`,sessionId:l.sessionId,command:l.command,cwd:l.cwd,pid:l.pid}};let d=e.registry.readOutput(l.sessionId,e.scopeKey),f=d?br({stdout:d.stdout,stderr:d.stderr,exitCode:l.exitCode,backgroundInfo:``}):[vr(l)],p=yr(d?.stdout??l.stdoutTail),m=await e.contextManager?.persistToolResult({toolCallId:t,toolName:`exec`,content:p.length>0?p:`(no output)`});return{content:[{type:`text`,text:[m?.content??(p.length>0?p:`(no output)`),...f.slice(1)].join(`
|
|
33
|
+
`)}],details:{status:l.status,sessionId:l.sessionId,command:l.command,cwd:l.cwd,exitCode:l.exitCode,exitSignal:l.exitSignal,toolResultRef:m?.reference}}}}}const wr=I.Object({action:I.String({description:`Process action: list | poll | log | kill`}),sessionId:I.Optional(I.String({description:`Session id for non-list actions`})),offset:I.Optional(I.Number({description:`Log line offset (0-based)`})),limit:I.Optional(I.Number({description:`Maximum lines to return`})),timeout:I.Optional(I.Number({description:`Poll wait time in milliseconds`}))});function Tr(e){return typeof e!=`number`||!Number.isFinite(e)||e<0?0:Math.max(0,Math.min(12e4,Math.floor(e)))}function q(e){return{content:[{type:`text`,text:e}],details:{status:`failed`}}}function Er(e){return{name:`process`,label:`Process`,description:`Manage background exec sessions: list, poll, log, kill.`,parameters:wr,async execute(t,n){let r=n.action?.trim().toLowerCase();if(r===`list`){let t=e.registry.list(e.scopeKey);return{content:[{type:`text`,text:t.length===0?`No running or recent sessions.`:t.map(e=>{let t=(e.endedAt??Date.now())-e.startedAt;return`${e.sessionId} ${e.status.padEnd(9)} ${t}ms :: ${e.command}`}).join(`
|
|
34
|
+
`)}],details:{status:`completed`,sessions:t}}}if(!n.sessionId?.trim())return q(`sessionId is required for this action.`);let i=n.sessionId.trim();if(r===`poll`){let t=await e.registry.wait(i,e.scopeKey,Tr(n.timeout));return t?{content:[{type:`text`,text:t.status===`running`?`Session ${i} is still running.`:`Session ${i} finished with status=${t.status}, exitCode=${t.exitCode??`null`}.`}],details:{status:t.status,sessionId:i,exitCode:t.exitCode,exitSignal:t.exitSignal,aggregated:t.status!==`running`}}:q(`No session found for ${i}`)}if(r===`log`){let t=e.registry.readLog({sessionId:i,scopeKey:e.scopeKey,offset:n.offset,limit:n.limit});return t?{content:[{type:`text`,text:t.text.trim().length>0?t.text:`(no output)`}],details:{status:t.status,sessionId:i,totalLines:t.totalLines,totalChars:t.totalChars,truncated:t.truncated,exitCode:t.exitCode,exitSignal:t.exitSignal}}:q(`No session found for ${i}`)}if(r===`kill`){let t=await e.registry.terminate(i,e.scopeKey);return t?{content:[{type:`text`,text:t.status===`running`?`Termination signal sent to ${i}.`:`Session ${i} terminated with status=${t.status}.`}],details:{status:t.status,sessionId:i,exitCode:t.exitCode,exitSignal:t.exitSignal}}:q(`No session found for ${i}`)}return q(`Unsupported action: ${n.action}`)}}}const Dr=2e5;function Or(e,t=4e3){return e?e.length>t?e.slice(-t):e:``}function kr(e,t){let n=e+t;return n.length<=Dr?{text:n,truncated:!1}:{text:n.slice(-Dr),truncated:!0}}function Ar(e,t,n){if(n.length===0)return;let r=n.toString(`utf-8`),i=kr(e.output,r);e.output=i.text;let a=kr(e[t],r);e[t]=a.text,(i.truncated||a.truncated)&&(e.outputTruncated=!0)}function J(e){return{sessionId:e.sessionId,scopeKey:e.scopeKey,command:e.command,cwd:e.cwd,pid:typeof e.child.pid==`number`?e.child.pid:void 0,startedAt:e.startedAt,endedAt:e.endedAt,status:e.status,exitCode:e.exitCode,exitSignal:e.exitSignal,outputTail:Or(e.output),stdoutTail:Or(e.stdout),stderrTail:Or(e.stderr),outputTruncated:e.outputTruncated}}function Y(e,t){return t?e.scopeKey===t:!0}function jr(e,t){return typeof e!=`number`||!Number.isFinite(e)||e<=0?t:Math.floor(e)}function Mr(e){return e?e.split(/\r?\n/):[]}function Nr(e){let t=Mr(e.record.output),n=e.offset===void 0&&e.limit===void 0,r=Math.max(0,(e.offset??0)|0),i=jr(e.limit,n?200:Math.max(1,t.length-r)),a=(n&&t.length>200?t.slice(t.length-200):t.slice(r,r+i)).join(`
|
|
35
|
+
`);return{sessionId:e.record.sessionId,status:e.record.status,text:a,totalLines:t.length,totalChars:e.record.output.length,truncated:e.record.outputTruncated,exitCode:e.record.exitCode,exitSignal:e.record.exitSignal}}function Pr(e){e.timeoutTimer&&=(clearTimeout(e.timeoutTimer),void 0),e.killTimer&&=(clearTimeout(e.killTimer),void 0),e.resolveDone()}function Fr(){let e=new Map,t=new Map,n=n=>{if(e.delete(n.sessionId),t.set(n.sessionId,n),t.size<=100)return;let r=Array.from(t.values()).sort((e,t)=>(e.endedAt??2**53-1)-(t.endedAt??2**53-1));for(;r.length>100;){let e=r.shift();if(!e)break;t.delete(e.sessionId)}},r=n=>e.get(n)??t.get(n)??null,i=(e,t)=>{e.endedAt===void 0&&(t?.(),e.endedAt=Date.now(),n(e),Pr(e))};return{start(t){let n=Oe(`bash`,[`-lc`,t.command],{cwd:t.cwd,env:{...process.env,...t.env??{}},stdio:[`pipe`,`pipe`,`pipe`]}),r=()=>{},a=new Promise(e=>{r=e}),o={sessionId:R(),scopeKey:t.scopeKey,command:t.command,cwd:t.cwd,startedAt:Date.now(),child:n,status:`running`,output:``,stdout:``,stderr:``,outputTruncated:!1,donePromise:a,resolveDone:r};e.set(o.sessionId,o),n.stdout.on(`data`,e=>Ar(o,`stdout`,e)),n.stderr.on(`data`,e=>Ar(o,`stderr`,e));let s=jr(t.timeoutSec,1800);return o.timeoutTimer=setTimeout(()=>{o.status===`running`&&(o.status=`timeout`,Ar(o,`stderr`,Buffer.from(`\n[Timed out after ${s}s]\n`)),o.child.kill(`SIGTERM`),o.killTimer=setTimeout(()=>{(o.status===`running`||o.status===`timeout`)&&o.child.kill(`SIGKILL`)},1e3))},s*1e3),n.on(`error`,e=>{i(o,()=>{o.status===`running`&&(o.status=`failed`),Ar(o,`stderr`,Buffer.from(`\n[Process error: ${e.message}]\n`))})}),n.on(`close`,(e,t)=>{i(o,()=>{o.exitCode=e,o.exitSignal=t,o.status===`running`?o.status=e===0?`completed`:`failed`:o.status===`killed`&&e===0&&(o.status=`completed`)})}),J(o)},get(e,t){let n=r(e);return!n||!Y(n,t)?null:J(n)},list(n){return[...e.values(),...t.values()].filter(e=>Y(e,n)).sort((e,t)=>t.startedAt-e.startedAt).map(e=>J(e))},async wait(e,t,n){let i=r(e);if(!i||!Y(i,t))return null;if(i.status!==`running`)return J(i);typeof n==`number`&&Number.isFinite(n)&&n>=0?await Promise.race([i.donePromise,new Promise(e=>{setTimeout(e,n)})]):await i.donePromise;let a=r(e);return!a||!Y(a,t)?null:J(a)},readLog(e){let t=r(e.sessionId);return!t||!Y(t,e.scopeKey)?null:Nr({record:t,offset:e.offset,limit:e.limit})},readOutput(e,t){let n=r(e);return!n||!Y(n,t)?null:{sessionId:n.sessionId,status:n.status,stdout:n.stdout,stderr:n.stderr,combined:n.output,truncated:n.outputTruncated,exitCode:n.exitCode,exitSignal:n.exitSignal}},async terminate(e,t){let n=r(e);if(!n||!Y(n,t))return null;if(n.status!==`running`)return J(n);n.status=`killed`,n.child.kill(`SIGTERM`),n.killTimer=setTimeout(()=>{(n.status===`running`||n.status===`killed`)&&n.child.kill(`SIGKILL`)},1e3),await Promise.race([n.donePromise,new Promise(e=>{setTimeout(e,1500)})]);let i=r(e);return i?J(i):null}}}function Ir(e){return Cr({workspaceDir:e,registry:Fr(),scopeKey:e})}const Lr=5*1024*1024,Rr=2e3;function zr(e,t){return F.isAbsolute(e)?F.normalize(e):F.normalize(F.join(t,e))}const Br=I.Object({path:I.String({description:`File path (relative to workspace or absolute)`}),offset:I.Optional(I.Number({description:`Line offset (1-based, default: 1)`})),limit:I.Optional(I.Number({description:`Maximum lines to read (default: 2000)`}))});function Vr(e,t){return{name:`read_file`,label:`Read File`,description:`Read the contents of a file`,parameters:Br,async execute(n,r){let i;try{i=zr(r.path,e)}catch(e){return{content:[{type:`text`,text:`Error: ${e instanceof Error?e.message:String(e)}`}],details:{content:``,lines:0,truncated:!1}}}let a=await t?.getReusableRead(i,r.offset,r.limit);if(a?.reused)return{content:[{type:`text`,text:`[file unchanged] ${r.path}`}],details:{content:``,lines:a.lineCount??0,truncated:!1,deduplicated:!0}};let o;try{o=await P.readFile(i)}catch(e){return{content:[{type:`text`,text:`Error: ${e.code===`ENOENT`?`File not found: ${r.path}`:String(e)}`}],details:{content:``,lines:0,truncated:!1}}}if(o.length>Lr){let e=o.slice(0,Lr).toString(`utf-8`);return{content:[{type:`text`,text:`${e}\n[...file truncated at ${Lr} bytes]`}],details:{content:e,lines:0,truncated:!0}}}let s=o.toString(`utf-8`).split(`
|
|
36
|
+
`),c=Math.max(1,r.offset??1),l=Math.min(Rr,r.limit??Rr),u=s.slice(c-1,c-1+l),d=u.length<s.length-(c-1),f=u.map((e,t)=>`${(c+t).toString().padStart(4)} ${e}`).join(`
|
|
36
37
|
`),p=d?`\n[...${s.length-(c-1+u.length)} more lines]`:``;return await t?.rememberRead({path:i,content:u.join(`
|
|
37
38
|
`),lineCount:u.length,offset:r.offset,limit:r.limit}),{content:[{type:`text`,text:f+p}],details:{content:u.join(`
|
|
38
|
-
`),lines:u.length,truncated:d}}}}}const
|
|
39
|
-
`)||`(empty directory)`}],details:{entries:a}}}}}const
|
|
40
|
-
`)}function
|
|
41
|
-
`);n.length>0&&n[n.length-1]===``&&n.pop();let r=
|
|
42
|
-
`)}function
|
|
43
|
-
`)}`);r.push([s,n.length,o]),i=s+n.length}return r.sort((e,t)=>e[0]-t[0]),r}function
|
|
44
|
-
`)}],details:{matches:i}}}}}const
|
|
45
|
-
`)||`(empty)`}],details:{lines:i}}}}}const
|
|
46
|
-
`)};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=
|
|
39
|
+
`),lines:u.length,truncated:d}}}}}const Hr=I.Object({path:I.String({description:`File path (relative to workspace or absolute)`}),content:I.String({description:`File content to write`})});function Ur(e,t){return{name:`write_file`,label:`Write File`,description:`Create or overwrite a file with the given content`,parameters:Hr,async execute(n,r){let i;try{i=zr(r.path,e)}catch(e){return{content:[{type:`text`,text:`Error: ${e instanceof Error?e.message:String(e)}`}],details:{path:r.path}}}try{await P.mkdir(F.dirname(i),{recursive:!0}),await P.writeFile(i,r.content,`utf-8`),await t?.invalidateReadPath(i)}catch(e){return{content:[{type:`text`,text:`Error writing file: ${e instanceof Error?e.message:String(e)}`}],details:{path:i}}}return{content:[{type:`text`,text:`File written: ${r.path}`}],details:{path:i}}}}}const Wr=I.Object({path:I.String({description:`File path (relative to workspace or absolute)`}),old_string:I.String({description:`Exact text to replace`}),new_string:I.String({description:`Replacement text`})});function Gr(e,t){return{name:`edit_file`,label:`Edit File`,description:`Replace the first occurrence of old_string with new_string in a file`,parameters:Wr,async execute(n,r){let i;try{i=zr(r.path,e)}catch(e){return{content:[{type:`text`,text:`Error: ${e instanceof Error?e.message:String(e)}`}],details:{path:r.path,occurrences:0}}}let a;try{a=await P.readFile(i,`utf-8`)}catch(e){return{content:[{type:`text`,text:`Error: ${e.code===`ENOENT`?`File not found: ${r.path}`:String(e)}`}],details:{path:i,occurrences:0}}}if(!a.includes(r.old_string))return{content:[{type:`text`,text:`Error: old_string not found in ${r.path}`}],details:{path:i,occurrences:0}};let o=a.replace(r.old_string,r.new_string);return await P.writeFile(i,o,`utf-8`),await t?.invalidateReadPath(i),{content:[{type:`text`,text:`File edited: ${r.path}`}],details:{path:i,occurrences:1}}}}}const Kr=I.Object({path:I.Optional(I.String({description:`Directory path (default: workspace root)`}))});function qr(e){return{name:`list_dir`,label:`List Directory`,description:`List the contents of a directory`,parameters:Kr,async execute(t,n){let r=n.path??`.`,i;try{i=zr(r,e)}catch(e){return{content:[{type:`text`,text:`Error: ${e instanceof Error?e.message:String(e)}`}],details:{entries:[]}}}let a;try{a=(await P.readdir(i,{withFileTypes:!0})).map(e=>`${e.name}${e.isDirectory()?`/`:``}`)}catch(e){return{content:[{type:`text`,text:`Error: ${e instanceof Error?e.message:String(e)}`}],details:{entries:[]}}}return{content:[{type:`text`,text:a.join(`
|
|
40
|
+
`)||`(empty directory)`}],details:{entries:a}}}}}const Jr=I.Object({input:I.String({description:`Patch content using the *** Begin Patch/End Patch format.`})});function Yr(e,t){let n=F.isAbsolute(e)?F.normalize(e):F.normalize(F.join(t,e));if(!n.startsWith(t+F.sep)&&n!==t)throw Error(`Path escapes workspace: ${e}`);return n}function Xr(e,t){let n=F.relative(t,e);return!n||n===``?F.basename(e):n.startsWith(`..`)||F.isAbsolute(n)?e:n}async function Zr(e){await P.mkdir(F.dirname(e),{recursive:!0})}function Qr(e){let t=[`Success. Updated the following files:`];for(let n of e.added)t.push(`A ${n}`);for(let n of e.modified)t.push(`M ${n}`);for(let n of e.deleted)t.push(`D ${n}`);return t.join(`
|
|
41
|
+
`)}function $r(e,t={}){return{name:`apply_patch`,label:`apply_patch`,description:`Apply a patch to one or more files using the apply_patch format. The input should include *** Begin Patch and *** End Patch markers.`,parameters:Jr,async execute(n,r){try{let i=r.input?.trim();if(!i)return{content:[{type:`text`,text:`Error: Provide a patch input.`}],details:{summary:{added:[],modified:[],deleted:[]}}};if(t.sessionId&&!(t.hitlResume?.request.kind===`approval`&&t.hitlResume.toolContext?.toolName===`apply_patch`&&t.hitlResume.toolContext.toolCallId===n&&JSON.stringify(t.hitlResume.toolContext.toolArgs)===JSON.stringify(r)&&t.hitlResume.resolution.action===`submit`&&(t.hitlResume.resolution.values?.selectedChoiceIds?.includes(`approve`)??!1)))throw new K({requestId:R(),sessionId:t.hitlResume?.request.sessionId??t.sessionId,kind:`approval`,title:`Confirm patch application`,prompt:`Applying this patch will modify files in the workspace. Approve before continuing.`,preview:{mimeType:`text/plain`,content:i},details:{tool:`apply_patch`},input:{mode:`choice`,choices:[{id:`approve`,label:`Approve`},{id:`deny`,label:`Deny`}]},policy:{resumable:!0,defaultOnTimeout:`deny`},createdAt:new Date().toISOString()},{turnId:n,phase:`before_tool`,resumeStrategy:`reenter_from_checkpoint`},{toolCallId:n,toolName:`apply_patch`,toolArgs:r});let a=ti(i);if(a.hunks.length===0)return{content:[{type:`text`,text:`Error: No files were modified.`}],details:{summary:{added:[],modified:[],deleted:[]}}};let o={added:[],modified:[],deleted:[]},s={added:new Set,modified:new Set,deleted:new Set};for(let t of a.hunks){if(t.kind===`add`){let n=Yr(t.path,e);await Zr(n),await P.writeFile(n,t.contents,`utf-8`),ei(o,s,`added`,Xr(n,e));continue}if(t.kind===`delete`){let n=Yr(t.path,e);await P.rm(n,{force:!0,recursive:!1}),ei(o,s,`deleted`,Xr(n,e));continue}let n=Yr(t.path,e),r=await ai(n,t.chunks);if(t.movePath){let i=Yr(t.movePath,e);await Zr(i),await P.writeFile(i,r,`utf-8`),await P.rm(n,{force:!0,recursive:!1}),ei(o,s,`modified`,Xr(i,e))}else await P.writeFile(n,r,`utf-8`),ei(o,s,`modified`,Xr(n,e))}return{content:[{type:`text`,text:Qr(o)}],details:{summary:o}}}catch(e){if(e instanceof K)throw e;return{content:[{type:`text`,text:`Error: ${e instanceof Error?e.message:String(e)}`}],details:{summary:{added:[],modified:[],deleted:[]}}}}}}}function ei(e,t,n,r){t[n].has(r)||(t[n].add(r),e[n].push(r))}function ti(e){let t=e.trim();if(!t)throw Error(`Invalid patch: input is empty.`);let n=t.split(/\r?\n/);ni(n);let r=[],i=n.slice(1,n.length-1),a=2;for(;i.length>0;){let{hunk:e,consumed:t}=ri(i,a);r.push(e),a+=t,i=i.slice(t)}return{hunks:r}}function ni(e){let t=e[0]?.trim(),n=e[e.length-1]?.trim();if(t!==`*** Begin Patch`)throw Error(`The first line of the patch must be '*** Begin Patch'`);if(n!==`*** End Patch`)throw Error(`The last line of the patch must be '*** End Patch'`)}function ri(e,t){if(e.length===0)throw Error(`Invalid patch hunk at line ${t}: empty hunk`);let n=e[0].trim();if(n.startsWith(`*** Add File: `)){let t=n.slice(14),r=``,i=1;for(let t of e.slice(1))if(t.startsWith(`+`))r+=`${t.slice(1)}\n`,i+=1;else break;return{hunk:{kind:`add`,path:t,contents:r},consumed:i}}if(n.startsWith(`*** Delete File: `))return{hunk:{kind:`delete`,path:n.slice(17)},consumed:1};if(n.startsWith(`*** Update File: `)){let r=n.slice(17),i=e.slice(1),a=1,o,s=i[0]?.trim();s?.startsWith(`*** Move to: `)&&(o=s.slice(13),i=i.slice(1),a+=1);let c=[];for(;i.length>0;){if(i[0].trim()===``){i=i.slice(1),a+=1;continue}if(i[0].startsWith(`***`))break;let{chunk:e,consumed:n}=ii(i,t+a,c.length===0);c.push(e),i=i.slice(n),a+=n}if(c.length===0)throw Error(`Invalid patch hunk at line ${t}: Update file hunk for path '${r}' is empty`);return{hunk:{kind:`update`,path:r,movePath:o,chunks:c},consumed:a}}throw Error(`Invalid patch hunk at line ${t}: '${e[0]}' is not a valid hunk header.`)}function ii(e,t,n){if(e.length===0)throw Error(`Invalid patch hunk at line ${t}: Update hunk does not contain any lines`);let r,i=0;if(e[0]===`@@`)i=1;else if(e[0].startsWith(`@@ `))r=e[0].slice(3),i=1;else if(!n)throw Error(`Invalid patch hunk at line ${t}: Expected update hunk to start with a @@ context marker.`);if(i>=e.length)throw Error(`Invalid patch hunk at line ${t+1}: Update hunk does not contain any lines`);let a={changeContext:r,oldLines:[],newLines:[],isEndOfFile:!1},o=0;for(let n of e.slice(i)){if(n===`*** End of File`){if(o===0)throw Error(`Invalid patch hunk at line ${t+1}: Update hunk does not contain any lines`);a.isEndOfFile=!0,o+=1;break}let e=n[0];if(!e){a.oldLines.push(``),a.newLines.push(``),o+=1;continue}if(e===` `){let e=n.slice(1);a.oldLines.push(e),a.newLines.push(e),o+=1;continue}if(e===`+`){a.newLines.push(n.slice(1)),o+=1;continue}if(e===`-`){a.oldLines.push(n.slice(1)),o+=1;continue}if(o===0)throw Error(`Invalid patch hunk at line ${t+1}: Unexpected line found in update hunk.`);break}return{chunk:a,consumed:o+i}}async function ai(e,t){let n=(await P.readFile(e,`utf-8`).catch(t=>{throw Error(`Failed to read file to update ${e}: ${t}`)})).split(`
|
|
42
|
+
`);n.length>0&&n[n.length-1]===``&&n.pop();let r=si(n,oi(n,e,t));return(r.length===0||r[r.length-1]!==``)&&(r=[...r,``]),r.join(`
|
|
43
|
+
`)}function oi(e,t,n){let r=[],i=0;for(let a of n){if(a.changeContext){let n=ci(e,[a.changeContext],i,!1);if(n===null)throw Error(`Failed to find context '${a.changeContext}' in ${t}`);i=n+1}if(a.oldLines.length===0){let t=e.length>0&&e[e.length-1]===``?e.length-1:e.length;r.push([t,0,a.newLines]);continue}let n=a.oldLines,o=a.newLines,s=ci(e,n,i,a.isEndOfFile);if(s===null&&n[n.length-1]===``&&(n=n.slice(0,-1),o.length>0&&o[o.length-1]===``&&(o=o.slice(0,-1)),s=ci(e,n,i,a.isEndOfFile)),s===null)throw Error(`Failed to find expected lines in ${t}:\n${a.oldLines.join(`
|
|
44
|
+
`)}`);r.push([s,n.length,o]),i=s+n.length}return r.sort((e,t)=>e[0]-t[0]),r}function si(e,t){let n=[...e];for(let[e,r,i]of[...t].toReversed()){for(let t=0;t<r;t+=1)e<n.length&&n.splice(e,1);for(let t=0;t<i.length;t+=1)n.splice(e+t,0,i[t])}return n}function ci(e,t,n,r){if(t.length===0)return n;if(t.length>e.length)return null;let i=e.length-t.length,a=r&&e.length>=t.length?i:n;if(a>i)return null;for(let n=a;n<=i;n+=1)if(li(e,t,n,e=>e))return n;for(let n=a;n<=i;n+=1)if(li(e,t,n,e=>e.trimEnd()))return n;for(let n=a;n<=i;n+=1)if(li(e,t,n,e=>e.trim()))return n;for(let n=a;n<=i;n+=1)if(li(e,t,n,e=>ui(e.trim())))return n;return null}function li(e,t,n,r){for(let i=0;i<t.length;i+=1)if(r(e[n+i])!==r(t[i]))return!1;return!0}function ui(e){return Array.from(e).map(e=>{switch(e){case`‐`:case`‑`:case`‒`:case`–`:case`—`:case`―`:case`−`:return`-`;case`‘`:case`’`:case`‚`:case`‛`:return`'`;case`“`:case`”`:case`„`:case`‟`:return`"`;case`\xA0`:case` `:case` `:case` `:case` `:case` `:case` `:case` `:case` `:case` `:case` `:case` `:case` `:return` `;default:return e}}).join(``)}const di=I.Object({question:I.String({description:`The question to ask the user.`}),options:I.Optional(I.Array(I.String(),{description:`Optional list of choices for the user to select from.`})),allow_free_text:I.Optional(I.Boolean({description:`Whether to allow the user to type a free-text response in addition to choices. Defaults to true.`}))});function fi(e){return{name:`clarify`,label:`Clarify`,description:`Ask the user a clarifying question when you need more information to proceed. Provide a clear question and optionally a list of choices. The current task will be paused until the user responds.`,parameters:di,async execute(t,n){let r=R(),i=n.options&&n.options.length>0,a;throw a=i?{mode:`choice`,choices:n.options.map((e,t)=>({id:`option-${t}`,label:e})),allowFreeText:n.allow_free_text!==!1}:{mode:`text`,multiline:!0,placeholder:`Type your response...`},new K({requestId:r,sessionId:e,kind:`clarify`,title:`Agent needs clarification`,prompt:n.question,input:a,policy:{resumable:!0},createdAt:new Date().toISOString()},{turnId:t,phase:`before_tool`,resumeStrategy:`reenter_from_checkpoint`},{toolCallId:t,toolName:`clarify`,toolArgs:n})}}}function pi(e){return F.join(e,`.aimax`)}function mi(e){return F.join(pi(e),`MEMORY.md`)}async function hi(e,t,n){e.onMemoryChanged&&await Promise.resolve(e.onMemoryChanged(n)).catch(()=>{}),t&&await Promise.resolve(t(n)).catch(()=>{})}function gi(e,t){let n=pi(e),r=T({providerId:t?.providerId,pluginId:t?.pluginId,dataDir:e,memoryDir:n,sessionId:t?.sessionId});return r?r.provider:h({dataDir:e,memoryDir:n,sessionId:t?.sessionId})}async function _i(e){return f(pi(e))}async function vi(e){try{return await P.readFile(e,`utf-8`)}catch(e){if(e.code===`ENOENT`)return null;throw e}}async function yi(e){return vi(mi(e))}async function bi(e,t,n){return await gi(e,n).search(t)}async function xi(e,t,n,r,i){try{return await gi(e,i).getLines(t,n,r)}catch{return null}}async function Si(e,t,n){let r=gi(e,n);await r.append(t),await hi(r,n?.onMemoryChanged,{reason:`append`,files:[`MEMORY.md`],source:`memory`,sessionId:n?.sessionId,providerId:n?.providerId??n?.pluginId,timestamp:new Date().toISOString()})}async function Ci(e,t,n,r){let i=gi(e,r);await i.updateFile(t,n),await hi(i,r?.onMemoryChanged,{reason:`update`,files:[t],source:`memory`,sessionId:r?.sessionId,providerId:r?.providerId??r?.pluginId,timestamp:new Date().toISOString()})}async function wi(e,t,n){let r=gi(e,n);await r.deleteFile(t),await hi(r,n?.onMemoryChanged,{reason:`delete`,files:[t],source:`memory`,sessionId:n?.sessionId,providerId:n?.providerId??n?.pluginId,timestamp:new Date().toISOString()})}const Ti=I.Object({query:I.String({description:`Search query (case-insensitive substring match)`})});function Ei(e,t){return{name:`memory_search`,label:`Memory Search`,description:`Search memory files for relevant information`,parameters:Ti,async execute(n,r){let i=(await bi(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(`
|
|
45
|
+
`)}],details:{matches:i}}}}}const Di=I.Object({file:I.String({description:`Memory file path`}),start_line:I.Number({description:`Start line number (1-based)`}),end_line:I.Number({description:`End line number (1-based)`})});function Oi(e,t){return{name:`memory_get`,label:`Memory Get`,description:`Read specific lines from a memory file`,parameters:Di,async execute(n,r){let i=await xi(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(`
|
|
46
|
+
`)||`(empty)`}],details:{lines:i}}}}}const ki=I.Object({content:I.String({description:`Content to append to MEMORY.md`})});function Ai(e,t){return{name:`memory_append`,label:`Memory Append`,description:`Append new information to the MEMORY.md file`,parameters:ki,async execute(n,r){try{return await Si(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 ji=I.Object({action:I.String({description:`A short description of the action that needs approval.`}),reason:I.String({description:`Why this action needs human approval.`}),details:I.Optional(I.String({description:`Additional details about the action (e.g. the command to execute).`}))});function Mi(e,t){return{name:`request_approval`,label:`Request Approval`,description:`Request explicit human approval before performing a high-risk action. Describe the action and why it needs approval. The task will be paused until the user approves or denies the action.`,parameters:ji,async execute(n,r){if(t?.request.kind===`approval`&&t.toolContext?.toolName===`request_approval`&&t.toolContext.toolCallId===n&&t.resolution.action===`submit`){let e=t.resolution.values?.selectedChoiceIds?.includes(`approve`)??!1;return{content:[{type:`text`,text:e?`Approval granted.`:`Approval denied.`}],details:{paused:!1,approved:e}}}let i=R(),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:`Approve`,description:`Allow this action to proceed`},{id:`deny`,label:`Deny`,description:`Reject this action`}]},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=I.Object({title:I.String({description:`A short title for the review (e.g. 'Weekly Report Draft').`}),description:I.String({description:`What the user should review and what kind of feedback you need.`}),content:I.String({description:`The content to review (text, markdown, or JSON).`}),content_type:I.Optional(I.String({description:`MIME type: text/plain, application/json, or text/markdown. Defaults to text/markdown.`}))});function Pi(e){return{name:`request_review`,label:`Request Review`,description:`Present a draft, document, or output for human review before proceeding. Include the content to review and a description of what feedback you need. The task will be paused until the user reviews and responds.`,parameters:Ni,async execute(t,n){let r=R(),i={mimeType:n.content_type??`text/markdown`,content:n.content};throw new K({requestId:r,sessionId:e,kind:`review`,title:n.title,prompt:n.description,preview:i,input:{mode:`choice`,choices:[{id:`approve`,label:`Approve`,description:`The content looks good, proceed`},{id:`revise`,label:`Request changes`,description:`Provide feedback for revision`},{id:`reject`,label:`Reject`,description:`Discard this draft`}],allowFreeText:!0},policy:{resumable:!0},createdAt:new Date().toISOString()},{turnId:t,phase:`before_tool`,resumeStrategy:`reenter_from_checkpoint`},{toolCallId:t,toolName:`request_review`,toolArgs:n})}}}const Fi=I.Object({task:I.String({description:`The task description for the subagent to execute`}),label:I.Optional(I.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,l){return{name:`sessions_spawn`,label:`Spawn Subagent`,description:`Delegate a task to a subagent that runs independently. 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(u,d){let f=d.task.trim(),p=d.label?.trim();if(!f){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=R(),g=new AbortController,_;try{_=await c(r,i)}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:f,label:p,depth:n+1,status:`running`,startedAt:Date.now(),abortController:g},y=l({dataDir:r,sessionId:_,message:f,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=I.Object({action:I.Union([`list`,`kill`].map(e=>I.Literal(e)),{description:`Action to perform: "list" to show subagents, "kill" to stop one or all`}),target:I.Optional(I.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(`
|
|
47
|
+
`)};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=I.Object({image:I.String({description:`Image path or URL`}),prompt:I.Optional(I.String({description:`Prompt for image analysis`})),model:I.Optional(I.String({description:`Optional model override`})),maxBytesMb:I.Optional(I.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}}}}function Wi(e,t){let n=F.join(e,`workspace`),r=t?.memoryOptions,i=Fr(),a=[Cr({sessionId:t?.sessionId,workspaceDir:n,registry:i,scopeKey:n,contextManager:t?.contextManager,hitlResume:t?.hitlResume}),Er({registry:i,scopeKey:n}),Vr(n,t?.contextManager),Ur(n,t?.contextManager),Gr(n,t?.contextManager),qr(n),$r(n,{sessionId:t?.sessionId,hitlResume:t?.hitlResume}),Ei(e,r),Oi(e,r),Ai(e,r),...t?.sessionId?[fi(t.sessionId),Mi(t.sessionId,t.hitlResume),Pi(t.sessionId)]:[]];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 Gi={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`},Ki=[`read_file`,`write_file`,`edit_file`,`list_dir`,`apply_patch`,`exec`,`process`,`memory_search`,`memory_get`,`memory_append`,`sessions_spawn`,`subagents`];function qi(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:[...Ki.filter(e=>t.has(e)),...n.filter(e=>!Ki.includes(e)).sort()],displayName:t}}function Ji(e){let{ordered:t,displayName:n}=qi(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)??Gi[e];return i?`- ${t}: ${i}`:`- ${t}`}).join(`
|
|
47
48
|
`),``].join(`
|
|
48
|
-
`)}function
|
|
49
|
-
`)}function
|
|
50
|
-
`)}function
|
|
49
|
+
`)}function Yi(){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(`
|
|
50
|
+
`)}function Xi(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(`
|
|
51
|
+
`)}function Zi(e){return e.length===0?``:[`## Skills (mandatory)`,`Before replying: scan <available_skills> <description> entries.`,"- If exactly one skill clearly applies: read its SKILL.md at <location> with `read_file`, then follow it.",`- If multiple could apply: choose the most specific one, then read/follow it.`,`- If none clearly apply: do not read any SKILL.md.`,`Constraints: never read more than one skill up front; only read after selecting.`,`<available_skills>\n${e.map(e=>[` <skill>`,` <name>${e.name}</name>`,` <description>${e.description}</description>`,` <location>${e.location}</location>`,` </skill>`].join(`
|
|
51
52
|
`)).join(`
|
|
52
53
|
`)}\n</available_skills>`,``].join(`
|
|
53
|
-
`)}function
|
|
54
|
-
`)}function
|
|
55
|
-
`)}function
|
|
56
|
-
`)}function
|
|
57
|
-
`)}function
|
|
58
|
-
`)}function
|
|
59
|
-
`)}function
|
|
60
|
-
`)}function
|
|
61
|
-
`)}function
|
|
62
|
-
`)}function
|
|
63
|
-
`)}function
|
|
64
|
-
`)}function
|
|
65
|
-
`):``}function
|
|
66
|
-
`,
|
|
67
|
-
`)}const
|
|
68
|
-
`).trim()}function wa(e){return e instanceof Error?e.message||e.name:typeof e==`string`?e:typeof e==`number`||typeof e==`boolean`||typeof e==`bigint`?`${e}`:ba(e)}function Ta(e,t,n,r){if(r!==void 0)return`error:${Q(wa(r))}`;if(!Z(n))return n===void 0?void 0:Q(n);let i=Z(n.details)?n.details:{},a=Ca(n);if(Sa(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 Ea(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 Da(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 Oa(e,t){return[e,t].toSorted().join(`|`)}function ka(e,t,n,r){let i=va(r);if(!i.enabled)return{stuck:!1};let a=e.toolCallHistory??[],o=ya(t,n),s=Ea(a,t,o),c=s.count,l=Sa(t,n),u=Da(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:${Oa(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 Aa(e,t,n,r,i){let a=va(i);e.toolCallHistory||=[],e.toolCallHistory.push({toolName:t,argsHash:ya(t,n),toolCallId:r,timestamp:Date.now()}),e.toolCallHistory.length>a.historySize&&e.toolCallHistory.shift()}function ja(e,t){let n=va(t.config),r=Ta(t.toolName,t.toolParams,t.result,t.error);if(!r)return;e.toolCallHistory||=[];let i=ya(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 Ma(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 Na(e){return e&&e.trim()||`tool`}function Pa(e,t,n){if(!e.execute)return e;let r=Na(e.name),i=e.execute.bind(e);return{...e,execute:async(e,a,o,s)=>{let c=n(t.sessionId),l=ka(c,r,a,t.config);if(l.stuck){if(l.level===`critical`)throw Error(l.message);Ma(c,l.warningKey??`${l.detector}:${r}`,l.count)&&t.onWarning?.(l)}Aa(c,r,a,e,t.config);try{let n=await i(e,a,o,s);return ja(c,{toolName:r,toolParams:a,toolCallId:e,result:n,config:t.config}),n}catch(n){throw ja(c,{toolName:r,toolParams:a,toolCallId:e,error:n,config:t.config}),n}}}}function Fa(e,t,n){return e.map(e=>Pa(e,t,n))}async function Ia(e){let{session:{runParams:t,sessionId:n,hookRegistry:r,hookContext:i,runContext:a,eventDispatcher:o},runtimeInputs:{contextFiles:s,bootstrapWarnings:c,skills:l,effectivePromptText:u,pluginTools:d},dependencies:{registry:f,spawnFn:p,createModel:m,abortSignal:h}}=e,g=t.channel===`CRON`,_=g?[]:await w(t.dataDir,n),v={model:t.llm.model,api:`openai-completions`},y=await or({dataDir:t.dataDir,sessionId:n}),b=g?{messages:[],priorSummary:void 0,compactionEntry:void 0,stats:{originalCount:0,keptCount:0,estimatedTokens:0,compacted:!1},compactionEvents:[]}:await sr({entries:_,modelInfo:v,contextWindowTokens:t.llm.contextWindow??2e5,llm:{baseUrl:t.llm.baseUrl,apiKey:t.llm.apiKey,model:t.llm.model},historyLimit:t.historyLimit,compactionEnabled:!0,signal:h,hooks:r,hookCtx:i,contextManager:y,dataDir:t.dataDir,sessionId:n});await La({sessionId:n,historyResult:b,runContext:a,eventDispatcher:o,hookRegistry:r,hookContext:i});let x=t.subagentContext?.depth??0,S=[...Vi(t.dataDir,{sessionId:t.subagentContext?.parentSessionId??n,registry:f,parentSessionId:n,depth:x,channel:t.channel,llm:t.llm,inheritedRunParams:{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:y,hitlResume:t.hitlResume,spawnFn:p}),...d],C=S.map(e=>typeof e.name==`string`?e.name.trim():``).filter(Boolean),T={};for(let e of S){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=ca({dataDir:t.dataDir,skills:l,contextFiles:s,toolNames:C,toolSummaries:T,promptMode:x>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:De.hostname()},currentDate:new Date().toISOString().split(`T`)[0],priorConversationSummary:b.priorSummary}),k=await r.dispatch(`before_prompt_build`,{prompt:u},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:u,systemPrompt:O},i,{eventDispatcher:o});let A=Fa(ha(S,r,i,{eventDispatcher:o}),{sessionId:n,config:t.loopDetection},Qe),j=t.llm.model,M=await r.dispatch(`before_model_resolve`,{prompt:u},i,{eventDispatcher:o});for(let e of M)e&&e.modelOverride&&(j=e.modelOverride);let N=m({...t.llm,model:j},n),ee=new Ee({initialState:{systemPrompt:O,model:N,tools:A,messages:[]},getApiKey:e=>t.llm.apiKey});return b.messages.length>0&&ee.replaceMessages(b.messages),{agent:ee,resolvedModelId:j,historyMessages:b.messages,historyResult:b,workspaceDir:a.workspaceDir}}async function La(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 Ra(e){let{agent:t,message:n,sessionId:r,modelId:i,historyMessages:a,eventDispatcher:o,skillUsageTracker:s,hooks:c,hookCtx:l,abortSignal:u,onTurnRecordProduced:d}=e,f=``,p=``,m=``,h=0,g=0,_,v,y=0,b=[],x=new Map,S=t.subscribe(async e=>{if(e.type===`message_update`){let t=e.assistantMessageEvent;if(t.type===`text_delta`&&typeof t.delta==`string`){let n=Wa(`partial`in t?t.partial:void 0)??Wa(`message`in t?t.message:void 0)??Wa(`message`in e?e.message:void 0),i=Ga(t.delta,n,p);i&&(await o.dispatchProgress(r,{type:`stream_text_delta`,text:i}),m+=i),n&&(p=n,m=n)}if(t.type===`done`){let e=t.message;f=Ua(e);let n=Ga(``,f,m||p);n&&(await o.dispatchProgress(r,{type:`stream_text_delta`,text:n}),m+=n),p=f,m=f,e.usage&&(h=e.usage.input,g=e.usage.output)}return}if(e.type===`message_end`){let t=e.message;if(t.usage&&(h=t.usage.input,g=t.usage.output),t.role===`assistant`&&Array.isArray(t.content)){let e=t,n=Ua(e);await c.dispatch(`assistant_message_end`,{sessionId:r,model:i,assistantText:n,assistantMessage:e,hasToolCalls:e.content.some(e=>e.type===`toolCall`),durationMs:y>0?Math.max(0,Date.now()-y):void 0,usage:t.usage?{input:h,output:g,total:h+g}:void 0},l)}return}if(e.type===`turn_end`){let t=e.message;(t.stopReason===`error`||t.stopReason===`aborted`)&&(v=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:Va(e.content.filter(e=>e.type===`text`).map(e=>e.text??``).join(``),r,e.toolCallId,e.toolName)}));b.push({message:t,toolResults:n}),d&&await d(za(t),n.map(Ba));return}if(e.type===`tool_execution_start`){m=``,x.set(e.toolCallId,e.args),s.onToolExecutionStart({toolName:e.toolName,args:e.args}),await o.dispatchProgress(r,{type:`tool_start`,toolCallId:e.toolCallId,name:e.toolName,input:e.args});return}if(e.type===`tool_execution_end`){await s.onToolExecutionEnd({toolName:e.toolName,isError:e.isError});let t=typeof e.result==`string`?e.result:JSON.stringify(e.result),n=x.get(e.toolCallId);x.delete(e.toolCallId),await o.dispatchProgress(r,{type:`tool_end`,toolCallId:e.toolCallId,name:e.toolName,input:n,output:t,isError:e.isError})}});try{if(await c.dispatch(`llm_input`,{sessionId:r,model:i,prompt:typeof n==`string`?n:JSON.stringify(n),historyMessages:a},l),u?.aborted)throw Error(`aborted`);if(y=Date.now(),await t.prompt(n),!_){let e=typeof t.state.error==`string`?t.state.error:void 0,n=v??e;n&&(_=Ka(n),await o.dispatchProgress(r,{type:`error`,message:_}))}}catch(e){_=Ka(e),await o.dispatchProgress(r,{type:`error`,message:_})}finally{S()}let C=b.length>0?b[b.length-1]?.message:void 0;await c.dispatch(`llm_output`,{sessionId:r,model:i,assistantTexts:f?[f]:[],lastAssistant:C,usage:{input:h,output:g,total:h+g}},l);let w=b.length>0?Ua(b[b.length-1].message):``;return d&&b.length===0&&f.trim().length>0&&await d({role:`assistant`,content:f,timestamp:new Date().toISOString()},[]),{text:w||f,inputTokens:h,outputTokens:g,error:_,turnRecords:b}}function za(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 Ba(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 Va(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:Ha(e),originalChars:Number(i[1]??`0`),truncated:!0,createdAt:new Date().toISOString()}}function Ha(e){let t=e.indexOf(`
|
|
54
|
+
`)}function Qi(){return[`## Memory Write`,`When the user asks to remember something or new long-term memory is needed, you must use memory_append. Do not use write_file or edit_file for memory writes.`,``].join(`
|
|
55
|
+
`)}function $i(e){return[`## Memory Recall`,`Before answering anything about prior work, decisions, dates, people, preferences, or todos: run memory_search on MEMORY.md + memory/*.md; then use memory_get to pull only the needed lines. If low confidence after search, say you checked.`,e===`off`?`Citations are disabled: do not include memory file paths or line numbers unless the user explicitly asks.`:`When useful, include memory evidence as Source: <path#line>.`,``].join(`
|
|
56
|
+
`)}function ea(e){let t=`${e.dataDir}/.aimax`,n=`${e.dataDir}/workspace`,r=e.sandboxInfo?.hostWorkspaceDir?.trim()||n,i=e.sandboxInfo?.containerWorkspaceDir?.trim(),a=e.sandboxInfo?.enabled&&i?`For file tools, paths resolve against the cloud workspace mount ${r}. For exec commands, use paths under ${i} (or relative paths from there). Prefer relative paths whenever possible.`:`This cloud workspace is mounted user storage. Prefer relative paths to keep file tools and shell commands aligned.`;return[`## Workspace`,`Your cloud working directory is: ${r}`,a,`User identity, memory, and agent state live under ${t}, not inside the cloud workspace.`,`Files such as AGENTS.md, SOUL.md, TOOLS.md, IDENTITY.md, USER.md, HEARTBEAT.md, MEMORY.md, and the memory/ directory belong under ${t}.`,`Only create or update those files at their real .aimax paths. Never create cloud workspace copies like ${r}/AGENTS.md or ${r}/MEMORY.md unless the user explicitly asks for separate cloud documents.`,``].join(`
|
|
57
|
+
`)}function ta(e){if(!e?.enabled)return``;let t=[`## Sandbox`,`You are running in a containerized cloud CLI runtime.`];return e.containerWorkspaceDir?.trim()&&t.push(`Container workdir: ${e.containerWorkspaceDir.trim()}`),e.hostWorkspaceDir?.trim()&&t.push(`Host-mounted workspace: ${e.hostWorkspaceDir.trim()}`),t.push(``),t.join(`
|
|
58
|
+
`)}function na(e){let t=[];if(e.timezone&&t.push(`Time zone: ${e.timezone}`),e.currentDate){t.push(`Current date: ${e.currentDate}`);let n=ra(e.currentDate);n&&t.push(`Day of week: ${n}`)}return t.length===0?``:[`## Current Date & Time`,...t,``].join(`
|
|
59
|
+
`)}function ra(e){let t=/^(\d{4})-(\d{2})-(\d{2})$/.exec(e.trim());if(!t)return null;let n=Number(t[1]),r=Number(t[2]),i=Number(t[3]),a=new Date(Date.UTC(n,r-1,i));return Number.isNaN(a.getTime())||a.getUTCFullYear()!==n||a.getUTCMonth()!==r-1||a.getUTCDate()!==i?null:[`Sunday`,`Monday`,`Tuesday`,`Wednesday`,`Thursday`,`Friday`,`Saturday`][a.getUTCDay()]}function ia(e){if(e.isMinimal||!e.enabled)return``;let t=(e.channels??[]).map(e=>e.trim()).filter(Boolean);return[`## Messaging`,`Reply in the current session for user-visible responses.`,`Use subagent tools for delegated long-running tasks and report concise progress back in this session.`,`Do not use shell/network commands to bypass the platform messaging pipeline.`,t.length>0?`Configured channels: ${t.join(` | `)}`:``,``].filter(Boolean).join(`
|
|
60
|
+
`)}function aa(e){if(e.isMinimal)return``;let t=e.docs,n=[`## Documentation`,t?.localPath?`Cloud docs mount: ${t.localPath}`:``,t?.webUrl?`Docs mirror: ${t.webUrl}`:``,t?.sourceUrl?`Source: ${t.sourceUrl}`:``,`For AiMax behavior, configuration, and architecture questions, consult documentation first.`,``].filter(Boolean);return n.length<=2?``:n.join(`
|
|
61
|
+
`)}function oa(e){if(!e)return``;let t=[e.hostname?`host=${e.hostname}`:``,e.os?`os=${e.os}`:``,e.node?`node=${e.node}`:``,e.model?`model=${e.model}`:``].filter(Boolean);return t.length===0?``:[`## Runtime`,`Runtime: ${t.join(` | `)}`,``].join(`
|
|
62
|
+
`)}function sa(e){return e.isMinimal?``:[`## Silent Replies`,`Do not send empty or filler replies.`,`If a tool already delivered the user-visible output, keep your final reply minimal and avoid duplication.`,``].join(`
|
|
63
|
+
`)}function ca(e){return e.isMinimal?``:[`## Heartbeats`,`Heartbeat prompt: ${e.heartbeatPrompt?.trim()||`Read HEARTBEAT.md if it exists (cloud workspace context). Follow it strictly. Do not infer or repeat old tasks from prior chats. If nothing needs attention, reply HEARTBEAT_OK.`}`,`If a user message matches the heartbeat prompt and nothing needs attention, reply exactly: HEARTBEAT_OK`,`If something needs attention, do NOT include "HEARTBEAT_OK"; respond with the alert text instead.`,``].join(`
|
|
64
|
+
`)}function la(e){let t=e.contextFiles,n=(e.bootstrapWarnings??[]).map(e=>e.trim()).filter(Boolean);if(t.length===0&&n.length===0)return``;let r=t.some(e=>(e.path.split(`/`).pop()?.toLowerCase()??``)===`soul.md`),i=[`# Project Context`,``];if(n.length>0){i.push(`⚠ Bootstrap truncation warning:`);for(let e of n)i.push(`- ${e}`);i.push(``)}t.length>0&&(i.push(`The following project context files have been loaded:`),i.push(`These are source-of-truth cloud files at their shown paths. If you update them, use the exact path shown in the heading, especially for files under .aimax.`)),r&&i.push(`If SOUL.md is present, embody its persona and tone. Avoid stiff, generic replies; follow its guidance unless higher-priority instructions override it.`),i.push(``);for(let e of t)i.push(`## ${e.path}`,``,e.content,``);return i.join(`
|
|
65
|
+
`)}function ua(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(`
|
|
66
|
+
`):``}function da(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:[...Ki],i=e.skills??[],a=e.contextFiles??[];return[`You are a personal assistant running inside AiMax.
|
|
67
|
+
`,Ji({toolNames:r,toolSummaries:e.toolSummaries}),Xi(n),Yi(),Zi(i),Qi(),$i(e.memoryCitationsMode??`off`),ea({dataDir:e.dataDir,sandboxInfo:e.sandboxInfo}),ta(e.sandboxInfo),na({currentDate:e.currentDate,timezone:e.timezone}),ia({isMinimal:n,enabled:e.messaging?.enabled,channels:e.messaging?.channels}),aa({isMinimal:n,docs:e.docs}),sa({isMinimal:n}),ca({isMinimal:n,heartbeatPrompt:e.heartbeatPrompt}),oa(e.runtimeInfo),la({contextFiles:a,bootstrapWarnings:e.bootstrapWarnings}),ua(e.priorConversationSummary)].filter(Boolean).join(`
|
|
68
|
+
`)}const fa=new ke;async function pa(e,t){return await fa.run(e,t)}function ma(e){return{async emit(t){let n=fa.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 ha=Symbol(`pluginToolOwner`);var ga=class{tools=[];register(e,t,n){let r=t.name,i=n?.names??(n?.name?[n.name]:r?[r]:[]);Object.defineProperty(t,ha,{value:e,enumerable:!1,configurable:!1,writable:!1}),this.tools.push({pluginId:e,tool:t,optional:n?.optional??!1,names:i})}list(){return[...this.tools]}namesForPlugin(e){return this.tools.filter(t=>t.pluginId===e).flatMap(e=>e.names)}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)}};function _a(e){return e[ha]}function va(e,t,n,r){return e.map(e=>{let i=e,a=e.name??`unknown`,o=_a(e);return{...i,async execute(e,s,c,l){let u=Date.now(),d=s??{},f=!1,p,m=async e=>o?await pa({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){throw await t.dispatch(`after_tool_call`,{toolCallId:e,toolName:a,params:d,error:String(i),durationMs:Date.now()-u},n,r),i}}}})}var ya=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 pa({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 ba(e,t){return typeof e!=`number`||!Number.isInteger(e)||e<=0?t:e}function xa(e){let t=ba(e?.warningThreshold,X.warningThreshold),n=ba(e?.criticalThreshold,X.criticalThreshold),r=ba(e?.globalCircuitBreakerThreshold,X.globalCircuitBreakerThreshold);return n<=t&&(n=t+1),r<=n&&(r=n+1),{enabled:e?.enabled??X.enabled,historySize:ba(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 Sa(e,t){return`${e}:${Q(t)}`}function Ca(e){if(typeof e!=`object`||!e)return JSON.stringify(e);if(Array.isArray(e))return`[${e.map(Ca).join(`,`)}]`;let t=e;return`{${Object.keys(t).toSorted().map(e=>`${JSON.stringify(e)}:${Ca(t[e])}`).join(`,`)}}`}function wa(e){try{return Ca(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=wa(e);return Te(`sha256`).update(t).digest(`hex`)}function Ta(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 Ea(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(`
|
|
69
|
+
`).trim()}function Da(e){return e instanceof Error?e.message||e.name:typeof e==`string`?e:typeof e==`number`||typeof e==`boolean`||typeof e==`bigint`?`${e}`:Ca(e)}function Oa(e,t,n,r){if(r!==void 0)return`error:${Q(Da(r))}`;if(!Z(n))return n===void 0?void 0:Q(n);let i=Z(n.details)?n.details:{},a=Ea(n);if(Ta(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 ka(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 Aa(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 ja(e,t){return[e,t].toSorted().join(`|`)}function Ma(e,t,n,r){let i=xa(r);if(!i.enabled)return{stuck:!1};let a=e.toolCallHistory??[],o=Sa(t,n),s=ka(a,t,o),c=s.count,l=Ta(t,n),u=Aa(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:${ja(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 Na(e,t,n,r,i){let a=xa(i);e.toolCallHistory||=[],e.toolCallHistory.push({toolName:t,argsHash:Sa(t,n),toolCallId:r,timestamp:Date.now()}),e.toolCallHistory.length>a.historySize&&e.toolCallHistory.shift()}function Pa(e,t){let n=xa(t.config),r=Oa(t.toolName,t.toolParams,t.result,t.error);if(!r)return;e.toolCallHistory||=[];let i=Sa(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 Fa(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 Ia(e){return e&&e.trim()||`tool`}function La(e,t,n){if(!e.execute)return e;let r=Ia(e.name),i=e.execute.bind(e);return{...e,execute:async(e,a,o,s)=>{let c=n(t.sessionId),l=Ma(c,r,a,t.config);if(l.stuck){if(l.level===`critical`)throw Error(l.message);Fa(c,l.warningKey??`${l.detector}:${r}`,l.count)&&t.onWarning?.(l)}Na(c,r,a,e,t.config);try{let n=await i(e,a,o,s);return Pa(c,{toolName:r,toolParams:a,toolCallId:e,result:n,config:t.config}),n}catch(n){throw Pa(c,{toolName:r,toolParams:a,toolCallId:e,error:n,config:t.config}),n}}}}function Ra(e,t,n){return e.map(e=>La(e,t,n))}async function za(e){let{session:{runParams:t,sessionId:n,hookRegistry:r,hookContext:i,runContext:a,eventDispatcher:o},runtimeInputs:{contextFiles:s,bootstrapWarnings:c,skills:l,effectivePromptText:u,pluginTools:d},dependencies:{registry:f,spawnFn:p,createModel:m,abortSignal:h}}=e,g=t.channel===`CRON`,_=g?[]:await w(t.dataDir,n),v={model:t.llm.model,api:`openai-completions`},y=await lr({dataDir:t.dataDir,sessionId:n}),b=g?{messages:[],priorSummary:void 0,compactionEntry:void 0,stats:{originalCount:0,keptCount:0,estimatedTokens:0,compacted:!1},compactionEvents:[]}:await ur({entries:_,modelInfo:v,contextWindowTokens:t.llm.contextWindow??2e5,llm:{baseUrl:t.llm.baseUrl,apiKey:t.llm.apiKey,model:t.llm.model},historyLimit:t.historyLimit,compactionEnabled:!0,signal:h,hooks:r,hookCtx:i,contextManager:y,dataDir:t.dataDir,sessionId:n});await Ba({sessionId:n,historyResult:b,runContext:a,eventDispatcher:o,hookRegistry:r,hookContext:i});let x=t.subagentContext?.depth??0,S=[...Wi(t.dataDir,{sessionId:t.subagentContext?.parentSessionId??n,registry:f,parentSessionId:n,depth:x,channel:t.channel,llm:t.llm,inheritedRunParams:{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:y,hitlResume:t.hitlResume,spawnFn:p}),...d],C=S.map(e=>typeof e.name==`string`?e.name.trim():``).filter(Boolean),T={};for(let e of S){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=da({dataDir:t.dataDir,skills:l,contextFiles:s,toolNames:C,toolSummaries:T,promptMode:x>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:De.hostname()},currentDate:new Date().toISOString().split(`T`)[0],priorConversationSummary:b.priorSummary}),k=await r.dispatch(`before_prompt_build`,{prompt:u},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:u,systemPrompt:O},i,{eventDispatcher:o});let A=Ra(va(S,r,i,{eventDispatcher:o}),{sessionId:n,config:t.loopDetection},Qe),j=t.llm.model,M=await r.dispatch(`before_model_resolve`,{prompt:u},i,{eventDispatcher:o});for(let e of M)e&&e.modelOverride&&(j=e.modelOverride);let N=m({...t.llm,model:j},n),ee=new Ee({initialState:{systemPrompt:O,model:N,tools:A,messages:[]},getApiKey:e=>t.llm.apiKey});return b.messages.length>0&&ee.replaceMessages(b.messages),{agent:ee,resolvedModelId:j,historyMessages:b.messages,historyResult:b,workspaceDir:a.workspaceDir}}async function Ba(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 Va(e){let{agent:t,message:n,sessionId:r,modelId:i,historyMessages:a,eventDispatcher:o,skillUsageTracker:s,hooks:c,hookCtx:l,abortSignal:u,onTurnRecordProduced:d}=e,f=``,p=``,m=``,h=0,g=0,_,v,y=0,b=[],x=new Map,S=t.subscribe(async e=>{if(e.type===`message_update`){let t=e.assistantMessageEvent;if(t.type===`text_delta`&&typeof t.delta==`string`){let n=qa(`partial`in t?t.partial:void 0)??qa(`message`in t?t.message:void 0)??qa(`message`in e?e.message:void 0),i=Ja(t.delta,n,p);i&&(await o.dispatchProgress(r,{type:`stream_text_delta`,text:i}),m+=i),n&&(p=n,m=n)}if(t.type===`done`){let e=t.message;f=Ka(e);let n=Ja(``,f,m||p);n&&(await o.dispatchProgress(r,{type:`stream_text_delta`,text:n}),m+=n),p=f,m=f,e.usage&&(h=e.usage.input,g=e.usage.output)}return}if(e.type===`message_end`){let t=e.message;if(t.usage&&(h=t.usage.input,g=t.usage.output),t.role===`assistant`&&Array.isArray(t.content)){let e=t,n=Ka(e);await c.dispatch(`assistant_message_end`,{sessionId:r,model:i,assistantText:n,assistantMessage:e,hasToolCalls:e.content.some(e=>e.type===`toolCall`),durationMs:y>0?Math.max(0,Date.now()-y):void 0,usage:t.usage?{input:h,output:g,total:h+g}:void 0},l)}return}if(e.type===`turn_end`){let t=e.message;(t.stopReason===`error`||t.stopReason===`aborted`)&&(v=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:Wa(e.content.filter(e=>e.type===`text`).map(e=>e.text??``).join(``),r,e.toolCallId,e.toolName)}));b.push({message:t,toolResults:n}),d&&await d(Ha(t),n.map(Ua));return}if(e.type===`tool_execution_start`){m=``,x.set(e.toolCallId,e.args),s.onToolExecutionStart({toolName:e.toolName,args:e.args}),await o.dispatchProgress(r,{type:`tool_start`,toolCallId:e.toolCallId,name:e.toolName,input:e.args});return}if(e.type===`tool_execution_end`){await s.onToolExecutionEnd({toolName:e.toolName,isError:e.isError});let t=typeof e.result==`string`?e.result:JSON.stringify(e.result),n=x.get(e.toolCallId);x.delete(e.toolCallId),await o.dispatchProgress(r,{type:`tool_end`,toolCallId:e.toolCallId,name:e.toolName,input:n,output:t,isError:e.isError})}});try{if(await c.dispatch(`llm_input`,{sessionId:r,model:i,prompt:typeof n==`string`?n:JSON.stringify(n),historyMessages:a},l),u?.aborted)throw Error(`aborted`);if(y=Date.now(),await t.prompt(n),!_){let e=typeof t.state.error==`string`?t.state.error:void 0,n=v??e;n&&(_=Ya(n),await o.dispatchProgress(r,{type:`error`,message:_}))}}catch(e){_=Ya(e),await o.dispatchProgress(r,{type:`error`,message:_})}finally{S()}let C=b.length>0?b[b.length-1]?.message:void 0;await c.dispatch(`llm_output`,{sessionId:r,model:i,assistantTexts:f?[f]:[],lastAssistant:C,usage:{input:h,output:g,total:h+g}},l);let w=b.length>0?Ka(b[b.length-1].message):``;return d&&b.length===0&&f.trim().length>0&&await d({role:`assistant`,content:f,timestamp:new Date().toISOString()},[]),{text:w||f,inputTokens:h,outputTokens:g,error:_,turnRecords:b}}function Ha(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 Ua(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 Wa(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:Ga(e),originalChars:Number(i[1]??`0`),truncated:!0,createdAt:new Date().toISOString()}}function Ga(e){let t=e.indexOf(`
|
|
69
70
|
Preview:
|
|
70
|
-
`);return t===-1?``:e.slice(t+10).replace(/\n\.\.\.$/,``)}function
|
|
71
|
+
`);return t===-1?``:e.slice(t+10).replace(/\n\.\.\.$/,``)}function Ka(e){return e.content.filter(e=>e.type===`text`).map(e=>e.text).join(``)}function qa(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 Ja(e,t,n){return t?n?t===n?``:t.startsWith(n)?t.slice(n.length):t:t:e}function Ya(e){let t=Xa(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 Xa(e){if(e instanceof V)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 Za(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=Qa(e);await u({role:`user`,content:g,timestamp:new Date().toISOString()});let _=await Va({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 Qa(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(`
|
|
71
72
|
|
|
72
73
|
---
|
|
73
74
|
|
|
74
|
-
`)}`}function Xa(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Za(e){return Array.isArray(e)?e.map(e=>typeof e==`string`?e.trim():``).filter(Boolean):[]}function Qa(e){let t=e.trim();return t===`~`?De.homedir():t.startsWith(`~/`)||t.startsWith(`~\\`)?F.join(De.homedir(),t.slice(2)):F.resolve(t)}const $a=new Ae({allErrors:!0,strict:!1}),eo=new Map;function to(e,t){let n=eo.get(t);if(n)return n;let r=$a.compile(e);return eo.set(t,r),r}function no(e){let t=e.cacheKey??JSON.stringify(e.schema),n=to(e.schema,t);return n(e.value)?{ok:!0}:{ok:!1,errors:(n.errors??[]).map(e=>({path:e.instancePath||`/`,message:e.message??`invalid`}))}}function ro(e){let t=Za(e?.allow),n=Za(e?.deny),r=Za(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 io(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=no({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 ao(e){try{return z.realpathSync(e)}catch{return null}}function oo(e){try{return z.statSync(e)}catch{return null}}function so(e,t){let n=F.relative(e,t);return n===``?!0:n.startsWith(`..`)?!1:!F.isAbsolute(n)}function co(e){return`0o${e.toString(8).padStart(3,`0`)}`}const lo=new Set([`.ts`,`.js`,`.mts`,`.cts`,`.mjs`,`.cjs`]),uo=[`index.ts`,`index.js`,`index.mts`,`index.cts`,`index.mjs`,`index.cjs`];function fo(e){let t=F.join(e,`package.json`);if(z.existsSync(t))try{let e=JSON.parse(z.readFileSync(t,`utf-8`));return Xa(e)?e:void 0}catch{return}}function po(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 mo(e){return e===void 0?process.platform===`win32`||typeof process.getuid!=`function`?null:process.getuid():e}function ho(e){let t=ao(e.source),n=ao(e.rootDir);return!t||!n||so(n,t)?null:{reason:`source_escapes_root`,sourcePath:e.source,rootPath:e.rootDir,targetPath:e.source,sourceRealPath:t,rootRealPath:n}}function go(e){if(process.platform===`win32`)return null;let t=[e.rootDir,e.source],n=new Set;for(let r of t){let t=F.resolve(r);if(n.has(t))continue;n.add(t);let i=oo(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 _o(e){return ho({source:e.source,rootDir:e.rootDir})||go({source:e.source,rootDir:e.rootDir,origin:e.origin,uid:mo(e.ownershipUid)})}function vo(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=${co(e.modeBits??0)})`:`blocked plugin candidate: suspicious ownership (${e.targetPath}, uid=${e.foundUid}, expected uid=${e.expectedUid} or root)`}function yo(e){let t=_o({source:e.source,rootDir:e.rootDir,origin:e.origin,ownershipUid:e.ownershipUid});return t?(e.diagnostics.push({level:`warn`,message:vo(t),source:e.source}),!0):!1}function bo(e){return F.basename(e,F.extname(e))}function xo(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 So(e){for(let t of uo){let n=F.join(e,t);if(z.existsSync(n))return n}return null}function Co(e){let t;try{t=z.readdirSync(e.rootDir,{withFileTypes:!0})}catch{return}for(let n of t){let t=F.join(e.rootDir,n.name);if(n.isFile()){if(!lo.has(F.extname(n.name)))continue;let r=F.dirname(t);if(yo({source:t,rootDir:r,origin:e.origin,diagnostics:e.diagnostics,ownershipUid:e.ownershipUid}))continue;e.candidates.push(xo({idHint:bo(t),source:t,rootDir:r,origin:e.origin,workspaceDir:e.workspaceDir}));continue}if(!n.isDirectory())continue;let r=fo(t),i=po(r);if(i.status===`ok`){for(let n of i.entries){let i=F.resolve(t,n);if(!so(t,i)){e.diagnostics.push({level:`warn`,message:`blocked plugin candidate: package entry escapes package root (${n})`,source:i});continue}if(!z.existsSync(i)){e.diagnostics.push({level:`warn`,message:`plugin entry missing: ${i}`,source:i});continue}if(!lo.has(F.extname(i))){e.diagnostics.push({level:`warn`,message:`plugin entry not a supported extension: ${i}`,source:i});continue}if(yo({source:i,rootDir:t,origin:e.origin,diagnostics:e.diagnostics,ownershipUid:e.ownershipUid}))continue;let a=r?.name?.trim(),o=a?`${a}/${bo(i)}`:bo(i);e.candidates.push(xo({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=So(t);a&&(yo({source:a,rootDir:t,origin:e.origin,diagnostics:e.diagnostics,ownershipUid:e.ownershipUid})||e.candidates.push(xo({idHint:F.basename(t),source:a,rootDir:t,origin:e.origin,workspaceDir:e.workspaceDir})))}}function wo(e){return e?e.map(Qa):[]}function To(){return F.join(Qa(`~`),`.aimax`,`extensions`)}function Eo(e){return F.join(e,`.aimax`,`extensions`)}function Do(e){return F.join(e,`.aimax`,`extensions`)}function Oo(e={}){let t=[],n=[],r=wo(e.extraPaths);for(let i of r){if(!z.existsSync(i)){n.push({level:`warn`,message:`plugin path not found: ${i}`,source:i});continue}let r=oo(i);if(!r){n.push({level:`warn`,message:`plugin path not readable: ${i}`,source:i});continue}if(r.isFile()){if(!lo.has(F.extname(i))){n.push({level:`warn`,message:`plugin file has unsupported extension: ${i}`,source:i});continue}let r=F.dirname(i);if(yo({source:i,rootDir:r,origin:`config`,diagnostics:n,ownershipUid:e.ownershipUid}))continue;t.push(xo({idHint:bo(i),source:i,rootDir:r,origin:`config`,workspaceDir:e.workspaceDir}));continue}r.isDirectory()&&Co({rootDir:i,origin:`config`,workspaceDir:e.workspaceDir,diagnostics:n,candidates:t,ownershipUid:e.ownershipUid})}return e.dataDir?Co({rootDir:Eo(e.dataDir),origin:`workspace`,workspaceDir:e.workspaceDir,diagnostics:n,candidates:t,ownershipUid:e.ownershipUid}):e.workspaceDir&&Co({rootDir:Do(e.workspaceDir),origin:`workspace`,workspaceDir:e.workspaceDir,diagnostics:n,candidates:t,ownershipUid:e.ownershipUid}),Co({rootDir:To(),origin:`global`,workspaceDir:e.workspaceDir,diagnostics:n,candidates:t,ownershipUid:e.ownershipUid}),e.bundledDir&&Co({rootDir:e.bundledDir,origin:`bundled`,workspaceDir:e.workspaceDir,diagnostics:n,candidates:t,ownershipUid:e.ownershipUid}),{candidates:t,diagnostics:n}}function ko(e){let t=e.rejectHardlinks??!0,n=ao(e.rootPath),r=ao(e.absolutePath);if(!n||!r)return{ok:!1,reason:`path`};if(!so(n,r))return{ok:!1,reason:`unsafe`};let i;try{i=z.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:z.openSync(r,`r`)}}catch{return{ok:!1,reason:`path`}}}const Ao=`aimax.plugin.json`,jo=[Ao];function Mo(e){for(let t of jo){let n=F.join(e,t);if(z.existsSync(n))return n}return F.join(e,Ao)}function No(e,t=!0){let n=Mo(e),r=ko({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(z.readFileSync(r.fd,`utf-8`))}catch(e){return{ok:!1,error:`failed to parse plugin manifest: ${String(e)}`,manifestPath:n}}finally{z.closeSync(r.fd)}if(!Xa(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=Xa(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=Za(i.skills),f;return Xa(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 Po(e){let t=new Map,n=[];for(let r of e){let e=No(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 Fo=function(e){return e.INFO=`INFO`,e.WARN=`WARN`,e.ERROR=`ERROR`,e}({});function Io(){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 Lo(e,t,n,r){process.stderr.write(`[${Io()}] [${e}] [plugin:${t}][logger:${n}] ${r}\n`)}function Ro(e){return{version:`0.1.0`,logging:{getLogger:t=>({info:n=>Lo(Fo.INFO,e.pluginId,t,n),warn:n=>Lo(Fo.WARN,e.pluginId,t,n),error:n=>Lo(Fo.ERROR,e.pluginId,t,n)})}}}function zo(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 Bo(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 Vo(e){let t=[...e.registry.diagnostics],n=new pa,r=new ga,i=[],o=[],s=e.runtime?.llm?rt({baseUrl:e.runtime.llm.baseUrl,apiKey:e.runtime.llm.apiKey,defaultModel:e.runtime.llm.model,hooks:r,hookCtx:e.runtime.hookCtx}):void 0,c=Ho(e.runtime?.llmAllowlist),l=je(import.meta.url,{interopDefault:!0,requireCache:!1});for(let u of e.registry.manifests.values()){let d=zo({config:e.plugins,pluginId:u.id,origin:u.origin,kind:u.manifest.kind}),f=Bo({id:u.id,source:u.source,origin:u.origin,enabled:d,configSchema:!0,skills:u.manifest.skills??[]});if(!d){o.push(f);continue}let p;try{p=l(u.source)}catch(e){f.status=`error`,f.error=String(e),t.push({level:`error`,message:`failed to load plugin ${u.id}: ${String(e)}`,pluginId:u.id,source:u.source}),o.push(f);continue}let m=p&&typeof p==`object`&&`default`in p?p.default:p,h=typeof m==`function`?m:m&&typeof m==`object`&&typeof m.register==`function`?m.register:void 0;if(!h){f.status=`error`,f.error=`plugin module does not export a register function`,t.push({level:`error`,message:`plugin ${u.id} has no register function`,pluginId:u.id,source:u.source}),o.push(f);continue}let g=Ro({pluginId:u.id}),_=e.plugins.entries[u.id]?.config,v={id:u.id,source:u.source,rootDir:u.rootDir,config:_,runtime:g,llm:{chat:async e=>{if(!s)throw Error(`LLM client is not configured`);if(!Uo(u.id,n,c))throw Error(`Plugin ${u.id} is not allowed to use LLM`);return s.chat(e)}},registerTool:(e,t)=>{n.register(u.id,e,t),f.toolCount+=1},registerEmbeddingProvider:e=>{if(u.manifest.kind!==`memory`)throw Error(`Plugin ${u.id} is not allowed to register embedding providers`);a({pluginId:u.id,id:e.id,create:e.create,config:_,rootDir:u.rootDir,source:u.source})},registerMemoryProvider:e=>{if(u.manifest.kind!==`memory`)throw Error(`Plugin ${u.id} is not allowed to register memory providers`);E({pluginId:u.id,id:e.id,create:e.create,config:_,rootDir:u.rootDir,source:u.source})},registerHook:(e,t,n)=>{r.register({pluginId:u.id,hookName:e,handler:t,priority:n?.priority,source:u.source}),f.hookCount+=1},registerSkillDir:e=>{let t=F.isAbsolute(e)?e:F.resolve(u.rootDir,e);i.push(t)},createProgressEmitter:()=>da(u.id)};try{h(v)}catch(e){f.status=`error`,f.error=String(e),t.push({level:`error`,message:`plugin ${u.id} registration failed: ${String(e)}`,pluginId:u.id,source:u.source})}if(u.manifest.skills&&u.manifest.skills.length>0)for(let e of u.manifest.skills){let t=F.isAbsolute(e)?e:F.resolve(u.rootDir,e);i.push(t)}o.push(f)}return{plugins:o,diagnostics:t,tools:n,hooks:r,skills:i}}function Ho(e){return(e??[]).map(e=>e.trim()).filter(Boolean)}function Uo(e,t,n){return n.length===0?!1:n.includes(e)?!0:t.namesForPlugin(e).some(e=>n.includes(e))}function Wo(e={}){let t=ro(e.config),n=Oo({dataDir:e.dataDir,workspaceDir:e.workspaceDir,extraPaths:t.loadPaths,bundledDir:e.bundledDir,ownershipUid:e.ownershipUid}),r=Po(n.candidates),i=io({config:t,registry:r}),a=Vo({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 Go(e){let{runParams:t,hookContext:n,sessionId:r,eventDispatcher:i}=e,a=e=>{i.dispatchDiagnostic(r,e).catch(()=>void 0)},o=t.plugins?Wo({...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 ga,pluginSkillDirs:o?.registry.skills??[],pluginTools:o?.registry.tools.resolveEnabled(t.plugins?.toolAllowlist)??[],memoryPluginId:t.memory?.pluginId??o?.normalizedConfig.slots?.memory}}async function Ko(e){let{runParams:t,requestedSessionId:n,eventDispatcher:r}=e,i=F.join(t.dataDir,`workspace`),a=n,o=!a;a?await l(t.dataDir,a):a=await c(t.dataDir,t.channel);let s={sessionId:a,workspaceDir:i,channel:t.channel},u=Go({runParams:t,hookContext:s,sessionId:a,eventDispatcher:r}),d=u.hookRegistry,f=await Rt({runParams:t,sessionId:a,hookContext:s,memoryProviderId:t.memory?.providerId,memoryPluginId:u.memoryPluginId,eventDispatcher:r,hookRegistry:d});return{sessionId:a,isNewSession:o,workspaceDir:i,hookContext:s,hookRegistry:d,pluginContext:u,runContext:f,start:e=>Ht({sessionId:a,runParams:t,hookRegistry:d,hookContext:s,eventDispatcher:r,...e})}}function qo(e){return e===null||typeof e==`string`||typeof e==`number`||typeof e==`boolean`?e:JSON.stringify(e)??String(e)}function Jo(e){if(!(e instanceof Error))return{errorValue:qo(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]=qo(n[e]));return t}async function Yo(e){await e.dispatcher.dispatchDiagnostic(e.sessionId,{level:`error`,scope:e.scope,phase:e.phase,message:e.message,details:{...e.details,...Jo(e.error)}})}function Xo(e,t){return F.join(n(e,t),`pending-hitl.json`)}function Zo(e,t){return F.join(n(e,t),`hitl-history.jsonl`)}async function Qo(e,t,r){let i=n(e,t);await P.mkdir(i,{recursive:!0});let a=Xo(e,t);await P.writeFile(a,JSON.stringify(r,null,2),`utf-8`)}async function $o(e,t,r){let i=n(e,t);await P.mkdir(i,{recursive:!0});let a=Zo(e,t),o=JSON.stringify(r)+`
|
|
75
|
-
`;await P.appendFile(a,o,`utf-8`)}async function
|
|
76
|
-
`)){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
|
|
75
|
+
`)}`}function $a(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function eo(e){return Array.isArray(e)?e.map(e=>typeof e==`string`?e.trim():``).filter(Boolean):[]}function to(e){let t=e.trim();return t===`~`?De.homedir():t.startsWith(`~/`)||t.startsWith(`~\\`)?F.join(De.homedir(),t.slice(2)):F.resolve(t)}const no=new Ae({allErrors:!0,strict:!1}),ro=new Map;function io(e,t){let n=ro.get(t);if(n)return n;let r=no.compile(e);return ro.set(t,r),r}function ao(e){let t=e.cacheKey??JSON.stringify(e.schema),n=io(e.schema,t);return n(e.value)?{ok:!0}:{ok:!1,errors:(n.errors??[]).map(e=>({path:e.instancePath||`/`,message:e.message??`invalid`}))}}function oo(e){let t=eo(e?.allow),n=eo(e?.deny),r=eo(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 so(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=ao({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 co(e){try{return z.realpathSync(e)}catch{return null}}function lo(e){try{return z.statSync(e)}catch{return null}}function uo(e,t){let n=F.relative(e,t);return n===``?!0:n.startsWith(`..`)?!1:!F.isAbsolute(n)}function fo(e){return`0o${e.toString(8).padStart(3,`0`)}`}const po=new Set([`.ts`,`.js`,`.mts`,`.cts`,`.mjs`,`.cjs`]),mo=[`index.ts`,`index.js`,`index.mts`,`index.cts`,`index.mjs`,`index.cjs`];function ho(e){let t=F.join(e,`package.json`);if(z.existsSync(t))try{let e=JSON.parse(z.readFileSync(t,`utf-8`));return $a(e)?e:void 0}catch{return}}function go(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 _o(e){return e===void 0?process.platform===`win32`||typeof process.getuid!=`function`?null:process.getuid():e}function vo(e){let t=co(e.source),n=co(e.rootDir);return!t||!n||uo(n,t)?null:{reason:`source_escapes_root`,sourcePath:e.source,rootPath:e.rootDir,targetPath:e.source,sourceRealPath:t,rootRealPath:n}}function yo(e){if(process.platform===`win32`)return null;let t=[e.rootDir,e.source],n=new Set;for(let r of t){let t=F.resolve(r);if(n.has(t))continue;n.add(t);let i=lo(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 bo(e){return vo({source:e.source,rootDir:e.rootDir})||yo({source:e.source,rootDir:e.rootDir,origin:e.origin,uid:_o(e.ownershipUid)})}function xo(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=${fo(e.modeBits??0)})`:`blocked plugin candidate: suspicious ownership (${e.targetPath}, uid=${e.foundUid}, expected uid=${e.expectedUid} or root)`}function So(e){let t=bo({source:e.source,rootDir:e.rootDir,origin:e.origin,ownershipUid:e.ownershipUid});return t?(e.diagnostics.push({level:`warn`,message:xo(t),source:e.source}),!0):!1}function Co(e){return F.basename(e,F.extname(e))}function wo(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 To(e){for(let t of mo){let n=F.join(e,t);if(z.existsSync(n))return n}return null}function Eo(e){let t;try{t=z.readdirSync(e.rootDir,{withFileTypes:!0})}catch{return}for(let n of t){let t=F.join(e.rootDir,n.name);if(n.isFile()){if(!po.has(F.extname(n.name)))continue;let r=F.dirname(t);if(So({source:t,rootDir:r,origin:e.origin,diagnostics:e.diagnostics,ownershipUid:e.ownershipUid}))continue;e.candidates.push(wo({idHint:Co(t),source:t,rootDir:r,origin:e.origin,workspaceDir:e.workspaceDir}));continue}if(!n.isDirectory())continue;let r=ho(t),i=go(r);if(i.status===`ok`){for(let n of i.entries){let i=F.resolve(t,n);if(!uo(t,i)){e.diagnostics.push({level:`warn`,message:`blocked plugin candidate: package entry escapes package root (${n})`,source:i});continue}if(!z.existsSync(i)){e.diagnostics.push({level:`warn`,message:`plugin entry missing: ${i}`,source:i});continue}if(!po.has(F.extname(i))){e.diagnostics.push({level:`warn`,message:`plugin entry not a supported extension: ${i}`,source:i});continue}if(So({source:i,rootDir:t,origin:e.origin,diagnostics:e.diagnostics,ownershipUid:e.ownershipUid}))continue;let a=r?.name?.trim(),o=a?`${a}/${Co(i)}`:Co(i);e.candidates.push(wo({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=To(t);a&&(So({source:a,rootDir:t,origin:e.origin,diagnostics:e.diagnostics,ownershipUid:e.ownershipUid})||e.candidates.push(wo({idHint:F.basename(t),source:a,rootDir:t,origin:e.origin,workspaceDir:e.workspaceDir})))}}function Do(e){return e?e.map(to):[]}function Oo(){return F.join(to(`~`),`.aimax`,`extensions`)}function ko(e){return F.join(e,`.aimax`,`extensions`)}function Ao(e){return F.join(e,`.aimax`,`extensions`)}function jo(e={}){let t=[],n=[],r=Do(e.extraPaths);for(let i of r){if(!z.existsSync(i)){n.push({level:`warn`,message:`plugin path not found: ${i}`,source:i});continue}let r=lo(i);if(!r){n.push({level:`warn`,message:`plugin path not readable: ${i}`,source:i});continue}if(r.isFile()){if(!po.has(F.extname(i))){n.push({level:`warn`,message:`plugin file has unsupported extension: ${i}`,source:i});continue}let r=F.dirname(i);if(So({source:i,rootDir:r,origin:`config`,diagnostics:n,ownershipUid:e.ownershipUid}))continue;t.push(wo({idHint:Co(i),source:i,rootDir:r,origin:`config`,workspaceDir:e.workspaceDir}));continue}r.isDirectory()&&Eo({rootDir:i,origin:`config`,workspaceDir:e.workspaceDir,diagnostics:n,candidates:t,ownershipUid:e.ownershipUid})}return e.dataDir?Eo({rootDir:ko(e.dataDir),origin:`workspace`,workspaceDir:e.workspaceDir,diagnostics:n,candidates:t,ownershipUid:e.ownershipUid}):e.workspaceDir&&Eo({rootDir:Ao(e.workspaceDir),origin:`workspace`,workspaceDir:e.workspaceDir,diagnostics:n,candidates:t,ownershipUid:e.ownershipUid}),Eo({rootDir:Oo(),origin:`global`,workspaceDir:e.workspaceDir,diagnostics:n,candidates:t,ownershipUid:e.ownershipUid}),e.bundledDir&&Eo({rootDir:e.bundledDir,origin:`bundled`,workspaceDir:e.workspaceDir,diagnostics:n,candidates:t,ownershipUid:e.ownershipUid}),{candidates:t,diagnostics:n}}function Mo(e){let t=e.rejectHardlinks??!0,n=co(e.rootPath),r=co(e.absolutePath);if(!n||!r)return{ok:!1,reason:`path`};if(!uo(n,r))return{ok:!1,reason:`unsafe`};let i;try{i=z.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:z.openSync(r,`r`)}}catch{return{ok:!1,reason:`path`}}}const No=`aimax.plugin.json`,Po=[No];function Fo(e){for(let t of Po){let n=F.join(e,t);if(z.existsSync(n))return n}return F.join(e,No)}function Io(e,t=!0){let n=Fo(e),r=Mo({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(z.readFileSync(r.fd,`utf-8`))}catch(e){return{ok:!1,error:`failed to parse plugin manifest: ${String(e)}`,manifestPath:n}}finally{z.closeSync(r.fd)}if(!$a(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=$a(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=eo(i.skills),f;return $a(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 Lo(e){let t=new Map,n=[];for(let r of e){let e=Io(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 Ro=function(e){return e.INFO=`INFO`,e.WARN=`WARN`,e.ERROR=`ERROR`,e}({});function zo(){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 Bo(e,t,n,r){process.stderr.write(`[${zo()}] [${e}] [plugin:${t}][logger:${n}] ${r}\n`)}function Vo(e){return{version:`0.1.0`,logging:{getLogger:t=>({info:n=>Bo(Ro.INFO,e.pluginId,t,n),warn:n=>Bo(Ro.WARN,e.pluginId,t,n),error:n=>Bo(Ro.ERROR,e.pluginId,t,n)})}}}function Ho(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 Uo(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 Wo(e){let t=[...e.registry.diagnostics],n=new ga,r=new ya,i=[],o=[],s=e.runtime?.llm?rt({baseUrl:e.runtime.llm.baseUrl,apiKey:e.runtime.llm.apiKey,defaultModel:e.runtime.llm.model,hooks:r,hookCtx:e.runtime.hookCtx}):void 0,c=Go(e.runtime?.llmAllowlist),l=je(import.meta.url,{interopDefault:!0,requireCache:!1});for(let u of e.registry.manifests.values()){let d=Ho({config:e.plugins,pluginId:u.id,origin:u.origin,kind:u.manifest.kind}),f=Uo({id:u.id,source:u.source,origin:u.origin,enabled:d,configSchema:!0,skills:u.manifest.skills??[]});if(!d){o.push(f);continue}let p;try{p=l(u.source)}catch(e){f.status=`error`,f.error=String(e),t.push({level:`error`,message:`failed to load plugin ${u.id}: ${String(e)}`,pluginId:u.id,source:u.source}),o.push(f);continue}let m=p&&typeof p==`object`&&`default`in p?p.default:p,h=typeof m==`function`?m:m&&typeof m==`object`&&typeof m.register==`function`?m.register:void 0;if(!h){f.status=`error`,f.error=`plugin module does not export a register function`,t.push({level:`error`,message:`plugin ${u.id} has no register function`,pluginId:u.id,source:u.source}),o.push(f);continue}let g=Vo({pluginId:u.id}),_=e.plugins.entries[u.id]?.config,v={id:u.id,source:u.source,rootDir:u.rootDir,config:_,runtime:g,llm:{chat:async e=>{if(!s)throw Error(`LLM client is not configured`);if(!Ko(u.id,n,c))throw Error(`Plugin ${u.id} is not allowed to use LLM`);return s.chat(e)}},registerTool:(e,t)=>{n.register(u.id,e,t),f.toolCount+=1},registerEmbeddingProvider:e=>{if(u.manifest.kind!==`memory`)throw Error(`Plugin ${u.id} is not allowed to register embedding providers`);a({pluginId:u.id,id:e.id,create:e.create,config:_,rootDir:u.rootDir,source:u.source})},registerMemoryProvider:e=>{if(u.manifest.kind!==`memory`)throw Error(`Plugin ${u.id} is not allowed to register memory providers`);E({pluginId:u.id,id:e.id,create:e.create,config:_,rootDir:u.rootDir,source:u.source})},registerHook:(e,t,n)=>{r.register({pluginId:u.id,hookName:e,handler:t,priority:n?.priority,source:u.source}),f.hookCount+=1},registerSkillDir:e=>{let t=F.isAbsolute(e)?e:F.resolve(u.rootDir,e);i.push(t)},createProgressEmitter:()=>ma(u.id)};try{h(v)}catch(e){f.status=`error`,f.error=String(e),t.push({level:`error`,message:`plugin ${u.id} registration failed: ${String(e)}`,pluginId:u.id,source:u.source})}if(u.manifest.skills&&u.manifest.skills.length>0)for(let e of u.manifest.skills){let t=F.isAbsolute(e)?e:F.resolve(u.rootDir,e);i.push(t)}o.push(f)}return{plugins:o,diagnostics:t,tools:n,hooks:r,skills:i}}function Go(e){return(e??[]).map(e=>e.trim()).filter(Boolean)}function Ko(e,t,n){return n.length===0?!1:n.includes(e)?!0:t.namesForPlugin(e).some(e=>n.includes(e))}function qo(e={}){let t=oo(e.config),n=jo({dataDir:e.dataDir,workspaceDir:e.workspaceDir,extraPaths:t.loadPaths,bundledDir:e.bundledDir,ownershipUid:e.ownershipUid}),r=Lo(n.candidates),i=so({config:t,registry:r}),a=Wo({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 Jo(e){let{runParams:t,hookContext:n,sessionId:r,eventDispatcher:i}=e,a=e=>{i.dispatchDiagnostic(r,e).catch(()=>void 0)},o=t.plugins?qo({...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 ya,pluginSkillDirs:o?.registry.skills??[],pluginTools:o?.registry.tools.resolveEnabled(t.plugins?.toolAllowlist)??[],memoryPluginId:t.memory?.pluginId??o?.normalizedConfig.slots?.memory}}async function Yo(e){let{runParams:t,requestedSessionId:n,eventDispatcher:r}=e,i=F.join(t.dataDir,`workspace`),a=n,o=!a;a?await l(t.dataDir,a):a=await c(t.dataDir,t.channel);let s={sessionId:a,workspaceDir:i,channel:t.channel},u=Jo({runParams:t,hookContext:s,sessionId:a,eventDispatcher:r}),d=u.hookRegistry,f=await Vt({runParams:t,sessionId:a,hookContext:s,memoryProviderId:t.memory?.providerId,memoryPluginId:u.memoryPluginId,eventDispatcher:r,hookRegistry:d});return{sessionId:a,isNewSession:o,workspaceDir:i,hookContext:s,hookRegistry:d,pluginContext:u,runContext:f,start:e=>Gt({sessionId:a,runParams:t,hookRegistry:d,hookContext:s,eventDispatcher:r,...e})}}function Xo(e){return e===null||typeof e==`string`||typeof e==`number`||typeof e==`boolean`?e:JSON.stringify(e)??String(e)}function Zo(e){if(!(e instanceof Error))return{errorValue:Xo(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]=Xo(n[e]));return t}async function Qo(e){await e.dispatcher.dispatchDiagnostic(e.sessionId,{level:`error`,scope:e.scope,phase:e.phase,message:e.message,details:{...e.details,...Zo(e.error)}})}function $o(e,t){return F.join(n(e,t),`pending-hitl.json`)}function es(e,t){return F.join(n(e,t),`hitl-history.jsonl`)}async function ts(e,t,r){let i=n(e,t);await P.mkdir(i,{recursive:!0});let a=$o(e,t);await P.writeFile(a,JSON.stringify(r,null,2),`utf-8`)}async function ns(e,t,r){let i=n(e,t);await P.mkdir(i,{recursive:!0});let a=es(e,t),o=JSON.stringify(r)+`
|
|
76
|
+
`;await P.appendFile(a,o,`utf-8`)}async function rs(e,t){let n=$o(e,t);try{let e=await P.readFile(n,`utf-8`);return JSON.parse(e)}catch(e){if(e.code===`ENOENT`)return null;throw e}}async function is(e,t){let n=es(e,t);try{let e=await P.readFile(n,`utf-8`),t=[];for(let n of e.split(`
|
|
77
|
+
`)){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 as(e,t,n,r,i,a){let o=new Date().toISOString(),s={version:1,sessionId:t,request:n,status:`pending`,checkpoint:r,context:i,toolContext:a,createdAt:o,updatedAt:o};return await ts(e,t,s),await ns(e,t,{requestId:n.requestId,sessionId:t,action:`requested`,payload:n,timestamp:o}),s}async function os(e,t,n,r,i){let a=await rs(e,t);if(!a||a.request.requestId!==n||a.status!==`pending`)return null;let o=new Date().toISOString(),s={...a,status:r,resolution:i,updatedAt:o};await ts(e,t,s);let c={resolved:`resolved`,expired:`expired`,cancelled:`cancelled`}[r];return await ns(e,t,{requestId:n,sessionId:t,action:c,payload:i??a.request,timestamp:o}),s}async function ss(e,t,n){let r=await rs(e,t);return!r||r.request.requestId!==n?null:r.status===`resolved`?r:null}async function cs(e,t){let n=$o(e,t);try{await P.unlink(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 us(e,t){Mt();let n=Date.now(),r=new Nt(e),i=Tn(e),a=i.transcriptMessage,o=!1,s=i.previousSessionId,c=await Yo({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}}),i.resetCommand&&(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 Ie(e.dataDir),v=[],y=ze(_,{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 Ge(e.dataDir,m.pluginSkillDirs),x=new nt({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 Dn({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 E=await za({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=>us(e,new Xe),createModel:ls,abortSignal:g.signal}}),D=E.agent,O=E.resolvedModelId;await r.dispatchDiagnostic(l,{level:`info`,scope:`runner`,phase:`runtime_created`,message:`agent runtime created`,details:{modelId:O,historyMessageCount:E.historyMessages.length,pluginToolCount:m.pluginTools.length}}),g.signal.addEventListener(`abort`,()=>D.abort());let k=0,A=0,j=``,M;try{o=await h.persistInitialUserEntry(a)||o,await r.dispatchDiagnostic(l,{level:`info`,scope:`runner`,phase:`first_turn_started`,message:`first agent turn started`});let e=await Va({agent:D,message:w,sessionId:l,modelId:O,historyMessages:E.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)}});j=e.text,k+=e.inputTokens,A+=e.outputTokens,e.error&&(M=e.error),await r.dispatchDiagnostic(l,{level:e.error?`warn`:`info`,scope:`runner`,phase:`first_turn_completed`,message:`first agent turn completed`,details:{hasError:!!e.error,error:e.error,inputTokens:e.inputTokens,outputTokens:e.outputTokens}}),await r.dispatchDiagnostic(l,{level:`info`,scope:`runner`,phase:`announce_loop_started`,message:`announce loop started`});let n=await Za({agent:D,registry:t,sessionId:l,resolvedModelId:O,eventDispatcher:r,skillUsageTracker:x,hookRegistry:p,hookContext:f,abortSignal:g.signal,appendEntry:S});n.text&&(j=n.text),k+=n.inputTokens,A+=n.outputTokens,n.error&&!M&&(M=n.error),await r.dispatchDiagnostic(l,{level:n.error?`warn`:`info`,scope:`runner`,phase:`announce_loop_completed`,message:`announce loop completed`,details:{hasError:!!n.error,error:n.error,inputTokens:n.inputTokens,outputTokens:n.outputTokens}})}catch(t){if(dr(t)){let i=t,o=e.subagentContext?.parentSessionId??l,s=o===i.request.sessionId?i.request:{...i.request,sessionId:o};await as(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:k,output:A,total:k+A};return Jt({sessionId:l,isNewSession:u,transcriptMessage:a,runParams:e,hookRegistry:p,hookContext:f,startTime:n,eventDispatcher:r,text:j||`[HITL paused] ${i.request.title}: ${i.request.prompt}`,usage:c,error:void 0,paused:{requestId:s.requestId,kind:s.kind,title:s.title}})}throw await Qo({dispatcher:r,sessionId:l,scope:`runner`,phase:`run_failed`,message:`agent run failed`,error:t,details:{channel:e.channel,isNewSession:u}}),t}finally{$e(l),h.stop()}let N={input:k,output:A,total:k+A};return await r.dispatchDiagnostic(l,{level:M?`warn`:`info`,scope:`runner`,phase:`run_completed`,message:`agent run completed`,details:{durationMs:Date.now()-n,inputTokens:N.input,outputTokens:N.output,totalTokens:N.total,hasError:!!M,error:M}}),Jt({sessionId:l,isNewSession:u,transcriptMessage:a,runParams:e,hookRegistry:p,hookContext:f,startTime:n,eventDispatcher:r,text:j,usage:N,error:M})}async function ds(e,t){let n=t??new Xe;try{return await us(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:Zo(t)}),t}}const fs={"AGENTS.md":`---
|
|
77
78
|
title: "AGENTS.md Template"
|
|
78
79
|
summary: ".aimax template for AGENTS.md"
|
|
79
80
|
read_when:
|
|
@@ -520,4 +521,4 @@ read_when:
|
|
|
520
521
|
# Add tasks below when you want the agent to check something periodically.
|
|
521
522
|
|
|
522
523
|
# This file lives at .aimax/HEARTBEAT.md, not in workspace/.
|
|
523
|
-
`},
|
|
524
|
+
`},ps=[`AGENTS.md`,`BOOTSTRAP.md`,`IDENTITY.md`,`USER.md`,`SOUL.md`,`TOOLS.md`,`HEARTBEAT.md`];async function $(e,t){try{if(!(await P.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 P.mkdir(e,{recursive:!0}),t.createdDirs.push(e)}async function ms(e,t,n){try{if(!(await P.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 P.mkdir(F.dirname(e),{recursive:!0});try{await P.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 hs(e){let t=B(e);return[e,t,F.join(t,`skills`),F.join(t,`sessions`),F.join(t,`memory`),F.join(e,`workspace`)]}function gs(e){let t=B(e);return[...ps.filter(e=>e!==`BOOTSTRAP.md`).map(e=>F.join(t,e)),F.join(t,`MEMORY.md`)]}function _s(e){return F.join(B(e),`.bootstrapped`)}async function vs(e){try{return(await P.stat(_s(e))).isFile()}catch(e){if(e.code===`ENOENT`)return!1;throw e}}async function ys(e){let t=_s(e);await P.mkdir(F.dirname(t),{recursive:!0}),await P.writeFile(t,``,{encoding:`utf-8`})}async function bs(e){let t=[],n=[];for(let n of hs(e))try{(await P.stat(n)).isDirectory()||t.push(n)}catch(e){if(e.code===`ENOENT`){t.push(n);continue}throw e}for(let t of gs(e))try{(await P.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 xs(e){return(await bs(e)).ready}async function Ss(e){if(await vs(e))return{ready:!0,performedBootstrap:!1};if((await bs(e)).ready)return await ys(e),{ready:!0,performedBootstrap:!1};let t=await Cs(e);return await ys(e),{ready:!0,performedBootstrap:!0,result:t}}async function Cs(e){let t={dataDir:e,createdDirs:[],skippedDirs:[],createdFiles:[],skippedFiles:[]},n=B(e),r=F.join(e,`workspace`),i=F.join(n,`skills`),a=F.join(n,`sessions`),o=F.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 ps){let r=fs[e]??``;await ms(F.join(n,e),r,t)}return await ms(F.join(n,`MEMORY.md`),``,t),t}async function ws(e){let t=F.join(e,`.aimax`,`subagents`,`runs.json`);try{let e=await P.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 Ts(e,t){let n=F.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 P.mkdir(F.dirname(n),{recursive:!0}),await P.writeFile(n,JSON.stringify(i,null,2),`utf-8`)}async function Es(e,t){let n=await ws(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 Ds(e,t=7){let n=await ws(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 Ts(e,n),i}async function Os(e,t,n){let r=await rs(e,t);return r?r.request.requestId===n?r.sessionId===t?r.status===`pending`?Me(r.request)?(await os(e,t,n,`expired`),{valid:!1,reason:`HITL request has expired`}):{valid:!0,state:r}:{valid:!1,reason:`HITL request is already "${r.status}", cannot resume`}:{valid:!1,reason:`Session ID mismatch: expected "${r.sessionId}", got "${t}"`}:{valid:!1,reason:`Request ID mismatch: expected "${r.request.requestId}", got "${n}"`}:{valid:!1,reason:`No pending HITL request found for this session`}}async function ks(e){let{dataDir:t,sessionId:n,requestId:r,resolution:i}=e,a=await ss(t,n,r);if(a){let e=a.resolution?.idempotencyKey;if(e&&i.idempotencyKey&&e===i.idempotencyKey)return{state:a,idempotentReplay:!0};throw Error(`HITL resume validation failed: HITL request is already "${a.status}", cannot resume`)}let o=await Os(t,n,r);if(!o.valid)throw Error(`HITL resume validation failed: ${o.reason}`);let s=await os(t,n,r,`resolved`,i);if(!s)throw Error(`Failed to transition HITL state to resolved (concurrent modification?)`);return{state:s,idempotentReplay:!1}}export{Fe as BOOTSTRAP_FILE_NAMES,Ne as BOOTSTRAP_MAX_CHARS,Pe as BOOTSTRAP_TOTAL_MAX_CHARS,K as HitlPauseSignal,Ye as MAX_CHILDREN_PER_SESSION,Je as MAX_SUBAGENT_DEPTH,v as MemoryIndexManager,No as PLUGIN_MANIFEST_FILENAME,Po as PLUGIN_MANIFEST_FILENAMES,ya as PluginHookRegistry,ga as PluginToolRegistry,Xe as SubagentRegistry,ce as addAgent,ie as addBinding,B as aimaxDir,Si as appendToMemory,s as appendTranscriptEntry,Cs as bootstrapMountLayout,ze as buildBootstrapContextFiles,qe as buildSkillsPrompt,Ii as buildSubagentAnnounceMessage,da as buildSystemPrompt,Ds as cleanupOldSubagentRecords,cs as clearPendingHitl,p as collapseLogPath,b as contextSnapshotPath,Wi as createAgentTools,$r as createApplyPatchTool,Ir as createBashTool,h as createBuiltinMemoryProvider,fi as createClarifyTool,lr as createContextManager,Gr as createEditFileTool,Cr as createExecTool,Ui as createImageTool,qr as createListDirTool,Ai as createMemoryAppendTool,Oi as createMemoryGetTool,Ei as createMemorySearchTool,as as createPendingHitl,ma as createPluginProgressEmitter,Vo as createPluginRuntime,Er as createProcessTool,Vr as createReadFileTool,Mi as createRequestApprovalTool,Pi as createRequestReviewTool,c as createSession,Rn as createSessionContextStore,Li as createSessionsSpawnTool,Vi as createSubagentsTool,Ur as createWriteFileTool,wi as deleteMemoryFile,jo as discoverAIMaxPlugins,Ss as ensureBootstrapMountLayout,l as ensureSession,_ as exportSession,Ft as generateSessionTitle,te as getAgentConfig,xi as getMemoryLines,vs as hasBootstrapSentinel,es as hitlHistoryPath,qo as initializePluginSystem,bs as inspectBootstrapMountLayout,m as inspectSession,xs as isBootstrapMountLayoutReady,dr as isHitlPauseSignal,k as listAgents,$t as listAvailableSlashCommands,ae as listBindings,_i as listMemoryFiles,d as listSessionSummaries,u as listSessions,Es as listSubagentRunsFromDisk,se as loadAgentsConfig,Ie as loadBootstrapFiles,rs as loadPendingHitl,rs as readPendingHitl,Io as loadPluginManifest,Lo as loadPluginManifestRegistry,Wo as loadPlugins,i as loadSessionContextSnapshot,x as loadSessionMetadata,We as loadSkills,Ke as loadSkillsFromDirs,Ge as loadSkillsWithPluginDirs,ws as loadSubagentRegistryFromDisk,w as loadTranscript,pi as memoryDir,o as metadataPath,A as normalizeAgentId,oo as normalizePluginsConfig,$o as pendingHitlPath,mi as primaryMemoryPath,is as readHitlHistory,vi as readMemoryFile,yi as readPrimaryMemory,a as registerEmbeddingProvider,E as registerMemoryProvider,ne as removeAgent,le as removeBindings,Ci as replaceMemoryFile,g as resetEmbeddingProviderRegistryForTests,D as resetMemoryProviderRegistryForTests,j as resolveAgentDir,M as resolveAgentIdByBinding,oe as resolveAgentsConfigPath,re as resolveDefaultAgentId,y as resolveEmbeddingProvider,ks as resolveHitlRequest,ks as resolvePendingHitl,T as resolveMemoryProvider,ee as resolveModelFallbacks,N as resolveModelString,Fo as resolvePluginManifestPath,ds as runAgent,O as saveAgentsConfig,C as saveSessionMetadata,Ts as saveSubagentRegistryToDisk,bi as searchMemory,n as sessionDir,e as sessionMemoryPath,S as sessionsDir,Be as skillsDir,r as toolResultsDir,t as transcriptPath,os as transitionHitlStatus,ue as updateAgentIdentity,so as validatePluginsConfig,Os as validateResume,va as wrapToolsWithHooks};
|