@opencow-ai/opencow-agent-sdk 0.4.18 → 0.4.19
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/capabilities/tools/AgentTool/agentLifecycleFinalizer.d.ts +3 -0
- package/dist/cli.mjs +430 -222
- package/dist/client.d.ts +3 -2
- package/dist/client.js +578 -251
- package/dist/entrypoints/sdk/runtimeTypes.d.ts +5 -7
- package/dist/sdk.js +578 -251
- package/dist/session/backgroundAbortRegistry.d.ts +15 -7
- package/dist/session/backgroundTaskScope.d.ts +29 -0
- package/package.json +1 -1
package/dist/client.js
CHANGED
|
@@ -234734,18 +234734,74 @@ var init_registerFrontmatterHooks = __esm(() => {
|
|
|
234734
234734
|
});
|
|
234735
234735
|
|
|
234736
234736
|
// src/session/backgroundAbortRegistry.ts
|
|
234737
|
-
function registerBackgroundAgentAbort(agentId,
|
|
234738
|
-
runs.
|
|
234737
|
+
function registerBackgroundAgentAbort(agentId, actions) {
|
|
234738
|
+
if (runs.has(agentId)) {
|
|
234739
|
+
throw new Error(`Background agent '${agentId}' is already registered`);
|
|
234740
|
+
}
|
|
234741
|
+
let resolveSettled = () => {};
|
|
234742
|
+
const settled = new Promise((resolve15) => {
|
|
234743
|
+
resolveSettled = resolve15;
|
|
234744
|
+
});
|
|
234745
|
+
runs.set(agentId, {
|
|
234746
|
+
...actions,
|
|
234747
|
+
stopFired: false,
|
|
234748
|
+
stopPromise: undefined,
|
|
234749
|
+
settled,
|
|
234750
|
+
resolveSettled,
|
|
234751
|
+
shellsStopped: false
|
|
234752
|
+
});
|
|
234739
234753
|
}
|
|
234740
234754
|
function unregisterBackgroundAgentAbort(agentId) {
|
|
234755
|
+
const run = runs.get(agentId);
|
|
234756
|
+
if (!run)
|
|
234757
|
+
return;
|
|
234741
234758
|
runs.delete(agentId);
|
|
234759
|
+
run.resolveSettled();
|
|
234742
234760
|
}
|
|
234743
234761
|
function abortBackgroundAgentById(agentId) {
|
|
234744
234762
|
const run = runs.get(agentId);
|
|
234745
234763
|
if (!run)
|
|
234746
|
-
return
|
|
234747
|
-
run.
|
|
234748
|
-
|
|
234764
|
+
return Promise.resolve();
|
|
234765
|
+
if (!run.stopPromise) {
|
|
234766
|
+
run.stopPromise = (async () => {
|
|
234767
|
+
const errors4 = [];
|
|
234768
|
+
let abortFailed = false;
|
|
234769
|
+
try {
|
|
234770
|
+
run.abort();
|
|
234771
|
+
} catch (error41) {
|
|
234772
|
+
abortFailed = true;
|
|
234773
|
+
errors4.push(error41);
|
|
234774
|
+
}
|
|
234775
|
+
try {
|
|
234776
|
+
stopBackgroundAgentShells(run);
|
|
234777
|
+
} catch (error41) {
|
|
234778
|
+
errors4.push(error41);
|
|
234779
|
+
}
|
|
234780
|
+
if (abortFailed) {
|
|
234781
|
+
throw new AggregateError(errors4, `Failed to stop background agent '${agentId}'`);
|
|
234782
|
+
}
|
|
234783
|
+
await run.settled;
|
|
234784
|
+
if (errors4.length > 0) {
|
|
234785
|
+
throw new AggregateError(errors4, `Failed to stop background agent '${agentId}'`);
|
|
234786
|
+
}
|
|
234787
|
+
})();
|
|
234788
|
+
}
|
|
234789
|
+
return run.stopPromise;
|
|
234790
|
+
}
|
|
234791
|
+
function hasBackgroundAgent(agentId) {
|
|
234792
|
+
return runs.has(agentId);
|
|
234793
|
+
}
|
|
234794
|
+
function stopBackgroundAgentShellsById(agentId) {
|
|
234795
|
+
const run = runs.get(agentId);
|
|
234796
|
+
if (run) {
|
|
234797
|
+
stopBackgroundAgentShells(run);
|
|
234798
|
+
}
|
|
234799
|
+
}
|
|
234800
|
+
function stopBackgroundAgentShells(run) {
|
|
234801
|
+
if (run.shellsStopped)
|
|
234802
|
+
return;
|
|
234803
|
+
run.shellsStopped = true;
|
|
234804
|
+
run.stopShells();
|
|
234749
234805
|
}
|
|
234750
234806
|
function markSubagentStopFired(agentId) {
|
|
234751
234807
|
const run = runs.get(agentId);
|
|
@@ -235703,6 +235759,23 @@ var init_formatting = __esm(() => {
|
|
|
235703
235759
|
init_xml();
|
|
235704
235760
|
});
|
|
235705
235761
|
|
|
235762
|
+
// src/capabilities/tools/AgentTool/agentLifecycleFinalizer.ts
|
|
235763
|
+
function createAgentLifecycleFinalizer(onCleanupError) {
|
|
235764
|
+
let finalization;
|
|
235765
|
+
return (cleanups) => {
|
|
235766
|
+
finalization ??= (async () => {
|
|
235767
|
+
for (const cleanup of cleanups) {
|
|
235768
|
+
try {
|
|
235769
|
+
await cleanup();
|
|
235770
|
+
} catch (error41) {
|
|
235771
|
+
onCleanupError(error41);
|
|
235772
|
+
}
|
|
235773
|
+
}
|
|
235774
|
+
})();
|
|
235775
|
+
return finalization;
|
|
235776
|
+
};
|
|
235777
|
+
}
|
|
235778
|
+
|
|
235706
235779
|
// src/capabilities/tools/AgentTool/runAgent.ts
|
|
235707
235780
|
import { randomUUID as randomUUID6 } from "crypto";
|
|
235708
235781
|
async function initializeAgentMcpServers(agentDefinition, parentClients) {
|
|
@@ -235725,44 +235798,6 @@ async function initializeAgentMcpServers(agentDefinition, parentClients) {
|
|
|
235725
235798
|
const agentClients = [];
|
|
235726
235799
|
const newlyCreatedClients = [];
|
|
235727
235800
|
const agentTools = [];
|
|
235728
|
-
for (const spec of agentDefinition.mcpServers) {
|
|
235729
|
-
let config2 = null;
|
|
235730
|
-
let name;
|
|
235731
|
-
let isNewlyCreated = false;
|
|
235732
|
-
if (typeof spec === "string") {
|
|
235733
|
-
name = spec;
|
|
235734
|
-
config2 = getMcpConfigByName(spec);
|
|
235735
|
-
if (!config2) {
|
|
235736
|
-
logForDebugging(`[Agent: ${agentDefinition.agentType}] MCP server not found: ${spec}`, { level: "warn" });
|
|
235737
|
-
continue;
|
|
235738
|
-
}
|
|
235739
|
-
} else {
|
|
235740
|
-
const entries = Object.entries(spec);
|
|
235741
|
-
if (entries.length !== 1) {
|
|
235742
|
-
logForDebugging(`[Agent: ${agentDefinition.agentType}] Invalid MCP server spec: expected exactly one key`, { level: "warn" });
|
|
235743
|
-
continue;
|
|
235744
|
-
}
|
|
235745
|
-
const [serverName, serverConfig] = entries[0];
|
|
235746
|
-
name = serverName;
|
|
235747
|
-
config2 = {
|
|
235748
|
-
...serverConfig,
|
|
235749
|
-
scope: "dynamic"
|
|
235750
|
-
};
|
|
235751
|
-
isNewlyCreated = true;
|
|
235752
|
-
}
|
|
235753
|
-
const client = await connectToServer(name, config2);
|
|
235754
|
-
agentClients.push(client);
|
|
235755
|
-
if (isNewlyCreated) {
|
|
235756
|
-
newlyCreatedClients.push(client);
|
|
235757
|
-
}
|
|
235758
|
-
if (client.type === "connected") {
|
|
235759
|
-
const tools = await fetchToolsForClient(client);
|
|
235760
|
-
agentTools.push(...tools);
|
|
235761
|
-
logForDebugging(`[Agent: ${agentDefinition.agentType}] Connected to MCP server '${name}' with ${tools.length} tools`);
|
|
235762
|
-
} else {
|
|
235763
|
-
logForDebugging(`[Agent: ${agentDefinition.agentType}] Failed to connect to MCP server '${name}': ${client.type}`, { level: "warn" });
|
|
235764
|
-
}
|
|
235765
|
-
}
|
|
235766
235801
|
const cleanup = async () => {
|
|
235767
235802
|
for (const client of newlyCreatedClients) {
|
|
235768
235803
|
if (client.type === "connected") {
|
|
@@ -235774,6 +235809,49 @@ async function initializeAgentMcpServers(agentDefinition, parentClients) {
|
|
|
235774
235809
|
}
|
|
235775
235810
|
}
|
|
235776
235811
|
};
|
|
235812
|
+
try {
|
|
235813
|
+
for (const spec of agentDefinition.mcpServers) {
|
|
235814
|
+
let config2 = null;
|
|
235815
|
+
let name;
|
|
235816
|
+
let isNewlyCreated = false;
|
|
235817
|
+
if (typeof spec === "string") {
|
|
235818
|
+
name = spec;
|
|
235819
|
+
config2 = getMcpConfigByName(spec);
|
|
235820
|
+
if (!config2) {
|
|
235821
|
+
logForDebugging(`[Agent: ${agentDefinition.agentType}] MCP server not found: ${spec}`, { level: "warn" });
|
|
235822
|
+
continue;
|
|
235823
|
+
}
|
|
235824
|
+
} else {
|
|
235825
|
+
const entries = Object.entries(spec);
|
|
235826
|
+
if (entries.length !== 1) {
|
|
235827
|
+
logForDebugging(`[Agent: ${agentDefinition.agentType}] Invalid MCP server spec: expected exactly one key`, { level: "warn" });
|
|
235828
|
+
continue;
|
|
235829
|
+
}
|
|
235830
|
+
const [serverName, serverConfig] = entries[0];
|
|
235831
|
+
name = serverName;
|
|
235832
|
+
config2 = {
|
|
235833
|
+
...serverConfig,
|
|
235834
|
+
scope: "dynamic"
|
|
235835
|
+
};
|
|
235836
|
+
isNewlyCreated = true;
|
|
235837
|
+
}
|
|
235838
|
+
const client = await connectToServer(name, config2);
|
|
235839
|
+
agentClients.push(client);
|
|
235840
|
+
if (isNewlyCreated) {
|
|
235841
|
+
newlyCreatedClients.push(client);
|
|
235842
|
+
}
|
|
235843
|
+
if (client.type === "connected") {
|
|
235844
|
+
const tools = await fetchToolsForClient(client);
|
|
235845
|
+
agentTools.push(...tools);
|
|
235846
|
+
logForDebugging(`[Agent: ${agentDefinition.agentType}] Connected to MCP server '${name}' with ${tools.length} tools`);
|
|
235847
|
+
} else {
|
|
235848
|
+
logForDebugging(`[Agent: ${agentDefinition.agentType}] Failed to connect to MCP server '${name}': ${client.type}`, { level: "warn" });
|
|
235849
|
+
}
|
|
235850
|
+
}
|
|
235851
|
+
} catch (error41) {
|
|
235852
|
+
await cleanup();
|
|
235853
|
+
throw error41;
|
|
235854
|
+
}
|
|
235777
235855
|
return {
|
|
235778
235856
|
clients: [...parentClients, ...agentClients],
|
|
235779
235857
|
tools: agentTools,
|
|
@@ -235926,121 +236004,140 @@ async function* runAgent({
|
|
|
235926
236004
|
const additionalWorkingDirectories = Array.from(appState.toolPermissionContext.additionalWorkingDirectories.keys());
|
|
235927
236005
|
const agentSystemPrompt = override?.systemPrompt ? override.systemPrompt : asSystemPrompt(await getAgentSystemPrompt(agentDefinition, toolUseContext, resolvedAgentModel, additionalWorkingDirectories, resolvedTools));
|
|
235928
236006
|
const agentAbortController = override?.abortController ? override.abortController : isAsync2 ? new AbortController : toolUseContext.abortController;
|
|
236007
|
+
const stopOwnedShells = () => {
|
|
236008
|
+
killShellTasksForAgent(agentId, toolUseContext.getAppState, rootSetAppState);
|
|
236009
|
+
};
|
|
235929
236010
|
if (isAsync2) {
|
|
235930
|
-
registerBackgroundAgentAbort(agentId,
|
|
235931
|
-
|
|
235932
|
-
|
|
235933
|
-
|
|
235934
|
-
|
|
235935
|
-
|
|
235936
|
-
|
|
236011
|
+
registerBackgroundAgentAbort(agentId, {
|
|
236012
|
+
abort: () => {
|
|
236013
|
+
killAsyncAgent(agentId, rootSetAppState);
|
|
236014
|
+
if (!agentAbortController.signal.aborted) {
|
|
236015
|
+
agentAbortController.abort();
|
|
236016
|
+
}
|
|
236017
|
+
},
|
|
236018
|
+
stopShells: stopOwnedShells
|
|
236019
|
+
});
|
|
235937
236020
|
}
|
|
235938
|
-
|
|
235939
|
-
|
|
235940
|
-
|
|
235941
|
-
|
|
235942
|
-
|
|
235943
|
-
|
|
235944
|
-
|
|
236021
|
+
let agentToolRuntimeContext;
|
|
236022
|
+
let mcpCleanup = async () => {};
|
|
236023
|
+
let lastAssistantForFallback = null;
|
|
236024
|
+
let agentRunError;
|
|
236025
|
+
const finalizeLifecycle = createAgentLifecycleFinalizer((error41) => {
|
|
236026
|
+
logForDebugging(`Agent ${agentId} cleanup failed: ${error41}`, {
|
|
236027
|
+
level: "warn"
|
|
235945
236028
|
});
|
|
235946
|
-
|
|
235947
|
-
|
|
235948
|
-
|
|
235949
|
-
|
|
235950
|
-
|
|
235951
|
-
|
|
235952
|
-
const skillsToPreload = agentDefinition.skills ?? [];
|
|
235953
|
-
if (skillsToPreload.length > 0) {
|
|
235954
|
-
const allSkills = await getSkillToolCommands(getProjectRoot());
|
|
235955
|
-
const validSkills = [];
|
|
235956
|
-
for (const skillName of skillsToPreload) {
|
|
235957
|
-
const resolvedName = resolveSkillName(skillName, allSkills, agentDefinition);
|
|
235958
|
-
if (!resolvedName) {
|
|
235959
|
-
logForDebugging(`[Agent: ${agentDefinition.agentType}] Warning: Skill '${skillName}' specified in frontmatter was not found`, { level: "warn" });
|
|
235960
|
-
continue;
|
|
235961
|
-
}
|
|
235962
|
-
const skill = getCommand(resolvedName, allSkills);
|
|
235963
|
-
if (skill.type !== "prompt") {
|
|
235964
|
-
logForDebugging(`[Agent: ${agentDefinition.agentType}] Warning: Skill '${skillName}' is not a prompt-based skill`, { level: "warn" });
|
|
235965
|
-
continue;
|
|
236029
|
+
});
|
|
236030
|
+
try {
|
|
236031
|
+
const additionalContexts = [];
|
|
236032
|
+
for await (const hookResult of executeSubagentStartHooks(agentId, agentDefinition.agentType, agentAbortController.signal, undefined, toolUseContext.toolUseId, isAsync2)) {
|
|
236033
|
+
if (hookResult.additionalContexts && hookResult.additionalContexts.length > 0) {
|
|
236034
|
+
additionalContexts.push(...hookResult.additionalContexts);
|
|
235966
236035
|
}
|
|
235967
|
-
validSkills.push({ skillName, skill });
|
|
235968
236036
|
}
|
|
235969
|
-
|
|
235970
|
-
|
|
235971
|
-
|
|
235972
|
-
|
|
235973
|
-
|
|
235974
|
-
|
|
235975
|
-
|
|
235976
|
-
|
|
235977
|
-
initialMessages.push(
|
|
235978
|
-
|
|
235979
|
-
|
|
235980
|
-
|
|
236037
|
+
if (additionalContexts.length > 0) {
|
|
236038
|
+
const contextMessage = createAttachmentMessage({
|
|
236039
|
+
type: "hook_additional_context",
|
|
236040
|
+
content: additionalContexts,
|
|
236041
|
+
hookName: "SubagentStart",
|
|
236042
|
+
toolUseID: randomUUID6(),
|
|
236043
|
+
hookEvent: "SubagentStart"
|
|
236044
|
+
});
|
|
236045
|
+
initialMessages.push(contextMessage);
|
|
236046
|
+
}
|
|
236047
|
+
const hooksAllowedForThisAgent = !isRestrictedToPluginOnly("hooks") || isSourceAdminTrusted(agentDefinition.source);
|
|
236048
|
+
if (agentDefinition.hooks && hooksAllowedForThisAgent) {
|
|
236049
|
+
registerFrontmatterHooks(rootSetAppState, agentId, agentDefinition.hooks, `agent '${agentDefinition.agentType}'`, true);
|
|
236050
|
+
}
|
|
236051
|
+
const skillsToPreload = agentDefinition.skills ?? [];
|
|
236052
|
+
if (skillsToPreload.length > 0) {
|
|
236053
|
+
const allSkills = await getSkillToolCommands(getProjectRoot());
|
|
236054
|
+
const validSkills = [];
|
|
236055
|
+
for (const skillName of skillsToPreload) {
|
|
236056
|
+
const resolvedName = resolveSkillName(skillName, allSkills, agentDefinition);
|
|
236057
|
+
if (!resolvedName) {
|
|
236058
|
+
logForDebugging(`[Agent: ${agentDefinition.agentType}] Warning: Skill '${skillName}' specified in frontmatter was not found`, { level: "warn" });
|
|
236059
|
+
continue;
|
|
236060
|
+
}
|
|
236061
|
+
const skill = getCommand(resolvedName, allSkills);
|
|
236062
|
+
if (skill.type !== "prompt") {
|
|
236063
|
+
logForDebugging(`[Agent: ${agentDefinition.agentType}] Warning: Skill '${skillName}' is not a prompt-based skill`, { level: "warn" });
|
|
236064
|
+
continue;
|
|
236065
|
+
}
|
|
236066
|
+
validSkills.push({ skillName, skill });
|
|
236067
|
+
}
|
|
236068
|
+
const loaded = await Promise.all(validSkills.map(async ({ skillName, skill }) => ({
|
|
236069
|
+
skillName,
|
|
236070
|
+
skill,
|
|
236071
|
+
content: await skill.getPromptForCommand("", toolUseContext)
|
|
236072
|
+
})));
|
|
236073
|
+
for (const { skillName, skill, content } of loaded) {
|
|
236074
|
+
logForDebugging(`[Agent: ${agentDefinition.agentType}] Preloaded skill '${skillName}'`);
|
|
236075
|
+
const metadata = formatSkillLoadingMetadata(skillName, skill.progressMessage);
|
|
236076
|
+
initialMessages.push(createUserMessage({
|
|
236077
|
+
content: [{ type: "text", text: metadata }, ...content],
|
|
236078
|
+
isMeta: true
|
|
236079
|
+
}));
|
|
236080
|
+
}
|
|
235981
236081
|
}
|
|
235982
|
-
|
|
235983
|
-
|
|
235984
|
-
|
|
235985
|
-
|
|
235986
|
-
|
|
235987
|
-
|
|
235988
|
-
|
|
235989
|
-
|
|
235990
|
-
|
|
235991
|
-
|
|
235992
|
-
|
|
235993
|
-
|
|
235994
|
-
|
|
235995
|
-
|
|
235996
|
-
|
|
235997
|
-
|
|
235998
|
-
|
|
235999
|
-
|
|
236000
|
-
|
|
236001
|
-
|
|
236002
|
-
|
|
236003
|
-
|
|
236004
|
-
|
|
236005
|
-
|
|
236006
|
-
|
|
236007
|
-
|
|
236008
|
-
|
|
236009
|
-
|
|
236010
|
-
|
|
236011
|
-
|
|
236012
|
-
|
|
236013
|
-
|
|
236014
|
-
|
|
236015
|
-
|
|
236016
|
-
|
|
236017
|
-
});
|
|
236018
|
-
if (preserveToolUseResults) {
|
|
236019
|
-
agentToolRuntimeContext.preserveToolUseResults = true;
|
|
236020
|
-
}
|
|
236021
|
-
if (onCacheSafeParams) {
|
|
236022
|
-
onCacheSafeParams({
|
|
236023
|
-
systemPrompt: agentSystemPrompt,
|
|
236024
|
-
userContext: resolvedUserContext,
|
|
236025
|
-
systemContext: resolvedSystemContext,
|
|
236026
|
-
toolUseContext: agentToolRuntimeContext,
|
|
236027
|
-
forkContextMessages: initialMessages
|
|
236082
|
+
const mcp = await initializeAgentMcpServers(agentDefinition, toolUseContext.options.mcpClients);
|
|
236083
|
+
const {
|
|
236084
|
+
clients: mergedMcpClients,
|
|
236085
|
+
tools: agentMcpTools
|
|
236086
|
+
} = mcp;
|
|
236087
|
+
mcpCleanup = mcp.cleanup;
|
|
236088
|
+
const allTools = agentMcpTools.length > 0 ? uniqBy_default([...resolvedTools, ...agentMcpTools], "name") : resolvedTools;
|
|
236089
|
+
const agentOptions = {
|
|
236090
|
+
isNonInteractiveSession: useExactTools ? toolUseContext.options.isNonInteractiveSession : isAsync2 ? true : toolUseContext.options.isNonInteractiveSession ?? false,
|
|
236091
|
+
appendSystemPrompt: toolUseContext.options.appendSystemPrompt,
|
|
236092
|
+
tools: allTools,
|
|
236093
|
+
commands: [],
|
|
236094
|
+
debug: toolUseContext.options.debug,
|
|
236095
|
+
verbose: toolUseContext.options.verbose,
|
|
236096
|
+
mainLoopModel: effectiveModel,
|
|
236097
|
+
providerOverride: providerOverride ?? undefined,
|
|
236098
|
+
thinkingConfig: toolUseContext.options.thinkingConfig,
|
|
236099
|
+
mcpClients: mergedMcpClients,
|
|
236100
|
+
mcpResources: toolUseContext.options.mcpResources,
|
|
236101
|
+
agentDefinitions: toolUseContext.options.agentDefinitions,
|
|
236102
|
+
subagentDisallowedTools: toolUseContext.options.subagentDisallowedTools,
|
|
236103
|
+
...useExactTools && { querySource }
|
|
236104
|
+
};
|
|
236105
|
+
agentToolRuntimeContext = createSubagentContext(toolUseContext, {
|
|
236106
|
+
options: agentOptions,
|
|
236107
|
+
agentId,
|
|
236108
|
+
agentType: agentDefinition.agentType,
|
|
236109
|
+
messages: initialMessages,
|
|
236110
|
+
readFileState: agentReadFileState,
|
|
236111
|
+
abortController: agentAbortController,
|
|
236112
|
+
getAppState: agentGetAppState,
|
|
236113
|
+
shareSetAppState: !isAsync2,
|
|
236114
|
+
shareSetResponseLength: true,
|
|
236115
|
+
criticalSystemReminder_EXPERIMENTAL: agentDefinition.criticalSystemReminder_EXPERIMENTAL,
|
|
236116
|
+
contentReplacementState
|
|
236028
236117
|
});
|
|
236029
|
-
|
|
236030
|
-
|
|
236031
|
-
|
|
236032
|
-
|
|
236033
|
-
|
|
236034
|
-
|
|
236035
|
-
|
|
236036
|
-
|
|
236037
|
-
|
|
236038
|
-
|
|
236039
|
-
|
|
236040
|
-
|
|
236041
|
-
|
|
236042
|
-
|
|
236043
|
-
|
|
236118
|
+
if (preserveToolUseResults) {
|
|
236119
|
+
agentToolRuntimeContext.preserveToolUseResults = true;
|
|
236120
|
+
}
|
|
236121
|
+
if (onCacheSafeParams) {
|
|
236122
|
+
onCacheSafeParams({
|
|
236123
|
+
systemPrompt: agentSystemPrompt,
|
|
236124
|
+
userContext: resolvedUserContext,
|
|
236125
|
+
systemContext: resolvedSystemContext,
|
|
236126
|
+
toolUseContext: agentToolRuntimeContext,
|
|
236127
|
+
forkContextMessages: initialMessages
|
|
236128
|
+
});
|
|
236129
|
+
}
|
|
236130
|
+
recordSidechainTranscript(initialMessages, agentId).catch((_err) => logForDebugging(`Failed to record sidechain transcript: ${_err}`));
|
|
236131
|
+
writeAgentMetadata(agentId, {
|
|
236132
|
+
agentType: agentDefinition.agentType,
|
|
236133
|
+
...worktreePath && { worktreePath },
|
|
236134
|
+
...description && { description }
|
|
236135
|
+
}).catch((_err) => logForDebugging(`Failed to write agent metadata: ${_err}`));
|
|
236136
|
+
let lastRecordedUuid = initialMessages.at(-1)?.uuid ?? null;
|
|
236137
|
+
let partialBaseMessage = null;
|
|
236138
|
+
const partialTextByIndex = new Map;
|
|
236139
|
+
const PARTIAL_PROGRESS_HOOK_INTERVAL_MS = 100;
|
|
236140
|
+
let lastPartialProgressHookAt = 0;
|
|
236044
236141
|
for await (const message of query({
|
|
236045
236142
|
messages: initialMessages,
|
|
236046
236143
|
systemPrompt: agentSystemPrompt,
|
|
@@ -236130,43 +236227,65 @@ async function* runAgent({
|
|
|
236130
236227
|
agentRunError = err2;
|
|
236131
236228
|
throw err2;
|
|
236132
236229
|
} finally {
|
|
236133
|
-
|
|
236134
|
-
|
|
236135
|
-
|
|
236136
|
-
|
|
236137
|
-
|
|
236138
|
-
logForDebugging(`Background agent ${agentId} crashed: ${errorMessage(agentRunError)}
|
|
236230
|
+
await finalizeLifecycle([
|
|
236231
|
+
async () => {
|
|
236232
|
+
const naturalStopAlreadyFired = isAsync2 && hasSubagentStopFired(agentId);
|
|
236233
|
+
if (isAsync2 && agentRunError !== undefined) {
|
|
236234
|
+
logForDebugging(`Background agent ${agentId} crashed: ${errorMessage(agentRunError)}
|
|
236139
236235
|
${agentRunError instanceof Error ? agentRunError.stack ?? "" : ""}`, { level: "error" });
|
|
236140
|
-
|
|
236141
|
-
|
|
236142
|
-
|
|
236143
|
-
|
|
236144
|
-
|
|
236145
|
-
|
|
236146
|
-
|
|
236147
|
-
|
|
236148
|
-
|
|
236149
|
-
|
|
236236
|
+
}
|
|
236237
|
+
if (isAsync2 && !naturalStopAlreadyFired) {
|
|
236238
|
+
try {
|
|
236239
|
+
const terminalContext = agentToolRuntimeContext ?? toolUseContext;
|
|
236240
|
+
const fallbackAppState = terminalContext.getAppState();
|
|
236241
|
+
const terminal = agentAbortController.signal.aborted ? { status: "stopped" } : agentRunError !== undefined ? { status: "failed", errorMessage: errorMessage(agentRunError) } : { status: "completed" };
|
|
236242
|
+
const fallbackStop = executeStopHooks(fallbackAppState.toolPermissionContext.mode, undefined, undefined, false, agentId, terminalContext, lastAssistantForFallback ? [lastAssistantForFallback] : undefined, agentDefinition.agentType, undefined, terminal);
|
|
236243
|
+
for await (const evt of fallbackStop) {}
|
|
236244
|
+
} catch (err2) {
|
|
236245
|
+
logForDebugging(`Fallback SubagentStop failed for ${agentId}: ${err2}`, {
|
|
236246
|
+
level: "warn"
|
|
236247
|
+
});
|
|
236248
|
+
}
|
|
236249
|
+
}
|
|
236250
|
+
},
|
|
236251
|
+
mcpCleanup,
|
|
236252
|
+
() => {
|
|
236253
|
+
if (agentDefinition.hooks) {
|
|
236254
|
+
clearSessionHooks(rootSetAppState, agentId);
|
|
236255
|
+
}
|
|
236256
|
+
},
|
|
236257
|
+
() => {
|
|
236258
|
+
if (false) {}
|
|
236259
|
+
},
|
|
236260
|
+
() => agentToolRuntimeContext?.readFileState.clear(),
|
|
236261
|
+
() => {
|
|
236262
|
+
initialMessages.length = 0;
|
|
236263
|
+
},
|
|
236264
|
+
() => unregisterAgent(agentId),
|
|
236265
|
+
() => clearAgentTranscriptSubdir(agentId),
|
|
236266
|
+
() => {
|
|
236267
|
+
rootSetAppState((prev) => {
|
|
236268
|
+
if (!(agentId in prev.todos))
|
|
236269
|
+
return prev;
|
|
236270
|
+
const { [agentId]: _removed, ...todos } = prev.todos;
|
|
236271
|
+
return { ...prev, todos };
|
|
236150
236272
|
});
|
|
236273
|
+
},
|
|
236274
|
+
() => {
|
|
236275
|
+
if (isAsync2) {
|
|
236276
|
+
stopBackgroundAgentShellsById(agentId);
|
|
236277
|
+
} else {
|
|
236278
|
+
stopOwnedShells();
|
|
236279
|
+
}
|
|
236280
|
+
},
|
|
236281
|
+
() => {
|
|
236282
|
+
if (false) {}
|
|
236283
|
+
},
|
|
236284
|
+
() => {
|
|
236285
|
+
if (isAsync2)
|
|
236286
|
+
unregisterBackgroundAgentAbort(agentId);
|
|
236151
236287
|
}
|
|
236152
|
-
|
|
236153
|
-
await mcpCleanup();
|
|
236154
|
-
if (agentDefinition.hooks) {
|
|
236155
|
-
clearSessionHooks(rootSetAppState, agentId);
|
|
236156
|
-
}
|
|
236157
|
-
if (false) {}
|
|
236158
|
-
agentToolRuntimeContext.readFileState.clear();
|
|
236159
|
-
initialMessages.length = 0;
|
|
236160
|
-
unregisterAgent(agentId);
|
|
236161
|
-
clearAgentTranscriptSubdir(agentId);
|
|
236162
|
-
rootSetAppState((prev) => {
|
|
236163
|
-
if (!(agentId in prev.todos))
|
|
236164
|
-
return prev;
|
|
236165
|
-
const { [agentId]: _removed, ...todos } = prev.todos;
|
|
236166
|
-
return { ...prev, todos };
|
|
236167
|
-
});
|
|
236168
|
-
killShellTasksForAgent(agentId, toolUseContext.getAppState, rootSetAppState);
|
|
236169
|
-
if (false) {}
|
|
236288
|
+
]);
|
|
236170
236289
|
}
|
|
236171
236290
|
}
|
|
236172
236291
|
function filterIncompleteToolCalls(messages) {
|
|
@@ -236238,6 +236357,7 @@ var init_runAgent = __esm(() => {
|
|
|
236238
236357
|
init_config5();
|
|
236239
236358
|
init_permissions2();
|
|
236240
236359
|
init_killShellTasks();
|
|
236360
|
+
init_LocalAgentTask();
|
|
236241
236361
|
init_attachments();
|
|
236242
236362
|
init_errors5();
|
|
236243
236363
|
init_file();
|
|
@@ -257722,6 +257842,75 @@ var init_LocalAgentTask = __esm(() => {
|
|
|
257722
257842
|
backgroundSignalResolvers = new Map;
|
|
257723
257843
|
});
|
|
257724
257844
|
|
|
257845
|
+
// src/session/backgroundTaskScope.ts
|
|
257846
|
+
class BackgroundTaskScope {
|
|
257847
|
+
tasks = new Set;
|
|
257848
|
+
stopPromise;
|
|
257849
|
+
stopped = false;
|
|
257850
|
+
register(task) {
|
|
257851
|
+
let registered = true;
|
|
257852
|
+
const unregister = () => {
|
|
257853
|
+
if (!registered)
|
|
257854
|
+
return;
|
|
257855
|
+
registered = false;
|
|
257856
|
+
this.tasks.delete(task);
|
|
257857
|
+
};
|
|
257858
|
+
this.tasks.add(task);
|
|
257859
|
+
task.settled.then(unregister, unregister);
|
|
257860
|
+
if (this.stopped) {
|
|
257861
|
+
this.stopTask(task).finally(unregister).catch(() => {});
|
|
257862
|
+
}
|
|
257863
|
+
return unregister;
|
|
257864
|
+
}
|
|
257865
|
+
stop() {
|
|
257866
|
+
if (!this.stopPromise) {
|
|
257867
|
+
this.stopPromise = this.drain().finally(() => {
|
|
257868
|
+
this.stopped = true;
|
|
257869
|
+
});
|
|
257870
|
+
}
|
|
257871
|
+
return this.stopPromise;
|
|
257872
|
+
}
|
|
257873
|
+
async drain() {
|
|
257874
|
+
const failures = [];
|
|
257875
|
+
while (this.tasks.size > 0) {
|
|
257876
|
+
const tasks = [...this.tasks];
|
|
257877
|
+
const results = await Promise.allSettled(tasks.map((task) => this.stopTask(task)));
|
|
257878
|
+
for (const result of results) {
|
|
257879
|
+
if (result.status === "rejected")
|
|
257880
|
+
failures.push(result.reason);
|
|
257881
|
+
}
|
|
257882
|
+
for (const task of tasks) {
|
|
257883
|
+
this.tasks.delete(task);
|
|
257884
|
+
}
|
|
257885
|
+
}
|
|
257886
|
+
if (failures.length > 0) {
|
|
257887
|
+
throw new AggregateError(failures, "BackgroundTaskScope cleanup failed");
|
|
257888
|
+
}
|
|
257889
|
+
}
|
|
257890
|
+
async stopTask(task) {
|
|
257891
|
+
try {
|
|
257892
|
+
await task.stop();
|
|
257893
|
+
} finally {
|
|
257894
|
+
await task.settled;
|
|
257895
|
+
}
|
|
257896
|
+
}
|
|
257897
|
+
}
|
|
257898
|
+
function bindBackgroundTaskScope(setAppState, scope) {
|
|
257899
|
+
scopesBySetAppState.set(setAppState, scope);
|
|
257900
|
+
return () => {
|
|
257901
|
+
if (scopesBySetAppState.get(setAppState) === scope) {
|
|
257902
|
+
scopesBySetAppState.delete(setAppState);
|
|
257903
|
+
}
|
|
257904
|
+
};
|
|
257905
|
+
}
|
|
257906
|
+
function getBackgroundTaskScope(setAppState) {
|
|
257907
|
+
return scopesBySetAppState.get(setAppState);
|
|
257908
|
+
}
|
|
257909
|
+
var scopesBySetAppState;
|
|
257910
|
+
var init_backgroundTaskScope = __esm(() => {
|
|
257911
|
+
scopesBySetAppState = new WeakMap;
|
|
257912
|
+
});
|
|
257913
|
+
|
|
257725
257914
|
// src/tasks/LocalShellTask/LocalShellTask.ts
|
|
257726
257915
|
function looksLikePrompt(tail) {
|
|
257727
257916
|
const lastLine = tail.trimEnd().split(`
|
|
@@ -257850,26 +258039,9 @@ async function spawnShellTask(input, context3) {
|
|
|
257850
258039
|
taskOutput
|
|
257851
258040
|
} = shellCommand;
|
|
257852
258041
|
const taskId = taskOutput.taskId;
|
|
257853
|
-
|
|
257854
|
-
|
|
257855
|
-
|
|
257856
|
-
const taskState = {
|
|
257857
|
-
...createTaskStateBase(taskId, "local_bash", description, toolUseId),
|
|
257858
|
-
type: "local_bash",
|
|
257859
|
-
status: "running",
|
|
257860
|
-
command,
|
|
257861
|
-
completionStatusSentInAttachment: false,
|
|
257862
|
-
shellCommand,
|
|
257863
|
-
unregisterCleanup,
|
|
257864
|
-
lastReportedTotalLines: 0,
|
|
257865
|
-
isBackgrounded: true,
|
|
257866
|
-
agentId,
|
|
257867
|
-
kind
|
|
257868
|
-
};
|
|
257869
|
-
registerTask(taskState, setAppState);
|
|
257870
|
-
shellCommand.background(taskId);
|
|
257871
|
-
const cancelStallWatchdog = startStallWatchdog(taskId, description, kind, toolUseId, agentId);
|
|
257872
|
-
shellCommand.result.then(async (result) => {
|
|
258042
|
+
let unregisterCleanup = () => {};
|
|
258043
|
+
let cancelStallWatchdog = () => {};
|
|
258044
|
+
const settled = shellCommand.result.then(async (result) => {
|
|
257873
258045
|
cancelStallWatchdog();
|
|
257874
258046
|
await flushAndCleanup(shellCommand);
|
|
257875
258047
|
let wasKilled = false;
|
|
@@ -257892,12 +258064,43 @@ async function spawnShellTask(input, context3) {
|
|
|
257892
258064
|
});
|
|
257893
258065
|
enqueueShellNotification(taskId, description, wasKilled ? "killed" : result.code === 0 ? "completed" : "failed", result.code, setAppState, toolUseId, kind, agentId);
|
|
257894
258066
|
evictTaskOutput(taskId);
|
|
258067
|
+
}).catch((error41) => {
|
|
258068
|
+
cancelStallWatchdog();
|
|
258069
|
+
logError(error41);
|
|
258070
|
+
}).finally(() => {
|
|
258071
|
+
unregisterCleanup();
|
|
257895
258072
|
});
|
|
258073
|
+
const stopAndSettle = async () => {
|
|
258074
|
+
killTask(taskId, setAppState);
|
|
258075
|
+
await settled;
|
|
258076
|
+
};
|
|
258077
|
+
const cleanupRegistration = () => {
|
|
258078
|
+
unregisterCleanup();
|
|
258079
|
+
};
|
|
258080
|
+
const taskState = {
|
|
258081
|
+
...createTaskStateBase(taskId, "local_bash", description, toolUseId),
|
|
258082
|
+
type: "local_bash",
|
|
258083
|
+
status: "running",
|
|
258084
|
+
command,
|
|
258085
|
+
completionStatusSentInAttachment: false,
|
|
258086
|
+
shellCommand,
|
|
258087
|
+
unregisterCleanup: cleanupRegistration,
|
|
258088
|
+
lastReportedTotalLines: 0,
|
|
258089
|
+
isBackgrounded: true,
|
|
258090
|
+
agentId,
|
|
258091
|
+
kind
|
|
258092
|
+
};
|
|
258093
|
+
registerTask(taskState, setAppState);
|
|
258094
|
+
const owner = getBackgroundTaskScope(setAppState);
|
|
258095
|
+
unregisterCleanup = owner ? owner.register({
|
|
258096
|
+
stop: stopAndSettle,
|
|
258097
|
+
settled
|
|
258098
|
+
}) : registerCleanup(stopAndSettle);
|
|
258099
|
+
shellCommand.background(taskId);
|
|
258100
|
+
cancelStallWatchdog = startStallWatchdog(taskId, description, kind, toolUseId, agentId);
|
|
257896
258101
|
return {
|
|
257897
258102
|
taskId,
|
|
257898
|
-
cleanup:
|
|
257899
|
-
unregisterCleanup();
|
|
257900
|
-
}
|
|
258103
|
+
cleanup: cleanupRegistration
|
|
257901
258104
|
};
|
|
257902
258105
|
}
|
|
257903
258106
|
function registerForeground(input, setAppState, toolUseId) {
|
|
@@ -258026,6 +258229,7 @@ var init_LocalShellTask = __esm(() => {
|
|
|
258026
258229
|
init_LocalAgentTask();
|
|
258027
258230
|
init_killShellTasks();
|
|
258028
258231
|
init_fsOperations();
|
|
258232
|
+
init_backgroundTaskScope();
|
|
258029
258233
|
PROMPT_PATTERNS = [
|
|
258030
258234
|
/\(y\/n\)/i,
|
|
258031
258235
|
/\[y\/n\]/i,
|
|
@@ -280341,6 +280545,9 @@ async function checkPermissionsAndCallTool(tool, toolUseID, input, toolUseContex
|
|
|
280341
280545
|
logError(hookError);
|
|
280342
280546
|
}
|
|
280343
280547
|
}
|
|
280548
|
+
if (toolUseContext.abortController.signal.aborted) {
|
|
280549
|
+
throw new AbortError;
|
|
280550
|
+
}
|
|
280344
280551
|
try {
|
|
280345
280552
|
const result = await tool.call(callInput, {
|
|
280346
280553
|
...toolUseContext,
|
|
@@ -282618,7 +282825,7 @@ function getAnthropicEnvMetadata() {
|
|
|
282618
282825
|
function getBuildAgeMinutes() {
|
|
282619
282826
|
if (false)
|
|
282620
282827
|
;
|
|
282621
|
-
const buildTime = new Date("2026-07-
|
|
282828
|
+
const buildTime = new Date("2026-07-20T09:45:03.714Z").getTime();
|
|
282622
282829
|
if (isNaN(buildTime))
|
|
282623
282830
|
return;
|
|
282624
282831
|
return Math.floor((Date.now() - buildTime) / 60000);
|
|
@@ -329467,8 +329674,9 @@ function registerSdkInlineSkillHandler() {
|
|
|
329467
329674
|
}
|
|
329468
329675
|
|
|
329469
329676
|
// src/session/sdkRuntime.ts
|
|
329470
|
-
init_LocalAgentTask();
|
|
329471
329677
|
init_backgroundAbortRegistry();
|
|
329678
|
+
init_backgroundTaskScope();
|
|
329679
|
+
init_sessionStorage();
|
|
329472
329680
|
init_hooks2();
|
|
329473
329681
|
init_debug();
|
|
329474
329682
|
init_errors5();
|
|
@@ -331711,7 +331919,8 @@ async function stopTask(taskId, context4) {
|
|
|
331711
331919
|
const appState = getAppState();
|
|
331712
331920
|
const task = appState.tasks?.[taskId];
|
|
331713
331921
|
if (!task) {
|
|
331714
|
-
if (
|
|
331922
|
+
if (hasBackgroundAgent(taskId)) {
|
|
331923
|
+
await abortBackgroundAgentById(taskId);
|
|
331715
331924
|
return { taskId, taskType: "local_agent", command: undefined };
|
|
331716
331925
|
}
|
|
331717
331926
|
throw new StopTaskError(`No task found with ID: ${taskId}`, "not_found");
|
|
@@ -331723,7 +331932,11 @@ async function stopTask(taskId, context4) {
|
|
|
331723
331932
|
if (!taskImpl) {
|
|
331724
331933
|
throw new StopTaskError(`Unsupported task type: ${task.type}`, "unsupported_type");
|
|
331725
331934
|
}
|
|
331726
|
-
|
|
331935
|
+
if (task.type === "local_agent" && hasBackgroundAgent(taskId)) {
|
|
331936
|
+
await abortBackgroundAgentById(taskId);
|
|
331937
|
+
} else {
|
|
331938
|
+
await taskImpl.kill(taskId, setAppState);
|
|
331939
|
+
}
|
|
331727
331940
|
if (isLocalShellTask(task)) {
|
|
331728
331941
|
let suppressed = false;
|
|
331729
331942
|
setAppState((prev) => {
|
|
@@ -331765,6 +331978,7 @@ var DESCRIPTION10 = `
|
|
|
331765
331978
|
|
|
331766
331979
|
// src/capabilities/tools/TaskStopTool/TaskStopTool.ts
|
|
331767
331980
|
init_toolUIRegistry();
|
|
331981
|
+
init_backgroundAbortRegistry();
|
|
331768
331982
|
var {
|
|
331769
331983
|
renderToolResultMessage: renderToolResultMessage17,
|
|
331770
331984
|
renderToolUseMessage: renderToolUseMessage17
|
|
@@ -331810,6 +332024,9 @@ var TaskStopTool = buildToolRuntime({
|
|
|
331810
332024
|
const appState = getAppState();
|
|
331811
332025
|
const task = appState.tasks?.[id];
|
|
331812
332026
|
if (!task) {
|
|
332027
|
+
if (hasBackgroundAgent(id)) {
|
|
332028
|
+
return { result: true };
|
|
332029
|
+
}
|
|
331813
332030
|
return {
|
|
331814
332031
|
result: false,
|
|
331815
332032
|
message: `No task found with ID: ${id}`,
|
|
@@ -334757,34 +334974,63 @@ function optionsWithProviderRoutingEnv(options2) {
|
|
|
334757
334974
|
}
|
|
334758
334975
|
return { ...options2, env: mergedEnv };
|
|
334759
334976
|
}
|
|
334760
|
-
function createQueryLike(generator, runtimeState,
|
|
334977
|
+
function createQueryLike(generator, runtimeState, finalize) {
|
|
334978
|
+
let finalizePromise;
|
|
334979
|
+
let closePromise;
|
|
334980
|
+
const finalizeOnce = () => {
|
|
334981
|
+
finalizePromise ??= finalize();
|
|
334982
|
+
return finalizePromise;
|
|
334983
|
+
};
|
|
334984
|
+
const stream4 = async function* () {
|
|
334985
|
+
try {
|
|
334986
|
+
yield* generator;
|
|
334987
|
+
} finally {
|
|
334988
|
+
await finalizeOnce();
|
|
334989
|
+
}
|
|
334990
|
+
}();
|
|
334761
334991
|
return {
|
|
334762
334992
|
[Symbol.asyncIterator]() {
|
|
334763
|
-
return
|
|
334993
|
+
return stream4;
|
|
334764
334994
|
},
|
|
334765
334995
|
async interrupt() {
|
|
334766
334996
|
runtimeState.abortController.abort();
|
|
334767
334997
|
runtimeState.abortController = createAbortController();
|
|
334768
334998
|
},
|
|
334769
334999
|
killAgent(agentId) {
|
|
334770
|
-
abortBackgroundAgentById(agentId);
|
|
334771
|
-
killAsyncAgent(agentId, runtimeState.setAppState);
|
|
335000
|
+
return abortBackgroundAgentById(agentId);
|
|
334772
335001
|
},
|
|
334773
|
-
|
|
334774
|
-
if (
|
|
334775
|
-
|
|
334776
|
-
|
|
334777
|
-
|
|
334778
|
-
|
|
334779
|
-
|
|
334780
|
-
|
|
334781
|
-
|
|
334782
|
-
|
|
334783
|
-
}
|
|
335002
|
+
close() {
|
|
335003
|
+
if (!closePromise) {
|
|
335004
|
+
runtimeState.closed = true;
|
|
335005
|
+
runtimeState.abortController.abort();
|
|
335006
|
+
closePromise = (async () => {
|
|
335007
|
+
try {
|
|
335008
|
+
await stream4.return(undefined);
|
|
335009
|
+
} finally {
|
|
335010
|
+
await finalizeOnce();
|
|
335011
|
+
}
|
|
335012
|
+
})();
|
|
334784
335013
|
}
|
|
335014
|
+
return closePromise;
|
|
334785
335015
|
}
|
|
334786
335016
|
};
|
|
334787
335017
|
}
|
|
335018
|
+
function trackProjectContextId(ownership, sessionId) {
|
|
335019
|
+
ownership.projectContextIds.add(sessionId);
|
|
335020
|
+
if (ownership.kind === "session") {
|
|
335021
|
+
ownership.trackProjectContextId(sessionId);
|
|
335022
|
+
}
|
|
335023
|
+
}
|
|
335024
|
+
async function closeOwnedQueryResources(scope, projectContextIds) {
|
|
335025
|
+
try {
|
|
335026
|
+
await scope.stop();
|
|
335027
|
+
} finally {
|
|
335028
|
+
for (const sessionId of projectContextIds) {
|
|
335029
|
+
clearProjectForSession(sessionId);
|
|
335030
|
+
}
|
|
335031
|
+
projectContextIds.clear();
|
|
335032
|
+
}
|
|
335033
|
+
}
|
|
334788
335034
|
async function* mergeAskWithStatus(askIterable, statusStream) {
|
|
334789
335035
|
const askIter = askIterable[Symbol.asyncIterator]();
|
|
334790
335036
|
let askNext = askIter.next();
|
|
@@ -334817,6 +335063,15 @@ function runSdkQueryRuntime(params) {
|
|
|
334817
335063
|
const cwd = typeof options2.cwd === "string" && options2.cwd.trim().length > 0 ? options2.cwd : process.cwd();
|
|
334818
335064
|
const optionsWithProviderRouting = optionsWithProviderRoutingEnv(options2);
|
|
334819
335065
|
const queryContext = buildQueryContextFromSdk(optionsWithProviderRouting);
|
|
335066
|
+
const ownership = params.resourceOwner ? {
|
|
335067
|
+
...params.resourceOwner,
|
|
335068
|
+
projectContextIds: new Set
|
|
335069
|
+
} : {
|
|
335070
|
+
kind: "standalone",
|
|
335071
|
+
backgroundTaskScope: new BackgroundTaskScope,
|
|
335072
|
+
projectContextIds: new Set
|
|
335073
|
+
};
|
|
335074
|
+
trackProjectContextId(ownership, queryContext.identity.sessionId);
|
|
334820
335075
|
const runtimeState = {
|
|
334821
335076
|
closed: false,
|
|
334822
335077
|
runningTurn: false,
|
|
@@ -334824,6 +335079,7 @@ function runSdkQueryRuntime(params) {
|
|
|
334824
335079
|
};
|
|
334825
335080
|
const fileCheckpointingOnChange = options2.fileCheckpointing?.onFileHistoryChange;
|
|
334826
335081
|
const appStateStore = buildAppStateStore(applyFileCheckpointingInitialState(applyDisallowedTools(applyPermissionMode(getDefaultAppState(), options2.permissionMode), options2.disallowedTools), options2.fileCheckpointing?.initialState), fileCheckpointingOnChange);
|
|
335082
|
+
const releaseBackgroundTaskScope = bindBackgroundTaskScope(appStateStore.setAppState, ownership.backgroundTaskScope);
|
|
334827
335083
|
const initialMessagesForReplay = options2.resume ? loadAndRestampHistoricalMessages(options2.resume, queryContext.identity.sessionId, options2.initialMessages) : options2.initialMessages;
|
|
334828
335084
|
let mutableMessages = normalizeInitialMessages(initialMessagesForReplay);
|
|
334829
335085
|
let readFileCache = createFileStateCacheWithSizeLimit(DEFAULT_READ_FILE_CACHE_SIZE);
|
|
@@ -335066,7 +335322,17 @@ function runSdkQueryRuntime(params) {
|
|
|
335066
335322
|
}
|
|
335067
335323
|
}();
|
|
335068
335324
|
const generator = bindAsyncGeneratorToScope(rawGenerator, queryContext);
|
|
335069
|
-
return createQueryLike(generator, runtimeState)
|
|
335325
|
+
return createQueryLike(generator, runtimeState, async () => {
|
|
335326
|
+
trackProjectContextId(ownership, queryContext.identity.sessionId);
|
|
335327
|
+
releaseBackgroundTaskScope();
|
|
335328
|
+
try {
|
|
335329
|
+
params.onStreamSettled?.();
|
|
335330
|
+
} finally {
|
|
335331
|
+
if (ownership.kind === "standalone") {
|
|
335332
|
+
await closeOwnedQueryResources(ownership.backgroundTaskScope, ownership.projectContextIds);
|
|
335333
|
+
}
|
|
335334
|
+
}
|
|
335335
|
+
});
|
|
335070
335336
|
}
|
|
335071
335337
|
|
|
335072
335338
|
// src/session/runtime.ts
|
|
@@ -335078,6 +335344,8 @@ init_hooks2();
|
|
|
335078
335344
|
init_AppStateStore();
|
|
335079
335345
|
init_debug();
|
|
335080
335346
|
init_errors5();
|
|
335347
|
+
init_backgroundTaskScope();
|
|
335348
|
+
init_sessionStorage();
|
|
335081
335349
|
function mergeTurnOptions(sessionOptions, turnOptions) {
|
|
335082
335350
|
if (!turnOptions)
|
|
335083
335351
|
return sessionOptions;
|
|
@@ -335094,6 +335362,10 @@ function mergeTurnOptions(sessionOptions, turnOptions) {
|
|
|
335094
335362
|
class SessionRuntime {
|
|
335095
335363
|
baseOptions;
|
|
335096
335364
|
closed = false;
|
|
335365
|
+
closePromise;
|
|
335366
|
+
backgroundTaskScope = new BackgroundTaskScope;
|
|
335367
|
+
projectContextIds = new Set;
|
|
335368
|
+
activeQueries = new Set;
|
|
335097
335369
|
accumulatedFileHistory;
|
|
335098
335370
|
constructor(options2) {
|
|
335099
335371
|
this.baseOptions = options2;
|
|
@@ -335117,13 +335389,34 @@ class SessionRuntime {
|
|
|
335117
335389
|
}
|
|
335118
335390
|
}
|
|
335119
335391
|
} : undefined;
|
|
335120
|
-
|
|
335392
|
+
let query2;
|
|
335393
|
+
query2 = runSdkQueryRuntime({
|
|
335121
335394
|
prompt: params.prompt,
|
|
335122
335395
|
options: {
|
|
335123
335396
|
...merged,
|
|
335124
335397
|
...fileCheckpointing ? { fileCheckpointing } : {}
|
|
335398
|
+
},
|
|
335399
|
+
resourceOwner: {
|
|
335400
|
+
kind: "session",
|
|
335401
|
+
backgroundTaskScope: this.backgroundTaskScope,
|
|
335402
|
+
trackProjectContextId: (sessionId) => {
|
|
335403
|
+
this.projectContextIds.add(sessionId);
|
|
335404
|
+
}
|
|
335405
|
+
},
|
|
335406
|
+
onStreamSettled: () => {
|
|
335407
|
+
this.activeQueries.delete(query2);
|
|
335125
335408
|
}
|
|
335126
335409
|
});
|
|
335410
|
+
this.activeQueries.add(query2);
|
|
335411
|
+
const closeQuery = query2.close.bind(query2);
|
|
335412
|
+
query2.close = async () => {
|
|
335413
|
+
try {
|
|
335414
|
+
await closeQuery();
|
|
335415
|
+
} finally {
|
|
335416
|
+
this.activeQueries.delete(query2);
|
|
335417
|
+
}
|
|
335418
|
+
};
|
|
335419
|
+
return query2;
|
|
335127
335420
|
}
|
|
335128
335421
|
async prompt(message, options2) {
|
|
335129
335422
|
const q = this.query({ prompt: message, options: options2 });
|
|
@@ -335138,32 +335431,66 @@ class SessionRuntime {
|
|
|
335138
335431
|
async getInfo() {
|
|
335139
335432
|
return;
|
|
335140
335433
|
}
|
|
335141
|
-
|
|
335142
|
-
if (this.
|
|
335143
|
-
|
|
335144
|
-
|
|
335145
|
-
|
|
335146
|
-
|
|
335147
|
-
|
|
335148
|
-
|
|
335149
|
-
|
|
335150
|
-
|
|
335151
|
-
|
|
335152
|
-
|
|
335434
|
+
close(reason = "normal") {
|
|
335435
|
+
if (!this.closePromise) {
|
|
335436
|
+
this.closed = true;
|
|
335437
|
+
this.closePromise = this.closeResources(reason);
|
|
335438
|
+
}
|
|
335439
|
+
return this.closePromise;
|
|
335440
|
+
}
|
|
335441
|
+
async closeResources(reason) {
|
|
335442
|
+
const failures = [];
|
|
335443
|
+
try {
|
|
335444
|
+
const activeQueries = [...this.activeQueries];
|
|
335445
|
+
const queryResults = await Promise.allSettled(activeQueries.map(async (query2) => {
|
|
335446
|
+
await query2.close();
|
|
335447
|
+
}));
|
|
335448
|
+
for (const result of queryResults) {
|
|
335449
|
+
if (result.status === "rejected")
|
|
335450
|
+
failures.push(result.reason);
|
|
335153
335451
|
}
|
|
335154
|
-
|
|
335452
|
+
this.activeQueries.clear();
|
|
335155
335453
|
try {
|
|
335156
|
-
await
|
|
335157
|
-
|
|
335158
|
-
|
|
335159
|
-
|
|
335160
|
-
|
|
335161
|
-
|
|
335454
|
+
await this.backgroundTaskScope.stop();
|
|
335455
|
+
} catch (err2) {
|
|
335456
|
+
failures.push(err2);
|
|
335457
|
+
}
|
|
335458
|
+
try {
|
|
335459
|
+
const ctx = buildRewindQueryContext(this.baseOptions);
|
|
335460
|
+
this.projectContextIds.add(ctx.identity.sessionId);
|
|
335461
|
+
await runWithQueryContext(ctx, async () => {
|
|
335462
|
+
if (this.baseOptions.hooks) {
|
|
335463
|
+
try {
|
|
335464
|
+
registerHookCallbacks2(this.baseOptions.hooks);
|
|
335465
|
+
} catch (err2) {
|
|
335466
|
+
logForDebugging(`SessionRuntime.close: registerHookCallbacks threw: ${errorMessage(err2)}`, { level: "warn" });
|
|
335467
|
+
}
|
|
335468
|
+
}
|
|
335469
|
+
let state3 = getDefaultAppState();
|
|
335470
|
+
try {
|
|
335471
|
+
await executeSessionEndHooks(reason, {
|
|
335472
|
+
getAppState: () => state3,
|
|
335473
|
+
setAppState: (updater) => {
|
|
335474
|
+
state3 = updater(state3);
|
|
335475
|
+
},
|
|
335476
|
+
timeoutMs: getSessionEndHookTimeoutMs()
|
|
335477
|
+
});
|
|
335478
|
+
} catch (err2) {
|
|
335479
|
+
logForDebugging(`SessionRuntime.close: SessionEnd hooks errored: ${errorMessage(err2)}`, { level: "warn" });
|
|
335480
|
+
}
|
|
335162
335481
|
});
|
|
335163
335482
|
} catch (err2) {
|
|
335164
|
-
logForDebugging(`SessionRuntime.close: SessionEnd
|
|
335483
|
+
logForDebugging(`SessionRuntime.close: SessionEnd context errored: ${errorMessage(err2)}`, { level: "warn" });
|
|
335165
335484
|
}
|
|
335166
|
-
}
|
|
335485
|
+
} finally {
|
|
335486
|
+
for (const sessionId of this.projectContextIds) {
|
|
335487
|
+
clearProjectForSession(sessionId);
|
|
335488
|
+
}
|
|
335489
|
+
this.projectContextIds.clear();
|
|
335490
|
+
}
|
|
335491
|
+
if (failures.length > 0) {
|
|
335492
|
+
throw new AggregateError(failures, "SessionRuntime cleanup failed");
|
|
335493
|
+
}
|
|
335167
335494
|
}
|
|
335168
335495
|
canRewindFiles(state3, messageUuid) {
|
|
335169
335496
|
const effective = this.accumulatedFileHistory ?? state3;
|
|
@@ -336140,4 +336467,4 @@ export {
|
|
|
336140
336467
|
AbortError2 as AbortError
|
|
336141
336468
|
};
|
|
336142
336469
|
|
|
336143
|
-
//# debugId=
|
|
336470
|
+
//# debugId=96A7445415A37CC164756E2164756E21
|