@astralyn/pi 0.87.2 → 0.87.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +10 -0
- package/dist/bundle/chunks/{chunk-NBIUJDV6.js → chunk-MJ45I4SM.js} +1 -1
- package/dist/bundle/chunks/{chunk-RFLBIA5Z.js → chunk-TYOQD6VQ.js} +33 -20
- package/dist/bundle/chunks/{virtual-modules-GOHLE5JL.js → virtual-modules-NDGCHNG7.js} +1 -1
- package/dist/bundle/cli.js +1 -1
- package/dist/bundle/index.js +1 -1
- package/dist/bundle/rpc-entry.js +1 -1
- package/dist/core/tools/tool-definition-wrapper.d.ts.map +1 -1
- package/dist/core/tools/tool-definition-wrapper.js +114 -1
- package/dist/core/tools/tool-definition-wrapper.js.map +1 -1
- package/dist/extensions/background/actions.d.ts.map +1 -1
- package/dist/extensions/background/actions.js +107 -55
- package/dist/extensions/background/actions.js.map +1 -1
- package/dist/extensions/background/index.js +3 -3
- package/dist/extensions/background/index.js.map +1 -1
- package/dist/extensions/question/index.d.ts.map +1 -1
- package/dist/extensions/question/index.js +3 -1
- package/dist/extensions/question/index.js.map +1 -1
- package/dist/extensions/question/schema.d.ts +18 -0
- package/dist/extensions/question/schema.d.ts.map +1 -1
- package/dist/extensions/question/schema.js +52 -0
- package/dist/extensions/question/schema.js.map +1 -1
- package/dist/extensions/subagent/index.d.ts.map +1 -1
- package/dist/extensions/subagent/index.js +3 -1
- package/dist/extensions/subagent/index.js.map +1 -1
- package/dist/extensions/subagent/resolve.d.ts +14 -1
- package/dist/extensions/subagent/resolve.d.ts.map +1 -1
- package/dist/extensions/subagent/resolve.js +32 -18
- package/dist/extensions/subagent/resolve.js.map +1 -1
- package/dist/extensions/subagent/runner.d.ts.map +1 -1
- package/dist/extensions/subagent/runner.js +4 -1
- package/dist/extensions/subagent/runner.js.map +1 -1
- package/dist/extensions/subagent/schema.d.ts +9 -0
- package/dist/extensions/subagent/schema.d.ts.map +1 -1
- package/dist/extensions/subagent/schema.js +30 -1
- package/dist/extensions/subagent/schema.js.map +1 -1
- package/dist/extensions/subagent/types.d.ts +2 -0
- package/dist/extensions/subagent/types.d.ts.map +1 -1
- package/dist/extensions/subagent/types.js.map +1 -1
- package/dist/extensions/todo/constants.d.ts +1 -1
- package/dist/extensions/todo/constants.d.ts.map +1 -1
- package/dist/extensions/todo/constants.js +8 -8
- package/dist/extensions/todo/constants.js.map +1 -1
- package/dist/extensions/todo/index.d.ts.map +1 -1
- package/dist/extensions/todo/index.js +1 -0
- package/dist/extensions/todo/index.js.map +1 -1
- package/dist/extensions/todo/schema.d.ts +30 -25
- package/dist/extensions/todo/schema.d.ts.map +1 -1
- package/dist/extensions/todo/schema.js +26 -20
- package/dist/extensions/todo/schema.js.map +1 -1
- package/dist/extensions/todo/state.d.ts +12 -8
- package/dist/extensions/todo/state.d.ts.map +1 -1
- package/dist/extensions/todo/state.js +255 -171
- package/dist/extensions/todo/state.js.map +1 -1
- package/dist/extensions/todo/view.d.ts +6 -2
- package/dist/extensions/todo/view.d.ts.map +1 -1
- package/dist/extensions/todo/view.js +234 -144
- package/dist/extensions/todo/view.js.map +1 -1
- package/docs/bundled/extensions/background.md +1 -1
- package/docs/bundled/extensions/question.md +1 -0
- package/docs/bundled/extensions/subagent.md +3 -1
- package/docs/bundled/extensions/todo.md +35 -23
- package/docs/extensions.md +2 -0
- package/npm-shrinkwrap.json +2 -2
- package/package.json +1 -1
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
import { createRequire as __piCreateRequire } from "node:module"; const require = __piCreateRequire(import.meta.url);
|
|
2
|
-
import{dist_exports as dist_exports3}from"./chunk-
|
|
2
|
+
import{dist_exports as dist_exports3}from"./chunk-MJ45I4SM.js";import{DISTRIBUTION_PACKAGE_NAME,all_exports,build_exports,compat_exports,compile_exports,dist_exports,dist_exports2,value_exports}from"./chunk-TYOQD6VQ.js";import"./chunk-JEIV47WR.js";import"./chunk-5FDOJRDS.js";import"./chunk-5B3S5DVL.js";import"./chunk-2IO5GDBS.js";import"./chunk-JI4WGISU.js";import"./chunk-4L3WN2XY.js";var oauth_exports={};var VIRTUAL_MODULES={typebox:build_exports,"typebox/compile":compile_exports,"typebox/value":value_exports,"@sinclair/typebox":build_exports,"@sinclair/typebox/compile":compile_exports,"@sinclair/typebox/value":value_exports,"@earendil-works/pi-agent-core":dist_exports2,"@earendil-works/pi-tui":dist_exports,"@earendil-works/pi-ai":compat_exports,"@earendil-works/pi-ai/compat":compat_exports,"@earendil-works/pi-ai/oauth":oauth_exports,"@earendil-works/pi-ai/providers/all":all_exports,"@earendil-works/pi-coding-agent":dist_exports3,[DISTRIBUTION_PACKAGE_NAME]:dist_exports3,"@mariozechner/pi-agent-core":dist_exports2,"@mariozechner/pi-tui":dist_exports,"@mariozechner/pi-ai":compat_exports,"@mariozechner/pi-ai/compat":compat_exports,"@mariozechner/pi-ai/oauth":oauth_exports,"@mariozechner/pi-ai/providers/all":all_exports,"@mariozechner/pi-coding-agent":dist_exports3};export{VIRTUAL_MODULES};
|
package/dist/bundle/cli.js
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
2
|
import { createRequire as __piCreateRequire } from "node:module"; const require = __piCreateRequire(import.meta.url);
|
|
3
|
-
import{APP_NAME,configureHttpDispatcher,main}from"./chunks/chunk-
|
|
3
|
+
import{APP_NAME,configureHttpDispatcher,main}from"./chunks/chunk-TYOQD6VQ.js";import"./chunks/chunk-JEIV47WR.js";import"./chunks/chunk-5FDOJRDS.js";import"./chunks/chunk-5B3S5DVL.js";import"./chunks/chunk-2IO5GDBS.js";import"./chunks/chunk-JI4WGISU.js";import"./chunks/chunk-4L3WN2XY.js";function setupCli(){process.title=APP_NAME,process.env.PI_CODING_AGENT="true",process.env.AI_AGENT="pi",process.emitWarning=(()=>{}),configureHttpDispatcher()}setupCli();main(process.argv.slice(2));
|
package/dist/bundle/index.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
import { createRequire as __piCreateRequire } from "node:module"; const require = __piCreateRequire(import.meta.url);
|
|
2
|
-
import{ShowImagesSelectorComponent,ThemeSelectorComponent}from"./chunks/chunk-
|
|
2
|
+
import{ShowImagesSelectorComponent,ThemeSelectorComponent}from"./chunks/chunk-MJ45I4SM.js";import{AgentSession,AgentSessionRuntime,ArminComponent,AssistantMessageComponent,BackgroundService,BashExecutionComponent,BorderedLoader,BranchSummaryMessageComponent,CONFIG_DIR_NAME,CURRENT_SESSION_VERSION,CompactionSummaryMessageComponent,CredentialSynchronizationError,CustomEditor,CustomMessageComponent,DEFAULT_COMPACTION_SETTINGS,DEFAULT_MAX_BYTES,DEFAULT_MAX_LINES,DefaultPackageManager,DefaultResourceLoader,DynamicBorder,ExtensionEditorComponent,ExtensionInputComponent,ExtensionRunner,ExtensionSelectorComponent,FooterComponent,InteractiveMode,LoginDialogComponent,ModelRegistry,ModelRuntime,ModelSelectorComponent,OAuthSelectorComponent,ProjectTrustStore,RpcClient,SessionManager,SessionSelectorComponent,SettingsManager,SettingsSelectorComponent,SkillInvocationMessageComponent,Theme,ThinkingSelectorComponent,ToolExecutionComponent,TreeSelectorComponent,UserMessageComponent,UserMessageSelectorComponent,VERSION,buildContextEntries,buildSessionContext,buildSessionProjection,calculateContextTokens,collectEntriesForBranchSummary,compact,convertToLlm,convertToPng,copyToClipboard,createAgentSession,createAgentSessionFromServices,createAgentSessionRuntime,createAgentSessionServices,createBashTool,createBashToolDefinition,createCodingTools,createEditTool,createEditToolDefinition,createEventBus,createExtensionRuntime,createFindTool,createFindToolDefinition,createGrepTool,createGrepToolDefinition,createLocalBashOperations,createLocalPowerShellOperations,createLsTool,createLsToolDefinition,createPowerShellTool,createPowerShellToolDefinition,createReadOnlyTools,createReadTool,createReadToolDefinition,createSyntheticSourceInfo,createWriteTool,createWriteToolDefinition,defineTool,detectSupportedImageMimeTypeFromFile,discoverAndLoadExtensions,estimateTokens,findCutPoint,findTurnStartIndex,formatDimensionNote,formatSize,formatSkillsForPrompt,generateBranchSummary,generateDiffString,generateSummary,generateSummaryWithUsage,generateUnifiedPatch,getAgentDir,getDocsPath,getExamplesPath,getLanguageFromPath,getLastAssistantUsage,getLatestCompactionEntry,getMarkdownTheme,getPackageDir,getPowerShellConfig,getReadmePath,getSelectListTheme,getSettingsListTheme,getShellConfig,hasTrustRequiringProjectResources,highlightCode,initTheme,isBashToolResult,isEditToolResult,isFindToolResult,isGrepToolResult,isLsToolResult,isPowerShellToolResult,isReadToolResult,isToolCallEventType,isWriteToolResult,keyHint,keyText,loadProjectContextFiles,loadSkills,loadSkillsFromDir,main,migrateSessionEntries,parseArgs,parseFrontmatter,parseSessionEntries,parseSkillBlock,prepareBranchEntries,rawKeyHint,readStoredCredential,renderDiff,resizeImage,resolveCliModel,resolveModelScopeWithDiagnostics,runPrintMode,runRpcMode,serializeConversation,sessionEntryToContextMessages,shouldCompact,stripFrontmatter,truncateHead,truncateLine,truncateTail,truncateToVisualLines,withFileMutationQueue,wrapRegisteredTool,wrapRegisteredTools}from"./chunks/chunk-TYOQD6VQ.js";import"./chunks/chunk-JEIV47WR.js";import"./chunks/chunk-5FDOJRDS.js";import"./chunks/chunk-5B3S5DVL.js";import"./chunks/chunk-2IO5GDBS.js";import"./chunks/chunk-JI4WGISU.js";import"./chunks/chunk-4L3WN2XY.js";export{AgentSession,AgentSessionRuntime,ArminComponent,AssistantMessageComponent,BackgroundService,BashExecutionComponent,BorderedLoader,BranchSummaryMessageComponent,CONFIG_DIR_NAME,CURRENT_SESSION_VERSION,CompactionSummaryMessageComponent,CredentialSynchronizationError,CustomEditor,CustomMessageComponent,DEFAULT_COMPACTION_SETTINGS,DEFAULT_MAX_BYTES,DEFAULT_MAX_LINES,DefaultPackageManager,DefaultResourceLoader,DynamicBorder,ExtensionEditorComponent,ExtensionInputComponent,ExtensionRunner,ExtensionSelectorComponent,FooterComponent,InteractiveMode,LoginDialogComponent,ModelRegistry,ModelRuntime,ModelSelectorComponent,OAuthSelectorComponent,ProjectTrustStore,RpcClient,SessionManager,SessionSelectorComponent,SettingsManager,SettingsSelectorComponent,ShowImagesSelectorComponent,SkillInvocationMessageComponent,Theme,ThemeSelectorComponent,ThinkingSelectorComponent,ToolExecutionComponent,TreeSelectorComponent,UserMessageComponent,UserMessageSelectorComponent,VERSION,buildContextEntries,buildSessionContext,buildSessionProjection,calculateContextTokens,collectEntriesForBranchSummary,compact,convertToLlm,convertToPng,copyToClipboard,createAgentSession,createAgentSessionFromServices,createAgentSessionRuntime,createAgentSessionServices,createBashTool,createBashToolDefinition,createCodingTools,createEditTool,createEditToolDefinition,createEventBus,createExtensionRuntime,createFindTool,createFindToolDefinition,createGrepTool,createGrepToolDefinition,createLocalBashOperations,createLocalPowerShellOperations,createLsTool,createLsToolDefinition,createPowerShellTool,createPowerShellToolDefinition,createReadOnlyTools,createReadTool,createReadToolDefinition,createSyntheticSourceInfo,createWriteTool,createWriteToolDefinition,defineTool,detectSupportedImageMimeTypeFromFile,discoverAndLoadExtensions,estimateTokens,findCutPoint,findTurnStartIndex,formatDimensionNote,formatSize,formatSkillsForPrompt,generateBranchSummary,generateDiffString,generateSummary,generateSummaryWithUsage,generateUnifiedPatch,getAgentDir,getDocsPath,getExamplesPath,getLanguageFromPath,getLastAssistantUsage,getLatestCompactionEntry,getMarkdownTheme,getPackageDir,getPowerShellConfig,getReadmePath,getSelectListTheme,getSettingsListTheme,getShellConfig,hasTrustRequiringProjectResources,highlightCode,initTheme,isBashToolResult,isEditToolResult,isFindToolResult,isGrepToolResult,isLsToolResult,isPowerShellToolResult,isReadToolResult,isToolCallEventType,isWriteToolResult,keyHint,keyText,loadProjectContextFiles,loadSkills,loadSkillsFromDir,main,migrateSessionEntries,parseArgs,parseFrontmatter,parseSessionEntries,parseSkillBlock,prepareBranchEntries,rawKeyHint,readStoredCredential,renderDiff,resizeImage,resolveCliModel,resolveModelScopeWithDiagnostics,runPrintMode,runRpcMode,serializeConversation,sessionEntryToContextMessages,shouldCompact,stripFrontmatter,truncateHead,truncateLine,truncateTail,truncateToVisualLines,withFileMutationQueue,wrapRegisteredTool,wrapRegisteredTools};
|
package/dist/bundle/rpc-entry.js
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
2
|
import { createRequire as __piCreateRequire } from "node:module"; const require = __piCreateRequire(import.meta.url);
|
|
3
|
-
import{APP_NAME,configureHttpDispatcher,main}from"./chunks/chunk-
|
|
3
|
+
import{APP_NAME,configureHttpDispatcher,main}from"./chunks/chunk-TYOQD6VQ.js";import"./chunks/chunk-JEIV47WR.js";import"./chunks/chunk-5FDOJRDS.js";import"./chunks/chunk-5B3S5DVL.js";import"./chunks/chunk-2IO5GDBS.js";import"./chunks/chunk-JI4WGISU.js";import"./chunks/chunk-4L3WN2XY.js";process.title=`${APP_NAME}-rpc`;process.env.PI_CODING_AGENT="true";process.env.AI_AGENT="pi";process.emitWarning=(()=>{});configureHttpDispatcher();main(["--mode","rpc",...process.argv.slice(2)]);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"tool-definition-wrapper.d.ts","sourceRoot":"","sources":["../../../src/core/tools/tool-definition-wrapper.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,+BAA+B,CAAC;
|
|
1
|
+
{"version":3,"file":"tool-definition-wrapper.d.ts","sourceRoot":"","sources":["../../../src/core/tools/tool-definition-wrapper.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,+BAA+B,CAAC;AAE/D,OAAO,KAAK,EAAU,OAAO,EAAE,MAAM,SAAS,CAAC;AAC/C,OAAO,KAAK,EAAE,gBAAgB,EAAE,cAAc,EAAE,MAAM,wBAAwB,CAAC;AAG/E,KAAK,oBAAoB,CAAC,OAAO,SAAS,OAAO,GAAG,OAAO,EAAE,QAAQ,GAAG,OAAO,IAAI,SAAS,CAAC,OAAO,EAAE,QAAQ,CAAC,GAAG;IACjH,SAAS,CAAC,EAAE,MAAM,CAAC;CACnB,CAAC;AAmHF,oEAAoE;AACpE,wBAAgB,kBAAkB,CAAC,OAAO,SAAS,OAAO,EAAE,QAAQ,GAAG,OAAO,EAC7E,UAAU,EAAE,cAAc,CAAC,OAAO,EAAE,QAAQ,CAAC,EAC7C,UAAU,CAAC,EAAE,MAAM,gBAAgB,GACjC,oBAAoB,CAAC,OAAO,EAAE,QAAQ,CAAC,CAazC;AAED,0EAA0E;AAC1E,wBAAgB,mBAAmB,CAClC,WAAW,EAAE,cAAc,CAAC,GAAG,EAAE,GAAG,CAAC,EAAE,EACvC,UAAU,CAAC,EAAE,MAAM,gBAAgB,GACjC,SAAS,CAAC,GAAG,CAAC,EAAE,CAElB;AAED;;;;;GAKG;AACH,wBAAgB,iCAAiC,CAAC,OAAO,SAAS,OAAO,EAAE,QAAQ,EAClF,IAAI,EAAE,oBAAoB,CAAC,OAAO,EAAE,QAAQ,CAAC,GAC3C,cAAc,CAAC,OAAO,EAAE,QAAQ,CAAC,CAYnC"}
|
|
@@ -1,3 +1,116 @@
|
|
|
1
|
+
import { validateToolArguments } from "@earendil-works/pi-ai";
|
|
2
|
+
import { truncateHead } from "./truncate.js";
|
|
3
|
+
const RECEIVED_ARGUMENTS_MARKER = "\n\nReceived arguments:\n";
|
|
4
|
+
const HINT_MARKER = "\n\nHint: ";
|
|
5
|
+
const RECEIVED_ARGUMENTS_MAX_BYTES = 2 * 1024;
|
|
6
|
+
const RECEIVED_ARGUMENTS_MAX_LINES = 40;
|
|
7
|
+
const FIELD_HINTS_MAX = 10;
|
|
8
|
+
function isRecord(value) {
|
|
9
|
+
return value !== null && typeof value === "object" && !Array.isArray(value);
|
|
10
|
+
}
|
|
11
|
+
/**
|
|
12
|
+
* Walk schema and arguments in sync to name, at every object with
|
|
13
|
+
* `additionalProperties: false`, the non-null fields the schema does not
|
|
14
|
+
* declare, and at every object, the required fields the arguments lack. The
|
|
15
|
+
* validator's own report says where validation failed; these hints say what
|
|
16
|
+
* the legal shape is. Paths use the validator's dotted style
|
|
17
|
+
* (`tasks[0].prompt`). Non-null unknown fields are reported rather than
|
|
18
|
+
* silently dropped: a field like `prompt_extra` may carry briefing content
|
|
19
|
+
* the caller intended to send.
|
|
20
|
+
*/
|
|
21
|
+
function collectFieldHints(schema, args) {
|
|
22
|
+
const hints = [];
|
|
23
|
+
const visit = (node, value, path) => {
|
|
24
|
+
if (hints.length >= FIELD_HINTS_MAX || !isRecord(node))
|
|
25
|
+
return;
|
|
26
|
+
if (node.type === "array" && Array.isArray(value)) {
|
|
27
|
+
for (let index = 0; index < value.length; index++) {
|
|
28
|
+
visit(node.items, value[index], `${path}[${index}]`);
|
|
29
|
+
}
|
|
30
|
+
return;
|
|
31
|
+
}
|
|
32
|
+
if (node.type !== "object" || !isRecord(value))
|
|
33
|
+
return;
|
|
34
|
+
const properties = isRecord(node.properties) ? node.properties : {};
|
|
35
|
+
const fields = Object.keys(properties);
|
|
36
|
+
const where = path || "root";
|
|
37
|
+
if (node.additionalProperties === false) {
|
|
38
|
+
for (const [key, entry] of Object.entries(value)) {
|
|
39
|
+
if (entry !== null && !(key in properties) && hints.length < FIELD_HINTS_MAX) {
|
|
40
|
+
const subject = path ? `${path}.${key}` : key;
|
|
41
|
+
hints.push(`${subject} is not a field; fields at ${where}: ${fields.join(", ")}`);
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
if (Array.isArray(node.required)) {
|
|
46
|
+
for (const key of node.required) {
|
|
47
|
+
if (typeof key === "string" && value[key] === undefined && hints.length < FIELD_HINTS_MAX) {
|
|
48
|
+
const subject = path ? `${path}.${key}` : key;
|
|
49
|
+
hints.push(`${subject} is required; fields at ${where}: ${fields.join(", ")}`);
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
for (const key of fields) {
|
|
54
|
+
if (value[key] !== undefined && value[key] !== null) {
|
|
55
|
+
visit(properties[key], value[key], path ? `${path}.${key}` : key);
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
};
|
|
59
|
+
visit(schema, args, "");
|
|
60
|
+
return hints;
|
|
61
|
+
}
|
|
62
|
+
/**
|
|
63
|
+
* Rebuild pi-ai's validation error so a model can self-correct: the legal
|
|
64
|
+
* fields are named next to each offending one, and the echoed arguments are
|
|
65
|
+
* bounded (a 50KB subagent prompt must not be reflected whole into context).
|
|
66
|
+
* The `Validation failed for tool "<name>":` prefix stays intact — the
|
|
67
|
+
* question tool's renderer parses it.
|
|
68
|
+
*/
|
|
69
|
+
function enrichValidationError(error, parameters, args) {
|
|
70
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
71
|
+
// A definition synthesized from an already-wrapped tool enriches on the
|
|
72
|
+
// inside; do not stack a second layer of hints on the same failure.
|
|
73
|
+
if (message.includes(HINT_MARKER))
|
|
74
|
+
return error instanceof Error ? error : new Error(message);
|
|
75
|
+
const hints = collectFieldHints(parameters, args);
|
|
76
|
+
const markerIndex = message.indexOf(RECEIVED_ARGUMENTS_MARKER);
|
|
77
|
+
const head = markerIndex === -1 ? message : message.slice(0, markerIndex);
|
|
78
|
+
const received = markerIndex === -1 ? "" : message.slice(markerIndex + RECEIVED_ARGUMENTS_MARKER.length);
|
|
79
|
+
let enriched = hints.length > 0 ? `${head}\n\nHint: ${hints.join("\nHint: ")}` : head;
|
|
80
|
+
if (markerIndex !== -1) {
|
|
81
|
+
const bounded = truncateHead(received, {
|
|
82
|
+
maxBytes: RECEIVED_ARGUMENTS_MAX_BYTES,
|
|
83
|
+
maxLines: RECEIVED_ARGUMENTS_MAX_LINES,
|
|
84
|
+
});
|
|
85
|
+
enriched += `${RECEIVED_ARGUMENTS_MARKER}${bounded.content}`;
|
|
86
|
+
if (bounded.truncated)
|
|
87
|
+
enriched += "\n… (arguments truncated)";
|
|
88
|
+
}
|
|
89
|
+
return new Error(enriched);
|
|
90
|
+
}
|
|
91
|
+
/**
|
|
92
|
+
* Pre-validate prepared arguments so a validation failure reaches the model
|
|
93
|
+
* with field-level hints. Valid arguments pass through untouched and are
|
|
94
|
+
* validated again by the agent loop as before.
|
|
95
|
+
*/
|
|
96
|
+
function wrapPrepareArguments(definition) {
|
|
97
|
+
const tool = { name: definition.name, description: definition.description, parameters: definition.parameters };
|
|
98
|
+
return (raw) => {
|
|
99
|
+
const args = definition.prepareArguments ? definition.prepareArguments(raw) : raw;
|
|
100
|
+
try {
|
|
101
|
+
validateToolArguments(tool, {
|
|
102
|
+
type: "toolCall",
|
|
103
|
+
id: "",
|
|
104
|
+
name: definition.name,
|
|
105
|
+
arguments: args,
|
|
106
|
+
});
|
|
107
|
+
}
|
|
108
|
+
catch (error) {
|
|
109
|
+
throw enrichValidationError(error, definition.parameters, args);
|
|
110
|
+
}
|
|
111
|
+
return args;
|
|
112
|
+
};
|
|
113
|
+
}
|
|
1
114
|
/** Wrap a ToolDefinition into an AgentTool for the core runtime. */
|
|
2
115
|
export function wrapToolDefinition(definition, ctxFactory) {
|
|
3
116
|
return {
|
|
@@ -7,7 +120,7 @@ export function wrapToolDefinition(definition, ctxFactory) {
|
|
|
7
120
|
parameters: definition.parameters,
|
|
8
121
|
constrainedSampling: definition.constrainedSampling,
|
|
9
122
|
toolGroup: definition.toolGroup,
|
|
10
|
-
prepareArguments: definition
|
|
123
|
+
prepareArguments: wrapPrepareArguments(definition),
|
|
11
124
|
executionMode: definition.executionMode,
|
|
12
125
|
execute: (toolCallId, params, signal, onUpdate, ctx) => definition.execute(toolCallId, params, signal, onUpdate, ctx ?? ctxFactory?.()),
|
|
13
126
|
};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"tool-definition-wrapper.js","sourceRoot":"","sources":["../../../src/core/tools/tool-definition-wrapper.ts"],"names":[],"mappings":"AAQA,oEAAoE;AACpE,MAAM,UAAU,kBAAkB,CACjC,UAA6C,EAC7C,UAAmC;IAEnC,OAAO;QACN,IAAI,EAAE,UAAU,CAAC,IAAI;QACrB,KAAK,EAAE,UAAU,CAAC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type { AgentTool } from \"@earendil-works/pi-agent-core\";\nimport type { TSchema } from \"typebox\";\nimport type { ExtensionContext, ToolDefinition } from \"../extensions/types.ts\";\n\ntype PresentableAgentTool<TParams extends TSchema = TSchema, TDetails = unknown> = AgentTool<TParams, TDetails> & {\n\ttoolGroup?: string;\n};\n\n/** Wrap a ToolDefinition into an AgentTool for the core runtime. */\nexport function wrapToolDefinition<TParams extends TSchema, TDetails = unknown>(\n\tdefinition: ToolDefinition<TParams, TDetails>,\n\tctxFactory?: () => ExtensionContext,\n): PresentableAgentTool<TParams, TDetails> {\n\treturn {\n\t\tname: definition.name,\n\t\tlabel: definition.label,\n\t\tdescription: definition.description,\n\t\tparameters: definition.parameters,\n\t\tconstrainedSampling: definition.constrainedSampling,\n\t\ttoolGroup: definition.toolGroup,\n\t\tprepareArguments: definition.prepareArguments,\n\t\texecutionMode: definition.executionMode,\n\t\texecute: (toolCallId, params, signal, onUpdate, ctx?: ExtensionContext) =>\n\t\t\tdefinition.execute(toolCallId, params, signal, onUpdate, ctx ?? (ctxFactory?.() as ExtensionContext)),\n\t};\n}\n\n/** Wrap multiple ToolDefinitions into AgentTools for the core runtime. */\nexport function wrapToolDefinitions(\n\tdefinitions: ToolDefinition<any, any>[],\n\tctxFactory?: () => ExtensionContext,\n): AgentTool<any>[] {\n\treturn definitions.map((definition) => wrapToolDefinition(definition, ctxFactory));\n}\n\n/**\n * Synthesize a minimal ToolDefinition from an AgentTool.\n *\n * This keeps AgentSession's internal registry definition-first even when a caller\n * provides plain AgentTool overrides that do not include prompt metadata or renderers.\n */\nexport function createToolDefinitionFromAgentTool<TParams extends TSchema, TDetails>(\n\ttool: PresentableAgentTool<TParams, TDetails>,\n): ToolDefinition<TParams, TDetails> {\n\treturn {\n\t\tname: tool.name,\n\t\tlabel: tool.label,\n\t\tdescription: tool.description,\n\t\tparameters: tool.parameters,\n\t\tconstrainedSampling: tool.constrainedSampling,\n\t\ttoolGroup: tool.toolGroup,\n\t\tprepareArguments: tool.prepareArguments,\n\t\texecutionMode: tool.executionMode,\n\t\texecute: async (toolCallId, params, signal, onUpdate) => tool.execute(toolCallId, params, signal, onUpdate),\n\t};\n}\n"]}
|
|
1
|
+
{"version":3,"file":"tool-definition-wrapper.js","sourceRoot":"","sources":["../../../src/core/tools/tool-definition-wrapper.ts"],"names":[],"mappings":"AACA,OAAO,EAAmB,qBAAqB,EAAE,MAAM,uBAAuB,CAAC;AAG/E,OAAO,EAAE,YAAY,EAAE,MAAM,eAAe,CAAC;AAM7C,MAAM,yBAAyB,GAAG,2BAA2B,CAAC;AAC9D,MAAM,WAAW,GAAG,YAAY,CAAC;AACjC,MAAM,4BAA4B,GAAG,CAAC,GAAG,IAAI,CAAC;AAC9C,MAAM,4BAA4B,GAAG,EAAE,CAAC;AACxC,MAAM,eAAe,GAAG,EAAE,CAAC;AAE3B,SAAS,QAAQ,CAAC,KAAc;IAC/B,OAAO,KAAK,KAAK,IAAI,IAAI,OAAO,KAAK,KAAK,QAAQ,IAAI,CAAC,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC,CAAC;AAC7E,CAAC;AAED;;;;;;;;;GASG;AACH,SAAS,iBAAiB,CAAC,MAAe,EAAE,IAAa;IACxD,MAAM,KAAK,GAAa,EAAE,CAAC;IAC3B,MAAM,KAAK,GAAG,CAAC,IAAa,EAAE,KAAc,EAAE,IAAY,EAAQ,EAAE;QACnE,IAAI,KAAK,CAAC,MAAM,IAAI,eAAe,IAAI,CAAC,QAAQ,CAAC,IAAI,CAAC;YAAE,OAAO;QAC/D,IAAI,IAAI,CAAC,IAAI,KAAK,OAAO,IAAI,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC,EAAE,CAAC;YACnD,KAAK,IAAI,KAAK,GAAG,CAAC,EAAE,KAAK,GAAG,KAAK,CAAC,MAAM,EAAE,KAAK,EAAE,EAAE,CAAC;gBACnD,KAAK,CAAC,IAAI,CAAC,KAAK,EAAE,KAAK,CAAC,KAAK,CAAC,EAAE,GAAG,IAAI,IA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IAAI,CAAC,IAAI;QACf,KAAK,EAAE,IAAI,CAAC,KAAK;QACjB,WAAW,EAAE,IAAI,CAAC,WAAW;QAC7B,UAAU,EAAE,IAAI,CAAC,UAAU;QAC3B,mBAAmB,EAAE,IAAI,CAAC,mBAAmB;QAC7C,SAAS,EAAE,IAAI,CAAC,SAAS;QACzB,gBAAgB,EAAE,IAAI,CAAC,gBAAgB;QACvC,aAAa,EAAE,IAAI,CAAC,aAAa;QACjC,OAAO,EAAE,KAAK,EAAE,UAAU,EAAE,MAAM,EAAE,MAAM,EAAE,QAAQ,EAAE,EAAE,CAAC,IAAI,CAAC,OAAO,CAAC,UAAU,EAAE,MAAM,EAAE,MAAM,EAAE,QAAQ,CAAC;KAC3G,CAAC;AACH,CAAC","sourcesContent":["import type { AgentTool } from \"@earendil-works/pi-agent-core\";\nimport { type JsonObject, validateToolArguments } from \"@earendil-works/pi-ai\";\nimport type { Static, TSchema } from \"typebox\";\nimport type { ExtensionContext, ToolDefinition } from \"../extensions/types.ts\";\nimport { truncateHead } from \"./truncate.ts\";\n\ntype PresentableAgentTool<TParams extends TSchema = TSchema, TDetails = unknown> = AgentTool<TParams, TDetails> & {\n\ttoolGroup?: string;\n};\n\nconst RECEIVED_ARGUMENTS_MARKER = \"\\n\\nReceived arguments:\\n\";\nconst HINT_MARKER = \"\\n\\nHint: \";\nconst RECEIVED_ARGUMENTS_MAX_BYTES = 2 * 1024;\nconst RECEIVED_ARGUMENTS_MAX_LINES = 40;\nconst FIELD_HINTS_MAX = 10;\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n\treturn value !== null && typeof value === \"object\" && !Array.isArray(value);\n}\n\n/**\n * Walk schema and arguments in sync to name, at every object with\n * `additionalProperties: false`, the non-null fields the schema does not\n * declare, and at every object, the required fields the arguments lack. The\n * validator's own report says where validation failed; these hints say what\n * the legal shape is. Paths use the validator's dotted style\n * (`tasks[0].prompt`). Non-null unknown fields are reported rather than\n * silently dropped: a field like `prompt_extra` may carry briefing content\n * the caller intended to send.\n */\nfunction collectFieldHints(schema: unknown, args: unknown): string[] {\n\tconst hints: string[] = [];\n\tconst visit = (node: unknown, value: unknown, path: string): void => {\n\t\tif (hints.length >= FIELD_HINTS_MAX || !isRecord(node)) return;\n\t\tif (node.type === \"array\" && Array.isArray(value)) {\n\t\t\tfor (let index = 0; index < value.length; index++) {\n\t\t\t\tvisit(node.items, value[index], `${path}[${index}]`);\n\t\t\t}\n\t\t\treturn;\n\t\t}\n\t\tif (node.type !== \"object\" || !isRecord(value)) return;\n\t\tconst properties = isRecord(node.properties) ? node.properties : {};\n\t\tconst fields = Object.keys(properties);\n\t\tconst where = path || \"root\";\n\t\tif (node.additionalProperties === false) {\n\t\t\tfor (const [key, entry] of Object.entries(value)) {\n\t\t\t\tif (entry !== null && !(key in properties) && hints.length < FIELD_HINTS_MAX) {\n\t\t\t\t\tconst subject = path ? `${path}.${key}` : key;\n\t\t\t\t\thints.push(`${subject} is not a field; fields at ${where}: ${fields.join(\", \")}`);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tif (Array.isArray(node.required)) {\n\t\t\tfor (const key of node.required) {\n\t\t\t\tif (typeof key === \"string\" && value[key] === undefined && hints.length < FIELD_HINTS_MAX) {\n\t\t\t\t\tconst subject = path ? `${path}.${key}` : key;\n\t\t\t\t\thints.push(`${subject} is required; fields at ${where}: ${fields.join(\", \")}`);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tfor (const key of fields) {\n\t\t\tif (value[key] !== undefined && value[key] !== null) {\n\t\t\t\tvisit(properties[key], value[key], path ? `${path}.${key}` : key);\n\t\t\t}\n\t\t}\n\t};\n\tvisit(schema, args, \"\");\n\treturn hints;\n}\n\n/**\n * Rebuild pi-ai's validation error so a model can self-correct: the legal\n * fields are named next to each offending one, and the echoed arguments are\n * bounded (a 50KB subagent prompt must not be reflected whole into context).\n * The `Validation failed for tool \"<name>\":` prefix stays intact — the\n * question tool's renderer parses it.\n */\nfunction enrichValidationError(error: unknown, parameters: TSchema, args: unknown): Error {\n\tconst message = error instanceof Error ? error.message : String(error);\n\t// A definition synthesized from an already-wrapped tool enriches on the\n\t// inside; do not stack a second layer of hints on the same failure.\n\tif (message.includes(HINT_MARKER)) return error instanceof Error ? error : new Error(message);\n\tconst hints = collectFieldHints(parameters, args);\n\tconst markerIndex = message.indexOf(RECEIVED_ARGUMENTS_MARKER);\n\tconst head = markerIndex === -1 ? message : message.slice(0, markerIndex);\n\tconst received = markerIndex === -1 ? \"\" : message.slice(markerIndex + RECEIVED_ARGUMENTS_MARKER.length);\n\tlet enriched = hints.length > 0 ? `${head}\\n\\nHint: ${hints.join(\"\\nHint: \")}` : head;\n\tif (markerIndex !== -1) {\n\t\tconst bounded = truncateHead(received, {\n\t\t\tmaxBytes: RECEIVED_ARGUMENTS_MAX_BYTES,\n\t\t\tmaxLines: RECEIVED_ARGUMENTS_MAX_LINES,\n\t\t});\n\t\tenriched += `${RECEIVED_ARGUMENTS_MARKER}${bounded.content}`;\n\t\tif (bounded.truncated) enriched += \"\\n… (arguments truncated)\";\n\t}\n\treturn new Error(enriched);\n}\n\n/**\n * Pre-validate prepared arguments so a validation failure reaches the model\n * with field-level hints. Valid arguments pass through untouched and are\n * validated again by the agent loop as before.\n */\nfunction wrapPrepareArguments<TParams extends TSchema, TDetails>(\n\tdefinition: ToolDefinition<TParams, TDetails>,\n): (raw: unknown) => Static<TParams> {\n\tconst tool = { name: definition.name, description: definition.description, parameters: definition.parameters };\n\treturn (raw: unknown): Static<TParams> => {\n\t\tconst args = definition.prepareArguments ? definition.prepareArguments(raw) : raw;\n\t\ttry {\n\t\t\tvalidateToolArguments(tool, {\n\t\t\t\ttype: \"toolCall\",\n\t\t\t\tid: \"\",\n\t\t\t\tname: definition.name,\n\t\t\t\targuments: args as JsonObject,\n\t\t\t});\n\t\t} catch (error) {\n\t\t\tthrow enrichValidationError(error, definition.parameters, args);\n\t\t}\n\t\treturn args as Static<TParams>;\n\t};\n}\n\n/** Wrap a ToolDefinition into an AgentTool for the core runtime. */\nexport function wrapToolDefinition<TParams extends TSchema, TDetails = unknown>(\n\tdefinition: ToolDefinition<TParams, TDetails>,\n\tctxFactory?: () => ExtensionContext,\n): PresentableAgentTool<TParams, TDetails> {\n\treturn {\n\t\tname: definition.name,\n\t\tlabel: definition.label,\n\t\tdescription: definition.description,\n\t\tparameters: definition.parameters,\n\t\tconstrainedSampling: definition.constrainedSampling,\n\t\ttoolGroup: definition.toolGroup,\n\t\tprepareArguments: wrapPrepareArguments(definition),\n\t\texecutionMode: definition.executionMode,\n\t\texecute: (toolCallId, params, signal, onUpdate, ctx?: ExtensionContext) =>\n\t\t\tdefinition.execute(toolCallId, params, signal, onUpdate, ctx ?? (ctxFactory?.() as ExtensionContext)),\n\t};\n}\n\n/** Wrap multiple ToolDefinitions into AgentTools for the core runtime. */\nexport function wrapToolDefinitions(\n\tdefinitions: ToolDefinition<any, any>[],\n\tctxFactory?: () => ExtensionContext,\n): AgentTool<any>[] {\n\treturn definitions.map((definition) => wrapToolDefinition(definition, ctxFactory));\n}\n\n/**\n * Synthesize a minimal ToolDefinition from an AgentTool.\n *\n * This keeps AgentSession's internal registry definition-first even when a caller\n * provides plain AgentTool overrides that do not include prompt metadata or renderers.\n */\nexport function createToolDefinitionFromAgentTool<TParams extends TSchema, TDetails>(\n\ttool: PresentableAgentTool<TParams, TDetails>,\n): ToolDefinition<TParams, TDetails> {\n\treturn {\n\t\tname: tool.name,\n\t\tlabel: tool.label,\n\t\tdescription: tool.description,\n\t\tparameters: tool.parameters,\n\t\tconstrainedSampling: tool.constrainedSampling,\n\t\ttoolGroup: tool.toolGroup,\n\t\tprepareArguments: tool.prepareArguments,\n\t\texecutionMode: tool.executionMode,\n\t\texecute: async (toolCallId, params, signal, onUpdate) => tool.execute(toolCallId, params, signal, onUpdate),\n\t};\n}\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"actions.d.ts","sourceRoot":"","sources":["../../../src/extensions/background/actions.ts"],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AwCzC;AACD,wBAAgB,OAAO,CAAC,UAAU,EAAE,iBAAiB,EAAE,KAAK,EAAE,OAAO,GAAG,eAAe,CAAC,aAAa,CAAC,CAoBrG;AACD,wBAAgB,OAAO,CAAC,UAAU,EAAE,iBAAiB,GAAG,eAAe,CAAC,aAAa,CAAC,CA2BrF"}
|
|
@@ -15,6 +15,41 @@ function result(text, details) {
|
|
|
15
15
|
export function describeTaskLine(task, now = Date.now()) {
|
|
16
16
|
return `${task.id} ${task.kind} ${task.status} (${task.mode}) ${runtimeLabel(task, now)} ${task.title.slice(0, 200)}`;
|
|
17
17
|
}
|
|
18
|
+
const UNKNOWN_ID_MESSAGE = "Unknown background task ID";
|
|
19
|
+
const AMBIGUOUS_ID_MESSAGE = "Ambiguous background task ID";
|
|
20
|
+
const LOOKUP_LIST_LIMIT = 10;
|
|
21
|
+
/** Task ids a lookup prefix can match: the full id or its kind-stripped suffix. */
|
|
22
|
+
function matchesLookupPrefix(task, id) {
|
|
23
|
+
return task.id.startsWith(id) || task.id.slice(task.kind.length + 1).startsWith(id);
|
|
24
|
+
}
|
|
25
|
+
/**
|
|
26
|
+
* Rewrite the service's bare lookup failure into an actionable one: an
|
|
27
|
+
* unknown id gets the session's current tasks (active first, then recent
|
|
28
|
+
* finishes) so the next call can use a real id without a separate list call,
|
|
29
|
+
* and an ambiguous prefix gets exactly the tasks it matched. A missing id
|
|
30
|
+
* stays an error — it is likely a mistyped id of a task still running.
|
|
31
|
+
*/
|
|
32
|
+
function lookupFailure(background, id, error) {
|
|
33
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
34
|
+
const ambiguous = message.includes(AMBIGUOUS_ID_MESSAGE);
|
|
35
|
+
if (!ambiguous && !message.includes(UNKNOWN_ID_MESSAGE)) {
|
|
36
|
+
return error instanceof Error ? error : new Error(message);
|
|
37
|
+
}
|
|
38
|
+
if (ambiguous) {
|
|
39
|
+
const matches = background.list().filter((task) => matchesLookupPrefix(task, id));
|
|
40
|
+
const lines = matches.map((task) => describeTaskLine(task)).join("\n");
|
|
41
|
+
return new Error(`Ambiguous background task ID "${id}" matches ${matches.length} tasks:\n${lines}`);
|
|
42
|
+
}
|
|
43
|
+
const tasks = background.list();
|
|
44
|
+
const active = tasks.filter((task) => !isBackgroundTerminal(task.status));
|
|
45
|
+
const finished = tasks.filter((task) => isBackgroundTerminal(task.status));
|
|
46
|
+
const shown = [...active, ...finished].slice(0, LOOKUP_LIST_LIMIT);
|
|
47
|
+
if (shown.length === 0) {
|
|
48
|
+
return new Error(`No background task "${id}" in this session. No background tasks in this session.`);
|
|
49
|
+
}
|
|
50
|
+
const lines = shown.map((task) => describeTaskLine(task)).join("\n");
|
|
51
|
+
return new Error(`No background task "${id}" in this session. IDs from other sessions are not valid here.\nCurrent tasks:\n${lines}`);
|
|
52
|
+
}
|
|
18
53
|
/** Reserve space for each independent diagnostic before allowing raw output to fill the budget. */
|
|
19
54
|
function readText(header, slice) {
|
|
20
55
|
const boundedField = (text, maxBytes) => truncateHead(boundText(sanitizeBinaryOutput(text), maxBytes), { maxBytes, maxLines: 100 }).content;
|
|
@@ -29,69 +64,86 @@ function readText(header, slice) {
|
|
|
29
64
|
.join("\n");
|
|
30
65
|
}
|
|
31
66
|
export async function runRead(background, input) {
|
|
32
|
-
const mode = input.mode ?? "tail";
|
|
33
|
-
const slice = await background.read(requireTaskId(input), { mode, bytes: clampReadBytes(input.bytes) });
|
|
34
|
-
return result(readText(`[${describeTaskLine(slice.task)} · ${slice.totalBytes} bytes${slice.truncated ? " · truncated" : ""}]`, slice), {
|
|
35
|
-
action: "read",
|
|
36
|
-
taskId: slice.task.id,
|
|
37
|
-
mode,
|
|
38
|
-
sliceBytes: Buffer.byteLength(slice.text),
|
|
39
|
-
totalBytes: slice.totalBytes,
|
|
40
|
-
outputPath: slice.task.outputPath ?? "",
|
|
41
|
-
kind: slice.task.kind,
|
|
42
|
-
status: slice.task.status,
|
|
43
|
-
});
|
|
44
|
-
}
|
|
45
|
-
export async function runWait(background, input, signal) {
|
|
46
67
|
const id = requireTaskId(input);
|
|
47
|
-
const release = background.pin(id);
|
|
48
68
|
try {
|
|
49
|
-
const
|
|
50
|
-
const
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
: timedOut
|
|
57
|
-
? " · wait window expired; execution continues"
|
|
58
|
-
: "";
|
|
59
|
-
const slice = await background.read(id, {
|
|
60
|
-
bytes: BG_WAIT_DELTA_BYTES,
|
|
61
|
-
sinceBytes: clampSinceBytes(input.sinceBytes),
|
|
62
|
-
});
|
|
63
|
-
signal?.throwIfAborted();
|
|
64
|
-
return result(readText(`[${describeTaskLine(task)}${windowNote}]`, slice), {
|
|
65
|
-
action: "wait",
|
|
66
|
-
taskId: task.id,
|
|
67
|
-
...(!timedOut ? { backgroundTaskId: task.id } : {}),
|
|
68
|
-
status: task.status,
|
|
69
|
-
kind: task.kind,
|
|
70
|
-
timedOut,
|
|
71
|
-
exitCode: undefined,
|
|
72
|
-
waitedMs: Date.now() - start,
|
|
73
|
-
deltaBytes: Buffer.byteLength(slice.text),
|
|
69
|
+
const mode = input.mode ?? "tail";
|
|
70
|
+
const slice = await background.read(id, { mode, bytes: clampReadBytes(input.bytes) });
|
|
71
|
+
return result(readText(`[${describeTaskLine(slice.task)} · ${slice.totalBytes} bytes${slice.truncated ? " · truncated" : ""}]`, slice), {
|
|
72
|
+
action: "read",
|
|
73
|
+
taskId: slice.task.id,
|
|
74
|
+
mode,
|
|
75
|
+
sliceBytes: Buffer.byteLength(slice.text),
|
|
74
76
|
totalBytes: slice.totalBytes,
|
|
75
|
-
|
|
76
|
-
|
|
77
|
+
outputPath: slice.task.outputPath ?? "",
|
|
78
|
+
kind: slice.task.kind,
|
|
79
|
+
status: slice.task.status,
|
|
77
80
|
});
|
|
78
81
|
}
|
|
79
|
-
|
|
80
|
-
|
|
82
|
+
catch (error) {
|
|
83
|
+
throw lookupFailure(background, id, error);
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
export async function runWait(background, input, signal) {
|
|
87
|
+
const id = requireTaskId(input);
|
|
88
|
+
try {
|
|
89
|
+
const release = background.pin(id);
|
|
90
|
+
try {
|
|
91
|
+
const start = Date.now();
|
|
92
|
+
const task = await background.wait(id, clampWaitMs(input.waitMs), signal);
|
|
93
|
+
const timedOut = !isBackgroundTerminal(task.status);
|
|
94
|
+
// A closed host resolves waits early without settling anything; do not claim
|
|
95
|
+
// the execution merely outlived the wait window.
|
|
96
|
+
const windowNote = background.closed
|
|
97
|
+
? " · host closed; execution state unconfirmed"
|
|
98
|
+
: timedOut
|
|
99
|
+
? " · wait window expired; execution continues"
|
|
100
|
+
: "";
|
|
101
|
+
const slice = await background.read(id, {
|
|
102
|
+
bytes: BG_WAIT_DELTA_BYTES,
|
|
103
|
+
sinceBytes: clampSinceBytes(input.sinceBytes),
|
|
104
|
+
});
|
|
105
|
+
signal?.throwIfAborted();
|
|
106
|
+
return result(readText(`[${describeTaskLine(task)}${windowNote}]`, slice), {
|
|
107
|
+
action: "wait",
|
|
108
|
+
taskId: task.id,
|
|
109
|
+
...(!timedOut ? { backgroundTaskId: task.id } : {}),
|
|
110
|
+
status: task.status,
|
|
111
|
+
kind: task.kind,
|
|
112
|
+
timedOut,
|
|
113
|
+
exitCode: undefined,
|
|
114
|
+
waitedMs: Date.now() - start,
|
|
115
|
+
deltaBytes: Buffer.byteLength(slice.text),
|
|
116
|
+
totalBytes: slice.totalBytes,
|
|
117
|
+
deltaTruncated: slice.truncated,
|
|
118
|
+
outputPath: task.outputPath ?? "",
|
|
119
|
+
});
|
|
120
|
+
}
|
|
121
|
+
finally {
|
|
122
|
+
release();
|
|
123
|
+
}
|
|
124
|
+
}
|
|
125
|
+
catch (error) {
|
|
126
|
+
throw lookupFailure(background, id, error);
|
|
81
127
|
}
|
|
82
128
|
}
|
|
83
129
|
export function runKill(background, input) {
|
|
84
|
-
const
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
130
|
+
const id = requireTaskId(input);
|
|
131
|
+
try {
|
|
132
|
+
const task = background.get(id);
|
|
133
|
+
const requested = background.kill(task.id);
|
|
134
|
+
return result(requested
|
|
135
|
+
? `Cancellation requested for ${task.id}. The task or whole group is stopping; cleanup may still be in progress.`
|
|
136
|
+
: `No new cancellation requested for ${task.id} (${background.get(task.id).status}).`, {
|
|
137
|
+
action: "kill",
|
|
138
|
+
taskId: task.id,
|
|
139
|
+
command: task.command ?? task.title,
|
|
140
|
+
requested,
|
|
141
|
+
status: background.get(task.id).status,
|
|
142
|
+
});
|
|
143
|
+
}
|
|
144
|
+
catch (error) {
|
|
145
|
+
throw lookupFailure(background, id, error);
|
|
146
|
+
}
|
|
95
147
|
}
|
|
96
148
|
export function runList(background) {
|
|
97
149
|
// Listings cover backgrounded work only; foreground executions deliver
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"actions.js","sourceRoot":"","sources":["../../../src/extensions/background/actions.ts"],"names":[],"mappings":"AAAA,wFAAwF;AACxF,OAAO,EAAE,SAAS,EAAE,MAAM,iCAAiC,CAAC;AAC5D,OAAO,EAIN,oBAAoB,GACpB,MAAM,gCAAgC,CAAC;AAExC,OAAO,EAAE,YAAY,EAAE,MAAM,8BAA8B,CAAC;AAC5D,OAAO,EAAE,oBAAoB,EAAE,MAAM,sBAAsB,CAAC;AAC5D,OAAO,EAAE,sBAAsB,EAAE,mBAAmB,EAAE,MAAM,gBAAgB,CAAC;AAC7E,OAAO,EAAgB,cAAc,EAAE,eAAe,EAAE,WAAW,EAAE,aAAa,EAAE,MAAM,aAAa,CAAC;AACxG,OAAO,EAAE,YAAY,EAAE,MAAM,gBAAgB,CAAC;AAG9C,MAAM,UAAU,WAAW,CAAC,IAAY;IACvC,OAAO,YAAY,CAAC,oBAAoB,CAAC,IAAI,CAAC,EAAE,EAAE,QAAQ,EAAE,EA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\nimport { boundText } from \"../../core/background/output.ts\";\nimport {\n\ttype BackgroundContext,\n\ttype BackgroundRead,\n\ttype BackgroundTask,\n\tisBackgroundTerminal,\n} from \"../../core/background/types.ts\";\nimport type { AgentToolResult } from \"../../core/extensions/types.ts\";\nimport { truncateHead } from \"../../core/tools/truncate.ts\";\nimport { sanitizeBinaryOutput } from \"../../utils/shell.ts\";\nimport { BG_LIST_FINISHED_SHOWN, BG_WAIT_DELTA_BYTES } from \"./constants.ts\";\nimport { type BgInput, clampReadBytes, clampSinceBytes, clampWaitMs, requireTaskId } from \"./schema.ts\";\nimport { runtimeLabel } from \"./task-view.ts\";\nimport type { BgDetails, BgKillDetails, BgListDetails, BgReadDetails, BgWaitDetails } from \"./types.ts\";\n\nexport function boundedText(text: string): string {\n\treturn truncateHead(sanitizeBinaryOutput(text), { maxBytes: 50 * 1024, maxLines: 2000 }).content;\n}\nfunction result<T extends BgDetails>(text: string, details: T): AgentToolResult<T> {\n\treturn { content: [{ type: \"text\", text: boundedText(text) }], details };\n}\nexport function describeTaskLine(task: BackgroundTask, now = Date.now()): string {\n\treturn `${task.id} ${task.kind} ${task.status} (${task.mode}) ${runtimeLabel(task, now)} ${task.title.slice(0, 200)}`;\n}\n/** Reserve space for each independent diagnostic before allowing raw output to fill the budget. */\nfunction readText(header: string, slice: BackgroundRead): string {\n\tconst boundedField = (text: string, maxBytes: number) =>\n\t\ttruncateHead(boundText(sanitizeBinaryOutput(text), maxBytes), { maxBytes, maxLines: 100 }).content;\n\treturn [\n\t\tboundedField(header, 4096),\n\t\tslice.task.error ? `Task error: ${boundedField(slice.task.error, 4096)}` : \"\",\n\t\tslice.readError ? `Output read error: ${boundedField(slice.readError, 4096)}` : \"\",\n\t\tboundedField(slice.task.outputPath ?? \"\", 8192),\n\t\tslice.text || \"(no output yet)\",\n\t]\n\t\t.filter(Boolean)\n\t\t.join(\"\\n\");\n}\nexport async function runRead(background: BackgroundContext, input: BgInput): Promise<AgentToolResult<BgReadDetails>> {\n\tconst mode = input.mode ?? \"tail\";\n\tconst slice = await background.read(requireTaskId(input), { mode, bytes: clampReadBytes(input.bytes) });\n\treturn result(\n\t\treadText(\n\t\t\t`[${describeTaskLine(slice.task)} · ${slice.totalBytes} bytes${slice.truncated ? \" · truncated\" : \"\"}]`,\n\t\t\tslice,\n\t\t),\n\t\t{\n\t\t\taction: \"read\",\n\t\t\ttaskId: slice.task.id,\n\t\t\tmode,\n\t\t\tsliceBytes: Buffer.byteLength(slice.text),\n\t\t\ttotalBytes: slice.totalBytes,\n\t\t\toutputPath: slice.task.outputPath ?? \"\",\n\t\t\tkind: slice.task.kind,\n\t\t\tstatus: slice.task.status,\n\t\t},\n\t);\n}\nexport async function runWait(\n\tbackground: BackgroundContext,\n\tinput: BgInput,\n\tsignal?: AbortSignal,\n): Promise<AgentToolResult<BgWaitDetails>> {\n\tconst id = requireTaskId(input);\n\tconst release = background.pin(id);\n\ttry {\n\t\tconst start = Date.now();\n\t\tconst task = await background.wait(id, clampWaitMs(input.waitMs), signal);\n\t\tconst timedOut = !isBackgroundTerminal(task.status);\n\t\t// A closed host resolves waits early without settling anything; do not claim\n\t\t// the execution merely outlived the wait window.\n\t\tconst windowNote = background.closed\n\t\t\t? \" · host closed; execution state unconfirmed\"\n\t\t\t: timedOut\n\t\t\t\t? \" · wait window expired; execution continues\"\n\t\t\t\t: \"\";\n\t\tconst slice = await background.read(id, {\n\t\t\tbytes: BG_WAIT_DELTA_BYTES,\n\t\t\tsinceBytes: clampSinceBytes(input.sinceBytes),\n\t\t});\n\t\tsignal?.throwIfAborted();\n\t\treturn result(readText(`[${describeTaskLine(task)}${windowNote}]`, slice), {\n\t\t\taction: \"wait\",\n\t\t\ttaskId: task.id,\n\t\t\t...(!timedOut ? { backgroundTaskId: task.id } : {}),\n\t\t\tstatus: task.status,\n\t\t\tkind: task.kind,\n\t\t\ttimedOut,\n\t\t\texitCode: undefined,\n\t\t\twaitedMs: Date.now() - start,\n\t\t\tdeltaBytes: Buffer.byteLength(slice.text),\n\t\t\ttotalBytes: slice.totalBytes,\n\t\t\tdeltaTruncated: slice.truncated,\n\t\t\toutputPath: task.outputPath ?? \"\",\n\t\t});\n\t} finally {\n\t\trelease();\n\t}\n}\nexport function runKill(background: BackgroundContext, input: BgInput): AgentToolResult<BgKillDetails> {\n\tconst task = background.get(requireTaskId(input));\n\tconst requested = background.kill(task.id);\n\treturn result(\n\t\trequested\n\t\t\t? `Cancellation requested for ${task.id}. The task or whole group is stopping; cleanup may still be in progress.`\n\t\t\t: `No new cancellation requested for ${task.id} (${background.get(task.id).status}).`,\n\t\t{\n\t\t\taction: \"kill\",\n\t\t\ttaskId: task.id,\n\t\t\tcommand: task.command ?? task.title,\n\t\t\trequested,\n\t\t\tstatus: background.get(task.id).status,\n\t\t},\n\t);\n}\nexport function runList(background: BackgroundContext): AgentToolResult<BgListDetails> {\n\t// Listings cover backgrounded work only; foreground executions deliver\n\t// inline in the transcript, so they are counted here rather than shown.\n\tconst all = background.list();\n\tconst tasks = all.filter((task) => task.mode === \"background\");\n\tconst foregroundOmitted = all.length - tasks.length;\n\tconst active = tasks.filter((task) => !isBackgroundTerminal(task.status));\n\tconst finished = tasks.filter((task) => isBackgroundTerminal(task.status));\n\tconst shown = [...active, ...finished.slice(0, BG_LIST_FINISHED_SHOWN)].slice(0, 100);\n\tconst hidden = tasks.length - shown.length;\n\tconst foregroundNote =\n\t\tforegroundOmitted > 0\n\t\t\t? `\\n${foregroundOmitted} foreground ${foregroundOmitted === 1 ? \"execution\" : \"executions\"} omitted — foreground work is delivered inline in the transcript.`\n\t\t\t: \"\";\n\treturn result(\n\t\tshown.length\n\t\t\t? `${shown.map((task) => describeTaskLine(task)).join(\"\\n\")}${hidden > 0 ? `\\n${hidden} more records not shown.` : \"\"}${foregroundNote}`\n\t\t\t: `No background tasks. Start work through bash or subagent with background: true.${foregroundNote}`,\n\t\t{\n\t\t\taction: \"list\",\n\t\t\trunning: active.length,\n\t\t\tfinished: finished.length,\n\t\t\tshown: shown.length,\n\t\t\thidden,\n\t\t\t...(foregroundOmitted > 0 ? { foregroundOmitted } : {}),\n\t\t},\n\t);\n}\n"]}
|
|
1
|
+
{"version":3,"file":"actions.js","sourceRoot":"","sources":["../../../src/extensions/background/actions.ts"],"names":[],"mappings":"AAAA,wFAAwF;AACxF,OAAO,EAAE,SAAS,EAAE,MAAM,iCAAiC,CAAC;AAC5D,OAAO,EAIN,oBAAoB,GACpB,MAAM,gCAAgC,CAAC;AAExC,OAAO,EAAE,YAAY,EAAE,MAAM,8BAA8B,CAAC;AAC5D,OAAO,EAAE,oBAAoB,EAAE,MAAM,sBAAsB,CAAC;AAC5D,OAAO,EAAE,sBAAsB,EAAE,mBAAmB,EAAE,MAAM,gBAAgB,CAAC;AAC7E,OAAO,EAAgB,cAAc,EAAE,eAAe,EAAE,WAAW,EAAE,aAAa,EAAE,MAAM,aAAa,CAAC;AACxG,OAAO,EAAE,YAAY,EAAE,MAAM,gBAAgB,CAAC;AAG9C,MAAM,UAAU,WAAW,CAAC,IAAY;IACvC,OAAO,YAAY,CAAC,oBAAoB,CAAC,IAAI,CAAC,EAAE,EAAE,QAAQ,EAAE,EAAE,GAAG,IAAI,EAAE,QAAQ,EAAE,IAAI,EAAE,CAAC,CAAC,OAAO,CAAC;AAClG,CAAC;AACD,SAAS,MAAM,CAAsB,IAAY,EAAE,OAAU;IAC5D,OAAO,EAAE,OAAO,EAAE,CAAC,EAAE,IAAI,EAAE,MAAM,EAAE,IAAI,EAAE,WAAW,CAAC,IAAI,CAAC,EAAE,CAAC,EAAE,OAAO,EAAE,CAAC;AAC1E,CAAC;AACD,MAAM,UAAU,gBAAgB,CAAC,IAAoB,EAAE,GAAG,GAAG,IAAI,CAAC,GAAG,EAAE;IACtE,OAAO,GAAG,IAAI,CAAC,EAAE,IAAI,IAAI,CAAC,IAAI,IAAI,IAAI,CAAC,MAAM,KAAK,IAAI,CAAC,IAAI,KAAK,YAAY,CAAC,IAAI,EAAE,GAAG,CAAC,IAAI,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AAC,MAAM,CAAC;IAC3C,MAAM,cAAc,GACnB,iBAAiB,GAAG,CAAC;QACpB,CAAC,CAAC,KAAK,iBAAiB,eAAe,iBAAiB,KAAK,CAAC,CAAC,CAAC,CAAC,WAAW,CAAC,CAAC,CAAC,YAAY,mEAAmE;QAC9J,CAAC,CAAC,EAAE,CAAC;IACP,OAAO,MAAM,CACZ,KAAK,CAAC,MAAM;QACX,CAAC,CAAC,GAAG,KAAK,CAAC,GAAG,CAAC,CAAC,IAAI,EAAE,EAAE,CAAC,gBAAgB,CAAC,IAAI,CAAC,CAAC,CAAC,IAAI,CAAC,IAAI,CAAC,GAAG,MAAM,GAAG,CAAC,CAAC,CAAC,CAAC,KAAK,MAAM,0BAA0B,CAAC,CAAC,CAAC,EAAE,GAAG,cAAc,EAAE;QACxI,CAAC,CAAC,kFAAkF,cAAc,EAAE,EACrG;QACC,MAAM,EAAE,MAAM;QACd,OAAO,EAAE,MAAM,CAAC,MAAM;QACtB,QAAQ,EAAE,QAAQ,CAAC,MAAM;QACzB,KAAK,EAAE,KAAK,CAAC,MAAM;QACnB,MAAM;QACN,GAAG,CAAC,iBAAiB,GAAG,CAAC,CAAC,CAAC,CAAC,EAAE,iBAAiB,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC;KACvD,CACD,CAAC;AACH,CAAC","sourcesContent":["/** Management only: execution and delivery belong to the session Background service. */\nimport { boundText } from \"../../core/background/output.ts\";\nimport {\n\ttype BackgroundContext,\n\ttype BackgroundRead,\n\ttype BackgroundTask,\n\tisBackgroundTerminal,\n} from \"../../core/background/types.ts\";\nimport type { AgentToolResult } from \"../../core/extensions/types.ts\";\nimport { truncateHead } from \"../../core/tools/truncate.ts\";\nimport { sanitizeBinaryOutput } from \"../../utils/shell.ts\";\nimport { BG_LIST_FINISHED_SHOWN, BG_WAIT_DELTA_BYTES } from \"./constants.ts\";\nimport { type BgInput, clampReadBytes, clampSinceBytes, clampWaitMs, requireTaskId } from \"./schema.ts\";\nimport { runtimeLabel } from \"./task-view.ts\";\nimport type { BgDetails, BgKillDetails, BgListDetails, BgReadDetails, BgWaitDetails } from \"./types.ts\";\n\nexport function boundedText(text: string): string {\n\treturn truncateHead(sanitizeBinaryOutput(text), { maxBytes: 50 * 1024, maxLines: 2000 }).content;\n}\nfunction result<T extends BgDetails>(text: string, details: T): AgentToolResult<T> {\n\treturn { content: [{ type: \"text\", text: boundedText(text) }], details };\n}\nexport function describeTaskLine(task: BackgroundTask, now = Date.now()): string {\n\treturn `${task.id} ${task.kind} ${task.status} (${task.mode}) ${runtimeLabel(task, now)} ${task.title.slice(0, 200)}`;\n}\n\nconst UNKNOWN_ID_MESSAGE = \"Unknown background task ID\";\nconst AMBIGUOUS_ID_MESSAGE = \"Ambiguous background task ID\";\nconst LOOKUP_LIST_LIMIT = 10;\n\n/** Task ids a lookup prefix can match: the full id or its kind-stripped suffix. */\nfunction matchesLookupPrefix(task: BackgroundTask, id: string): boolean {\n\treturn task.id.startsWith(id) || task.id.slice(task.kind.length + 1).startsWith(id);\n}\n\n/**\n * Rewrite the service's bare lookup failure into an actionable one: an\n * unknown id gets the session's current tasks (active first, then recent\n * finishes) so the next call can use a real id without a separate list call,\n * and an ambiguous prefix gets exactly the tasks it matched. A missing id\n * stays an error — it is likely a mistyped id of a task still running.\n */\nfunction lookupFailure(background: BackgroundContext, id: string, error: unknown): Error {\n\tconst message = error instanceof Error ? error.message : String(error);\n\tconst ambiguous = message.includes(AMBIGUOUS_ID_MESSAGE);\n\tif (!ambiguous && !message.includes(UNKNOWN_ID_MESSAGE)) {\n\t\treturn error instanceof Error ? error : new Error(message);\n\t}\n\tif (ambiguous) {\n\t\tconst matches = background.list().filter((task) => matchesLookupPrefix(task, id));\n\t\tconst lines = matches.map((task) => describeTaskLine(task)).join(\"\\n\");\n\t\treturn new Error(`Ambiguous background task ID \"${id}\" matches ${matches.length} tasks:\\n${lines}`);\n\t}\n\tconst tasks = background.list();\n\tconst active = tasks.filter((task) => !isBackgroundTerminal(task.status));\n\tconst finished = tasks.filter((task) => isBackgroundTerminal(task.status));\n\tconst shown = [...active, ...finished].slice(0, LOOKUP_LIST_LIMIT);\n\tif (shown.length === 0) {\n\t\treturn new Error(`No background task \"${id}\" in this session. No background tasks in this session.`);\n\t}\n\tconst lines = shown.map((task) => describeTaskLine(task)).join(\"\\n\");\n\treturn new Error(\n\t\t`No background task \"${id}\" in this session. IDs from other sessions are not valid here.\\nCurrent tasks:\\n${lines}`,\n\t);\n}\n/** Reserve space for each independent diagnostic before allowing raw output to fill the budget. */\nfunction readText(header: string, slice: BackgroundRead): string {\n\tconst boundedField = (text: string, maxBytes: number) =>\n\t\ttruncateHead(boundText(sanitizeBinaryOutput(text), maxBytes), { maxBytes, maxLines: 100 }).content;\n\treturn [\n\t\tboundedField(header, 4096),\n\t\tslice.task.error ? `Task error: ${boundedField(slice.task.error, 4096)}` : \"\",\n\t\tslice.readError ? `Output read error: ${boundedField(slice.readError, 4096)}` : \"\",\n\t\tboundedField(slice.task.outputPath ?? \"\", 8192),\n\t\tslice.text || \"(no output yet)\",\n\t]\n\t\t.filter(Boolean)\n\t\t.join(\"\\n\");\n}\nexport async function runRead(background: BackgroundContext, input: BgInput): Promise<AgentToolResult<BgReadDetails>> {\n\tconst id = requireTaskId(input);\n\ttry {\n\t\tconst mode = input.mode ?? \"tail\";\n\t\tconst slice = await background.read(id, { mode, bytes: clampReadBytes(input.bytes) });\n\t\treturn result(\n\t\t\treadText(\n\t\t\t\t`[${describeTaskLine(slice.task)} · ${slice.totalBytes} bytes${slice.truncated ? \" · truncated\" : \"\"}]`,\n\t\t\t\tslice,\n\t\t\t),\n\t\t\t{\n\t\t\t\taction: \"read\",\n\t\t\t\ttaskId: slice.task.id,\n\t\t\t\tmode,\n\t\t\t\tsliceBytes: Buffer.byteLength(slice.text),\n\t\t\t\ttotalBytes: slice.totalBytes,\n\t\t\t\toutputPath: slice.task.outputPath ?? \"\",\n\t\t\t\tkind: slice.task.kind,\n\t\t\t\tstatus: slice.task.status,\n\t\t\t},\n\t\t);\n\t} catch (error) {\n\t\tthrow lookupFailure(background, id, error);\n\t}\n}\nexport async function runWait(\n\tbackground: BackgroundContext,\n\tinput: BgInput,\n\tsignal?: AbortSignal,\n): Promise<AgentToolResult<BgWaitDetails>> {\n\tconst id = requireTaskId(input);\n\ttry {\n\t\tconst release = background.pin(id);\n\t\ttry {\n\t\t\tconst start = Date.now();\n\t\t\tconst task = await background.wait(id, clampWaitMs(input.waitMs), signal);\n\t\t\tconst timedOut = !isBackgroundTerminal(task.status);\n\t\t\t// A closed host resolves waits early without settling anything; do not claim\n\t\t\t// the execution merely outlived the wait window.\n\t\t\tconst windowNote = background.closed\n\t\t\t\t? \" · host closed; execution state unconfirmed\"\n\t\t\t\t: timedOut\n\t\t\t\t\t? \" · wait window expired; execution continues\"\n\t\t\t\t\t: \"\";\n\t\t\tconst slice = await background.read(id, {\n\t\t\t\tbytes: BG_WAIT_DELTA_BYTES,\n\t\t\t\tsinceBytes: clampSinceBytes(input.sinceBytes),\n\t\t\t});\n\t\t\tsignal?.throwIfAborted();\n\t\t\treturn result(readText(`[${describeTaskLine(task)}${windowNote}]`, slice), {\n\t\t\t\taction: \"wait\",\n\t\t\t\ttaskId: task.id,\n\t\t\t\t...(!timedOut ? { backgroundTaskId: task.id } : {}),\n\t\t\t\tstatus: task.status,\n\t\t\t\tkind: task.kind,\n\t\t\t\ttimedOut,\n\t\t\t\texitCode: undefined,\n\t\t\t\twaitedMs: Date.now() - start,\n\t\t\t\tdeltaBytes: Buffer.byteLength(slice.text),\n\t\t\t\ttotalBytes: slice.totalBytes,\n\t\t\t\tdeltaTruncated: slice.truncated,\n\t\t\t\toutputPath: task.outputPath ?? \"\",\n\t\t\t});\n\t\t} finally {\n\t\t\trelease();\n\t\t}\n\t} catch (error) {\n\t\tthrow lookupFailure(background, id, error);\n\t}\n}\nexport function runKill(background: BackgroundContext, input: BgInput): AgentToolResult<BgKillDetails> {\n\tconst id = requireTaskId(input);\n\ttry {\n\t\tconst task = background.get(id);\n\t\tconst requested = background.kill(task.id);\n\t\treturn result(\n\t\t\trequested\n\t\t\t\t? `Cancellation requested for ${task.id}. The task or whole group is stopping; cleanup may still be in progress.`\n\t\t\t\t: `No new cancellation requested for ${task.id} (${background.get(task.id).status}).`,\n\t\t\t{\n\t\t\t\taction: \"kill\",\n\t\t\t\ttaskId: task.id,\n\t\t\t\tcommand: task.command ?? task.title,\n\t\t\t\trequested,\n\t\t\t\tstatus: background.get(task.id).status,\n\t\t\t},\n\t\t);\n\t} catch (error) {\n\t\tthrow lookupFailure(background, id, error);\n\t}\n}\nexport function runList(background: BackgroundContext): AgentToolResult<BgListDetails> {\n\t// Listings cover backgrounded work only; foreground executions deliver\n\t// inline in the transcript, so they are counted here rather than shown.\n\tconst all = background.list();\n\tconst tasks = all.filter((task) => task.mode === \"background\");\n\tconst foregroundOmitted = all.length - tasks.length;\n\tconst active = tasks.filter((task) => !isBackgroundTerminal(task.status));\n\tconst finished = tasks.filter((task) => isBackgroundTerminal(task.status));\n\tconst shown = [...active, ...finished.slice(0, BG_LIST_FINISHED_SHOWN)].slice(0, 100);\n\tconst hidden = tasks.length - shown.length;\n\tconst foregroundNote =\n\t\tforegroundOmitted > 0\n\t\t\t? `\\n${foregroundOmitted} foreground ${foregroundOmitted === 1 ? \"execution\" : \"executions\"} omitted — foreground work is delivered inline in the transcript.`\n\t\t\t: \"\";\n\treturn result(\n\t\tshown.length\n\t\t\t? `${shown.map((task) => describeTaskLine(task)).join(\"\\n\")}${hidden > 0 ? `\\n${hidden} more records not shown.` : \"\"}${foregroundNote}`\n\t\t\t: `No background tasks. Start work through bash or subagent with background: true.${foregroundNote}`,\n\t\t{\n\t\t\taction: \"list\",\n\t\t\trunning: active.length,\n\t\t\tfinished: finished.length,\n\t\t\tshown: shown.length,\n\t\t\thidden,\n\t\t\t...(foregroundOmitted > 0 ? { foregroundOmitted } : {}),\n\t\t},\n\t);\n}\n"]}
|
|
@@ -53,6 +53,7 @@ export function createBackgroundExtension() {
|
|
|
53
53
|
promptSnippet: BG_PROMPT_SNIPPET,
|
|
54
54
|
promptGuidelines: BG_PROMPT_GUIDELINES,
|
|
55
55
|
parameters: bgSchema,
|
|
56
|
+
constrainedSampling: { type: "json_schema", strict: "prefer" },
|
|
56
57
|
async execute(_id, params, signal, _onUpdate, ctx) {
|
|
57
58
|
try {
|
|
58
59
|
switch (params.action) {
|
|
@@ -67,10 +68,9 @@ export function createBackgroundExtension() {
|
|
|
67
68
|
}
|
|
68
69
|
}
|
|
69
70
|
catch (error) {
|
|
71
|
+
// Lookup failures already carry the current task list from actions.ts.
|
|
70
72
|
const message = error instanceof Error ? error.message : String(error);
|
|
71
|
-
|
|
72
|
-
const hint = message.includes("background task ID") ? " Use action list to find the execution id." : "";
|
|
73
|
-
throw new Error(boundedText(`${message}${hint}`));
|
|
73
|
+
throw new Error(boundedText(message));
|
|
74
74
|
}
|
|
75
75
|
},
|
|
76
76
|
renderCall: renderBgCall,
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../../src/extensions/background/index.ts"],"names":[],"mappings":"AAAA,sFAAsF;AACtF,OAAO,kBAAkB,CAAC;AAC1B,OAAO,EAAE,cAAc,EAAE,MAAM,wBAAwB,CAAC;AACxD,OAAO,EAAE,oBAAoB,EAAE,MAAM,gCAAgC,CAAC;AAEtE,OAAO,EAAE,WAAW,EAAE,gBAAgB,EAAE,OAAO,EAAE,OAAO,EAAE,OAAO,EAAE,OAAO,EAAE,MAAM,cAAc,CAAC;AACjG,OAAO,EAAE,0BAA0B,EAAE,MAAM,wBAAwB,CAAC;AACpE,OAAO,EAAE,kBAAkB,EAAE,oBAAoB,EAAE,MAAM,gBAAgB,CAAC;AAC1E,OAAO,EAAE,mBAAmB,EAAE,MAAM,cAAc,CAAC;AACnD,OAAO,EAAsB,4BAA4B,EAAE,YAAY,EAAE,cAAc,EAAE,MAAM,aAAa,CAAC;AAC7G,OAAO,EAAE,oBAAoB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AE,EAAE;oBACjC,MAAM,KAAK,GAAG,GAAG,EAAE;wBAClB,IAAI,SAAS,KAAK,KAAK;4BAAE,SAAS,GAAG,SAAS,CAAC;wBAC/C,IAAI,EAAE,CAAC;oBACR,CAAC,CAAC;oBACF,SAAS,GAAG,KAAK,CAAC;oBAClB,OAAO,IAAI,mBAAmB,CAAC,EAAE,GAAG,EAAE,KAAK,EAAE,WAAW,EAAE,IAAI,EAAE,GAAG,CAAC,UAAU,EAAE,OAAO,EAAE,KAAK,EAAE,CAAC,CAAC;gBACnG,CAAC,EACD,EAAE,OAAO,EAAE,IAAI,EAAE,cAAc,EAAE,EAAE,MAAM,EAAE,QAAQ,EAAE,KAAK,EAAE,MAAM,EAAE,SAAS,EAAE,MAAM,EAAE,EAAE,CACzF,CAAC;YACH,CAAC;SACD,CAAC,CAAC;IACJ,CAAC,CAAC;AACH,CAAC;AACD,eAAe,yBAAyB,EAAE,CAAC","sourcesContent":["/** bg is an observer/controller of the public session-owned Background capability. */\nimport \"./keybindings.ts\";\nimport { getKeybindings } from \"@earendil-works/pi-tui\";\nimport { isBackgroundTerminal } from \"../../core/background/types.ts\";\nimport type { ExtensionAPI } from \"../../core/extensions/types.ts\";\nimport { boundedText, describeTaskLine, runKill, runList, runRead, runWait } from \"./actions.ts\";\nimport { renderBackgroundCompletion } from \"./completion-render.ts\";\nimport { BG_COMPLETION_TYPE, BG_NOTIFICATION_TYPE } from \"./constants.ts\";\nimport { BackgroundTasksMenu } from \"./manager.ts\";\nimport { type BgRenderState, renderBackgroundNotification, renderBgCall, renderBgResult } from \"./render.ts\";\nimport { BG_PROMPT_GUIDELINES, BG_PROMPT_SNIPPET, BG_TOOL_DESCRIPTION, bgSchema } from \"./schema.ts\";\nimport type { BgDetails, BgNotificationDetails } from \"./types.ts\";\n\nexport function createBackgroundExtension(): (pi: ExtensionAPI) => void {\n\treturn (pi) => {\n\t\tlet unsubscribe: (() => void) | undefined;\n\t\tlet unsubscribeDetachKey: (() => void) | undefined;\n\t\tlet closeMenu: (() => void) | undefined;\n\t\tpi.on(\"session_start\", (_event, ctx) => {\n\t\t\tunsubscribe?.();\n\t\t\tunsubscribeDetachKey?.();\n\t\t\tconst update = () => {\n\t\t\t\t// The status counts backgrounded work only; foreground executions\n\t\t\t\t// are already visible as ordinary tool rows in the transcript.\n\t\t\t\tconst tasks = ctx.background.list().filter((task) => task.mode === \"background\");\n\t\t\t\tconst running = tasks.filter((task) => !isBackgroundTerminal(task.status)).length;\n\t\t\t\tctx.ui.setStatus(\n\t\t\t\t\t\"background\",\n\t\t\t\t\ttasks.length ? `bg ${running} active · ${tasks.length - running} finished` : undefined,\n\t\t\t\t);\n\t\t\t};\n\t\t\tunsubscribe = ctx.background.subscribe(update);\n\t\t\tunsubscribeDetachKey = ctx.ui.onTerminalInput((data) => {\n\t\t\t\tif (!getKeybindings().matches(data, \"app.backgroundTasks.detach\")) return undefined;\n\t\t\t\tconst count = ctx.background.detachForeground();\n\t\t\t\t// Nothing can move: let the key fall through to editor bindings instead of\n\t\t\t\t// spending it on a \"nothing happened\" status line.\n\t\t\t\tif (count === 0) return undefined;\n\t\t\t\tctx.ui.notify(\n\t\t\t\t\t`Moved ${count} execution${count === 1 ? \"\" : \"s\"} to the background. Use /bg to manage tasks.`,\n\t\t\t\t);\n\t\t\t\treturn { consume: true };\n\t\t\t});\n\t\t\tupdate();\n\t\t});\n\t\tpi.on(\"session_shutdown\", (_event, ctx) => {\n\t\t\tunsubscribe?.();\n\t\t\tunsubscribe = undefined;\n\t\t\tunsubscribeDetachKey?.();\n\t\t\tunsubscribeDetachKey = undefined;\n\t\t\tcloseMenu?.();\n\t\t\tcloseMenu = undefined;\n\t\t\tctx.ui.setStatus(\"background\", undefined);\n\t\t});\n\t\tpi.registerTool<typeof bgSchema, BgDetails, BgRenderState>({\n\t\t\tname: \"bg\",\n\t\t\tlabel: \"bg\",\n\t\t\tdescription: BG_TOOL_DESCRIPTION,\n\t\t\tpromptSnippet: BG_PROMPT_SNIPPET,\n\t\t\tpromptGuidelines: BG_PROMPT_GUIDELINES,\n\t\t\tparameters: bgSchema,\n\t\t\tconstrainedSampling: { type: \"json_schema\", strict: \"prefer\" },\n\t\t\tasync execute(_id, params, signal, _onUpdate, ctx) {\n\t\t\t\ttry {\n\t\t\t\t\tswitch (params.action) {\n\t\t\t\t\t\tcase \"read\":\n\t\t\t\t\t\t\treturn await runRead(ctx.background, params);\n\t\t\t\t\t\tcase \"wait\":\n\t\t\t\t\t\t\treturn await runWait(ctx.background, params, signal);\n\t\t\t\t\t\tcase \"kill\":\n\t\t\t\t\t\t\treturn runKill(ctx.background, params);\n\t\t\t\t\t\tcase \"list\":\n\t\t\t\t\t\t\treturn runList(ctx.background);\n\t\t\t\t\t}\n\t\t\t\t} catch (error) {\n\t\t\t\t\t// Lookup failures already carry the current task list from actions.ts.\n\t\t\t\t\tconst message = error instanceof Error ? error.message : String(error);\n\t\t\t\t\tthrow new Error(boundedText(message));\n\t\t\t\t}\n\t\t\t},\n\t\t\trenderCall: renderBgCall,\n\t\t\trenderResult: renderBgResult,\n\t\t});\n\t\t// Stored legacy create results and notification details remain renderable.\n\t\tpi.registerMessageRenderer<BgNotificationDetails>(BG_NOTIFICATION_TYPE, renderBackgroundNotification);\n\t\tpi.registerMessageRenderer(BG_COMPLETION_TYPE, renderBackgroundCompletion);\n\t\tpi.registerCommand(\"bg\", {\n\t\t\tdescription: \"View and manage Bash tasks and Subagent groups\",\n\t\t\thandler: async (_args, ctx) => {\n\t\t\t\tif (ctx.mode !== \"tui\") {\n\t\t\t\t\tctx.ui.notify(\n\t\t\t\t\t\tboundedText(\n\t\t\t\t\t\t\tctx.background\n\t\t\t\t\t\t\t\t.list()\n\t\t\t\t\t\t\t\t.filter((task) => task.mode === \"background\")\n\t\t\t\t\t\t\t\t.slice(0, 10)\n\t\t\t\t\t\t\t\t.map((task) => describeTaskLine(task))\n\t\t\t\t\t\t\t\t.join(\"\\n\"),\n\t\t\t\t\t\t) || \"No background tasks.\",\n\t\t\t\t\t\t\"info\",\n\t\t\t\t\t);\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tcloseMenu?.();\n\t\t\t\tawait ctx.ui.custom<void>(\n\t\t\t\t\t(tui, theme, keybindings, done) => {\n\t\t\t\t\t\tconst close = () => {\n\t\t\t\t\t\t\tif (closeMenu === close) closeMenu = undefined;\n\t\t\t\t\t\t\tdone();\n\t\t\t\t\t\t};\n\t\t\t\t\t\tcloseMenu = close;\n\t\t\t\t\t\treturn new BackgroundTasksMenu({ tui, theme, keybindings, host: ctx.background, onClose: close });\n\t\t\t\t\t},\n\t\t\t\t\t{ overlay: true, overlayOptions: { anchor: \"center\", width: \"100%\", maxHeight: \"100%\" } },\n\t\t\t\t);\n\t\t\t},\n\t\t});\n\t};\n}\nexport default createBackgroundExtension();\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../src/extensions/question/index.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AACH,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,gCAAgC,CAAC;AAcnE,MAAM,CAAC,OAAO,UAAU,QAAQ,CAAC,EAAE,EAAE,YAAY,GAAG,IAAI,
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../src/extensions/question/index.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AACH,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,gCAAgC,CAAC;AAcnE,MAAM,CAAC,OAAO,UAAU,QAAQ,CAAC,EAAE,EAAE,YAAY,GAAG,IAAI,CAqCvD"}
|
|
@@ -2,7 +2,7 @@ import { QUESTION_DESCRIPTION, QUESTION_LABEL, QUESTION_PROMPT_GUIDELINES, QUEST
|
|
|
2
2
|
import { createQuestionDialog } from "./dialog.js";
|
|
3
3
|
import { renderQuestionCall, renderQuestionResult } from "./render.js";
|
|
4
4
|
import { cancelResult, clarificationResult, errorResult, successResult } from "./results.js";
|
|
5
|
-
import { QuestionParams, validateQuestions } from "./schema.js";
|
|
5
|
+
import { normalizeQuestionArguments, QuestionParams, validateQuestions } from "./schema.js";
|
|
6
6
|
export default function question(pi) {
|
|
7
7
|
pi.registerTool({
|
|
8
8
|
name: QUESTION_TOOL_NAME,
|
|
@@ -11,6 +11,8 @@ export default function question(pi) {
|
|
|
11
11
|
promptSnippet: QUESTION_PROMPT_SNIPPET,
|
|
12
12
|
promptGuidelines: QUESTION_PROMPT_GUIDELINES,
|
|
13
13
|
parameters: QuestionParams,
|
|
14
|
+
constrainedSampling: { type: "json_schema", strict: "prefer" },
|
|
15
|
+
prepareArguments: normalizeQuestionArguments,
|
|
14
16
|
executionMode: "sequential",
|
|
15
17
|
renderCall(args, theme, context) {
|
|
16
18
|
return renderQuestionCall(args, theme, context.expanded);
|