@roll-agent/runtime 0.27.0 → 1.0.1
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/engine/agent-session.d.ts +8 -5
- package/dist/engine/agent-session.js +1 -1
- package/dist/engine/cancelled-turn-recovery.d.ts +1 -11
- package/dist/engine/capability-manifest.d.ts +3 -3
- package/dist/engine/compaction-checkpoint.d.ts +486 -3903
- package/dist/engine/compaction-checkpoint.js +1 -1
- package/dist/engine/compaction-semantic-state.d.ts +210 -1804
- package/dist/engine/compactor.d.ts +5 -0
- package/dist/engine/compactor.js +1 -1
- package/dist/engine/conversation-engine.d.ts +24 -42
- package/dist/engine/conversation-engine.js +1 -1
- package/dist/engine/explicit-skill-context.d.ts +6 -62
- package/dist/engine/explicit-skill-context.js +1 -1
- package/dist/engine/model-catalog.d.ts +3 -27
- package/dist/engine/request-budget.d.ts +9 -50
- package/dist/host-contracts/agent-host.d.ts +39 -0
- package/dist/host-contracts/agent-host.js +1 -0
- package/dist/host-contracts/index.d.ts +7 -0
- package/dist/host-contracts/index.js +1 -0
- package/dist/host-contracts/runtime-settings.d.ts +68 -0
- package/dist/host-contracts/runtime-settings.js +1 -0
- package/dist/host-contracts/schedule-tools.d.ts +138 -0
- package/dist/host-contracts/schedule-tools.js +1 -0
- package/dist/index.d.ts +7 -2
- package/dist/index.js +1 -1
- package/dist/interaction/user-input-interaction-manager.d.ts +1 -1
- package/dist/scheduler/calendar.d.ts +13 -51
- package/dist/scheduler/trigger.d.ts +20 -156
- package/dist/server/protocol.d.ts +11 -73
- package/dist/server/runtime-client-interaction-lifecycle.d.ts +2 -2
- package/dist/skills/contracts.d.ts +24 -0
- package/dist/skills/contracts.js +1 -0
- package/dist/skills/index.d.ts +2 -0
- package/dist/skills/index.js +1 -0
- package/dist/skills/invocation.d.ts +29 -0
- package/dist/skills/invocation.js +1 -0
- package/dist/store/semantic-ledger.d.ts +27 -72
- package/dist/store/thread-origin.d.ts +8 -100
- package/dist/store/thread-store.d.ts +3 -3
- package/dist/store/turn-input.d.ts +11 -135
- package/dist/store/turn-input.js +1 -1
- package/dist/tool-bridge/bash-tool.d.ts +1 -13
- package/dist/tool-bridge/build-tools.d.ts +5 -5
- package/dist/tool-bridge/build-tools.js +1 -1
- package/dist/tool-bridge/file-tools/edit-file-tool.d.ts +2 -24
- package/dist/tool-bridge/file-tools/glob-tool.d.ts +1 -7
- package/dist/tool-bridge/file-tools/grep-tool.d.ts +1 -15
- package/dist/tool-bridge/file-tools/list-dir-tool.d.ts +1 -5
- package/dist/tool-bridge/file-tools/read-file-tool.d.ts +1 -9
- package/dist/tool-bridge/file-tools/verify-file-tool.d.ts +5 -8
- package/dist/tool-bridge/file-tools/write-file-tool.d.ts +1 -7
- package/dist/tool-bridge/model-input-schema.d.ts +3 -0
- package/dist/tool-bridge/model-input-schema.js +1 -0
- package/dist/tool-bridge/naming.d.ts +2 -2
- package/dist/tool-bridge/normalize-result.js +1 -1
- package/dist/tool-bridge/observation-recall-tool.d.ts +1 -9
- package/dist/tool-bridge/schedule-create-input.d.ts +9 -75
- package/dist/tool-bridge/schedule-tool.d.ts +1 -1
- package/dist/tool-bridge/schedule-tool.js +1 -1
- package/dist/tool-bridge/session-exec-tool.d.ts +3 -23
- package/dist/tool-bridge/skill-tool.d.ts +2 -8
- package/dist/tool-bridge/skill-tool.js +1 -1
- package/dist/tool-bridge/tool-approval-continuation.d.ts +1 -1
- package/dist/tool-bridge/tool-approval-continuation.js +1 -1
- package/dist/tool-bridge/tool-execution-coordinator.d.ts +3 -26
- package/dist/tool-bridge/tool-execution-coordinator.js +1 -1
- package/dist/tool-bridge/transcript-tool.d.ts +7 -35
- package/dist/tool-bridge/user-input-tool.js +1 -1
- package/dist/tool-contracts/agent-types.d.ts +32 -0
- package/dist/tool-contracts/agent-types.js +1 -0
- package/dist/tool-contracts/execution-timeout.d.ts +2 -0
- package/dist/tool-contracts/execution-timeout.js +1 -0
- package/dist/tool-contracts/index.d.ts +8 -0
- package/dist/tool-contracts/index.js +1 -0
- package/dist/tool-contracts/issues.d.ts +22 -0
- package/dist/tool-contracts/issues.js +1 -0
- package/dist/tool-contracts/json-schema-refs.d.ts +19 -0
- package/dist/tool-contracts/json-schema-refs.js +1 -0
- package/dist/tool-contracts/preflight.d.ts +16 -0
- package/dist/tool-contracts/preflight.js +1 -0
- package/dist/tool-contracts/resource-hints.d.ts +26 -0
- package/dist/tool-contracts/resource-hints.js +1 -0
- package/dist/tool-contracts/results.d.ts +7 -0
- package/dist/tool-contracts/results.js +1 -0
- package/dist/tool-contracts/schema.d.ts +13 -0
- package/dist/tool-contracts/schema.js +1 -0
- package/dist/types/cancellation.d.ts +6 -10
- package/dist/types/events.d.ts +12 -0
- package/dist/types/events.js +1 -1
- package/package.json +17 -6
|
@@ -13,30 +13,8 @@ declare const editFileInputSchema: z.ZodObject<{
|
|
|
13
13
|
old_string: z.ZodString;
|
|
14
14
|
new_string: z.ZodString;
|
|
15
15
|
replace_all: z.ZodOptional<z.ZodBoolean>;
|
|
16
|
-
},
|
|
17
|
-
|
|
18
|
-
new_string: string;
|
|
19
|
-
replace_all?: boolean | undefined;
|
|
20
|
-
}, {
|
|
21
|
-
old_string: string;
|
|
22
|
-
new_string: string;
|
|
23
|
-
replace_all?: boolean | undefined;
|
|
24
|
-
}>, "many">;
|
|
25
|
-
}, "strip", z.ZodTypeAny, {
|
|
26
|
-
file_path: string;
|
|
27
|
-
edits: {
|
|
28
|
-
old_string: string;
|
|
29
|
-
new_string: string;
|
|
30
|
-
replace_all?: boolean | undefined;
|
|
31
|
-
}[];
|
|
32
|
-
}, {
|
|
33
|
-
file_path: string;
|
|
34
|
-
edits: {
|
|
35
|
-
old_string: string;
|
|
36
|
-
new_string: string;
|
|
37
|
-
replace_all?: boolean | undefined;
|
|
38
|
-
}[];
|
|
39
|
-
}>;
|
|
16
|
+
}, z.core.$strip>>;
|
|
17
|
+
}, z.core.$strip>;
|
|
40
18
|
export type EditFileInput = z.infer<typeof editFileInputSchema>;
|
|
41
19
|
export declare function executeEditFile(settings: ResolvedFileToolsSettings, tracker: FileStateTracker, input: EditFileInput, approval?: FileWriteApproval): NormalizedToolResult;
|
|
42
20
|
export declare function buildEditFileTool(settings: ResolvedFileToolsSettings, tracker: FileStateTracker, registry: ToolRegistry, ctx: ToolBridgeContext): ToolSet;
|
|
@@ -8,13 +8,7 @@ export declare const GLOB_TOOL_NAME = "glob";
|
|
|
8
8
|
declare const globInputSchema: z.ZodObject<{
|
|
9
9
|
pattern: z.ZodString;
|
|
10
10
|
path: z.ZodOptional<z.ZodString>;
|
|
11
|
-
},
|
|
12
|
-
pattern: string;
|
|
13
|
-
path?: string | undefined;
|
|
14
|
-
}, {
|
|
15
|
-
pattern: string;
|
|
16
|
-
path?: string | undefined;
|
|
17
|
-
}>;
|
|
11
|
+
}, z.core.$strip>;
|
|
18
12
|
export type GlobInput = z.infer<typeof globInputSchema>;
|
|
19
13
|
export declare function executeGlob(settings: ResolvedFileToolsSettings, input: GlobInput, abortSignal?: AbortSignal): Promise<NormalizedToolResult>;
|
|
20
14
|
export declare function buildGlobTool(settings: ResolvedFileToolsSettings, registry: ToolRegistry, ctx: ToolBridgeContext): ToolSet;
|
|
@@ -12,21 +12,7 @@ declare const grepInputSchema: z.ZodObject<{
|
|
|
12
12
|
context: z.ZodOptional<z.ZodNumber>;
|
|
13
13
|
ignore_case: z.ZodOptional<z.ZodBoolean>;
|
|
14
14
|
max_results: z.ZodOptional<z.ZodNumber>;
|
|
15
|
-
},
|
|
16
|
-
pattern: string;
|
|
17
|
-
path?: string | undefined;
|
|
18
|
-
context?: number | undefined;
|
|
19
|
-
max_results?: number | undefined;
|
|
20
|
-
glob?: string | undefined;
|
|
21
|
-
ignore_case?: boolean | undefined;
|
|
22
|
-
}, {
|
|
23
|
-
pattern: string;
|
|
24
|
-
path?: string | undefined;
|
|
25
|
-
context?: number | undefined;
|
|
26
|
-
max_results?: number | undefined;
|
|
27
|
-
glob?: string | undefined;
|
|
28
|
-
ignore_case?: boolean | undefined;
|
|
29
|
-
}>;
|
|
15
|
+
}, z.core.$strip>;
|
|
30
16
|
export type GrepInput = z.infer<typeof grepInputSchema>;
|
|
31
17
|
export declare function executeGrep(settings: ResolvedFileToolsSettings, input: GrepInput, abortSignal?: AbortSignal): Promise<NormalizedToolResult>;
|
|
32
18
|
export declare function buildGrepTool(settings: ResolvedFileToolsSettings, registry: ToolRegistry, ctx: ToolBridgeContext): ToolSet;
|
|
@@ -7,11 +7,7 @@ import { type ResolvedFileToolsSettings } from "./settings.ts";
|
|
|
7
7
|
export declare const LIST_DIR_TOOL_NAME = "list_dir";
|
|
8
8
|
declare const listDirInputSchema: z.ZodObject<{
|
|
9
9
|
path: z.ZodOptional<z.ZodString>;
|
|
10
|
-
},
|
|
11
|
-
path?: string | undefined;
|
|
12
|
-
}, {
|
|
13
|
-
path?: string | undefined;
|
|
14
|
-
}>;
|
|
10
|
+
}, z.core.$strip>;
|
|
15
11
|
export type ListDirInput = z.infer<typeof listDirInputSchema>;
|
|
16
12
|
export declare function executeListDir(settings: ResolvedFileToolsSettings, input: ListDirInput): NormalizedToolResult;
|
|
17
13
|
export declare function buildListDirTool(settings: ResolvedFileToolsSettings, registry: ToolRegistry, ctx: ToolBridgeContext): ToolSet;
|
|
@@ -10,15 +10,7 @@ declare const readFileInputSchema: z.ZodObject<{
|
|
|
10
10
|
path: z.ZodString;
|
|
11
11
|
offset: z.ZodOptional<z.ZodNumber>;
|
|
12
12
|
limit: z.ZodOptional<z.ZodNumber>;
|
|
13
|
-
},
|
|
14
|
-
path: string;
|
|
15
|
-
limit?: number | undefined;
|
|
16
|
-
offset?: number | undefined;
|
|
17
|
-
}, {
|
|
18
|
-
path: string;
|
|
19
|
-
limit?: number | undefined;
|
|
20
|
-
offset?: number | undefined;
|
|
21
|
-
}>;
|
|
13
|
+
}, z.core.$strip>;
|
|
22
14
|
export type ReadFileInput = z.infer<typeof readFileInputSchema>;
|
|
23
15
|
export declare function executeReadFile(settings: ResolvedFileToolsSettings, tracker: FileStateTracker, input: ReadFileInput): NormalizedToolResult;
|
|
24
16
|
export declare function buildReadFileTool(settings: ResolvedFileToolsSettings, tracker: FileStateTracker, registry: ToolRegistry, ctx: ToolBridgeContext): ToolSet;
|
|
@@ -8,14 +8,11 @@ import { type ResolvedFileToolsSettings } from "./settings.ts";
|
|
|
8
8
|
export declare const VERIFY_FILE_TOOL_NAME = "verify_file";
|
|
9
9
|
declare const verifyFileInputSchema: z.ZodObject<{
|
|
10
10
|
path: z.ZodString;
|
|
11
|
-
level: z.ZodOptional<z.ZodEnum<
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
},
|
|
16
|
-
path: string;
|
|
17
|
-
level?: "project" | "fast" | undefined;
|
|
18
|
-
}>;
|
|
11
|
+
level: z.ZodOptional<z.ZodEnum<{
|
|
12
|
+
project: "project";
|
|
13
|
+
fast: "fast";
|
|
14
|
+
}>>;
|
|
15
|
+
}, z.core.$strip>;
|
|
19
16
|
export type VerifyFileInput = z.infer<typeof verifyFileInputSchema>;
|
|
20
17
|
export declare function renderVerifyReport(absolutePath: string, outcomes: readonly VerifierOutcome[], fastLevelHiddenIds: readonly string[]): string;
|
|
21
18
|
export declare function executeVerifyFile(settings: ResolvedFileToolsSettings, input: VerifyFileInput, abortSignal?: AbortSignal): Promise<NormalizedToolResult>;
|
|
@@ -10,13 +10,7 @@ export declare const WRITE_FILE_TOOL_NAME = "write_file";
|
|
|
10
10
|
declare const writeFileInputSchema: z.ZodObject<{
|
|
11
11
|
file_path: z.ZodString;
|
|
12
12
|
content: z.ZodString;
|
|
13
|
-
},
|
|
14
|
-
content: string;
|
|
15
|
-
file_path: string;
|
|
16
|
-
}, {
|
|
17
|
-
content: string;
|
|
18
|
-
file_path: string;
|
|
19
|
-
}>;
|
|
13
|
+
}, z.core.$strip>;
|
|
20
14
|
export type WriteFileInput = z.infer<typeof writeFileInputSchema>;
|
|
21
15
|
export declare function executeWriteFile(settings: ResolvedFileToolsSettings, tracker: FileStateTracker, input: WriteFileInput, approval?: FileWriteApproval): NormalizedToolResult;
|
|
22
16
|
export declare function buildWriteFileTool(settings: ResolvedFileToolsSettings, tracker: FileStateTracker, registry: ToolRegistry, ctx: ToolBridgeContext): ToolSet;
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{asSchema as e,jsonSchema as o}from"ai";function t(e){const o=e[0];return void 0!==o&&"boolean"!=typeof o&&(o.required?.some(o=>{const t=new Set;return e.every(e=>{if("boolean"==typeof e||"object"!==e.type||void 0!==e.$ref||!e.required?.includes(o))return!1;const n=e.properties?.[o];return void 0!==n&&"boolean"!=typeof n&&void 0===n.$ref&&"string"==typeof n.const&&!t.has(n.const)&&(t.add(n.const),!0)})})??!1)}function n(e){return"boolean"==typeof e?e:r(e)}function r(e){const o={...e};for(const t of["properties","patternProperties","definitions"]){const r=e[t];void 0!==r&&(o[t]=Object.fromEntries(Object.entries(r).map(([e,o])=>[e,n(o)])))}for(const t of["allOf","anyOf","oneOf"]){const r=e[t];void 0!==r&&(o[t]=r.map(n))}void 0!==e.items&&(o.items=Array.isArray(e.items)?e.items.map(n):n(e.items));for(const t of["additionalProperties","additionalItems","contains","propertyNames","not","if","then","else"]){const r=e[t];void 0!==r&&(o[t]=n(r))}return void 0!==o.oneOf&&void 0===o.anyOf&&t(o.oneOf)&&(o.anyOf=o.oneOf,delete o.oneOf),o}function i(e){return"then"in e&&"function"==typeof e.then}export function modelToolInputSchema(t){const n=e(t);return o(()=>{const e=n.jsonSchema;return i(e)?e.then(r):r(e)},void 0===n.validate?{}:{validate:n.validate})}
|
|
@@ -1,9 +1,9 @@
|
|
|
1
1
|
import type { AppOutputContract } from "@roll-agent/protocol/app-output";
|
|
2
|
-
import type { AgentRuntimeOwnership, AgentSourceType,
|
|
2
|
+
import type { AgentRuntimeOwnership, AgentSourceType, AgentTransportKind } from "../tool-contracts/agent-types.ts";
|
|
3
3
|
import type { ToolAnnotations } from "../types/policy.ts";
|
|
4
4
|
export interface ToolRouteMetadata {
|
|
5
5
|
readonly agentSource?: AgentSourceType;
|
|
6
|
-
readonly transport?:
|
|
6
|
+
readonly transport?: AgentTransportKind;
|
|
7
7
|
readonly runtimeOwnership?: AgentRuntimeOwnership;
|
|
8
8
|
readonly annotations?: ToolAnnotations;
|
|
9
9
|
readonly appOutput?: AppOutputContract;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{normalizeAppOutput as t,hasCompletedAppOutputMarker as e}from"./normalize-app-output.js";import{extractTextContent as n,isToolErrorResult as o}from"
|
|
1
|
+
import{normalizeAppOutput as t,hasCompletedAppOutputMarker as e}from"./normalize-app-output.js";import{extractTextContent as n,isToolErrorResult as o}from"../tool-contracts/results.js";export const TOOL_OUTCOME_KINDS={success:"success",userRejected:"user_rejected",policyDenied:"policy_denied",invalidInput:"invalid_input",cancelled:"cancelled",toolFailed:"tool_failed"};export const TOOL_CANCELLATION_EXECUTION_STATES={notExecuted:"not_executed",outcomeUnknown:"outcome_unknown"};const r=16e3,i=64,u=6e4,s=12e6,l=128,c="\n\n[工具模型内容已截断;完整结果仍保留在 raw 视图]";function a(t){return"object"==typeof t&&null!==t&&!Array.isArray(t)}function p(t){if(null===t||"string"==typeof t||"boolean"==typeof t||"number"==typeof t&&Number.isFinite(t))return t;if(Array.isArray(t))return t.map(p);if(a(t)){const e={};for(const[n,o]of Object.entries(t))e[n]=p(o);return e}return void 0===t?null:String(t)}function d(t){if(!t)return!1;const e=t.replace(/([a-z0-9])([A-Z])/gu,"$1_$2").toLowerCase().split(/[^a-z0-9]+/u).filter(t=>t.length>0);return 1===e.length&&["data","image","audio"].includes(e[0]??"")||e.some(t=>["base64","blob","bytes"].includes(t))||e.includes("data")&&e.some(t=>["image","audio","binary"].includes(t))}function f(t){return`[binary content omitted: ${String(t.length)} chars]`}function y(t,e,n){return t.length<=e?t:e<=n.length?n.slice(0,e):`${t.slice(0,e-n.length)}${n}`}function O(t,e,n=0){if(n>16)return"[nested value omitted]";if("string"==typeof t)return d(e)||/^data:[^,]+;base64,/iu.test(t)?f(t):y(t,u,c);if(null===t||"boolean"==typeof t||"number"==typeof t)return Number.isFinite(t)||"number"!=typeof t?t:String(t);if(Array.isArray(t)){const e=t.slice(0,l).map(t=>O(t,void 0,n+1));return t.length>l&&e.push(`[${String(t.length-l)} items omitted]`),e}if(a(t)){const e={},o=Object.entries(t).filter(([t])=>"_meta"!==t);for(const[t,r]of o.slice(0,l))e[t]=O(r,t,n+1);return o.length>l&&(e["[omitted]"]=`${String(o.length-l)} fields`),e}return void 0===t?null:String(t)}function m(t,e,n=0){if(n>12)return"[nested value omitted]";if("string"==typeof t)return d(e)||/^data:[^,]+;base64,/iu.test(t)?f(t):t.length<=r?t:T(t);if(null===t||"boolean"==typeof t||"number"==typeof t)return Number.isFinite(t)||"number"!=typeof t?t:String(t);if(Array.isArray(t)){const e=t.slice(0,i).map(t=>m(t,void 0,n+1));return t.length>i&&e.push(`[${String(t.length-i)} items omitted]`),e}if(a(t)){const e={},o=Object.entries(t).filter(([t])=>"_meta"!==t);for(const[t,r]of o.slice(0,i))e[t]=m(r,t,n+1);return o.length>i&&(e["[omitted]"]=`${String(o.length-i)} fields`),e}return void 0===t?null:String(t)}function g(t){return"string"==typeof t?t:JSON.stringify(p(t),null,2)}function T(t){return t.length<=r?t:`${t.slice(0,r)}\n\n[工具展示内容已截断]`}function x(t,e=!1){const n=O(t),o=g(n);if(o.length<=u)return e?{type:"error-json",value:n}:{type:"json",value:n};const r=y(o,u,c);return e?{type:"error-text",value:r}:{type:"text",value:r}}function _(t,e=!1){const n=y(t,u,c);return e?{type:"error-text",value:n}:{type:"text",value:n}}function h(t){const e=[];let n=u,o=s;for(const r of t.slice(0,l)){if(n<=0&&o<=0)break;if("text"===r.type){if(n<=0)continue;const t=y(r.text,n,c);e.push({type:"text",text:t}),n-=t.length;continue}const t=r.data.data.length;if(t<=o){e.push(r),o-=t;continue}if(n<=0)continue;const i=y(`[${r.mediaType} file omitted from model projection: ${String(t)} chars]`,n,c);e.push({type:"text",text:i}),n-=i.length}if(t.length>l&&n>0){const o=y(`[${String(t.length-l)} model content parts omitted]`,n,c);e.push({type:"text",text:o})}return e}function v(t,e){return e.kind===TOOL_OUTCOME_KINDS.userRejected?{type:"execution-denied",...void 0!==e.reason?{reason:e.reason}:{}}:e.kind===TOOL_OUTCOME_KINDS.success?"string"==typeof t?_(t):x(t):x({code:e.kind,message:"string"==typeof t?t:g(t),...void 0!==e.reason?{reason:e.reason}:{}},!0)}export function createToolResult(t,e,n={}){const o=t.kind!==TOOL_OUTCOME_KINDS.success;return{raw:Object.prototype.hasOwnProperty.call(n,"raw")?n.raw:e,model:n.model??v(e,t),display:e,outcome:t,output:e,isError:o}}export function successfulToolResult(t,e={}){return createToolResult({kind:TOOL_OUTCOME_KINDS.success},t,e)}export function failedToolResult(t,e,n={}){return createToolResult({kind:t,...void 0!==n.reason?{reason:n.reason}:{}},e,n)}function S(t){return a(t)?t.content:void 0}function b(t){return a(t)?t.structuredContent:void 0}function E(t){return a(t)&&"toolResult"in t?{value:t.toolResult,wrapped:!0}:{value:t,wrapped:!1}}function N(t){if("string"==typeof t.data&&"string"==typeof t.mimeType)return{type:"file",data:{type:"data",data:t.data},mediaType:t.mimeType}}function C(t){const e=a(t.resource)?t.resource:void 0;if(!e)return;const n="string"==typeof e.uri?e.uri:"embedded resource";return"string"==typeof e.text?{type:"text",text:`[${n}]\n${e.text}`}:"string"==typeof e.blob?{type:"file",data:{type:"data",data:e.blob},mediaType:"string"==typeof e.mimeType?e.mimeType:"application/octet-stream",filename:n}:void 0}function $(t){if("string"!=typeof t.uri)return;const e="string"==typeof t.name?t.name:"resource",n="string"==typeof t.description?` — ${t.description}`:"";return{type:"text",text:`[${e}] ${t.uri}${n}`}}function L(t){if(a(t)&&"string"==typeof t.type)return"text"===t.type&&"string"==typeof t.text?{type:"text",text:t.text}:"image"===t.type||"audio"===t.type?N(t):"resource"===t.type?C(t):"resource_link"===t.type?$(t):void 0}function k(t,e,n,o){if(n)return v(e,{kind:TOOL_OUTCOME_KINDS.toolFailed});const r=S(t),i=Array.isArray(r)?r.flatMap(t=>{const e=L(t);return void 0===e?[]:[e]}):[],u=b(t);return void 0!==u&&i.length>0&&i.push({type:"text",text:`[structuredContent]\n${g(O(u))}`}),i.length>0?{type:"content",value:h(i)}:void 0!==u?x(u):o?"string"==typeof t?_(t):x(t):v(e,{kind:TOOL_OUTCOME_KINDS.success})}function I(t,e,o){const u=n(S(t));if(u.length>0)return T(u.join("\n"));const s=b(t);if(void 0!==s){const t=m(s),e=g(t);return e.length<=r?t:T(e)}const l=S(t);if(Array.isArray(l)&&l.length>0){const t=l.slice(0,i).flatMap(t=>{if(!a(t)||"string"!=typeof t.type)return[];const e="string"==typeof t.mimeType?` ${t.mimeType}`:"";return[`[${t.type}${e}]`]});if(t.length>0){const e=l.length-Math.min(l.length,i);return`${t.join("\n")}${e>0?`\n[另有 ${String(e)} 项未展示]`:""}`}}if(o){const e=m(t),n=g(e);return n.length<=r?e:T(n)}return e?"工具执行失败(无可展示的文本结果)":"工具执行完成(无可展示的文本结果)"}export function normalizeToolResult(n,r){const i=E(n),u=o(i.value)&&!(void 0!==r&&e(i.value)),s=I(i.value,u,i.wrapped);return{...createToolResult(u?{kind:TOOL_OUTCOME_KINDS.toolFailed}:{kind:TOOL_OUTCOME_KINDS.success},s,{raw:n,model:k(i.value,s,u,i.wrapped)}),...void 0===r?{}:{appOutput:t(i.value,r)}}}export function isToolCancellationExecutionState(t){return Object.values(TOOL_CANCELLATION_EXECUTION_STATES).some(e=>e===t)}function A(t){return!(!a(t)||"string"!=typeof t.kind)&&(!!Object.values(TOOL_OUTCOME_KINDS).some(e=>e===t.kind)&&((void 0===t.reason||"string"==typeof t.reason)&&(t.kind!==TOOL_OUTCOME_KINDS.cancelled?void 0===t.executionState:void 0===t.executionState||isToolCancellationExecutionState(t.executionState))))}export function isNormalizedToolResult(t){return a(t)&&"raw"in t&&"model"in t&&"display"in t&&A(t.outcome)}export function readToolOutcome(t){return isNormalizedToolResult(t)?t.outcome:a(t)&&"execution-denied"===t.type?{kind:TOOL_OUTCOME_KINDS.userRejected,..."string"==typeof t.reason?{reason:t.reason}:{}}:a(t)&&"string"==typeof t.type&&t.type.startsWith("error")||M(t)?{kind:TOOL_OUTCOME_KINDS.toolFailed}:{kind:TOOL_OUTCOME_KINDS.success}}function M(t){return a(t)&&!0===t.isError}export function readIsError(t){return readToolOutcome(t).kind!==TOOL_OUTCOME_KINDS.success}export function readDisplayOutput(t){return isNormalizedToolResult(t)?t.display:a(t)&&"output"in t?t.output:t}export function toolResultToModelOutput(t){return t.model}
|
|
@@ -7,15 +7,7 @@ declare const inputSchema: z.ZodObject<{
|
|
|
7
7
|
resultId: z.ZodString;
|
|
8
8
|
afterNode: z.ZodOptional<z.ZodNumber>;
|
|
9
9
|
limit: z.ZodOptional<z.ZodNumber>;
|
|
10
|
-
},
|
|
11
|
-
resultId: string;
|
|
12
|
-
limit?: number | undefined;
|
|
13
|
-
afterNode?: number | undefined;
|
|
14
|
-
}, {
|
|
15
|
-
resultId: string;
|
|
16
|
-
limit?: number | undefined;
|
|
17
|
-
afterNode?: number | undefined;
|
|
18
|
-
}>;
|
|
10
|
+
}, z.core.$strict>;
|
|
19
11
|
export type ObservationRecallInput = z.infer<typeof inputSchema>;
|
|
20
12
|
export type ObservationRecallReader = (input: ObservationRecallInput) => unknown;
|
|
21
13
|
export declare function buildObservationRecallToolset(reader: ObservationRecallReader, registry: ToolRegistry, coordinator?: ToolExecutionCoordinator, resourceKey?: string): ToolSet;
|
|
@@ -1,91 +1,25 @@
|
|
|
1
1
|
import { z } from "zod";
|
|
2
|
-
import type { ScheduleToolCreateRequest } from "
|
|
2
|
+
import type { ScheduleToolCreateRequest } from "../host-contracts/schedule-tools.ts";
|
|
3
3
|
/** Provider strict mode requires every property; null represents only declared defaults. */
|
|
4
4
|
export declare const scheduleCreateInputSchema: z.ZodObject<{
|
|
5
5
|
name: z.ZodString;
|
|
6
6
|
prompt: z.ZodString;
|
|
7
|
-
recurrence: z.ZodDiscriminatedUnion<
|
|
7
|
+
recurrence: z.ZodDiscriminatedUnion<[z.ZodObject<{
|
|
8
8
|
kind: z.ZodLiteral<"interval">;
|
|
9
9
|
every: z.ZodString;
|
|
10
|
-
},
|
|
11
|
-
kind: "interval";
|
|
12
|
-
every: string;
|
|
13
|
-
}, {
|
|
14
|
-
kind: "interval";
|
|
15
|
-
every: string;
|
|
16
|
-
}>, z.ZodObject<{
|
|
10
|
+
}, z.core.$strict>, z.ZodObject<{
|
|
17
11
|
time: z.ZodString;
|
|
18
|
-
} & {
|
|
19
12
|
kind: z.ZodLiteral<"daily">;
|
|
20
|
-
timeZone: z.ZodNullable<z.
|
|
21
|
-
},
|
|
22
|
-
|
|
23
|
-
time: string;
|
|
24
|
-
timeZone: string | null;
|
|
25
|
-
}, {
|
|
26
|
-
kind: "daily";
|
|
27
|
-
time: string;
|
|
28
|
-
timeZone: string | null;
|
|
29
|
-
}>, z.ZodObject<{
|
|
13
|
+
timeZone: z.ZodNullable<z.ZodPipe<z.ZodString, z.ZodTransform<string, string>>>;
|
|
14
|
+
}, z.core.$strict>, z.ZodObject<{
|
|
15
|
+
weekdays: z.ZodPipe<z.ZodArray<z.ZodNumber>, z.ZodTransform<number[], number[]>>;
|
|
30
16
|
time: z.ZodString;
|
|
31
|
-
weekdays: z.ZodEffects<z.ZodArray<z.ZodNumber, "many">, number[], number[]>;
|
|
32
|
-
} & {
|
|
33
17
|
kind: z.ZodLiteral<"weekly">;
|
|
34
|
-
timeZone: z.ZodNullable<z.
|
|
35
|
-
},
|
|
36
|
-
kind: "weekly";
|
|
37
|
-
time: string;
|
|
38
|
-
timeZone: string | null;
|
|
39
|
-
weekdays: number[];
|
|
40
|
-
}, {
|
|
41
|
-
kind: "weekly";
|
|
42
|
-
time: string;
|
|
43
|
-
timeZone: string | null;
|
|
44
|
-
weekdays: number[];
|
|
45
|
-
}>]>;
|
|
18
|
+
timeZone: z.ZodNullable<z.ZodPipe<z.ZodString, z.ZodTransform<string, string>>>;
|
|
19
|
+
}, z.core.$strict>], "kind">;
|
|
46
20
|
startAt: z.ZodNullable<z.ZodString>;
|
|
47
21
|
cwd: z.ZodNullable<z.ZodString>;
|
|
48
22
|
rounds: z.ZodNullable<z.ZodNumber>;
|
|
49
23
|
maxRun: z.ZodNullable<z.ZodString>;
|
|
50
|
-
},
|
|
51
|
-
name: string;
|
|
52
|
-
prompt: string;
|
|
53
|
-
cwd: string | null;
|
|
54
|
-
startAt: string | null;
|
|
55
|
-
maxRun: string | null;
|
|
56
|
-
rounds: number | null;
|
|
57
|
-
recurrence: {
|
|
58
|
-
kind: "interval";
|
|
59
|
-
every: string;
|
|
60
|
-
} | {
|
|
61
|
-
kind: "daily";
|
|
62
|
-
time: string;
|
|
63
|
-
timeZone: string | null;
|
|
64
|
-
} | {
|
|
65
|
-
kind: "weekly";
|
|
66
|
-
time: string;
|
|
67
|
-
timeZone: string | null;
|
|
68
|
-
weekdays: number[];
|
|
69
|
-
};
|
|
70
|
-
}, {
|
|
71
|
-
name: string;
|
|
72
|
-
prompt: string;
|
|
73
|
-
cwd: string | null;
|
|
74
|
-
startAt: string | null;
|
|
75
|
-
maxRun: string | null;
|
|
76
|
-
rounds: number | null;
|
|
77
|
-
recurrence: {
|
|
78
|
-
kind: "interval";
|
|
79
|
-
every: string;
|
|
80
|
-
} | {
|
|
81
|
-
kind: "daily";
|
|
82
|
-
time: string;
|
|
83
|
-
timeZone: string | null;
|
|
84
|
-
} | {
|
|
85
|
-
kind: "weekly";
|
|
86
|
-
time: string;
|
|
87
|
-
timeZone: string | null;
|
|
88
|
-
weekdays: number[];
|
|
89
|
-
};
|
|
90
|
-
}>;
|
|
24
|
+
}, z.core.$strict>;
|
|
91
25
|
export declare function toScheduleCreateRequest(input: z.output<typeof scheduleCreateInputSchema>): ScheduleToolCreateRequest;
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { type ToolSet } from "ai";
|
|
2
|
-
import type { ScheduleToolPort } from "
|
|
2
|
+
import type { ScheduleToolPort } from "../host-contracts/schedule-tools.ts";
|
|
3
3
|
import { type ToolBridgeContext } from "./build-tools.ts";
|
|
4
4
|
import type { ToolRegistry } from "./naming.ts";
|
|
5
5
|
export declare const SCHEDULE_TOOL_AGENT_NAME = "roll";
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{tool as e}from"ai";import{z as t}from"zod";import{buildScheduleExtendTools as r}from"./schedule-extend-tool.js";import{SCHEDULE_STATUSES as n}from"../scheduler/types.js";import{systemTimeZone as
|
|
1
|
+
import{tool as e}from"ai";import{z as t}from"zod";import{buildScheduleExtendTools as r}from"./schedule-extend-tool.js";import{SCHEDULE_STATUSES as n}from"../scheduler/types.js";import{systemTimeZone as o}from"../scheduler/calendar.js";import{computeNextRunAtMs as i}from"../scheduler/trigger.js";import{scheduleCreateInputSchema as s,toScheduleCreateRequest as a}from"./schedule-create-input.js";import{modelToolInputSchema as u}from"./model-input-schema.js";import{gateToolCall as c}from"./build-tools.js";import{TOOL_OUTCOME_KINDS as l,failedToolResult as d,successfulToolResult as m,toolResultToModelOutput as p}from"./normalize-result.js";import{TOOL_RESOURCE_ACCESS_MODES as g,executeCoordinatedTool as $}from"./tool-execution-coordinator.js";export const SCHEDULE_TOOL_AGENT_NAME="roll";export const SCHEDULE_CREATE_TOOL_NAME="schedule_create";export const SCHEDULE_LIST_TOOL_NAME="schedule_list";export const SCHEDULE_CREATE_TOOL_ID="roll__schedule_create";export const SCHEDULE_LIST_TOOL_ID="roll__schedule_list";const f=t.object({status:t.enum(["all",...Object.values(n)]).optional().describe("按状态过滤,省略时返回全部"),offset:t.number().int().min(0).optional().describe("分页偏移,默认 0"),limit:t.number().int().min(1).max(100).optional().describe("最多返回条数,默认 50")}),h=Symbol("schedule-invalid-input");function _(e){return"object"==typeof e&&null!==e&&e.kind===h}function x(e){return"object"==typeof e&&null!==e&&!1===e.ok}function y(e){const t="invalid_input"===e.code||"schedule_invalid"===e.code||"schedule_trigger_invalid"===e.code?l.invalidInput:l.toolFailed;return d(t,e.message,{raw:e})}function v(e){return 0===e.warnings.length?"":`\n${e.warnings.map(e=>`注意:${e.message}。`).join("\n")}`}function E(e){const t="calendar"===e.trigger.kind?e.trigger.calendar.timeZone:e.trigger.timeZone??o();return{name:e.name,prompt:e.prompt,every:e.everyDisplay,recurrence:e.everyDisplay,cwd:e.cwd,maxRun:e.maxRunDisplay,firstRunAt:S(e.firstRunAt,t),firstRunAtIso:e.firstRunAt,timeZone:t,...1===e.maxRounds?{}:{nextRunAtEstimate:S(new Date(i(e.trigger,Date.parse(e.firstRunAt))).toISOString(),t)},timingSemantics:"interval"===e.trigger.kind?"第二轮时间仅为预计;按每轮实际领取时间加间隔计算,延迟领取时顺延,不固定每天执行":"按保存的时区和日历规则匹配;跳时日期跳过,重复钟点仅执行较早一次",rounds:void 0===e.maxRounds?"不限轮数":`最多自动执行 ${String(e.maxRounds)} 轮`,lifecycle:void 0===e.maxRounds?"会持续运行,直到暂停或删除;创建时记录当前权限边界":"达到轮数上限后,最后一轮执行、重试及清场结算完毕自动结束;创建时记录当前权限边界",...e.readiness.warnings.length>0?{serviceStatus:e.readiness.warnings.map(e=>e.message).join(";")}:{}}}function S(e,t=o()){const r=new Date(e);return Number.isNaN(r.getTime())?e:r.toLocaleString("zh-CN",{timeZone:t,hour12:!1})}export function buildScheduleToolset(t,n,i){const R=t.includeCreate??!0,j=R?n.register("roll","schedule_create"):void 0,A=n.register("roll","schedule_list"),w={captureExecutionState:e=>{const r=s.safeParse(e);return r.success?t.port.captureCreate(a(r.data),t.sessionCwd):{kind:h,message:`参数校验失败: ${r.error.issues.map(e=>`${e.path.join(".")||"input"}: ${e.message}`).join("; ")}。使用唯一 recurrence 分支;今天/明天某时填写 startAt,缺少两轮间隔先询问用户。缺省字段填写 null。不要原样重试相同参数。`}},prepare:async(e,t)=>{if(_(t))return d(l.invalidInput,t.message);if(x(t))return y(t);const r=t;return c(i,"roll","schedule_create",E(r),void 0,{explanation:`将登记定时任务「${r.name}」(${r.everyDisplay})`})},resources:()=>[{key:"schedule-ledger",mode:g.write}]};void 0!==j&&i.coordinator?.register(j,w);const D={prepare:async e=>c(i,"roll","schedule_list",e??{},{readOnlyHint:!0}),resources:()=>[{key:"schedule-ledger",mode:g.read}]};i.coordinator?.register(A,D);const b=void 0===j?{}:{[j]:e({description:"登记定时任务,每轮无人值守 chat 执行 prompt。startAt=开始时间,recurrence=重复规则,rounds=总轮数,三个维度独立。今天/明天某时不是 daily;缺少两轮间隔先澄清,不能猜成每天一次。信息齐全后只做工具自带的完整参数确认,不重复口头确认。可选值用 null 表示缺省。不支持 cron 或每天开启一组多轮循环。",inputSchema:u(s),strict:!0,toModelOutput:({output:e})=>p(e),execute:async(e,r)=>$(i.coordinator,w,j,r.toolCallId,e,r.abortSignal,async e=>{if(_(e))return d(l.invalidInput,e.message);if(x(e))return y(e);const r=e,n=await t.port.create(r);if(x(n))return y(n);const i=n.schedule,s="calendar"===i.trigger.spec?.kind?i.trigger.spec.calendar.timeZone:i.trigger.spec?.timeZone??o(),a=n.created?`已登记定时任务 "${i.name}"(${i.trigger.display},单次上限 ${i.maxRun.display})。`:n.reauthorized?`已存在相同定义的任务 "${i.name}"(id ${i.id}),未重复创建;已按当前权限边界重新授权。`:`已存在相同定义的任务 "${i.name}"(id ${i.id}),未重复创建。`,u=void 0===i.nextRunAt?"":`下次运行约 ${S(i.nextRunAt,s)}(${s})。`,c=v(n.readiness)||(n.readiness.automaticRunsReady?"":"\n注意:调度服务未就绪,任务不会自动执行。");return m(`${a}${null===i.rounds.max?"":`最多自动执行 ${String(i.rounds.max)} 轮。`}${i.roundsDisplay}。${u}${c}`,{raw:n})})})},O={[A]:e({description:"列出当前配置下已登记的定时任务(含状态、频率、下次运行时间与最近错误摘要)。创建前可用它确认是否已有同类任务。",inputSchema:f,toModelOutput:({output:e})=>p(e),execute:async(e,r)=>$(i.coordinator,D,A,r.toolCallId,e,r.abortSignal,async()=>{const r=f.safeParse(e??{});if(!r.success)return d(l.invalidInput,`参数校验失败: ${r.error.issues.map(e=>e.message).join("; ")}`);const n=await t.port.list(r.data,t.sessionCwd);if(x(n))return y(n);if(0===n.total)return m(`暂无定时任务。${v(n.readiness)}`.trim(),{raw:n});const i=n.schedules.map(e=>{const t="active"===e.status&&void 0!==e.nextRunAt?`,下次 ${S(e.nextRunAt,e.timeZone)}(${e.timeZone??o()})`:"",r=void 0===e.lastError?"":`,最近错误:${e.lastError}`;return`- ${e.name}(${e.status},${e.trigger},${e.roundsDisplay}${t})id=${e.id}\n 内容:${e.promptExcerpt}${r}`}),s=n.hasMore?`\n共 ${String(n.total)} 个,仅显示 ${String(n.schedules.length)} 个;用 offset/limit 翻页。`:"";return m(`${i.join("\n")}${s}${v(n.readiness)}`,{raw:n})})})};return{createTools:b,extendTools:R?r(t,n,i):{},listTools:O}}
|
|
@@ -27,33 +27,13 @@ declare const execCommandInputSchema: z.ZodObject<{
|
|
|
27
27
|
workdir: z.ZodOptional<z.ZodString>;
|
|
28
28
|
yield_time_ms: z.ZodOptional<z.ZodNumber>;
|
|
29
29
|
max_output_tokens: z.ZodOptional<z.ZodNumber>;
|
|
30
|
-
},
|
|
31
|
-
command: string;
|
|
32
|
-
explanation?: string | undefined;
|
|
33
|
-
workdir?: string | undefined;
|
|
34
|
-
yield_time_ms?: number | undefined;
|
|
35
|
-
max_output_tokens?: number | undefined;
|
|
36
|
-
}, {
|
|
37
|
-
command: string;
|
|
38
|
-
explanation?: string | undefined;
|
|
39
|
-
workdir?: string | undefined;
|
|
40
|
-
yield_time_ms?: number | undefined;
|
|
41
|
-
max_output_tokens?: number | undefined;
|
|
42
|
-
}>;
|
|
30
|
+
}, z.core.$strip>;
|
|
43
31
|
declare const execPollInputSchema: z.ZodObject<{
|
|
44
32
|
session_id: z.ZodNumber;
|
|
45
33
|
chars: z.ZodDefault<z.ZodString>;
|
|
46
34
|
yield_time_ms: z.ZodOptional<z.ZodNumber>;
|
|
47
|
-
},
|
|
48
|
-
|
|
49
|
-
chars: string;
|
|
50
|
-
yield_time_ms?: number | undefined;
|
|
51
|
-
}, {
|
|
52
|
-
session_id: number;
|
|
53
|
-
yield_time_ms?: number | undefined;
|
|
54
|
-
chars?: string | undefined;
|
|
55
|
-
}>;
|
|
56
|
-
declare const execListInputSchema: z.ZodObject<{}, "strip", z.ZodTypeAny, {}, {}>;
|
|
35
|
+
}, z.core.$strip>;
|
|
36
|
+
declare const execListInputSchema: z.ZodObject<{}, z.core.$strip>;
|
|
57
37
|
export type ExecCommandInput = z.infer<typeof execCommandInputSchema>;
|
|
58
38
|
export type ExecPollInput = z.infer<typeof execPollInputSchema>;
|
|
59
39
|
export type ExecListInput = z.infer<typeof execListInputSchema>;
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { type ToolSet } from "ai";
|
|
2
2
|
import { z } from "zod";
|
|
3
|
-
import { SKILL_TOOL_ID, type SkillLibrary } from "
|
|
3
|
+
import { SKILL_TOOL_ID, type SkillLibrary } from "../skills/contracts.ts";
|
|
4
4
|
import type { ToolRegistry } from "./naming.ts";
|
|
5
5
|
import { type NormalizedToolResult } from "./normalize-result.ts";
|
|
6
6
|
import { type ToolExecutionCoordinator } from "./tool-execution-coordinator.ts";
|
|
@@ -10,13 +10,7 @@ export { SKILL_TOOL_ID };
|
|
|
10
10
|
declare const skillToolInputSchema: z.ZodObject<{
|
|
11
11
|
name: z.ZodString;
|
|
12
12
|
reference: z.ZodOptional<z.ZodString>;
|
|
13
|
-
},
|
|
14
|
-
name: string;
|
|
15
|
-
reference?: string | undefined;
|
|
16
|
-
}, {
|
|
17
|
-
name: string;
|
|
18
|
-
reference?: string | undefined;
|
|
19
|
-
}>;
|
|
13
|
+
}, z.core.$strip>;
|
|
20
14
|
export type SkillToolInput = z.infer<typeof skillToolInputSchema>;
|
|
21
15
|
export declare function executeSkillTool(library: SkillLibrary, input: SkillToolInput): NormalizedToolResult;
|
|
22
16
|
export declare function buildSkillToolset(library: SkillLibrary | (() => SkillLibrary), registry: ToolRegistry, coordinator?: ToolExecutionCoordinator): ToolSet;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{tool as e}from"ai";import{z as
|
|
1
|
+
import{tool as e}from"ai";import{z as o}from"zod";import{SKILL_TOOL_ID as r}from"../skills/contracts.js";import{TOOL_OUTCOME_KINDS as n,failedToolResult as t,successfulToolResult as i,toolResultToModelOutput as l}from"./normalize-result.js";import{TOOL_RESOURCE_ACCESS_MODES as s,executeCoordinatedTool as c}from"./tool-execution-coordinator.js";export const SKILL_TOOL_AGENT_NAME="roll";export const SKILL_TOOL_NAME="skill";export{r as SKILL_TOOL_ID};const m=6e4,f=new Set(["",".","./","/","skill.md","./skill.md","/skill.md"]),u=o.object({name:o.string().trim().min(1).describe("要加载的 skill 名称(见 system prompt 中的 Skills 目录)"),reference:o.string().optional().describe("仅在加载 references/ 下的文件时填写,如 references/workflows.md;加载主 SKILL.md 时省略此参数")});function a(e){return e.length<=m?e:`${e.slice(0,m)}\n\n[内容过长已截断,共 ${String(e.length)} 字符]`}function d(e){if(void 0===e)return;const o=e.trim();return f.has(o.toLowerCase())?void 0:o}function k(e,o){return void 0===e?o:[`SKILL_ROOT=${e}`,"这是该 skill 的 canonical absolute root。所有 scripts/、references/ 和其它相对路径必须相对 SKILL_ROOT 解析;执行脚本时将 workdir 设为 SKILL_ROOT,不要搜索其它 skill 目录。","",o].join("\n")}function p(e,o){const r=e.list().map(e=>e.name).join(", ");return t(n.invalidInput,`skill "${o}" 不存在。可用 skill: ${r}`)}function L(e,o){const r=e.load(o);if(!r)return e.list().some(e=>e.name===o)?t(n.toolFailed,`skill "${o}" 已发现,但主文档加载失败;请检查 SKILL.md 是否可读及格式是否有效`):p(e,o);const l=r.referencePaths.length>0?`\n\n可用 references(传 reference 参数加载):\n${r.referencePaths.map(e=>`- ${e}`).join("\n")}`:"";return i(k(r.skillRoot,`${a(r.content)}${l}`))}function S(e,o,r){if(!e.list().some(e=>e.name===o))return p(e,o);const l=void 0===e.loadReferenceDocument?void 0:e.loadReferenceDocument(o,r),s=void 0===e.loadReferenceDocument?e.loadReference(o,r):l?.content;return void 0===s?t(n.invalidInput,`skill "${o}" 中不存在 reference "${r}"。加载主 SKILL.md 时请省略 reference;加载附加文档时仅支持 skill 目录内 references/ 下的文件。`):i(k(l?.skillRoot,a(s)))}export function executeSkillTool(e,o){const r=d(o.reference);return void 0!==r?S(e,o.name,r):L(e,o.name)}export function buildSkillToolset(o,r,n){const t="function"==typeof o?o:()=>o,i=r.register("roll","skill"),m={resources:()=>[{key:"skill-library",mode:s.read}]};return n?.register(i,m),{[i]:e({description:"加载 skill 主说明书时只传 name,不要传 reference;仅加载其 references/ 下的文件时才传 reference。执行涉及某个 skill 领域的任务前,先用它读取流程与约束。",inputSchema:u,toModelOutput:({output:e})=>l(e),execute:(e,o)=>c(n,m,i,o.toolCallId,e,o.abortSignal,()=>Promise.resolve(executeSkillTool(t(),e)))})}}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import type { AgentTool } from "
|
|
1
|
+
import type { AgentTool } from "../tool-contracts/agent-types.ts";
|
|
2
2
|
import type { ToolAnnotations } from "../types/policy.ts";
|
|
3
3
|
import type { ToolBridgeContext } from "./build-tools.ts";
|
|
4
4
|
import { type NormalizedToolResult } from "./normalize-result.ts";
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{z as t}from"zod";import{preflightToolCall as e}from"
|
|
1
|
+
import{z as t}from"zod";import{preflightToolCall as e}from"../tool-contracts/preflight.js";import{createToolResult as o,failedToolResult as r,normalizeToolResult as n,TOOL_OUTCOME_KINDS as a}from"./normalize-result.js";const i=t.object({id:t.string().min(1).max(256)}).strict(),s=t.object({code:t.literal("needs_confirmation"),details:t.object({executionState:t.literal("not_executed"),approvalRequest:t.object({id:t.string().min(1).max(256),tool:t.string().min(1).max(256),expiresAt:t.string().datetime(),summary:t.string().max(2e3).optional(),retryInput:t.union([t.object({scriptApproval:i}).strict(),t.object({toolActionApproval:i}).strict()])})})});function c(e,o){const r=t.object({isError:t.literal(!0),content:t.array(t.object({type:t.literal("text"),text:t.string().max(65536)})).length(1)}).safeParse(e);if(!r.success)return;let n;try{n=JSON.parse(r.data.content[0].text)}catch{return}const a=s.safeParse(n);if(!a.success)return;const i=a.data.details.approvalRequest,c="scriptApproval"in i.retryInput?i.retryInput.scriptApproval:i.retryInput.toolActionApproval;return i.tool!==o||c.id!==i.id||Date.parse(i.expiresAt)<=Date.now()?void 0:i}function l(){return o({kind:a.cancelled,executionState:"not_executed"},"已取消审批;工具未执行操作")}async function p(t,e){if(void 0===e)return t;if(e.aborted)return;let o=()=>{};const r=new Promise(t=>{o=()=>t(void 0),e.addEventListener("abort",o,{once:!0})});try{return await Promise.race([t,r])}finally{e.removeEventListener("abort",o)}}export async function executeWithToolApproval(t){if(t.signal?.aborted)return l();const o=structuredClone(t.input),i=await t.call(structuredClone(o)),s=c(i,t.agentTool.name);if(void 0===s)return n(i,t.agentTool.appOutput);if(t.signal?.aborted)return l();const u={...structuredClone(o),...s.retryInput};if(!e(t.agentTool,u).ok)return n(i,t.agentTool.appOutput);const d=structuredClone(o);delete d.scriptApproval,delete d.toolActionApproval;const m=await p(t.ctx.requestApproval({agentName:t.agentName,toolName:t.agentTool.name,input:d,reason:"tool_requested_confirmation",explanation:s.summary??"工具尚未执行操作;仅批准本次完整参数,不自动重放已执行步骤。"}),t.signal);if(t.signal?.aborted||void 0===m)return l();if(!m.approved)return r(a.userRejected,"用户拒绝本次操作;工具未执行操作");if(Date.parse(s.expiresAt)<=Date.now())return n(i,t.agentTool.appOutput);const g=t.ctx.policy?.check({agentName:t.agentName,toolName:t.agentTool.name,input:structuredClone(u),...void 0===t.annotations?{}:{annotations:t.annotations}});return"deny"===g?.action?r(a.policyDenied,"审批期间策略已改变,未执行操作"):t.signal?.aborted?l():n(await t.call(u),t.agentTool.appOutput)}
|
|
@@ -1,29 +1,7 @@
|
|
|
1
1
|
import type { NormalizedToolResult } from "./normalize-result.ts";
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
};
|
|
6
|
-
export declare const OPAQUE_SIDE_EFFECT_RESOURCE = "shell:opaque-side-effects";
|
|
7
|
-
export type ToolResourceAccessMode = (typeof TOOL_RESOURCE_ACCESS_MODES)[keyof typeof TOOL_RESOURCE_ACCESS_MODES];
|
|
8
|
-
export interface ToolResourceAccess {
|
|
9
|
-
readonly key: string;
|
|
10
|
-
readonly mode: ToolResourceAccessMode;
|
|
11
|
-
}
|
|
12
|
-
export declare const TOOL_RESOURCE_HINT_KINDS: {
|
|
13
|
-
readonly file: "file";
|
|
14
|
-
readonly browserSession: "browser-session";
|
|
15
|
-
readonly conversation: "conversation";
|
|
16
|
-
readonly custom: "custom";
|
|
17
|
-
};
|
|
18
|
-
export type ToolResourceHintKind = (typeof TOOL_RESOURCE_HINT_KINDS)[keyof typeof TOOL_RESOURCE_HINT_KINDS];
|
|
19
|
-
export interface ToolResourceHint {
|
|
20
|
-
/** Top-level tool input field containing one resource id or an array of ids. */
|
|
21
|
-
readonly field: string;
|
|
22
|
-
readonly kind: ToolResourceHintKind;
|
|
23
|
-
readonly mode?: ToolResourceAccessMode;
|
|
24
|
-
/** Required for `custom`; ignored for built-in kinds. */
|
|
25
|
-
readonly namespace?: string;
|
|
26
|
-
}
|
|
2
|
+
import { type ToolResourceAccess } from "../tool-contracts/resource-hints.ts";
|
|
3
|
+
export { TOOL_RESOURCE_ACCESS_MODES, OPAQUE_SIDE_EFFECT_RESOURCE, TOOL_RESOURCE_HINT_KINDS, } from "../tool-contracts/resource-hints.ts";
|
|
4
|
+
export type { ToolResourceAccessMode, ToolResourceAccess, ToolResourceHintKind, ToolResourceHint, } from "../tool-contracts/resource-hints.ts";
|
|
27
5
|
export interface ToolExecutionPlan {
|
|
28
6
|
readonly prepare?: (input: unknown, capturedState: unknown) => NormalizedToolResult | undefined | Promise<NormalizedToolResult | undefined>;
|
|
29
7
|
readonly resources: (input: unknown, capturedState: unknown) => readonly ToolResourceAccess[];
|
|
@@ -79,4 +57,3 @@ export declare class ToolExecutionCoordinator {
|
|
|
79
57
|
private cleanupBatchIfComplete;
|
|
80
58
|
}
|
|
81
59
|
export declare function executeCoordinatedTool(coordinator: ToolExecutionCoordinator | undefined, plan: ToolExecutionPlan, toolId: string, toolCallId: string, input: unknown, abortSignal: AbortSignal | undefined, operation: (capturedState: unknown) => Promise<NormalizedToolResult>): Promise<NormalizedToolResult>;
|
|
82
|
-
export {};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{TOOL_OUTCOME_KINDS as e,failedToolResult as t,readToolOutcome as r}from"./normalize-result.js";
|
|
1
|
+
import{TOOL_OUTCOME_KINDS as e,failedToolResult as t,readToolOutcome as r}from"./normalize-result.js";import{TOOL_RESOURCE_ACCESS_MODES as a}from"../tool-contracts/resource-hints.js";export{TOOL_RESOURCE_ACCESS_MODES,OPAQUE_SIDE_EFFECT_RESOURCE,TOOL_RESOURCE_HINT_KINDS}from"../tool-contracts/resource-hints.js";const o=Symbol("tool-call-occurrence-state");function c(e){return{toolCallId:e,[o]:{started:!1}}}class ToolExecutionCancelledError extends Error{constructor(){super("tool execution cancelled"),this.name="ToolExecutionCancelledError"}}function s(e){return e instanceof Error?e.message:String(e)}function i(e){return e.reason??new ToolExecutionCancelledError}function l(){const e=Promise.withResolvers();return{promise:e.promise,release:e.resolve,released:!1}}function n(e,t){return void 0===t?e:t.aborted?Promise.reject(i(t)):new Promise((r,a)=>{const o=()=>{t.removeEventListener("abort",o),a(i(t))};t.addEventListener("abort",o,{once:!0}),e.then(()=>{t.removeEventListener("abort",o),r()},e=>{t.removeEventListener("abort",o),a(e)})})}function d(e){const t=new Map;for(const r of e){const e=r.key.trim();if(0===e.length)continue;void 0!==t.get(e)&&r.mode!==a.write||t.set(e,r.mode)}return[...t].sort(([e],[t])=>e<t?-1:e>t?1:0).map(([e,t])=>({key:e,mode:t}))}class ResourceLockManager{locks=new Map;async run(e,t,r){const a=[];try{for(const r of d(e))a.push(await this.acquire(r,t));if(t?.aborted)throw new ToolExecutionCancelledError;return await r()}finally{for(const e of a.reverse())e()}}acquire(e,t){if(t?.aborted)return Promise.reject(new ToolExecutionCancelledError);const r=this.locks.get(e.key)??{readers:0,writer:!1,queue:[]};this.locks.set(e.key,r);const o=r.queue.some(e=>e.mode===a.write);return(e.mode===a.read?!r.writer&&!o:!r.writer&&0===r.readers&&0===r.queue.length)?(this.grant(r,e.mode),Promise.resolve(()=>this.release(e.key,r,e.mode))):new Promise((a,o)=>{const c={mode:e.mode,resolve:()=>{t?.removeEventListener("abort",s),this.grant(r,e.mode),a(()=>this.release(e.key,r,e.mode))},reject:o,signal:t,onAbort:void 0===t?void 0:()=>s()},s=()=>{const t=r.queue.indexOf(c);t>=0&&r.queue.splice(t,1),o(new ToolExecutionCancelledError),this.drain(e.key,r)};r.queue.push(c),t?.addEventListener("abort",s,{once:!0})})}grant(e,t){t===a.read?e.readers+=1:e.writer=!0}release(e,t,r){r===a.read?t.readers-=1:t.writer=!1,this.drain(e,t)}drain(e,t){if(t.writer||t.readers>0)return;for(;t.queue[0]?.signal?.aborted;){const e=t.queue.shift();e?.reject(new ToolExecutionCancelledError)}const r=t.queue[0];if(void 0!==r){if(r.mode===a.write)return t.queue.shift(),void r.resolve();for(;t.queue[0]?.mode===a.read;)t.queue.shift()?.resolve()}else this.locks.delete(e)}}export class ToolExecutionCoordinator{plans=new Map;prepared=new Map;unbatchedOccurrences=new Map;batches=new Map;toolCallBatches=new Map;locks=new ResourceLockManager;activeBatch;preparationTail=Promise.resolve();register(e,t){this.plans.set(e,t)}describeResources(e,t){try{const r=this.plans.get(e),a=r?.captureExecutionState?.(t);return[...r?.resources(t,a)??[]]}catch{return[]}}captureToolCallOccurrence(e){const t=this.toolCallBatches.get(e)??this.activeBatch;if(t)return this.batchOccurrence(t,e);const r=c(e);return this.unbatchedOccurrences.set(e,r),r}hasExecutionStarted(e){return e[o].started}startBatch(e){this.activeBatch&&!this.activeBatch.sealed&&this.cancelBatch(this.activeBatch);const t={callId:e,toolCallIds:new Set,toolCallOccurrences:new Map,preparedToolCallIds:new Set,completedToolCallIds:new Set,admission:l(),userRejected:!1,cancelled:!1,sealed:!1};this.batches.set(e,t),this.activeBatch=t}async prepare(a,o,c){const s=this.toolCallBatches.get(a)??this.activeBatch;s&&this.trackBatchCall(s,a);const i=this.preparationTail;let l;this.preparationTail=new Promise(e=>{l=e}),await i;try{const i=this.plans.get(o),l=s?.cancelled?{blocked:t(e.cancelled,"工具批次已结束,本调用未执行"),resources:[],capturedState:void 0}:s?.userRejected?{blocked:t(e.cancelled,"同批次已有工具被用户拒绝,本调用未执行"),resources:[],capturedState:void 0}:await this.prepareWithPlan(i,c),{blocked:n}=l;n&&r(n).kind===e.userRejected&&s&&(s.userRejected=!0),!0!==s?.cancelled&&this.prepared.set(a,{toolId:o,input:c,batch:s,...l})}finally{s&&(s.preparedToolCallIds.add(a),this.releaseBatchAdmissionIfReady(s)),l?.()}}sealBatch(e,t=[]){const r=this.batches.get(e);if(r){for(const e of t)this.plans.has(e.toolId)&&this.trackBatchCall(r,e.toolCallId);r.sealed=!0,this.releaseBatchAdmissionIfReady(r),0===r.toolCallIds.size&&this.batches.delete(e)}this.activeBatch?.callId===e&&(this.activeBatch=void 0)}finishTurn(){for(const e of this.batches.values())this.cancelBatch(e);this.prepared.clear(),this.unbatchedOccurrences.clear(),this.batches.clear(),this.toolCallBatches.clear(),this.activeBatch=void 0,this.preparationTail=Promise.resolve()}async execute(r,a,c,l,d){const h=this.toolCallBatches.get(r)??this.activeBatch;let u,p;h&&this.trackBatchCall(h,r);try{if(h&&(await n(h.admission.promise,l),h.cancelled))return t(e.cancelled,"工具批次已结束,本调用未执行");if(u=this.prepared.get(r),void 0===u){if(h)return t(e.toolFailed,"工具批次准入状态不完整,本调用未执行");if(l?.aborted)throw i(l);const r=this.plans.get(a);u={toolId:a,input:c,batch:void 0,...await this.prepareWithPlan(r,c)}}if(u.blocked)return u.blocked;if(u.batch?.userRejected)return t(e.cancelled,"同批次已有工具被用户拒绝,本调用未执行");if(l?.aborted)throw i(l);const s=this.plans.get(a),f=u;p=this.executionOccurrence(f.batch??h,r);const m=p;return await this.locks.run(f.resources,l,async()=>{const e=await(s?.revalidateExecution?.(c,f.capturedState));return e||(m[o].started=!0,d(f.capturedState))})}catch(r){if(l?.aborted)throw i(l);return r instanceof ToolExecutionCancelledError?t(e.cancelled,"工具调用已取消",{raw:r}):t(e.toolFailed,s(r),{raw:r})}finally{const e=u?.batch??h,t=this.prepared.get(r);(void 0!==u&&t===u||void 0===u&&void 0!==e&&t?.batch===e)&&this.prepared.delete(r),void 0!==p&&void 0===e&&this.unbatchedOccurrences.get(r)===p&&this.unbatchedOccurrences.delete(r),this.completeBatchCall(e,r)}}async prepareWithPlan(r,a){try{const e=r?.captureExecutionState?.(a),t=await(r?.prepare?.(a,e));return t?{blocked:t,resources:[],capturedState:void 0}:{blocked:void 0,resources:r?.resources(a,e)??[],capturedState:e}}catch(r){return{blocked:t(e.toolFailed,s(r),{raw:r}),resources:[],capturedState:void 0}}}completeBatchCall(e,t){e&&(e.completedToolCallIds.add(t),this.cleanupBatchIfComplete(e))}trackBatchCall(e,t){e.toolCallIds.add(t),this.batchOccurrence(e,t),this.toolCallBatches.set(t,e)}batchOccurrence(e,t){const r=e.toolCallOccurrences.get(t);if(r)return r;const a=c(t);return e.toolCallOccurrences.set(t,a),a}executionOccurrence(e,t){if(e)return this.batchOccurrence(e,t);const r=this.unbatchedOccurrences.get(t);if(r)return r;const a=c(t);return this.unbatchedOccurrences.set(t,a),a}releaseBatchAdmissionIfReady(e){if(!e.admission.released){if(!e.sealed)return;if(!e.cancelled&&[...e.toolCallIds].some(t=>!e.preparedToolCallIds.has(t)))return;e.admission.released=!0,e.admission.release()}this.cleanupBatchIfComplete(e)}cancelBatch(e){e.cancelled=!0,e.sealed=!0,this.releaseBatchAdmissionIfReady(e)}cleanupBatchIfComplete(e){if(e.admission.released&&!(e.completedToolCallIds.size<e.toolCallIds.size)){this.batches.get(e.callId)===e&&this.batches.delete(e.callId);for(const t of e.toolCallIds)this.toolCallBatches.get(t)===e&&this.toolCallBatches.delete(t),this.prepared.get(t)?.batch===e&&this.prepared.delete(t)}}}export async function executeCoordinatedTool(r,a,o,c,l,n,d){if(r)return r.execute(c,o,l,n,d);try{if(n?.aborted)throw i(n);const e=a.captureExecutionState?.(l),t=await(a.prepare?.(l,e));if(t)return t;if(n?.aborted)throw i(n);const r=await(a.revalidateExecution?.(l,e));return r||await d(e)}catch(r){if(n?.aborted)throw i(n);return t(e.toolFailed,s(r),{raw:r})}}
|