stable-harness 0.0.44 → 0.0.46
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/node_modules/@stable-harness/adapter-deepagents/dist/src/adapter.js +1 -1
- package/node_modules/@stable-harness/adapter-deepagents/dist/src/internal/builtin-tool-policy.js +1 -1
- package/node_modules/@stable-harness/adapter-deepagents/dist/src/internal/gateway-tools.js +1 -1
- package/node_modules/@stable-harness/adapter-deepagents/dist/src/internal/stream-events.d.ts +1 -1
- package/node_modules/@stable-harness/adapter-deepagents/dist/src/internal/stream-events.js +1 -1
- package/node_modules/@stable-harness/adapter-deepagents/dist/src/types.d.ts +1 -1
- package/node_modules/@stable-harness/adapter-deepagents/package.json +3 -3
- package/node_modules/@stable-harness/core/dist/execution-contract.js +1 -1
- package/node_modules/@stable-harness/core/dist/quality/event-evidence.js +1 -1
- package/node_modules/@stable-harness/core/dist/recovery/tool-call.js +1 -1
- package/node_modules/@stable-harness/core/dist/runtime/policy/tool-invocation.js +1 -1
- package/node_modules/@stable-harness/core/dist/runtime/progress-narration.js +1 -1
- package/node_modules/@stable-harness/core/dist/trace.js +1 -1
- package/node_modules/@stable-harness/protocols/dist/src/openai-stream.js +1 -1
- package/package.json +4 -4
- package/packages/adapter-deepagents/dist/src/adapter.js +1 -1
- package/packages/adapter-deepagents/dist/src/internal/builtin-tool-policy.js +1 -1
- package/packages/adapter-deepagents/dist/src/internal/gateway-tools.js +1 -1
- package/packages/adapter-deepagents/dist/src/internal/stream-events.d.ts +1 -1
- package/packages/adapter-deepagents/dist/src/internal/stream-events.js +1 -1
- package/packages/adapter-deepagents/dist/src/types.d.ts +1 -1
- package/packages/adapter-deepagents/package.json +3 -3
- package/packages/core/dist/execution-contract.js +1 -1
- package/packages/core/dist/quality/event-evidence.js +1 -1
- package/packages/core/dist/recovery/tool-call.js +1 -1
- package/packages/core/dist/runtime/policy/tool-invocation.js +1 -1
- package/packages/core/dist/runtime/progress-narration.js +1 -1
- package/packages/core/dist/trace.js +1 -1
- package/packages/evaluation/dist/src/tool-call-metrics.js +1 -1
- package/packages/protocols/dist/src/openai-stream.js +1 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
import{realpathSync as e}from"node:fs";import t from"node:path";import{buildRuntimeSystemPrompt as r}from"@stable-harness/core";import{createBuiltinToolPolicyMiddleware as n,createObserverMiddleware as o}from"./internal/builtin-tool-policy.js";import{resolveFilesystemPermissions as s}from"./internal/builtin/permissions.js";import{createToolRepeatState as a}from"@stable-harness/core";import{buildGatewayTools as i,stringifyDeepAgentResult as p}from"./internal/gateway-tools.js";import{resolveDeepAgentsNativeMemories as c}from"./memory.js";import{buildDeepAgentRequest as d}from"./internal/messages.js";import{createRawToolCallParserMiddleware as l}from"./internal/raw-tool-call-parser.js";import{createBackendModel as u}from"./model-providers.js";import{createDeepAgentsRetryMiddleware as m}from"./retry-policy.js";import{streamDeepAgentResult as g}from"./internal/stream-events.js";export function createDeepAgentsAdapter(e={}){return{name:"deepagents",canRun:e=>"deepagents"===e.backend,async run(t){if(t.emit({type:"runtime.adapter.event",requestId:t.requestId,sessionId:t.sessionId,agentId:t.agent.id,event:{adapter:"deepagents",phase:"agent.handoff",modelRef:t.agent.modelRef,tools:t.agent.tools,subagents:t.agent.subagents}}),e.runner)return e.runner(t);const r=e.createDeepAgent?void 0:await async function loadDeepAgentsModule(){try{return await async function importOptionalPackage(e){return import(e)}("deepagents")}catch(e){throw new Error(`DeepAgents package is required for the default adapter path: ${function formatError(e){return e instanceof Error?e.message:String(e)}(e)}`)}}(),n=e.createDeepAgent??function readCreateDeepAgent(e){const t=e?.createDeepAgent;if("function"==typeof t)return t;throw new Error("DeepAgents package does not export createDeepAgent.")}(r),o=n(function buildDeepAgentParams(e,t,r){const n={...readDeepAgentsConfig(t),...readDeepAgentsConfig(e.agent.config.deepagents)},o=resolveDeepAgentsSkills(e,e.agent),a=n.permissions??s(e,e.agent),p=requestScopedRepeatState(e,e.agent.id);return pruneUndefined({name:e.agent.id,model:n.model??resolveAgentModel(e,e.agent),systemPrompt:buildSystemPrompt(e,e.agent),backend:n.backend??resolveDeepAgentsBackend(e,r,o),checkpointer:n.checkpointer,store:n.store,middleware:mergeMiddleware(e,e.agent,n.middleware,p),responseFormat:n.responseFormat,contextSchema:n.contextSchema,interruptOn:n.interruptOn,generalPurposeAgent:readBoolean(n.generalPurposeAgent),taskDescription:readString(n.taskDescription),permissions:a,tools:i(e,e.agent.id,e.agent.tools,resolveAgentRepairModel(e,e.agent,n),p),subagents:e.agent.subagents.map(t=>{const r=e.workspace.agents.get(t),n=readDeepAgentsConfig(r?.config.deepagents),o=n.permissions??s(e,r),a=scopedInput(e,r),p=requestScopedRepeatState(e,t);return pruneUndefined({name:t,description:r?.description??readString(r?.config.description)??r?.id,systemPrompt:buildSystemPrompt(e,r),model:n.model??(r?resolveAgentModel(e,r):void 0),middleware:mergeMiddleware(a,r,n.middleware,p),interruptOn:n.interruptOn,generalPurposeAgent:readBoolean(n.generalPurposeAgent),taskDescription:readString(n.taskDescription),permissions:o,responseFormat:n.responseFormat,tools:i(e,t,r?.tools??[],resolveAgentRepairModel(a,r,n),p),memory:resolveDeepAgentsMemory(e,r),skills:resolveDeepAgentsSkills(e,r)})}),memory:resolveDeepAgentsMemory(e,e.agent),skills:o})}(t,e.config,r)),a=d(t),c=function buildDeepAgentInvokeConfig(e){return pruneUndefined({recursionLimit:readNumber(readDeepAgentsConfig(e.config.deepagents).recursionLimit)??readNumber(e.config.recursionLimit)})}(t.agent);if(!0===t.request.metadata?.openaiStream&&o.streamEvents)
|
|
1
|
+
import{realpathSync as e}from"node:fs";import t from"node:path";import{buildRuntimeSystemPrompt as r}from"@stable-harness/core";import{createBuiltinToolPolicyMiddleware as n,createObserverMiddleware as o}from"./internal/builtin-tool-policy.js";import{resolveFilesystemPermissions as s}from"./internal/builtin/permissions.js";import{createToolRepeatState as a}from"@stable-harness/core";import{buildGatewayTools as i,stringifyDeepAgentResult as p}from"./internal/gateway-tools.js";import{resolveDeepAgentsNativeMemories as c}from"./memory.js";import{buildDeepAgentRequest as d}from"./internal/messages.js";import{createRawToolCallParserMiddleware as l}from"./internal/raw-tool-call-parser.js";import{createBackendModel as u}from"./model-providers.js";import{createDeepAgentsRetryMiddleware as m}from"./retry-policy.js";import{streamDeepAgentResult as g}from"./internal/stream-events.js";export function createDeepAgentsAdapter(e={}){return{name:"deepagents",canRun:e=>"deepagents"===e.backend,async run(t){if(t.emit({type:"runtime.adapter.event",requestId:t.requestId,sessionId:t.sessionId,agentId:t.agent.id,event:{adapter:"deepagents",phase:"agent.handoff",modelRef:t.agent.modelRef,tools:t.agent.tools,subagents:t.agent.subagents}}),e.runner)return e.runner(t);const r=e.createDeepAgent?void 0:await async function loadDeepAgentsModule(){try{return await async function importOptionalPackage(e){return import(e)}("deepagents")}catch(e){throw new Error(`DeepAgents package is required for the default adapter path: ${function formatError(e){return e instanceof Error?e.message:String(e)}(e)}`)}}(),n=e.createDeepAgent??function readCreateDeepAgent(e){const t=e?.createDeepAgent;if("function"==typeof t)return t;throw new Error("DeepAgents package does not export createDeepAgent.")}(r),o=n(function buildDeepAgentParams(e,t,r){const n={...readDeepAgentsConfig(t),...readDeepAgentsConfig(e.agent.config.deepagents)},o=resolveDeepAgentsSkills(e,e.agent),a=n.permissions??s(e,e.agent),p=requestScopedRepeatState(e,e.agent.id);return pruneUndefined({name:e.agent.id,model:n.model??resolveAgentModel(e,e.agent),systemPrompt:buildSystemPrompt(e,e.agent),backend:n.backend??resolveDeepAgentsBackend(e,r,o),checkpointer:n.checkpointer,store:n.store,middleware:mergeMiddleware(e,e.agent,n.middleware,p),responseFormat:n.responseFormat,contextSchema:n.contextSchema,interruptOn:n.interruptOn,generalPurposeAgent:readBoolean(n.generalPurposeAgent),taskDescription:readString(n.taskDescription),permissions:a,tools:i(e,e.agent.id,e.agent.tools,resolveAgentRepairModel(e,e.agent,n),p),subagents:e.agent.subagents.map(t=>{const r=e.workspace.agents.get(t),n=readDeepAgentsConfig(r?.config.deepagents),o=n.permissions??s(e,r),a=scopedInput(e,r),p=requestScopedRepeatState(e,t);return pruneUndefined({name:t,description:r?.description??readString(r?.config.description)??r?.id,systemPrompt:buildSystemPrompt(e,r),model:n.model??(r?resolveAgentModel(e,r):void 0),middleware:mergeMiddleware(a,r,n.middleware,p),interruptOn:n.interruptOn,generalPurposeAgent:readBoolean(n.generalPurposeAgent),taskDescription:readString(n.taskDescription),permissions:o,responseFormat:n.responseFormat,tools:i(e,t,r?.tools??[],resolveAgentRepairModel(a,r,n),p),memory:resolveDeepAgentsMemory(e,r),skills:resolveDeepAgentsSkills(e,r)})}),memory:resolveDeepAgentsMemory(e,e.agent),skills:o})}(t,e.config,r)),a=d(t),c=function buildDeepAgentInvokeConfig(e){return pruneUndefined({recursionLimit:readNumber(readDeepAgentsConfig(e.config.deepagents).recursionLimit)??readNumber(e.config.recursionLimit)})}(t.agent);if(!0===t.request.metadata?.openaiStream&&o.streamEvents){const e=await o.streamEvents(a,{version:"v3",...c});return g(t,e,p)}const l=await o.invoke(a,c);return p(l)}}}function buildSystemPrompt(e,t){const n=t?.systemPrompt??readString(t?.config.systemPrompt);return r({workspace:e.workspace,request:e.request,agent:t},n)}function resolveDeepAgentsMemory(e,t){const r=readDeepAgentsStringArray(t?.config,"memory");if(r)return r;const n=[...readAgentMemorySources(e.workspace.root,t),...c(e.workspace).map(e=>`/memories/${e.id}.md`)],o=[...new Set(n)];return o.length>0?o:void 0}function readAgentMemorySources(e,t){return(t?.memory??[]).flatMap(t=>"string"==typeof t&&t.trim()?[backendMemorySourcePath(e,t.trim())]:isRecord(t)&&"string"==typeof t.path&&t.path.trim()?[backendMemorySourcePath(e,t.path.trim())]:[])}function backendMemorySourcePath(e,r){if(r.startsWith("/"))return r;if(t.isAbsolute(r)){const n=t.relative(e,r);return n&&!n.startsWith("..")?`/${n.split(t.sep).join("/")}`:canonicalPath(r)}const n=r.split(t.sep).join("/");return n.startsWith("/")?n:`/${n}`}function resolveDeepAgentsSkills(e,r){const n=readDeepAgentsStringArray(r?.config,"skills");if(n)return n;const o=[...new Set((r?.skills??[]).map(t=>e.workspace.skills.get(t)?.path).filter(e=>"string"==typeof e&&e.trim().length>0).map(r=>function backendSkillSourcePath(e,r){const n=t.dirname(t.dirname(r)),o=t.relative(e,n);return!o||o.startsWith("..")||t.isAbsolute(o)?""===o?"/":canonicalPath(n):`/${o.split(t.sep).join("/")}`}(e.workspace.root,r)))];return o.length>0?o:void 0}function resolveDeepAgentsBackend(e,t,r){if(t?.FilesystemBackend&&r&&0!==r.length)return()=>new t.FilesystemBackend({rootDir:e.workspace.root})}function mergeMiddleware(e,t,r,s=a(e.workspace.runtime.toolGateway)){const i=Array.isArray(r)?r:[],p=scopedInput(e,t),c=new Set;return[o(p,{observedToolIds:c,repeatState:s}),n(p,{repeatState:s}),...m(e.workspace.runtime.retry),...i,l(p)]}function requestScopedRepeatState(e,t){const r=`deepagents.repeat.${t}`,n=e.requestState?.get(r);if(n)return n;const o=a(e.workspace.runtime.toolGateway);return e.requestState&&o&&e.requestState.set(r,o),o}function scopedInput(e,t){return t?{...e,agent:t}:e}function resolveAgentModel(e,t){const r=t.modelRef?e.workspace.models.get(t.modelRef):void 0;return r?u(r):void 0}function resolveAgentRepairModel(e,t,r){const n=r.model;if(isRepairModel(n))return n;if(!t)return;const o=resolveAgentModel(e,t);return isRepairModel(o)?o:void 0}function readDeepAgentsConfig(e){return isRecord(e)?e:{}}function readDeepAgentsStringArray(e,t){const r=isRecord(e)?e:{},n=readDeepAgentsConfig(r.deepagents),o="memory"===t?["memory","memorySources"]:["skills","skillSources"];for(const e of o){const t=readStringArray(n[e]);if(t)return t}return readStringArray(r[t])}function pruneUndefined(e){return Object.fromEntries(Object.entries(e).filter(([,e])=>void 0!==e))}function readString(e){return"string"==typeof e&&e.trim()?e:void 0}function readNumber(e){return"number"==typeof e&&Number.isFinite(e)?e:void 0}function readBoolean(e){return"boolean"==typeof e?e:void 0}function readStringArray(e){return Array.isArray(e)?e.filter(e=>"string"==typeof e):void 0}function canonicalPath(t){try{return e.native(t)}catch{return t}}function isRecord(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function isRepairModel(e){return"object"==typeof e&&null!==e&&"invoke"in e&&"function"==typeof e.invoke}
|
package/node_modules/@stable-harness/adapter-deepagents/dist/src/internal/builtin-tool-policy.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{ToolMessage as t}from"@langchain/core/messages";import{afterToolInvoke as e,beforeToolInvoke as o,createToolRepeatState as r}from"@stable-harness/core";import{filesystemBuiltinToolIds as
|
|
1
|
+
import{ToolMessage as t}from"@langchain/core/messages";import{afterToolInvoke as e,beforeToolInvoke as o,createToolRepeatState as r}from"@stable-harness/core";import{filesystemBuiltinToolIds as n,isFilesystemDisabled as i,isFilesystemTool as s,validateFilesystemBuiltinCall as a}from"./builtin/permissions.js";import{repairTaskCall as l}from"./builtin/task-inventory.js";import{repairBuiltinToolRequest as u}from"./builtin-call-repair.js";import{stringifyDeepAgentResult as c,toolControlProjection as d}from"./gateway-tools.js";import{isSuccessfulEvidenceOutput as p,observedToolEvidence as m,recordObservedToolEvidence as g}from"./gateway/tool-evidence.js";import{validateSkillFileBuiltinCall as f}from"./skill-file-policy.js";import{filterRepeatLimitedTools as v}from"./tool-repeat-visibility.js";import{traceProjectionForBuiltinTool as b}from"./trace-projection.js";const T=new Set(["write_todos","read_todos","task","execute",...n]);export function createBuiltinToolPolicyMiddleware(t,e={}){return{name:"StableHarnessBuiltinToolPolicy",async wrapModelCall(o,r){const n=Array.isArray(o.tools)?v(o.tools.filter(e=>!function hasHiddenBuiltins(t){return i(t)||!isTaskVisible(t)}(t)||isModelVisibleBuiltin(t,e.name)),e.repeatState):o.tools,s=function normalizeToolChoice(t,e,o){return"required"===e?o&&o.length>0?e:"auto":function isForcedHiddenTool(t,e){return"string"==typeof e?.function?.name&&!isModelVisibleBuiltin(t,e.function.name)}(t,e)?"auto":e}(t,o.toolChoice,n);return r({...o,tools:n,toolChoice:s})}}}export function createObserverMiddleware(n,i={}){const s=i.repeatState??r(n.workspace.runtime.toolGateway);return{name:"StableHarnessObserver",async wrapToolCall(r,d){const g=r.toolCall?.name;if(!g||!T.has(g))return d(r);const v=await u({toolId:g,request:r,workspaceRoot:n.workspace.root});emitToolEvent(n,g,"agent.tool.start",v.toolCall?.args);const b="task"===g?await l(n,v):{request:v},h=b.request,y=b.blocked;if(y)return emitToolEvent(n,g,"agent.tool.result",h.toolCall?.args,{output:y.content}),y;const k=a(n,g,h);if(k)return emitToolEvent(n,g,"agent.tool.result",h.toolCall?.args,{output:k.content}),k;const C=f(n,g,h);if(C)return emitToolEvent(n,g,"agent.tool.result",h.toolCall?.args,{output:C.content}),C;try{const a=s?o(g,h.toolCall?.args,s):void 0;if(a)return emitToolEvent(n,g,"agent.tool.result",h.toolCall?.args,{output:a.eventOutput}),builtinToolMessage(r,g,function modelOutputForRepeatedBuiltin(t,e){return"task"!==t?e:function readPreviousOutput(t){try{const e=JSON.parse(t);if(!isRecord(e)||"repeated_tool_call_limit"!==e.status||"string"!=typeof e.previousOutput)return;const o=e.previousOutput.trim();return o.length>0?o:void 0}catch{return}}(e)??e}(g,a.modelOutput));const l=await d(h),u=function observedToolOutput(t,e,o){return"write_todos"===t?JSON.stringify({status:"recorded",args:e.toolCall?.args}):c(o)}(g,h,l),m=s?e({toolId:g,args:h.toolCall?.args,output:u,successful:!(l instanceof t&&"error"===l.status)&&p(u),state:s}):{};return emitToolEvent(n,g,"agent.tool.result",h.toolCall?.args,{output:m.eventOutput??u}),i.observedToolIds?.add(g),void 0===m.modelOutput?l:builtinToolMessage(r,g,m.modelOutput)}catch(e){const o=function recoverableBuiltinToolError(e,o,r,n){const i=formatError(n);if("task"===o&&/repeat limit reached for tool/iu.test(i)){const o=function formatObservedEvidence(t){const e=m(t);if(0===e.length)return"";const o=e.map(t=>[`Agent: ${t.agentId}`,`Tool: ${t.toolId}`,t.output].join("\n")).join("\n\n---\n\n");return o.length>12e3?`${o.slice(0,12e3)}\n[truncated]`:o}(e);return new t({tool_call_id:r.toolCall?.id??"stable-harness-task-repeat-limit",name:"task",content:JSON.stringify({status:"delegated_task_repeat_limit",finalizationRequired:!0,instruction:"The delegated agent reached a configured tool repeat limit. Stop delegating this evidence need and do not send a synthesis task to another subagent for the same need. Finalize only from observedEvidence and other evidence that is already visible in this run. If the visible evidence is insufficient for a requested claim, report an explicit blocker or evidence gap instead of estimating, inventing, or using generic knowledge.",...o?{observedEvidence:o}:{},error:previewError(i)})})}if(/Received tool input did not match expected schema|Invalid input:/iu.test(i))return new t({tool_call_id:r.toolCall?.id??`stable-harness-${o}-argument-error`,name:o,status:"error",content:JSON.stringify({status:"tool_argument_error",toolId:o,instruction:"The upstream builtin tool rejected these arguments. Fix the tool arguments according to the tool schema, or choose a more appropriate available tool.",error:previewError(i)})})}(n,g,r,e);if(o)return emitToolEvent(n,g,"agent.tool.result",v.toolCall?.args,{output:o.content}),o;throw emitToolEvent(n,g,"agent.tool.result",v.toolCall?.args,{error:formatError(e)}),e}}}}function builtinToolMessage(e,o,r){return new t({tool_call_id:e.toolCall?.id??`stable-harness-${o}-repeat-guard`,name:o,content:r})}function emitToolEvent(t,e,o,r,n={}){"string"==typeof n.output&&g(t,t.agent.id,e,n.output),t.emit({type:"runtime.adapter.event",requestId:t.requestId,sessionId:t.sessionId,agentId:t.agent.id,event:{adapter:"deepagents",eventGroup:"tool_execution",eventType:"agent.tool.start"===o?"deepagents.tool_execution.start":"deepagents.tool_execution.result",phase:o,toolId:e,..."agent.tool.start"===o?{args:r}:{},...n,..."string"==typeof n.output?d(n.output):{},...b(e,o,r)}})}function isTaskVisible(t){const e=function readConfigRecord(t,e){const o=isRecord(t)?t:{};return isRecord(o[e])?o[e]:void 0}(t.agent.config,"builtinTools")?.modelExposed;return!1!==e&&(!Array.isArray(e)||e.includes("task"))}function isModelVisibleBuiltin(t,e){return(!i(t)||!s(e))&&("task"!==e||isTaskVisible(t))}function isRecord(t){return"object"==typeof t&&null!==t&&!Array.isArray(t)}function formatError(t){return t instanceof Error?t.message:String(t)}function previewError(t){const e=t.replace(/\s+/gu," ").trim();return e.length>800?`${e.slice(0,797)}...`:e}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{ToolMessage as t}from"@langchain/core/messages";import{tool as e}from"@langchain/core/tools";import{afterToolInvoke as o,beforeToolInvoke as r,createToolRepeatState as n,missingRequiredPlanContent as s,missingToolDependencyContent as a,toolInvocationEvents as i}from"@stable-harness/core";import{isSuccessfulEvidenceOutput as u,observedToolEvidence as l,recordObservedToolEvidence as c}from"./gateway/tool-evidence.js";import{emitStructuredToolFailure as d}from"./gateway/tool-failure-events.js";export function buildGatewayTools(l,c,p,f,g=n(l.workspace.runtime.toolGateway)){return l.toolGateway?p.flatMap(n=>{const p=l.toolGateway?.get(n);if(!p)return[];const m=l.workspace.tools.get(n),y=m?.schema??p.schema;return[e(async e=>async function invokeGuardedGatewayTool(e){emitToolResult(e.input,e.agentId,e.toolId,void 0);const n=i({request:e.input.request,getEvents:e.input.getEvents}),l=s({agent:e.input.agent,events:n,toolId:e.toolId});if(l)return emitToolResult(e.input,e.agentId,e.toolId,l),l;const c=a({agent:e.input.agent,events:n,toolId:e.toolId});if(c)return emitToolResult(e.input,e.agentId,e.toolId,c),c;const p=e.repeatState?r(e.toolId,e.args,e.repeatState):void 0;if(p)return emitToolResult(e.input,e.agentId,e.toolId,p.eventOutput),p.modelOutput;const f=await async function invokeGatewayTool(e,o,r,n,s){try{if(e.toolFailureTracker?.isCircuitOpen(r))throw new Error(`Tool circuit is open: ${r}`);const t=await e.toolGateway.invoke({toolId:r,args:n,repairModel:s,context:{workspaceRoot:e.workspace.root,requestId:e.requestId,sessionId:e.sessionId,agentId:o,requestInput:e.request.input,observedEvidence:formatObservedEvidenceForToolContext(e),approvalIds:readApprovalIds(e.request.metadata)}});return e.toolFailureTracker?.recordSuccess(r),t}catch(n){if(d(e,o,r,n),function isToolArgumentValidationError(t){return t instanceof Error&&"ToolArgumentValidationError"===t.name&&"string"==typeof t.toolId&&Array.isArray(t.issues)}(n))return new t({tool_call_id:`stable-harness-${r}-argument-guard`,name:r,status:"error",content:formatToolArgumentError(n)});if(e.workspace.runtime.retry?.tools?.enabled)throw n;return new t({tool_call_id:`stable-harness-${r}-execution-error`,name:r,status:"error",content:JSON.stringify({error:"tool_execution_failed",toolId:r,message:formatError(n),retry:"Use the error as evidence, adjust the tool arguments if possible, or return a final answer with the blocker."})})}}(e.input,e.agentId,e.toolId,e.args,e.repairModel),g=f instanceof t?String(f.content):stringifyDeepAgentResult(f.output),m=e.repeatState?o({toolId:e.toolId,args:e.args,output:g,successful:!(f instanceof t&&"error"===f.status)&&u(g),state:e.repeatState}):{};return emitToolResult(e.input,e.agentId,e.toolId,m.eventOutput??g),void 0!==m.modelOutput?m.modelOutput:f instanceof t?f:g}({input:l,agentId:c,toolId:n,args:e,repairModel:f,repeatState:g}),{name:n,description:buildToolDescription(m?.description??p.description??n,y,l.workspace.runtime.toolGateway,n),schema:{type:"object",additionalProperties:!0}})]}):[]}function emitToolResult(t,e,o,r){void 0!==r&&c(t,e,o,r),t.emit({type:"runtime.adapter.event",requestId:t.requestId,sessionId:t.sessionId,agentId:e,event:void 0===r?{adapter:"deepagents",phase:"agent.tool.start",toolId:o}:{adapter:"deepagents",phase:"agent.tool.result",toolId:o,output:previewToolOutput(r),evidenceOutput:r,...toolControlProjection(r)}})}export function stringifyDeepAgentResult(e){if(e instanceof t)return function stringifyToolMessageContent(t){return"string"==typeof t?t:JSON.stringify(t)}(e.content);if("string"==typeof e)return e;if(isRecord(e)){const t=e.structuredResponse??e.structured_response;if(void 0!==t)return"string"==typeof t?t:JSON.stringify(t);const o=(Array.isArray(e.messages)?e.messages:[]).at(-1);if(isRecord(o)&&"string"==typeof o.content)return o.content;const r=(isRecord(e.update)&&Array.isArray(e.update.messages)?e.update.messages:[]).at(-1);if(isRecord(r)&&isRecord(r.kwargs)&&"string"==typeof r.kwargs.content)return r.kwargs.content;if(isRecord(r)&&"string"==typeof r.content)return r.content}return JSON.stringify(e)}function buildToolDescription(t,e,o,r){const n=function toolRepeatPolicyDescription(t,e){const o=function repeatGuardConfig(t){return isRecord(t)&&isRecord(t.repeatGuard)?t.repeatGuard:{}}(t),r=function readPositiveIntegerMap(t){return isRecord(t)?new Map(Object.entries(t).map(([t,e])=>[t,readPositiveInteger(e)]).filter(t=>void 0!==t[1])):new Map}(o.maxSuccessfulCallsByTool).get(e)??readPositiveInteger(o.maxSuccessfulCallsPerTool);return void 0===r?"":`Stable runtime repeat policy: call this tool at most ${r} successful time(s) for this request. If more detail is needed, include the dimensions in the first call and synthesize after the result returns.`}(o,r),s=n?`${t}\n\n${n}`:t;return e?`${s}\n\nStable tool input schema:\n${previewToolOutput(JSON.stringify(e))}`:s}function readPositiveInteger(t){return"number"==typeof t&&Number.isInteger(t)&&t>0?t:void 0}function previewToolOutput(t){const e=t.replace(/\s+/gu," ").trim();return e.length>500?`${e.slice(0,497)}...`:e}export function toolControlProjection(t){const e=function parseJsonRecord(t){try{const e=JSON.parse(t);return isRecord(e)?e:void 0}catch{return}}(t);if("string"==typeof e?.status)return{controlStatus:e.status};const o=function readTextStatus(t){return String(t).match(/^Status:\s*([A-Za-z0-9_-]+)/imu)?.[1]}(t);return o?{controlStatus:o}:"string"==typeof e?.error?{controlStatus:e.error}:t.startsWith("Task delegation target is not in the workspace inventory")?{controlStatus:"task_inventory_blocked"}:{}}function readApprovalIds(t){const e=t?.approvalIds??t?.approvalId;return"string"==typeof e&&e.trim()?[e.trim()]:Array.isArray(e)?e.filter(t=>"string"==typeof t&&t.trim().length>0):void 0}function formatObservedEvidenceForToolContext(t){const e=l(t).map(t=>`Tool: ${t.toolId}\n${t.output}`).join("\n\n---\n\n");return e.length>12e3?`${e.slice(0,12e3)}\n[truncated]`:e}function formatToolArgumentError(t){return JSON.stringify({error:"tool_argument_validation_failed",toolId:t.toolId,issues:t.issues,retry:"Call the same tool again with arguments that satisfy the reported schema and semantic issues."})}function isRecord(t){return"object"==typeof t&&null!==t&&!Array.isArray(t)}function formatError(t){return t instanceof Error?t.message:String(t)}
|
|
1
|
+
import{ToolMessage as t}from"@langchain/core/messages";import{tool as e}from"@langchain/core/tools";import{afterToolInvoke as o,beforeToolInvoke as r,createToolRepeatState as n,missingRequiredPlanContent as s,missingToolDependencyContent as a,toolInvocationEvents as i}from"@stable-harness/core";import{isSuccessfulEvidenceOutput as u,observedToolEvidence as l,recordObservedToolEvidence as c}from"./gateway/tool-evidence.js";import{emitStructuredToolFailure as d}from"./gateway/tool-failure-events.js";export function buildGatewayTools(l,c,p,f,g=n(l.workspace.runtime.toolGateway)){return l.toolGateway?p.flatMap(n=>{const p=l.toolGateway?.get(n);if(!p)return[];const m=l.workspace.tools.get(n),y=m?.schema??p.schema;return[e(async e=>async function invokeGuardedGatewayTool(e){emitToolResult(e.input,e.agentId,e.toolId,void 0);const n=i({request:e.input.request,getEvents:e.input.getEvents}),l=s({agent:e.input.agent,events:n,toolId:e.toolId});if(l)return emitToolResult(e.input,e.agentId,e.toolId,l),l;const c=a({agent:e.input.agent,events:n,toolId:e.toolId});if(c)return emitToolResult(e.input,e.agentId,e.toolId,c),c;const p=e.repeatState?r(e.toolId,e.args,e.repeatState):void 0;if(p)return emitToolResult(e.input,e.agentId,e.toolId,p.eventOutput),p.modelOutput;const f=await async function invokeGatewayTool(e,o,r,n,s){try{if(e.toolFailureTracker?.isCircuitOpen(r))throw new Error(`Tool circuit is open: ${r}`);const t=await e.toolGateway.invoke({toolId:r,args:n,repairModel:s,context:{workspaceRoot:e.workspace.root,requestId:e.requestId,sessionId:e.sessionId,agentId:o,requestInput:e.request.input,observedEvidence:formatObservedEvidenceForToolContext(e),approvalIds:readApprovalIds(e.request.metadata)}});return e.toolFailureTracker?.recordSuccess(r),t}catch(n){if(d(e,o,r,n),function isToolArgumentValidationError(t){return t instanceof Error&&"ToolArgumentValidationError"===t.name&&"string"==typeof t.toolId&&Array.isArray(t.issues)}(n))return new t({tool_call_id:`stable-harness-${r}-argument-guard`,name:r,status:"error",content:formatToolArgumentError(n)});if(e.workspace.runtime.retry?.tools?.enabled)throw n;return new t({tool_call_id:`stable-harness-${r}-execution-error`,name:r,status:"error",content:JSON.stringify({error:"tool_execution_failed",toolId:r,message:formatError(n),retry:"Use the error as evidence, adjust the tool arguments if possible, or return a final answer with the blocker."})})}}(e.input,e.agentId,e.toolId,e.args,e.repairModel),g=f instanceof t?String(f.content):stringifyDeepAgentResult(f.output),m=e.repeatState?o({toolId:e.toolId,args:e.args,output:g,successful:!(f instanceof t&&"error"===f.status)&&u(g),state:e.repeatState}):{};return emitToolResult(e.input,e.agentId,e.toolId,m.eventOutput??g),void 0!==m.modelOutput?m.modelOutput:f instanceof t?f:g}({input:l,agentId:c,toolId:n,args:e,repairModel:f,repeatState:g}),{name:n,description:buildToolDescription(m?.description??p.description??n,y,l.workspace.runtime.toolGateway,n),schema:{type:"object",additionalProperties:!0}})]}):[]}function emitToolResult(t,e,o,r){void 0!==r&&c(t,e,o,r),t.emit({type:"runtime.adapter.event",requestId:t.requestId,sessionId:t.sessionId,agentId:e,event:void 0===r?{adapter:"deepagents",eventGroup:"tool_execution",eventType:"deepagents.tool_execution.start",phase:"agent.tool.start",toolId:o}:{adapter:"deepagents",eventGroup:"tool_execution",eventType:"deepagents.tool_execution.result",phase:"agent.tool.result",toolId:o,output:previewToolOutput(r),evidenceOutput:r,...toolControlProjection(r)}})}export function stringifyDeepAgentResult(e){if(e instanceof t)return function stringifyToolMessageContent(t){return"string"==typeof t?t:JSON.stringify(t)}(e.content);if("string"==typeof e)return e;if(isRecord(e)){const t=e.structuredResponse??e.structured_response;if(void 0!==t)return"string"==typeof t?t:JSON.stringify(t);const o=(Array.isArray(e.messages)?e.messages:[]).at(-1);if(isRecord(o)&&"string"==typeof o.content)return o.content;const r=(isRecord(e.update)&&Array.isArray(e.update.messages)?e.update.messages:[]).at(-1);if(isRecord(r)&&isRecord(r.kwargs)&&"string"==typeof r.kwargs.content)return r.kwargs.content;if(isRecord(r)&&"string"==typeof r.content)return r.content}return JSON.stringify(e)}function buildToolDescription(t,e,o,r){const n=function toolRepeatPolicyDescription(t,e){const o=function repeatGuardConfig(t){return isRecord(t)&&isRecord(t.repeatGuard)?t.repeatGuard:{}}(t),r=function readPositiveIntegerMap(t){return isRecord(t)?new Map(Object.entries(t).map(([t,e])=>[t,readPositiveInteger(e)]).filter(t=>void 0!==t[1])):new Map}(o.maxSuccessfulCallsByTool).get(e)??readPositiveInteger(o.maxSuccessfulCallsPerTool);return void 0===r?"":`Stable runtime repeat policy: call this tool at most ${r} successful time(s) for this request. If more detail is needed, include the dimensions in the first call and synthesize after the result returns.`}(o,r),s=n?`${t}\n\n${n}`:t;return e?`${s}\n\nStable tool input schema:\n${previewToolOutput(JSON.stringify(e))}`:s}function readPositiveInteger(t){return"number"==typeof t&&Number.isInteger(t)&&t>0?t:void 0}function previewToolOutput(t){const e=t.replace(/\s+/gu," ").trim();return e.length>500?`${e.slice(0,497)}...`:e}export function toolControlProjection(t){const e=function parseJsonRecord(t){try{const e=JSON.parse(t);return isRecord(e)?e:void 0}catch{return}}(t);if("string"==typeof e?.status)return{controlStatus:e.status};const o=function readTextStatus(t){return String(t).match(/^Status:\s*([A-Za-z0-9_-]+)/imu)?.[1]}(t);return o?{controlStatus:o}:"string"==typeof e?.error?{controlStatus:e.error}:t.startsWith("Task delegation target is not in the workspace inventory")?{controlStatus:"task_inventory_blocked"}:{}}function readApprovalIds(t){const e=t?.approvalIds??t?.approvalId;return"string"==typeof e&&e.trim()?[e.trim()]:Array.isArray(e)?e.filter(t=>"string"==typeof t&&t.trim().length>0):void 0}function formatObservedEvidenceForToolContext(t){const e=l(t).map(t=>`Tool: ${t.toolId}\n${t.output}`).join("\n\n---\n\n");return e.length>12e3?`${e.slice(0,12e3)}\n[truncated]`:e}function formatToolArgumentError(t){return JSON.stringify({error:"tool_argument_validation_failed",toolId:t.toolId,issues:t.issues,retry:"Call the same tool again with arguments that satisfy the reported schema and semantic issues."})}function isRecord(t){return"object"==typeof t&&null!==t&&!Array.isArray(t)}function formatError(t){return t instanceof Error?t.message:String(t)}
|
package/node_modules/@stable-harness/adapter-deepagents/dist/src/internal/stream-events.d.ts
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
import type { RuntimeAdapter } from "@stable-harness/core";
|
|
2
|
-
export declare function streamDeepAgentResult(input: Parameters<RuntimeAdapter["run"]>[0],
|
|
2
|
+
export declare function streamDeepAgentResult(input: Parameters<RuntimeAdapter["run"]>[0], run: unknown, stringify: (value: unknown) => string): Promise<string>;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
export async function streamDeepAgentResult(t,e,
|
|
1
|
+
export async function streamDeepAgentResult(e,t,a){const s=function readRunProjection(e){const t=readRecord(e);if(!t)return;const a={messages:readAsyncIterable(t.messages),toolCalls:readAsyncIterable(t.toolCalls??t.tool_calls),subagents:readAsyncIterable(t.subagents),values:readAsyncIterable(t.values),extensions:readExtensions(t.extensions),output:t.output};return a.messages||a.toolCalls||a.subagents||a.values||a.extensions||a.output?a:void 0}(t);if(!s)throw new Error("DeepAgents streamEvents(version: v3) did not expose v3 projections.");let n,o="";return await Promise.all([consumeMessages(e,s.messages,e.agent.id,e=>{o+=e}),consumeToolCalls(e,s.toolCalls,e.agent.id),consumeSubagents(e,s.subagents),consumeValues(e,s.values,e.agent.id),consumeExtensions(e,s.extensions,e.agent.id),readFinalOutput(s.output,a).then(e=>{n=e})]),n??o}async function consumeMessages(e,t,a,s){if(t)for await(const n of t)await consumeMessage(e,n,a,s)}async function consumeMessage(e,t,a,s){const n=readRecord(t);n?await Promise.all([consumeTextProjection(e,n.text??n.content,a,s),consumeReasoning(e,n.reasoning,a),consumeModelToolCalls(e,readAsyncIterable(n.toolCalls??n.tool_calls),a),emitMessageOutput(e,n,a),emitMessageUsage(e,n,a)]):await emitTextValue(e,t,a,s)}async function consumeTextProjection(e,t,a,s){if(isAsyncIterable(t))for await(const n of t)await emitTextValue(e,n,a,s);else await emitTextValue(e,await resolveValue(t),a,s)}async function emitTextValue(e,t,a,s){const n=readContentText(await resolveValue(t));n&&(emitAdapterEvent(e,"message","delta",{phase:"agent.message.delta",sourceAgentId:a,text:n}),a===e.agent.id&&(s?.(n),emitAdapterEvent(e,"message","coordinator_delta",{phase:"agent.output.delta",text:n})))}async function consumeReasoning(e,t,a){if(isAsyncIterable(t))for await(const s of t)emitReasoning(e,s,a);else emitReasoning(e,await resolveValue(t),a)}function emitReasoning(e,t,a){const s=readContentText(t);s&&emitAdapterEvent(e,"reasoning","delta",{phase:"agent.reasoning.delta",sourceAgentId:a,text:s})}async function consumeModelToolCalls(e,t,a){if(t)for await(const s of t){const t=readRecord(s)??{};emitAdapterEvent(e,"tool_call","delta",{phase:"agent.tool.call.delta",sourceAgentId:a,toolId:readString(t.name)??readString(t.toolId),toolCallId:readString(t.callId)??readString(t.id),args:await resolveValue(t.input??t.args),delta:await resolveValue(t.delta??t.argsDelta??t.arguments)})}}async function consumeToolCalls(e,t,a){if(!t)return;let s=0;for await(const n of t){s+=1;const t=readRecord(n)??{},o=readString(t.name)??readString(t.toolId)??`tool-${s}`,r=readString(t.callId)??readString(t.id)??`${a}:${o}:${s}`;emitAdapterEvent(e,"tool_execution","start",{phase:"agent.tool.start",sourceAgentId:a,toolId:o,toolCallId:r,args:await resolveValue(t.input??t.args),upstream:passthroughRecord(t)}),await consumeToolOutputDeltas(e,t,a,o,r),await emitToolResult(e,t,a,o,r)}}async function consumeToolOutputDeltas(e,t,a,s,n){const o=readAsyncIterable(t.outputDeltas??t.output_delta??t.outputChunks);if(o)for await(const t of o)emitAdapterEvent(e,"tool_execution","output_delta",{phase:"agent.tool.output.delta",sourceAgentId:a,toolId:s,toolCallId:n,delta:t})}async function consumeSubagents(e,t){if(!t)return;const a=[];let s=0;for await(const n of t)s+=1,a.push(consumeSubagent(e,n,s));await Promise.all(a)}async function consumeSubagent(e,t,a){const s=readRecord(t)??{},n=readString(s.name)??`subagent-${a}`,o=readString(s.callId)??readString(s.id)??`${n}:${a}`;emitAdapterEvent(e,"subagent","start",{phase:"agent.subagent.start",subagentId:n,callId:o,taskInput:await resolveValue(s.taskInput),namespace:s.namespace,upstream:passthroughRecord(s)});try{await Promise.all([consumeMessages(e,readAsyncIterable(s.messages),n),consumeToolCalls(e,readAsyncIterable(s.toolCalls??s.tool_calls),n),consumeSubagents(e,readAsyncIterable(s.subagents)),consumeValues(e,readAsyncIterable(s.values),n),consumeExtensions(e,readExtensions(s.extensions),n),resolveValue(s.output)]),emitAdapterEvent(e,"subagent","result",{phase:"agent.subagent.result",subagentId:n,callId:o,status:"completed"})}catch(t){emitAdapterEvent(e,"subagent","result",{phase:"agent.subagent.result",subagentId:n,callId:o,status:"failed",error:formatError(t)})}}async function consumeValues(e,t,a){if(t)for await(const s of t)emitAdapterEvent(e,"state","snapshot",{phase:"agent.state.snapshot",sourceAgentId:a,snapshot:s})}async function consumeExtensions(e,t,a){t&&await Promise.all(Object.entries(t).map(async([t,s])=>{for await(const n of s)emitAdapterEvent(e,"extension","event",{phase:"agent.extension",sourceAgentId:a,name:t,value:n})}))}async function emitToolResult(e,t,a,s,n){try{emitAdapterEvent(e,"tool_execution","result",{phase:"agent.tool.result",sourceAgentId:a,toolId:s,toolCallId:n,status:await resolveValue(t.status),output:await resolveValue(t.output),error:await resolveValue(t.error),upstream:passthroughRecord(t)})}catch(t){emitAdapterEvent(e,"tool_execution","result",{phase:"agent.tool.result",sourceAgentId:a,toolId:s,toolCallId:n,status:"failed",error:formatError(t)})}}async function readFinalOutput(e,t){const a=await resolveValue(e);if(void 0!==a)return t(a)||void 0}async function emitMessageOutput(e,t,a){"output"in t&&emitAdapterEvent(e,"message","output",{phase:"agent.message.output",sourceAgentId:a,output:await resolveValue(t.output),upstream:passthroughRecord(t)})}async function emitMessageUsage(e,t,a){if(!("usage"in t))return;const s=await resolveValue(t.usage);s&&emitAdapterEvent(e,"message","usage",{phase:"agent.message.usage",sourceAgentId:a,usage:s})}function readContentText(e){return"string"==typeof e?e||void 0:Array.isArray(e)&&e.map(e=>readString(readRecord(e)?.text)??("string"==typeof e?e:"")).join("")||void 0}function emitAdapterEvent(e,t,a,s){e.emit({type:"runtime.adapter.event",requestId:e.requestId,sessionId:e.sessionId,agentId:e.agent.id,event:{adapter:"deepagents",eventGroup:t,eventType:`deepagents.${t}.${a}`,...s}})}async function resolveValue(e){return await e}function readAsyncIterable(e){return isAsyncIterable(e)?e:void 0}function readExtensions(e){const t=readRecord(e);if(!t)return;const a=Object.entries(t).filter(e=>isAsyncIterable(e[1]));return a.length>0?Object.fromEntries(a):void 0}function passthroughRecord(e){return Object.fromEntries(Object.entries(e).filter(([,e])=>!isAsyncIterable(e)&&!function isPromiseLike(e){return isRecord(e)&&"function"==typeof e.then}(e)))}function readRecord(e){return isRecord(e)?e:void 0}function readString(e){return"string"==typeof e&&e.trim()?e:void 0}function formatError(e){return e instanceof Error?e.message:String(e)}function isAsyncIterable(e){return isRecord(e)&&"function"==typeof e[Symbol.asyncIterator]}function isRecord(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import type { RuntimeAdapterContext, RuntimeAdapterResult } from "@stable-harness/core";
|
|
2
2
|
export type DeepAgentFactory = (params?: Record<string, unknown>) => {
|
|
3
3
|
invoke(input: Record<string, unknown>, options?: Record<string, unknown>): Promise<unknown>;
|
|
4
|
-
streamEvents?(input: Record<string, unknown>, options?: Record<string, unknown>):
|
|
4
|
+
streamEvents?(input: Record<string, unknown>, options?: Record<string, unknown>): unknown;
|
|
5
5
|
};
|
|
6
6
|
export type DeepAgentsModule = {
|
|
7
7
|
createDeepAgent?: unknown;
|
|
@@ -11,12 +11,12 @@
|
|
|
11
11
|
"types": "dist/src/index.d.ts",
|
|
12
12
|
"peerDependencies": {
|
|
13
13
|
"@easynet/better-call": "^0.1.60",
|
|
14
|
-
"@langchain/core": "^1.1.
|
|
14
|
+
"@langchain/core": "^1.1.46",
|
|
15
15
|
"@langchain/ollama": "^1.2.7",
|
|
16
16
|
"@langchain/openai": "^1.4.5",
|
|
17
17
|
"@stable-harness/core": "0.0.1",
|
|
18
|
-
"deepagents": "^1.
|
|
19
|
-
"langchain": "^1.
|
|
18
|
+
"deepagents": "^1.10.1",
|
|
19
|
+
"langchain": "^1.4.0"
|
|
20
20
|
},
|
|
21
21
|
"peerDependenciesMeta": {
|
|
22
22
|
"deepagents": {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
export function assertExecutionContract(e){(function contractDisabled(e){const t=isRecord(e?.executionContract)?e.executionContract:void 0;return!1===t?.enabled})(e.metadata)||(function assertRequiredPlan(e){const t=readExecutionContract(e.agent);if(!t.requiresPlan)return;const n=readStringArray(t.planEvidenceTools);if(0===n.length)throw e.emit({type:"runtime.execution.contract.failed",requestId:e.requestId,sessionId:e.sessionId,agentId:e.agent.id,reason:"invalid_plan_contract"}),new Error("Execution contract requires plan evidence tools when requiresPlan is enabled");const r=e.store.getRun(e.requestId),o=new Set((r?.events??[]).flatMap(readEvidenceToolId));if(!n.some(e=>o.has(e)))throw e.emit({type:"runtime.execution.contract.failed",requestId:e.requestId,sessionId:e.sessionId,agentId:e.agent.id,reason:"missing_plan",missingEvidenceTools:n}),new Error(`Execution contract requires a planning checkpoint from one of: ${n.join(", ")}`)}(e),function assertRequiredEvidenceTools(e){const t=function readRequiredEvidenceTools(e){return readStringArray(readExecutionContract(e).requiredEvidenceTools)}(e.agent);if(0===t.length)return;const n=e.store.getRun(e.requestId),r=new Set((n?.events??[]).flatMap(readEvidenceToolId)),o=t.filter(e=>!r.has(e));if(0!==o.length)throw e.emit({type:"runtime.execution.contract.failed",requestId:e.requestId,sessionId:e.sessionId,agentId:e.agent.id,reason:"missing_required_evidence",missingEvidenceTools:o}),new Error(`Execution contract missing required evidence tools: ${o.join(", ")}`)}(e),function assertToolDependencies(e){const t=readExecutionContract(e.agent),n=isRecord(t.toolDependencies)?t.toolDependencies:{},r=Object.entries(n).map(([e,t])=>[e,readStringArray(t)]).filter(e=>e[1].length>0);if(0===r.length)return;const o=e.store.getRun(e.requestId),i=new Set((o?.events??[]).flatMap(readEvidenceToolId)),s=r.filter(([e])=>i.has(e)).flatMap(([e,t])=>t.filter(e=>!i.has(e)).map(t=>`${e} requires ${t}`));if(0!==s.length)throw e.emit({type:"runtime.execution.contract.failed",requestId:e.requestId,sessionId:e.sessionId,agentId:e.agent.id,reason:"missing_tool_dependency",missingEvidenceTools:s}),new Error(`Execution contract missing required tool dependencies: ${s.join(", ")}`)}(e))}function readExecutionContract(e){return isRecord(e.config.executionContract)?e.config.executionContract:{}}function readEvidenceToolId(e){return"runtime.tool.direct.completed"===e.type?[e.toolId]:"runtime.adapter.event"===e.type&&isRecord(e.event)
|
|
1
|
+
export function assertExecutionContract(e){(function contractDisabled(e){const t=isRecord(e?.executionContract)?e.executionContract:void 0;return!1===t?.enabled})(e.metadata)||(function assertRequiredPlan(e){const t=readExecutionContract(e.agent);if(!t.requiresPlan)return;const n=readStringArray(t.planEvidenceTools);if(0===n.length)throw e.emit({type:"runtime.execution.contract.failed",requestId:e.requestId,sessionId:e.sessionId,agentId:e.agent.id,reason:"invalid_plan_contract"}),new Error("Execution contract requires plan evidence tools when requiresPlan is enabled");const r=e.store.getRun(e.requestId),o=new Set((r?.events??[]).flatMap(readEvidenceToolId));if(!n.some(e=>o.has(e)))throw e.emit({type:"runtime.execution.contract.failed",requestId:e.requestId,sessionId:e.sessionId,agentId:e.agent.id,reason:"missing_plan",missingEvidenceTools:n}),new Error(`Execution contract requires a planning checkpoint from one of: ${n.join(", ")}`)}(e),function assertRequiredEvidenceTools(e){const t=function readRequiredEvidenceTools(e){return readStringArray(readExecutionContract(e).requiredEvidenceTools)}(e.agent);if(0===t.length)return;const n=e.store.getRun(e.requestId),r=new Set((n?.events??[]).flatMap(readEvidenceToolId)),o=t.filter(e=>!r.has(e));if(0!==o.length)throw e.emit({type:"runtime.execution.contract.failed",requestId:e.requestId,sessionId:e.sessionId,agentId:e.agent.id,reason:"missing_required_evidence",missingEvidenceTools:o}),new Error(`Execution contract missing required evidence tools: ${o.join(", ")}`)}(e),function assertToolDependencies(e){const t=readExecutionContract(e.agent),n=isRecord(t.toolDependencies)?t.toolDependencies:{},r=Object.entries(n).map(([e,t])=>[e,readStringArray(t)]).filter(e=>e[1].length>0);if(0===r.length)return;const o=e.store.getRun(e.requestId),i=new Set((o?.events??[]).flatMap(readEvidenceToolId)),s=r.filter(([e])=>i.has(e)).flatMap(([e,t])=>t.filter(e=>!i.has(e)).map(t=>`${e} requires ${t}`));if(0!==s.length)throw e.emit({type:"runtime.execution.contract.failed",requestId:e.requestId,sessionId:e.sessionId,agentId:e.agent.id,reason:"missing_tool_dependency",missingEvidenceTools:s}),new Error(`Execution contract missing required tool dependencies: ${s.join(", ")}`)}(e))}function readExecutionContract(e){return isRecord(e.config.executionContract)?e.config.executionContract:{}}function readEvidenceToolId(e){return"runtime.tool.direct.completed"===e.type?[e.toolId]:"runtime.adapter.event"===e.type&&isRecord(e.event)&&function isToolResultEvent(e){return"deepagents.tool_execution.result"===e.eventType||"agent.tool.result"===e.phase}(e.event)&&"string"==typeof e.event.toolId&&function isSuccessfulEvidenceEvent(e){const t=function readString(e){return"string"==typeof e&&e.length>0?e:void 0}(e.controlStatus)??function readOutputStatus(e){if("string"!=typeof e)return;const t=function parseJsonRecord(e){try{const t=JSON.parse(e);return isRecord(t)?t:void 0}catch{return}}(e);return"string"==typeof t?.status?t.status:e.match(/^Status:\s*([A-Za-z0-9_-]+)/imu)?.[1]}(e.output);return!t||/^(?:completed|success|ok|recorded)$/iu.test(t)}(e.event)?[e.event.toolId]:[]}function isRecord(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function readStringArray(e){return Array.isArray(e)?e.filter(e=>"string"==typeof e&&e.length>0):[]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
export function hasPlanningEvidence(t){return t.some(t=>{const e=readAdapterEvent(t);return!!e&&("plan"===e.traceType||String(e.traceLabel??"").startsWith("plan.")||"write_todos"===e.toolId&&String(e.phase??"").startsWith("agent.tool."))})}export function successfulEvidenceToolIds(t){const e=t.flatMap(t=>{if("runtime.tool.direct.completed"===t.type)return[t.toolId];const e=readAdapterEvent(t);return e&&"
|
|
1
|
+
export function hasPlanningEvidence(t){return t.some(t=>{const e=readAdapterEvent(t);return!!e&&("plan"===e.traceType||String(e.traceLabel??"").startsWith("plan.")||"write_todos"===e.toolId&&String(e.phase??"").startsWith("agent.tool."))})}export function successfulEvidenceToolIds(t){const e=t.flatMap(t=>{if("runtime.tool.direct.completed"===t.type)return[t.toolId];const e=readAdapterEvent(t);return isToolResultEvent(e)&&"string"==typeof e.toolId&&isSuccessfulEvidenceEvent(e)?[e.toolId]:[]});return[...new Set(e)]}export function successfulEvidenceOutputs(t){return successfulEvidenceItems(t).map(t=>t.output)}export function successfulEvidenceItems(t){return t.flatMap(t=>{if("runtime.tool.direct.completed"===t.type)return stringifyEvidence(t.output).map(e=>({source:t.toolId,output:e}));const e=readAdapterEvent(t);return isToolResultEvent(e)&&"string"==typeof e.toolId?!isSuccessfulEvidenceEvent(e)||function isPlanningTool(t){return/^(?:write_todos|read_todos)$/u.test(t)}(e.toolId)?[]:stringifyEvidence(e.evidenceOutput??e.output).filter(t=>function isUsableEvidenceOutput(t,e){return"task"!==t||!function looksLikeUnexecutedToolIntent(t){const e=t.trim();return!(e.length>4e3)&&[/\b(?:I need to|I will|I'll|I am going to|I'm going to|Let me)\s+(?:call|use|run|invoke|get|fetch|check)\b[\s\S]{0,1200}\b(?:tool|function|system_time|web_search|url_text_fetch|task)\b/iu,/(?:我需要|我要|我会|我将|让我|我来|接下来我(?:会|将)?)\s*(?:先)?(?:调用|使用|运行|执行|检查|获取|查看)\b[\s\S]{0,1200}\b(?:工具|函数|system_time|web_search|url_text_fetch|task)\b/iu,/```(?:json)?\s*(?:system_time|web_search|url_text_fetch|task)\s*```/iu].some(t=>t.test(e))}(e)&&!function looksLikeDelegatedCommentary(t){const e=t.trim();return!(e.length>8e3)&&[/(?:这篇文章|this article)[\s\S]{0,1200}(?:我认为|我认同|打动我|值得深入探讨|特别认同|what I find|I think|I agree)/iu,/(?:你还有什么|还想深入探讨|would you like|do you want).{0,120}[??]\s*$/iu].some(t=>t.test(e))}(e)}(e.toolId,t)).map(t=>({source:e.toolId,output:t})):[]})}export function controlBlockers(t){const e=function successfulEventIndexesBySource(t){const e=new Map;return t.forEach((t,n)=>{const o=function successfulEventSource(t){if("runtime.tool.direct.completed"===t.type)return t.toolId;const e=readAdapterEvent(t);return isToolResultEvent(e)&&"string"==typeof e.toolId&&isSuccessfulEvidenceEvent(e)?e.toolId:void 0}(t);o&&e.set(o,[...e.get(o)??[],n])}),e}(t);return t.flatMap((t,n)=>{const o=readAdapterEvent(t),r=readString(o?.controlStatus)??readOutputStatus(o?.output),s=readString(o?.toolId)??"tool";return r&&isBlockerStatus(r)?isResolvedByLaterCompletion(r)&&function completedAfter(t,e,n){return(t.get(e)??[]).some(t=>t>n)}(e,s,n)?[]:[`${s}:${r}`]:[]})}export function controlGaps(t){const e=new Set(successfulEvidenceItems(t).map(t=>t.source));return t.flatMap(t=>{const n=readAdapterEvent(t),o=readString(n?.controlStatus)??readOutputStatus(n?.output),r=readString(n?.toolId)??"tool";return o&&isGapStatus(o)?e.has(r)&&isResolvedByLaterCompletion(o)?[]:[`${r}:${o}`]:[]})}function stringifyEvidence(t){return"string"==typeof t?t.trim()?[t]:[]:null==t?[]:[JSON.stringify(t)]}function readAdapterEvent(t){return"runtime.adapter.event"===t.type&&isRecord(t.event)?t.event:void 0}function isSuccessfulEvidenceEvent(t){const e=readString(t.controlStatus)??readOutputStatus(t.output);return!e||/^(?:completed|success|ok|recorded)$/iu.test(e)}function isBlockerStatus(t){return/^(?:blocked|approval_required|schema_repair_failed|tool_argument_error|invalid_input)$/iu.test(t)}function isGapStatus(t){return/^(?:dependency_required|plan_required|repeated_tool_call_limit|duplicate_tool_call)$/iu.test(t)}function isResolvedByLaterCompletion(t){return isGapStatus(t)||isBlockerStatus(t)}function isToolResultEvent(t){return"deepagents.tool_execution.result"===t?.eventType||"agent.tool.result"===t?.phase}function readOutputStatus(t){if("string"!=typeof t)return;const e=function parseJsonRecord(t){try{const e=JSON.parse(t);return isRecord(e)?e:void 0}catch{return}}(t);return"string"==typeof e?.status?e.status:t.match(/^Status:\s*([A-Za-z0-9_-]+)/imu)?.[1]}function isRecord(t){return"object"==typeof t&&null!==t&&!Array.isArray(t)}function readString(t){return"string"==typeof t&&t.trim()?t:void 0}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
export function toolCallRecoveryEnabled(e){return!0===readToolCallRecovery(e).enabled}export function isRecoverableAdapterError(e,t){const o=readToolCallRecovery(t);if(!0!==o.enabled)return!1;const n=e instanceof Error?e.message:String(e);return readRegexps(o.adapterErrorPatterns,[/XML syntax error|tool.?call.*syntax|malformed.*(?:XML|tool)|Non string tool message content|repeat limit reached for tool/iu]).some(e=>e.test(n))}export function buildAdapterErrorRecoveryPrompt(e,t,o){const n=t instanceof Error?t.message:String(t),r=readToolCallRecovery(o).instruction;return recoverRequest(e,["Stable runtime recovery: the backend failed while parsing a tool call.",`Parser error: ${n}`,"string"==typeof r?r:"Continue the same user request using the backend's normal tool-calling mechanism, then return a final human-readable answer.","Do not print raw tool-call markup, JSON tool-call envelopes, or pseudo tool-call text in the final answer."])}export function buildResultRecoveryRequest(e){const t=readToolCallRecovery(e.policy);if(!0!==t.enabled)return;if(containsRawToolCallText(e.output,t)){const t=recentToolEvidence(e.events,1e3);return recoverRequest(e.request,["Stable runtime recovery: your previous final answer printed raw tool-call markup instead of executing the tool.","Continue the same user request by calling the available upstream tool normally when more evidence is required.","If you call a tool, the next assistant action must be the backend's structured tool call itself, with no prose before it.",...e.availableToolIds?.length?[`Available configured tools: ${e.availableToolIds.join(", ")}`,"Do not invent, print, or call tools that are not in this list."]:[],"If the conversation context already contains enough evidence to answer, synthesize the final answer from that context instead.","Do not print XML, JSON, markdown fences, pseudo tool-call text, plans, or future-intent text such as saying you will call or wait for a tool.",...t.length>0?["","Recent executed tool evidence:",...t]:[],"","Previous invalid final answer:",e.output])}if(containsToolExecutionErrorText(e.output,t)){const t=recentToolEvidence(e.events,1e3);return recoverRequest(e.request,["Stable runtime recovery: your previous final answer exposed a backend tool execution error instead of handling it.","Continue the same user request using the backend's normal structured tool-calling mechanism.","Do not retry the same invalid tool arguments. If the failed tool is not required to answer the user, synthesize the final answer from the available context instead.",...e.availableToolIds?.length?[`Available configured tools: ${e.availableToolIds.join(", ")}`,"Do not invent, print, or call tools that are not in this list."]:[],"Do not print tool error stacks, schema validation diagnostics, raw tool-call markup, JSON tool-call envelopes, or pseudo tool-call text in the final answer.",...t.length>0?["","Recent executed tool evidence:",...t]:[],"","Previous invalid final answer:",e.output])}const o=function lastConfiguredEventHint(e,t){const o=function readEventRecoveryHints(e){return(Array.isArray(e)?e:[]).flatMap(e=>isRecord(e)&&"string"==typeof e.instruction?[{..."string"==typeof e.toolId?{toolId:e.toolId}:{},..."string"==typeof e.phase?{phase:e.phase}:{},..."string"==typeof e.outputIncludes?{outputIncludes:e.outputIncludes}:{},..."string"==typeof e.outputMatches?{outputMatches:e.outputMatches}:{},instruction:e.instruction}]:[])}(t.eventRecoveryHints);if(0!==o.length)return e.flatMap(e=>function readMatchingHints(e,t){const o="runtime.adapter.event"===e.type&&isRecord(e.event)?e.event:void 0;return o?t.filter(e=>function eventMatchesHint(e,t){return(!t.toolId||e.toolId===t.toolId)&&(!t.phase||e.phase===t.phase)&&(t.outputIncludes?"string"==typeof e.output&&e.output.includes(t.outputIncludes):!t.outputMatches||"string"==typeof e.output&&new RegExp(t.outputMatches,"u").test(e.output))}(o,e)).map(e=>({output:"string"==typeof o.output?o.output:"Adapter event matched configured recovery hint.",instruction:e.instruction})):[]}(e,o)).at(-1)}(e.events,t);return o?recoverRequest(e.request,["Stable runtime recovery: a previous adapter event matched a configured recovery hint.",o.output,o.instruction]):void 0}export function buildExecutionContractRecoveryRequest(e){if(!0!==readToolCallRecovery(e.policy).enabled)return;const t=function lastMissingEvidenceTools(e){for(let t=e.length-1;t>=0;t-=1){const o=e[t];if("runtime.execution.contract.failed"===o?.type)return readStringArray(o.missingEvidenceTools)}return[]}(e.events);return 0!==t.length?recoverRequest(e.request,["Stable runtime recovery: the execution contract was not satisfied.",`Required evidence tool(s) were missing: ${t.join(", ")}`,"Continue the same user request by calling the missing required evidence tool(s) through the backend's normal structured tool-calling mechanism.","Do not produce a final answer until the required evidence tool call has executed and you have synthesized its result.","Do not print XML, JSON, markdown fences, pseudo tool-call text, plans, or future-intent text in the final answer."]):void 0}export function assertNoRawToolCallOutput(e,t){if(containsRawToolCallOutput(e,t))throw new Error(`Adapter returned raw tool-call text as the final answer after recovery. The backend must execute tools instead of printing tool-call markup. Output preview: ${previewOutput(e)}`)}export function containsRawToolCallOutput(e,t){const o=readToolCallRecovery(t);return!0===o.enabled&&containsRawToolCallText(e,o)}export function containsRecoverableResultOutput(e,t){const o=readToolCallRecovery(t);return!0===o.enabled&&containsRecoverableResultFailureText(e,o)}export function assertNoToolExecutionErrorOutput(e,t){const o=readToolCallRecovery(t);if(!0===o.enabled&&containsToolExecutionErrorText(e,o))throw new Error(`Adapter returned a tool execution error as the final answer after recovery. Output preview: ${previewOutput(e)}`)}export function rawToolCallFailureMessage(){return["The model attempted to call a tool but returned the tool call as text instead of executing it.","Please retry the request or use a model/backend configuration with reliable tool calling for this workspace."].join(" ")}export function buildEvidenceSynthesisOutput(e){const t=readToolCallRecovery(e.policy);if(!0!==t.enabled||!1===t.synthesizeFromEvidenceOnFailure||!containsRecoverableResultFailureText(e.output,t))return;const o=function latestDelegatedTaskReport(e){return e.flatMap(e=>{const t="runtime.adapter.event"===e.type&&isRecord(e.event)?e.event:void 0;if(!t||"agent.tool.result"!==t.phase||"task"!==t.toolId)return[];const o="string"==typeof t.output?t.output.trim():"";return function looksLikeFinalReport(e){const t=e.trim();return!(t.length<80)&&(/^#{1,3}\s+\S/mu.test(t)||/\n#{1,3}\s+\S/mu.test(t)||/\n-{3,}\n/u.test(t))}(o)?[o]:[]}).at(-1)||void 0}(e.events);if(o)return o;const n=recentToolEvidence(e.events,6e3);return 0!==n.length?"zh"==(/\p{Script=Han}/u.test(e.request.input)?"zh":"en")?function buildChineseEvidenceSynthesis(e,t){return["上游模型在已有工具证据后仍输出了伪工具调用;runtime 已拒绝该 raw 输出,并直接交付已执行工具返回的证据结果。","","已执行的工具证据:",...t,"",`被拒绝的最终输出预览:${previewRejectedOutput(e)}`].join("\n")}(e.output,n):function buildEnglishEvidenceSynthesis(e,t){return["The upstream model still returned pseudo tool-call text after tool evidence was available. The runtime rejected that raw output and is returning the executed tool evidence directly.","","Executed tool evidence:",...t,"",`Rejected final output preview: ${previewRejectedOutput(e)}`].join("\n")}(e.output,n):void 0}function previewOutput(e){const t=e.replace(/\s+/gu," ").trim();return t.length>300?`${t.slice(0,297)}...`:t}function previewRejectedOutput(e){return previewOutput(e).replace(/[<>]/gu,"")}export function rawToolCallOutputPreview(e){return previewOutput(e)}function recoverRequest(e,t){return{...e,input:[e.input,"",...t].join("\n"),metadata:{...e.metadata,stableHarnessRecovery:"tool_call"}}}function containsRawToolCallText(e,t){const o=readRegexps(t.rawOutputPatterns,[/\{\s*"name"\s*:\s*"[^"]+"\s*,\s*"arguments"\s*:/iu,/\{\s*"tool_name"\s*:\s*"[^"]+"\s*,\s*"parameters"\s*:/iu,/\{\s*"type"\s*:\s*"[^"]+"\s*,\s*"args"\s*:/iu,/^\s*[A-Za-z_][\w.-]*\s*\([^)]{0,2000}\)\s*$/iu,/^\s*[A-Za-z_][\w.-]*(?:_command|_tool|_analysis|_investigate|task)\s*$/iu,/```(?:json)?[\s\S]{0,4000}"(?:tool_name|tool|name|subagent_type)"\s*:/iu,/```(?:json)?[\s\S]{0,4000}"(?:tool_name|tool|name|subagent_type)"\s*:[\s\S]{0,4000}"(?:arguments|parameters|task)"\s*:/iu,/```(?:json)?[\s\S]{0,2000}"query"\s*:[\s\S]{0,2000}"(?:max_results|count|freshness|market)"\s*:/iu]);return!![/<\s*(?:tool_call|task)\b[^>]*>/iu,/<\s*\/\s*(?:tool_call|task)\s*>/iu,/<\s*\/?\s*tool_code\b[^>]*>/iu,/<\s*\/?\s*[A-Za-z_][\w.-]*(?:_command|_tool|_analysis|_investigate|_todos|task)\b[^>]*>/iu].some(t=>t.test(e))||function looksLikeStandaloneRecoveryCandidate(e){const t=e.trim();return t.length<=6e3||/^\s*(?:```|\{|\[|[A-Za-z_][\w.-]*\s*\()/u.test(t)}(e)&&(o.some(t=>t.test(e))||[/^[\s\S]{0,2400}\b(?:I need to|I will|I'll|I am going to|I'm going to)\s+(?:call|use|invoke|delegate)\b[\s\S]{0,1200}\b(?:tool|function|specialist|subagent)\b[\s\S]{0,400}$/iu,/^[\s\S]{0,2400}\b(?:I will|I'll|I am going to|I'm going to)\s+(?:investigate|gather|check)\b[\s\S]{0,1200}\b(?:evidence|cluster|system|results?)\b[\s\S]{0,400}$/iu,/^[\s\S]{0,2400}\b(?:waiting for|wait for)\b[\s\S]{0,1200}\b(?:tool|function|specialist|subagent)\b[\s\S]{0,400}$/iu,/^[\s\S]{0,2400}\b(?:Would you like me to|Do you want me to|Should I|I can help with)\b[\s\S]{0,1200}\?[\s\S]{0,400}$/iu,/^[\s\S]{0,2400}\bCould you please provide\b[\s\S]{0,1200}\b(?:tool|function|specialist|subagent|task)\b[\s\S]{0,400}$/iu,/^[\s\S]{0,2400}\b(?:I don't|I do not) have enough information\b[\s\S]{0,1200}\b(?:tool|function|specialist|subagent|task|context)\b[\s\S]{0,400}$/iu,/^[\s\S]{0,2400}\bLet me\s+(?:call|use|invoke|delegate|check|run|verify|gather|inspect)\b[\s\S]{0,1200}\b(?:tool|function|specialist|subagent|results?|data|evidence|commands?)\b[\s\S]{0,400}$/iu,/^[\s\S]{0,2400}(?:我需要|我要|我会|我将|让我|我来|接下来我(?:会|将)?)\s*(?:先)?(?:调用|使用|运行|执行|检查|读取|收集|调查|验证|查看)[\s\S]{0,1200}$/iu,/^[\s\S]{0,2400}(?:要不要|是否需要|需要我|你想让我)[\s\S]{0,1200}(?:继续|进一步|帮你|分析|检查)[\s\S]{0,1200}[??][\s\S]{0,400}$/iu].some(t=>t.test(e)))}function containsRecoverableResultFailureText(e,t){return containsRawToolCallText(e,t)||containsToolExecutionErrorText(e,t)}function containsToolExecutionErrorText(e,t){return readRegexps(t.toolFailureOutputPatterns,[/^Error invoking tool ['"][^'"]+['"] with kwargs /iu,/Received tool input did not match expected schema/iu,/ToolMessage.*status.*error/iu]).some(t=>t.test(e))}function recentToolEvidence(e,t){return e.flatMap(e=>{const o="runtime.adapter.event"===e.type&&isRecord(e.event)?e.event:void 0;return o&&"agent.tool.result"===o.phase&&"string"==typeof o.toolId?function isControlToolOutput(e){if("string"!=typeof e||!e.trim().startsWith("{"))return!1;try{const t=JSON.parse(e),o=isRecord(t)?t.status:void 0;return"duplicate_tool_call"===o||"repeated_tool_call_limit"===o||"tool_argument_error"===o}catch{return!1}}(o.output)?[]:[`- ${o.toolId}: ${formatToolEvidence(o,t)}`]:[]}).slice(-5)}function formatToolEvidence(e,t=1e3){return"string"==typeof e.output&&e.output.trim()?e.output.slice(0,t):"string"==typeof e.error&&e.error.trim()?`error: ${e.error.slice(0,t)}`:isRecord(e.args)?`completed with args: ${previewOutput(JSON.stringify(e.args))}`:"completed"}function readToolCallRecovery(e){if(!isRecord(e))return{};const t=isRecord(e.recovery)?e.recovery:{};return isRecord(t.toolCall)?t.toolCall:{}}function readRegexps(e,t){const o=(Array.isArray(e)?e:[]).filter(e=>"string"==typeof e&&e.length>0).map(e=>new RegExp(e,"iu"));return o.length>0?o:t}function readStringArray(e){return Array.isArray(e)?e.filter(e=>"string"==typeof e&&e.length>0):[]}function isRecord(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}
|
|
1
|
+
export function toolCallRecoveryEnabled(e){return!0===readToolCallRecovery(e).enabled}export function isRecoverableAdapterError(e,t){const o=readToolCallRecovery(t);if(!0!==o.enabled)return!1;const n=e instanceof Error?e.message:String(e);return readRegexps(o.adapterErrorPatterns,[/XML syntax error|tool.?call.*syntax|malformed.*(?:XML|tool)|Non string tool message content|repeat limit reached for tool/iu]).some(e=>e.test(n))}export function buildAdapterErrorRecoveryPrompt(e,t,o){const n=t instanceof Error?t.message:String(t),r=readToolCallRecovery(o).instruction;return recoverRequest(e,["Stable runtime recovery: the backend failed while parsing a tool call.",`Parser error: ${n}`,"string"==typeof r?r:"Continue the same user request using the backend's normal tool-calling mechanism, then return a final human-readable answer.","Do not print raw tool-call markup, JSON tool-call envelopes, or pseudo tool-call text in the final answer."])}export function buildResultRecoveryRequest(e){const t=readToolCallRecovery(e.policy);if(!0!==t.enabled)return;if(containsRawToolCallText(e.output,t)){const t=recentToolEvidence(e.events,1e3);return recoverRequest(e.request,["Stable runtime recovery: your previous final answer printed raw tool-call markup instead of executing the tool.","Continue the same user request by calling the available upstream tool normally when more evidence is required.","If you call a tool, the next assistant action must be the backend's structured tool call itself, with no prose before it.",...e.availableToolIds?.length?[`Available configured tools: ${e.availableToolIds.join(", ")}`,"Do not invent, print, or call tools that are not in this list."]:[],"If the conversation context already contains enough evidence to answer, synthesize the final answer from that context instead.","Do not print XML, JSON, markdown fences, pseudo tool-call text, plans, or future-intent text such as saying you will call or wait for a tool.",...t.length>0?["","Recent executed tool evidence:",...t]:[],"","Previous invalid final answer:",e.output])}if(containsToolExecutionErrorText(e.output,t)){const t=recentToolEvidence(e.events,1e3);return recoverRequest(e.request,["Stable runtime recovery: your previous final answer exposed a backend tool execution error instead of handling it.","Continue the same user request using the backend's normal structured tool-calling mechanism.","Do not retry the same invalid tool arguments. If the failed tool is not required to answer the user, synthesize the final answer from the available context instead.",...e.availableToolIds?.length?[`Available configured tools: ${e.availableToolIds.join(", ")}`,"Do not invent, print, or call tools that are not in this list."]:[],"Do not print tool error stacks, schema validation diagnostics, raw tool-call markup, JSON tool-call envelopes, or pseudo tool-call text in the final answer.",...t.length>0?["","Recent executed tool evidence:",...t]:[],"","Previous invalid final answer:",e.output])}const o=function lastConfiguredEventHint(e,t){const o=function readEventRecoveryHints(e){return(Array.isArray(e)?e:[]).flatMap(e=>isRecord(e)&&"string"==typeof e.instruction?[{..."string"==typeof e.toolId?{toolId:e.toolId}:{},..."string"==typeof e.phase?{phase:e.phase}:{},..."string"==typeof e.outputIncludes?{outputIncludes:e.outputIncludes}:{},..."string"==typeof e.outputMatches?{outputMatches:e.outputMatches}:{},instruction:e.instruction}]:[])}(t.eventRecoveryHints);if(0!==o.length)return e.flatMap(e=>function readMatchingHints(e,t){const o="runtime.adapter.event"===e.type&&isRecord(e.event)?e.event:void 0;return o?t.filter(e=>function eventMatchesHint(e,t){return(!t.toolId||e.toolId===t.toolId)&&(!t.phase||e.phase===t.phase)&&(t.outputIncludes?"string"==typeof e.output&&e.output.includes(t.outputIncludes):!t.outputMatches||"string"==typeof e.output&&new RegExp(t.outputMatches,"u").test(e.output))}(o,e)).map(e=>({output:"string"==typeof o.output?o.output:"Adapter event matched configured recovery hint.",instruction:e.instruction})):[]}(e,o)).at(-1)}(e.events,t);return o?recoverRequest(e.request,["Stable runtime recovery: a previous adapter event matched a configured recovery hint.",o.output,o.instruction]):void 0}export function buildExecutionContractRecoveryRequest(e){if(!0!==readToolCallRecovery(e.policy).enabled)return;const t=function lastMissingEvidenceTools(e){for(let t=e.length-1;t>=0;t-=1){const o=e[t];if("runtime.execution.contract.failed"===o?.type)return readStringArray(o.missingEvidenceTools)}return[]}(e.events);return 0!==t.length?recoverRequest(e.request,["Stable runtime recovery: the execution contract was not satisfied.",`Required evidence tool(s) were missing: ${t.join(", ")}`,"Continue the same user request by calling the missing required evidence tool(s) through the backend's normal structured tool-calling mechanism.","Do not produce a final answer until the required evidence tool call has executed and you have synthesized its result.","Do not print XML, JSON, markdown fences, pseudo tool-call text, plans, or future-intent text in the final answer."]):void 0}export function assertNoRawToolCallOutput(e,t){if(containsRawToolCallOutput(e,t))throw new Error(`Adapter returned raw tool-call text as the final answer after recovery. The backend must execute tools instead of printing tool-call markup. Output preview: ${previewOutput(e)}`)}export function containsRawToolCallOutput(e,t){const o=readToolCallRecovery(t);return!0===o.enabled&&containsRawToolCallText(e,o)}export function containsRecoverableResultOutput(e,t){const o=readToolCallRecovery(t);return!0===o.enabled&&containsRecoverableResultFailureText(e,o)}export function assertNoToolExecutionErrorOutput(e,t){const o=readToolCallRecovery(t);if(!0===o.enabled&&containsToolExecutionErrorText(e,o))throw new Error(`Adapter returned a tool execution error as the final answer after recovery. Output preview: ${previewOutput(e)}`)}export function rawToolCallFailureMessage(){return["The model attempted to call a tool but returned the tool call as text instead of executing it.","Please retry the request or use a model/backend configuration with reliable tool calling for this workspace."].join(" ")}export function buildEvidenceSynthesisOutput(e){const t=readToolCallRecovery(e.policy);if(!0!==t.enabled||!1===t.synthesizeFromEvidenceOnFailure||!containsRecoverableResultFailureText(e.output,t))return;const o=function latestDelegatedTaskReport(e){return e.flatMap(e=>{const t="runtime.adapter.event"===e.type&&isRecord(e.event)?e.event:void 0;if(!isToolResultEvent(t)||"task"!==t.toolId)return[];const o="string"==typeof t.output?t.output.trim():"";return function looksLikeFinalReport(e){const t=e.trim();return!(t.length<80)&&(/^#{1,3}\s+\S/mu.test(t)||/\n#{1,3}\s+\S/mu.test(t)||/\n-{3,}\n/u.test(t))}(o)?[o]:[]}).at(-1)||void 0}(e.events);if(o)return o;const n=recentToolEvidence(e.events,6e3);return 0!==n.length?"zh"==(/\p{Script=Han}/u.test(e.request.input)?"zh":"en")?function buildChineseEvidenceSynthesis(e,t){return["上游模型在已有工具证据后仍输出了伪工具调用;runtime 已拒绝该 raw 输出,并直接交付已执行工具返回的证据结果。","","已执行的工具证据:",...t,"",`被拒绝的最终输出预览:${previewRejectedOutput(e)}`].join("\n")}(e.output,n):function buildEnglishEvidenceSynthesis(e,t){return["The upstream model still returned pseudo tool-call text after tool evidence was available. The runtime rejected that raw output and is returning the executed tool evidence directly.","","Executed tool evidence:",...t,"",`Rejected final output preview: ${previewRejectedOutput(e)}`].join("\n")}(e.output,n):void 0}function previewOutput(e){const t=e.replace(/\s+/gu," ").trim();return t.length>300?`${t.slice(0,297)}...`:t}function previewRejectedOutput(e){return previewOutput(e).replace(/[<>]/gu,"")}export function rawToolCallOutputPreview(e){return previewOutput(e)}function recoverRequest(e,t){return{...e,input:[e.input,"",...t].join("\n"),metadata:{...e.metadata,stableHarnessRecovery:"tool_call"}}}function containsRawToolCallText(e,t){const o=readRegexps(t.rawOutputPatterns,[/\{\s*"name"\s*:\s*"[^"]+"\s*,\s*"arguments"\s*:/iu,/\{\s*"tool_name"\s*:\s*"[^"]+"\s*,\s*"parameters"\s*:/iu,/\{\s*"type"\s*:\s*"[^"]+"\s*,\s*"args"\s*:/iu,/^\s*[A-Za-z_][\w.-]*\s*\([^)]{0,2000}\)\s*$/iu,/^\s*[A-Za-z_][\w.-]*(?:_command|_tool|_analysis|_investigate|task)\s*$/iu,/```(?:json)?[\s\S]{0,4000}"(?:tool_name|tool|name|subagent_type)"\s*:/iu,/```(?:json)?[\s\S]{0,4000}"(?:tool_name|tool|name|subagent_type)"\s*:[\s\S]{0,4000}"(?:arguments|parameters|task)"\s*:/iu,/```(?:json)?[\s\S]{0,2000}"query"\s*:[\s\S]{0,2000}"(?:max_results|count|freshness|market)"\s*:/iu]);return!![/<\s*(?:tool_call|task)\b[^>]*>/iu,/<\s*\/\s*(?:tool_call|task)\s*>/iu,/<\s*\/?\s*tool_code\b[^>]*>/iu,/<\s*\/?\s*[A-Za-z_][\w.-]*(?:_command|_tool|_analysis|_investigate|_todos|task)\b[^>]*>/iu].some(t=>t.test(e))||function looksLikeStandaloneRecoveryCandidate(e){const t=e.trim();return t.length<=6e3||/^\s*(?:```|\{|\[|[A-Za-z_][\w.-]*\s*\()/u.test(t)}(e)&&(o.some(t=>t.test(e))||[/^[\s\S]{0,2400}\b(?:I need to|I will|I'll|I am going to|I'm going to)\s+(?:call|use|invoke|delegate)\b[\s\S]{0,1200}\b(?:tool|function|specialist|subagent)\b[\s\S]{0,400}$/iu,/^[\s\S]{0,2400}\b(?:I will|I'll|I am going to|I'm going to)\s+(?:investigate|gather|check)\b[\s\S]{0,1200}\b(?:evidence|cluster|system|results?)\b[\s\S]{0,400}$/iu,/^[\s\S]{0,2400}\b(?:waiting for|wait for)\b[\s\S]{0,1200}\b(?:tool|function|specialist|subagent)\b[\s\S]{0,400}$/iu,/^[\s\S]{0,2400}\b(?:Would you like me to|Do you want me to|Should I|I can help with)\b[\s\S]{0,1200}\?[\s\S]{0,400}$/iu,/^[\s\S]{0,2400}\bCould you please provide\b[\s\S]{0,1200}\b(?:tool|function|specialist|subagent|task)\b[\s\S]{0,400}$/iu,/^[\s\S]{0,2400}\b(?:I don't|I do not) have enough information\b[\s\S]{0,1200}\b(?:tool|function|specialist|subagent|task|context)\b[\s\S]{0,400}$/iu,/^[\s\S]{0,2400}\bLet me\s+(?:call|use|invoke|delegate|check|run|verify|gather|inspect)\b[\s\S]{0,1200}\b(?:tool|function|specialist|subagent|results?|data|evidence|commands?)\b[\s\S]{0,400}$/iu,/^[\s\S]{0,2400}(?:我需要|我要|我会|我将|让我|我来|接下来我(?:会|将)?)\s*(?:先)?(?:调用|使用|运行|执行|检查|读取|收集|调查|验证|查看)[\s\S]{0,1200}$/iu,/^[\s\S]{0,2400}(?:要不要|是否需要|需要我|你想让我)[\s\S]{0,1200}(?:继续|进一步|帮你|分析|检查)[\s\S]{0,1200}[??][\s\S]{0,400}$/iu].some(t=>t.test(e)))}function containsRecoverableResultFailureText(e,t){return containsRawToolCallText(e,t)||containsToolExecutionErrorText(e,t)}function containsToolExecutionErrorText(e,t){return readRegexps(t.toolFailureOutputPatterns,[/^Error invoking tool ['"][^'"]+['"] with kwargs /iu,/Received tool input did not match expected schema/iu,/ToolMessage.*status.*error/iu]).some(t=>t.test(e))}function recentToolEvidence(e,t){return e.flatMap(e=>{const o="runtime.adapter.event"===e.type&&isRecord(e.event)?e.event:void 0;return isToolResultEvent(o)&&"string"==typeof o.toolId?function isControlToolOutput(e){if("string"!=typeof e||!e.trim().startsWith("{"))return!1;try{const t=JSON.parse(e),o=isRecord(t)?t.status:void 0;return"duplicate_tool_call"===o||"repeated_tool_call_limit"===o||"tool_argument_error"===o}catch{return!1}}(o.output)?[]:[`- ${o.toolId}: ${formatToolEvidence(o,t)}`]:[]}).slice(-5)}function isToolResultEvent(e){return"deepagents.tool_execution.result"===e?.eventType||"agent.tool.result"===e?.phase}function formatToolEvidence(e,t=1e3){return"string"==typeof e.output&&e.output.trim()?e.output.slice(0,t):"string"==typeof e.error&&e.error.trim()?`error: ${e.error.slice(0,t)}`:isRecord(e.args)?`completed with args: ${previewOutput(JSON.stringify(e.args))}`:"completed"}function readToolCallRecovery(e){if(!isRecord(e))return{};const t=isRecord(e.recovery)?e.recovery:{};return isRecord(t.toolCall)?t.toolCall:{}}function readRegexps(e,t){const o=(Array.isArray(e)?e:[]).filter(e=>"string"==typeof e&&e.length>0).map(e=>new RegExp(e,"iu"));return o.length>0?o:t}function readStringArray(e){return Array.isArray(e)?e.filter(e=>"string"==typeof e&&e.length>0):[]}function isRecord(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
export function createToolRepeatState(e){if(function repeatGuardEnabled(e){return!0===repeatGuardConfig(e).enabled}(e))return{successfulCalls:new Map,duplicateCallCounts:new Map,latestSuccessfulOutputByTool:new Map,successfulToolCounts:new Map,toolCallCounts:new Map,maxDuplicateCallsPerTool:readPositiveInteger(repeatGuardConfig(e).maxDuplicateCallsPerTool)??3,maxCallsPerTool:readPositiveInteger(repeatGuardConfig(e).maxCallsPerTool),maxSuccessfulCallsPerTool:readPositiveInteger(repeatGuardConfig(e).maxSuccessfulCallsPerTool),maxCallsByTool:readPositiveIntegerMap(repeatGuardConfig(e).maxCallsByTool),maxSuccessfulCallsByTool:readPositiveIntegerMap(repeatGuardConfig(e).maxSuccessfulCallsByTool),returnPreviousOutputOnRepeatLimit:!0===repeatGuardConfig(e).returnPreviousOutputOnRepeatLimit}}export function beforeToolInvoke(e,t,o){const n=o.toolCallCounts.get(e)??0;o.toolCallCounts.set(e,n+1);const r=o.maxCallsByTool.get(e)??o.maxCallsPerTool;if(void 0!==r&&n>=r){const t=o.latestSuccessfulOutputByTool.get(e),n=repeatedToolCallLimitContent(e,t);return{eventOutput:n,modelOutput:repeatLimitModelOutput(n,t,o)}}const l=o.maxSuccessfulCallsByTool.get(e)??o.maxSuccessfulCallsPerTool;if(void 0!==l&&(o.successfulToolCounts.get(e)??0)>=l){const t=o.latestSuccessfulOutputByTool.get(e),n=repeatedToolCallLimitContent(e,t);return{eventOutput:n,modelOutput:repeatLimitModelOutput(n,t,o)}}const
|
|
1
|
+
export function createToolRepeatState(e){if(function repeatGuardEnabled(e){return!0===repeatGuardConfig(e).enabled}(e))return{successfulCalls:new Map,duplicateCallCounts:new Map,latestSuccessfulOutputByTool:new Map,successfulToolCounts:new Map,toolCallCounts:new Map,maxDuplicateCallsPerTool:readPositiveInteger(repeatGuardConfig(e).maxDuplicateCallsPerTool)??3,maxCallsPerTool:readPositiveInteger(repeatGuardConfig(e).maxCallsPerTool),maxSuccessfulCallsPerTool:readPositiveInteger(repeatGuardConfig(e).maxSuccessfulCallsPerTool),maxCallsByTool:readPositiveIntegerMap(repeatGuardConfig(e).maxCallsByTool),maxSuccessfulCallsByTool:readPositiveIntegerMap(repeatGuardConfig(e).maxSuccessfulCallsByTool),returnPreviousOutputOnRepeatLimit:!0===repeatGuardConfig(e).returnPreviousOutputOnRepeatLimit}}export function beforeToolInvoke(e,t,o){const n=o.toolCallCounts.get(e)??0;o.toolCallCounts.set(e,n+1);const r=o.maxCallsByTool.get(e)??o.maxCallsPerTool;if(void 0!==r&&n>=r){const t=o.latestSuccessfulOutputByTool.get(e),n=repeatedToolCallLimitContent(e,t);return{eventOutput:n,modelOutput:repeatLimitModelOutput(n,t,o)}}const l=o.maxSuccessfulCallsByTool.get(e)??o.maxSuccessfulCallsPerTool;if(void 0!==l&&(o.successfulToolCounts.get(e)??0)>=l){const t=o.latestSuccessfulOutputByTool.get(e),n=repeatedToolCallLimitContent(e,t);return{eventOutput:n,modelOutput:repeatLimitModelOutput(n,t,o)}}const s=stableToolCallKey(e,t),u=o.successfulCalls.get(s);if(void 0!==u){const t=o.duplicateCallCounts.get(s)??0;if(o.duplicateCallCounts.set(s,t+1),void 0!==o.maxDuplicateCallsPerTool&&t>=o.maxDuplicateCallsPerTool){const t=repeatedToolCallLimitContent(e);return{eventOutput:t,modelOutput:t}}const n=function duplicateToolCallContent(e,t){return JSON.stringify({status:"duplicate_tool_call",toolId:e,instruction:"This agent already completed an equivalent tool call. Use the prior evidence instead of calling the tool again.",previousOutput:t})}(e,u);return{eventOutput:n,modelOutput:u}}}export function afterToolInvoke(e){return e.successful?(e.state.successfulCalls.set(stableToolCallKey(e.toolId,e.args),e.output),e.state.latestSuccessfulOutputByTool.set(e.toolId,e.output),e.state.successfulToolCounts.set(e.toolId,(e.state.successfulToolCounts.get(e.toolId)??0)+1),{}):{}}export function isToolRepeatLimitReached(e,t){if(!t)return!1;const o=t.maxCallsByTool.get(e)??t.maxCallsPerTool;if(void 0!==o&&(t.toolCallCounts.get(e)??0)>=o)return!0;const n=t.maxSuccessfulCallsByTool.get(e)??t.maxSuccessfulCallsPerTool;return void 0!==n&&(t.successfulToolCounts.get(e)??0)>=n}export function missingRequiredPlanContent(e){const t=readRecord(e.agent.config.executionContract);if(!0!==t.requiresPlan)return"";const o=readStringArray(t.planEvidenceTools);if(0===o.length||o.includes(e.toolId))return"";const n=new Set(e.events.flatMap(readEvidenceToolId));return o.some(e=>n.has(e))?"":["Status: plan_required",`Evidence tool: ${e.toolId}`,`Blocker: execution contract requires a planning checkpoint from one of: ${o.join(", ")} before evidence tools run.`,"Instruction: call the planning tool first, then retry this atomic evidence tool with repaired arguments."].join("\n")}export function missingToolDependencyContent(e){const t=readRecord(e.agent.config.executionContract),o=readStringArray(readRecord(t.toolDependencies)[e.toolId]);if(0===o.length)return"";const n=new Set(e.events.flatMap(readEvidenceToolId)),r=o.filter(e=>!n.has(e));return 0===r.length?"":["Status: dependency_required",`Evidence tool: ${e.toolId}`,`Blocker: this atomic evidence tool requires completed dependency evidence from: ${r.join(", ")}.`,"Instruction: complete the dependency tool first, evaluate it, then retry this atomic evidence tool."].join("\n")}export function toolInvocationEvents(e){const t=e.getEvents?.();return t??[]}function repeatGuardConfig(e){const t=readRecord(e);return readRecord(t.repeatGuard)}function readPositiveInteger(e){return"number"==typeof e&&Number.isInteger(e)&&e>0?e:void 0}function readPositiveIntegerMap(e){const t=readRecord(e);return new Map(Object.entries(t).map(([e,t])=>[e,readPositiveInteger(t)]).filter(e=>void 0!==e[1]))}function repeatLimitModelOutput(e,t,o){return o.returnPreviousOutputOnRepeatLimit&&void 0!==t&&0!==t.trim().length?t:e}function repeatedToolCallLimitContent(e,t){return JSON.stringify({status:"repeated_tool_call_limit",toolId:e,instruction:"This tool reached the configured repeat limit for this request. Do not call this tool or a substitute tool for the same evidence need again. Use previousOutput and the collected evidence to produce the final answer now, or report the remaining gap explicitly.",...void 0!==t?{previousOutput:t}:{}})}function stableToolCallKey(e,t){return`${e}:${stableJson(t)}`}function stableJson(e){return Array.isArray(e)?`[${e.map(stableJson).join(",")}]`:isRecord(e)?`{${Object.keys(e).sort().map(t=>`${JSON.stringify(t)}:${stableJson(e[t])}`).join(",")}}`:JSON.stringify(e)}function readEvidenceToolId(e){return"runtime.tool.direct.completed"===e.type?[e.toolId]:"runtime.adapter.event"===e.type&&isRecord(e.event)&&function isToolResultEvent(e){return"deepagents.tool_execution.result"===e.eventType||"agent.tool.result"===e.phase}(e.event)&&"string"==typeof e.event.toolId&&function isSuccessfulEvidenceEvent(e){const t=function readString(e){return"string"==typeof e&&e.length>0?e:void 0}(e.controlStatus)??function readOutputStatus(e){if("string"!=typeof e)return;const t=function parseJsonRecord(e){try{const t=JSON.parse(e);return isRecord(t)?t:void 0}catch{return}}(e);return"string"==typeof t?.status?t.status:e.match(/^Status:\s*([A-Za-z0-9_-]+)/imu)?.[1]}(e.output);return!t||/^(?:completed|success|ok|recorded)$/iu.test(t)}(e.event)?[e.event.toolId]:[]}function readRecord(e){return isRecord(e)?e:{}}function readStringArray(e){return Array.isArray(e)?e.filter(e=>"string"==typeof e&&e.length>0):[]}function isRecord(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
export function resolveProgressNarrator(e){if(!1===e.options)return;const t=readProgressPolicy(e.policy);return e.options?.enabled??t.enabled?e.options?.provider??function createTemplateProgressNarrator(){const e=new Map,t=new Map;return{name:"template",narrate(r,n){var o;"runtime.request.started"===r.type&&(e.set(r.requestId,{language:(o=r.input??"",/\p{Script=Han}/u.test(o)?"zh":void 0),input:r.input}),t.delete(r.requestId));const i=function templateMessage(e,t){const r="zh"===t?.language;return"runtime.request.started"===e.type?r?`我开始处理这个请求:${summarizeText(e.input)}`:`I'm starting on this request: ${summarizeText(e.input)}`:"runtime.request.completed"===e.type?r?"我已经完成执行链,正在交付最终结果。":"I've finished the execution chain and am returning the final result.":"runtime.request.failed"===e.type?r?"执行链失败了,我会保留具体错误方便定位。":"The execution chain failed; I'm keeping the concrete error visible for diagnosis.":"runtime.request.cancelled"===e.type?r?"这个请求已取消,后续执行会停止。":"The request was cancelled, so the remaining execution will stop.":"runtime.tool.direct.started"===e.type?r?`我正在运行 ${e.toolId}。`:`I'm running ${e.toolId}.`:"runtime.tool.direct.completed"===e.type?r?`${e.toolId} 已返回结果,我会继续使用这份证据。`:`${e.toolId} returned; I'll keep using that evidence.`:"runtime.workflow.started"===e.type?r?`我正在启动 workflow ${e.workflowId}。`:`I'm starting workflow ${e.workflowId}.`:"runtime.workflow.completed"===e.type?r?`workflow ${e.workflowId} 已完成。`:`Workflow ${e.workflowId} is complete.`:"runtime.specDriven.phase.started"===e.type?r?`我正在进入 spec-driven 阶段 ${e.phaseId}。`:`I'm starting spec-driven phase ${e.phaseId}.`:"runtime.specDriven.phase.blocked"===e.type?r?`spec-driven 阶段 ${e.phaseId} 被 gate 阻塞。`:`Spec-driven phase ${e.phaseId} is blocked by a gate.`:"runtime.specDriven.phase.completed"===e.type?r?`spec-driven 阶段 ${e.phaseId} 已完成。`:`Spec-driven phase ${e.phaseId} is complete.`:"runtime.specDriven.phase.verified"===e.type?r?`spec-driven 阶段 ${e.phaseId} 已验证。`:`Spec-driven phase ${e.phaseId} is verified.`:"runtime.artifact.created"===e.type?r?"我已经保存一份运行产物。":"I've saved a runtime artifact.":"runtime.execution.contract.failed"===e.type?r?"运行证据没有满足执行契约,我会进入恢复或失败路径。":"The run evidence did not satisfy the execution contract, so I'll recover or fail explicitly.":"runtime.inventory.repair"===e.type?inventoryRepairMessage(e.status,e.diagnostic.layer,r):"runtime.skill.candidate.created"===e.type?r?`我发现一个可沉淀的 skill 候选:${e.name}。`:`I found a reusable skill candidate: ${e.name}.`:e.type.startsWith("runtime.memory.")?function memoryMessage(e,t){return"runtime.memory.lifecycle"===e.type?t?`我进入记忆阶段:${e.hook}。`:`I'm in the memory lifecycle phase: ${e.hook}.`:"runtime.memory.recall.completed"===e.type?t?`我召回了 ${e.recordIds.length} 条相关记忆。`:`I recalled ${e.recordIds.length} relevant memory records.`:"runtime.memory.candidate.submitted"===e.type?t?"我提交了一条候选记忆。":"I submitted a memory candidate.":"runtime.memory.approval.requested"===e.type?t?"我提交了记忆审批请求。":"I requested memory approval.":"runtime.memory.plugin.started"===e.type?t?`我正在运行记忆插件 ${e.provider}。`:`I'm running memory plugin ${e.provider}.`:"runtime.memory.plugin.completed"===e.type?t?`记忆插件 ${e.provider} 已完成。`:`Memory plugin ${e.provider} completed.`:"runtime.memory.plugin.failed"===e.type?t?`记忆插件 ${e.provider} 失败了;主任务会继续,不把它当成执行结果。`:`Memory plugin ${e.provider} failed; the main task will continue without treating it as the result.`:"runtime.memory.maintenance.started"===e.type?t?`我正在维护 ${e.target} 记忆。`:`I'm maintaining ${e.target} memory.`:"runtime.memory.maintenance.completed"===e.type?t?`${e.target} 记忆维护完成。`:`${e.target} memory maintenance completed.`:"runtime.memory.maintenance.failed"===e.type?t?`${e.target} 记忆维护失败。`:`${e.target} memory maintenance failed.`:void 0}(e,r):"runtime.adapter.event"===e.type?function adapterMessage(e,t){if(isRecord(e)){if("agent.handoff"===e.phase)return t?"我把请求交给上游 agent backend,让它负责规划和执行。":"I'm handing the request to the upstream agent backend for planning and execution.";if("agent.tool.start"===e.phase&&"string"==typeof e.toolId)return function toolStartMessage(e,t,r){if("task"===e){const e=function readTaskTarget(e){const t=isRecord(e)?e:{};return readString(t.subagent_type)??readString(t.subagentType)}(t),n=function readDescription(e){const t=isRecord(e)?e:{};return summarizeText(readString(t.description)??readString(t.task))}(t);if(e&&n)return r?`我正在请求 task 工具委派给 ${e}:${n}`:`I'm asking the task tool to delegate to ${e}: ${n}`;if(e)return r?`我正在请求 task 工具委派给 ${e}。`:`I'm asking the task tool to delegate to ${e}.`}return r?`我正在运行 ${e} 收集证据。`:`I'm running ${e} to gather evidence.`}(e.toolId,e.args,t);if("agent.tool.result"===e.phase&&"string"==typeof e.toolId)return function toolResultMessage(e,t,r,n,o){if(r)return o?`${e} 返回错误:${summarizeText(String(r))}`:`${e} returned an error: ${summarizeText(String(r))}`;const i="string"==typeof n?n:function readToolControlStatus(e){const t=function parseToolOutputRecord(e){if(isRecord(e))return e;if("string"==typeof e)try{const t=JSON.parse(e);return isRecord(t)?t:void 0}catch{return}}(e);return"string"==typeof t?.status?t.status:"string"==typeof t?.error?t.error:"string"==typeof e&&e.startsWith("Task delegation target is not in the workspace inventory")?"task_inventory_blocked":void 0}(t);if(i)return function toolControlMessage(e,t,r){return"duplicate_tool_call"===t?r?`${e} 重复调用已复用已有证据。`:`${e} repeated an equivalent call, so the existing evidence was reused.`:"repeated_tool_call_limit"===t?r?`${e} 出现重复调用循环,我会基于已有证据继续收敛。`:`${e} entered a repeated-call loop, so I'll continue from the evidence already collected.`:"tool_argument_error"===t||"tool_argument_validation_failed"===t?r?`${e} 参数被工具 schema 拒绝,我会让 agent 修正参数或改用合适工具。`:`${e} arguments were rejected by the tool schema; I'll have the agent repair them or choose a suitable tool.`:"task_inventory_blocked"===t?r?"task 委派目标不在当前 workspace inventory 中,已被运行时策略阻止。":"The task delegation target is not in the current workspace inventory and was blocked by runtime policy.":r?`${e} 返回运行时控制状态:${t}。`:`${e} returned runtime control status: ${t}.`}(e,i,o);if("task"===e)return o?"委派任务已返回结果,我会基于这些证据继续推进。":"The delegated task returned; I'll keep going with that evidence.";const a=function summarizeToolOutput(e){if("string"==typeof e)return summarizeText(e);if(isRecord(e)){if("string"==typeof e.status)return summarizeText(e.status);if("string"==typeof e.summary)return summarizeText(e.summary)}}(t);return o?`${e} 已返回${a?`:${a}`:",我会继续判断下一步。"}`:`${e} returned${a?`: ${a}`:"; I'll decide the next step from here."}`}(e.toolId,e.output,e.error,e.controlStatus,t);if("agent.langgraph.invoke"===e.phase)return t?"我正在调用 workflow backend。":"I'm invoking the workflow backend.";if("agent.node.completed"===e.phase&&"string"==typeof e.nodeId)return t?`节点 ${e.nodeId} 已完成。`:`Node ${e.nodeId} is complete.`;if("inventory.repair"===e.phase&&"string"==typeof e.status){const r=isRecord(e.diagnostic)?e.diagnostic:{};return inventoryRepairMessage(e.status,readString(r.layer)??"selection",t)}}}(e.event,r):void 0}(r,e.get(r.requestId));if(i&&i!==t.get(r.requestId))return t.set(r.requestId,i),"runtime.request.failed"!==r.type&&"runtime.request.cancelled"!==r.type||(e.delete(r.requestId),t.delete(r.requestId)),function pruneRequestState(e,t){for(;e.size>200;){const r=e.keys().next().value;if(!r)break;e.delete(r),t.delete(r)}}(e,t),{message:i,style:n.style,model:n.model}}}}():void 0}export function createProgressNarrationEvent(e){if(!e.narrator||"runtime.progress.narration"===e.source.type)return;const t=readProgressPolicy(e.policy),r=!1===e.options?void 0:e.options,n=e.narrator.narrate(e.source,{style:r?.style??t.style,model:r?.model??t.model});return function isPromiseLike(e){return isRecord(e)&&"function"==typeof e.then}(n)?n.then(t=>toNarrationEvent(e.source,e.narrator,t)):toNarrationEvent(e.source,e.narrator,n)}export function createProgressNarrationCapability(e){const t=resolveProgressNarrator(e);if(t)return{id:"runtime.progress.narration",onEvent(r,n){try{const o=createProgressNarrationEvent({source:r,narrator:t,options:e.options,policy:e.policy});!function isRuntimeEventPromise(e){return isRecord(e)&&"function"==typeof e.then}(o)?o&&n(o):o.then(e=>{e&&n(e)}).catch(()=>{})}catch{return}}}}function toNarrationEvent(e,t,r){if(r?.message.trim())return{type:"runtime.progress.narration",requestId:e.requestId,sessionId:e.sessionId,agentId:e.agentId,message:r.message,provider:t.name,sourceEventTypes:r.sourceEventTypes??[e.type],sourceEventIds:r.sourceEventIds??(e.eventId?[e.eventId]:void 0),model:r.model,style:r.style}}function inventoryRepairMessage(e,t,r){return"repaired"===e?r?`${t} 选择已按 workspace inventory 修正。`:`${t} selection was repaired against the workspace inventory.`:r?`${t} 选择不在 workspace inventory 中,已被阻止。`:`${t} selection was blocked because it is outside the workspace inventory.`}function summarizeText(e){const t=e?.replace(/\s+/gu," ").trim();return t?t.length>120?`${t.slice(0,117)}...`:t:""}function readString(e){return"string"==typeof e&&e.trim()?e:void 0}function readProgressPolicy(e){const t=isRecord(e?.progress)?e.progress:{},r=isRecord(t.narration)?t.narration:{};return{enabled:"boolean"==typeof r.enabled?r.enabled:void 0,style:"string"==typeof r.style?r.style:void 0,model:"string"==typeof r.model?r.model:void 0}}function isRecord(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}
|
|
1
|
+
export function resolveProgressNarrator(e){if(!1===e.options)return;const t=readProgressPolicy(e.policy);return e.options?.enabled??t.enabled?e.options?.provider??function createTemplateProgressNarrator(){const e=new Map,t=new Map;return{name:"template",narrate(r,n){var o;"runtime.request.started"===r.type&&(e.set(r.requestId,{language:(o=r.input??"",/\p{Script=Han}/u.test(o)?"zh":void 0),input:r.input}),t.delete(r.requestId));const i=function templateMessage(e,t){const r="zh"===t?.language;return"runtime.request.started"===e.type?r?`我开始处理这个请求:${summarizeText(e.input)}`:`I'm starting on this request: ${summarizeText(e.input)}`:"runtime.request.completed"===e.type?r?"我已经完成执行链,正在交付最终结果。":"I've finished the execution chain and am returning the final result.":"runtime.request.failed"===e.type?r?"执行链失败了,我会保留具体错误方便定位。":"The execution chain failed; I'm keeping the concrete error visible for diagnosis.":"runtime.request.cancelled"===e.type?r?"这个请求已取消,后续执行会停止。":"The request was cancelled, so the remaining execution will stop.":"runtime.tool.direct.started"===e.type?r?`我正在运行 ${e.toolId}。`:`I'm running ${e.toolId}.`:"runtime.tool.direct.completed"===e.type?r?`${e.toolId} 已返回结果,我会继续使用这份证据。`:`${e.toolId} returned; I'll keep using that evidence.`:"runtime.workflow.started"===e.type?r?`我正在启动 workflow ${e.workflowId}。`:`I'm starting workflow ${e.workflowId}.`:"runtime.workflow.completed"===e.type?r?`workflow ${e.workflowId} 已完成。`:`Workflow ${e.workflowId} is complete.`:"runtime.specDriven.phase.started"===e.type?r?`我正在进入 spec-driven 阶段 ${e.phaseId}。`:`I'm starting spec-driven phase ${e.phaseId}.`:"runtime.specDriven.phase.blocked"===e.type?r?`spec-driven 阶段 ${e.phaseId} 被 gate 阻塞。`:`Spec-driven phase ${e.phaseId} is blocked by a gate.`:"runtime.specDriven.phase.completed"===e.type?r?`spec-driven 阶段 ${e.phaseId} 已完成。`:`Spec-driven phase ${e.phaseId} is complete.`:"runtime.specDriven.phase.verified"===e.type?r?`spec-driven 阶段 ${e.phaseId} 已验证。`:`Spec-driven phase ${e.phaseId} is verified.`:"runtime.artifact.created"===e.type?r?"我已经保存一份运行产物。":"I've saved a runtime artifact.":"runtime.execution.contract.failed"===e.type?r?"运行证据没有满足执行契约,我会进入恢复或失败路径。":"The run evidence did not satisfy the execution contract, so I'll recover or fail explicitly.":"runtime.inventory.repair"===e.type?inventoryRepairMessage(e.status,e.diagnostic.layer,r):"runtime.skill.candidate.created"===e.type?r?`我发现一个可沉淀的 skill 候选:${e.name}。`:`I found a reusable skill candidate: ${e.name}.`:e.type.startsWith("runtime.memory.")?function memoryMessage(e,t){return"runtime.memory.lifecycle"===e.type?t?`我进入记忆阶段:${e.hook}。`:`I'm in the memory lifecycle phase: ${e.hook}.`:"runtime.memory.recall.completed"===e.type?t?`我召回了 ${e.recordIds.length} 条相关记忆。`:`I recalled ${e.recordIds.length} relevant memory records.`:"runtime.memory.candidate.submitted"===e.type?t?"我提交了一条候选记忆。":"I submitted a memory candidate.":"runtime.memory.approval.requested"===e.type?t?"我提交了记忆审批请求。":"I requested memory approval.":"runtime.memory.plugin.started"===e.type?t?`我正在运行记忆插件 ${e.provider}。`:`I'm running memory plugin ${e.provider}.`:"runtime.memory.plugin.completed"===e.type?t?`记忆插件 ${e.provider} 已完成。`:`Memory plugin ${e.provider} completed.`:"runtime.memory.plugin.failed"===e.type?t?`记忆插件 ${e.provider} 失败了;主任务会继续,不把它当成执行结果。`:`Memory plugin ${e.provider} failed; the main task will continue without treating it as the result.`:"runtime.memory.maintenance.started"===e.type?t?`我正在维护 ${e.target} 记忆。`:`I'm maintaining ${e.target} memory.`:"runtime.memory.maintenance.completed"===e.type?t?`${e.target} 记忆维护完成。`:`${e.target} memory maintenance completed.`:"runtime.memory.maintenance.failed"===e.type?t?`${e.target} 记忆维护失败。`:`${e.target} memory maintenance failed.`:void 0}(e,r):"runtime.adapter.event"===e.type?function adapterMessage(e,t){if(isRecord(e)){if("agent.handoff"===e.phase)return t?"我把请求交给上游 agent backend,让它负责规划和执行。":"I'm handing the request to the upstream agent backend for planning and execution.";if(function isToolStartEvent(e){return"deepagents.tool_execution.start"===e.eventType||"agent.tool.start"===e.phase}(e)&&"string"==typeof e.toolId)return function toolStartMessage(e,t,r){if("task"===e){const e=function readTaskTarget(e){const t=isRecord(e)?e:{};return readString(t.subagent_type)??readString(t.subagentType)}(t),n=function readDescription(e){const t=isRecord(e)?e:{};return summarizeText(readString(t.description)??readString(t.task))}(t);if(e&&n)return r?`我正在请求 task 工具委派给 ${e}:${n}`:`I'm asking the task tool to delegate to ${e}: ${n}`;if(e)return r?`我正在请求 task 工具委派给 ${e}。`:`I'm asking the task tool to delegate to ${e}.`}return r?`我正在运行 ${e} 收集证据。`:`I'm running ${e} to gather evidence.`}(e.toolId,e.args,t);if(function isToolResultEvent(e){return"deepagents.tool_execution.result"===e.eventType||"agent.tool.result"===e.phase}(e)&&"string"==typeof e.toolId)return function toolResultMessage(e,t,r,n,o){if(r)return o?`${e} 返回错误:${summarizeText(String(r))}`:`${e} returned an error: ${summarizeText(String(r))}`;const i="string"==typeof n?n:function readToolControlStatus(e){const t=function parseToolOutputRecord(e){if(isRecord(e))return e;if("string"==typeof e)try{const t=JSON.parse(e);return isRecord(t)?t:void 0}catch{return}}(e);return"string"==typeof t?.status?t.status:"string"==typeof t?.error?t.error:"string"==typeof e&&e.startsWith("Task delegation target is not in the workspace inventory")?"task_inventory_blocked":void 0}(t);if(i)return function toolControlMessage(e,t,r){return"duplicate_tool_call"===t?r?`${e} 重复调用已复用已有证据。`:`${e} repeated an equivalent call, so the existing evidence was reused.`:"repeated_tool_call_limit"===t?r?`${e} 出现重复调用循环,我会基于已有证据继续收敛。`:`${e} entered a repeated-call loop, so I'll continue from the evidence already collected.`:"tool_argument_error"===t||"tool_argument_validation_failed"===t?r?`${e} 参数被工具 schema 拒绝,我会让 agent 修正参数或改用合适工具。`:`${e} arguments were rejected by the tool schema; I'll have the agent repair them or choose a suitable tool.`:"task_inventory_blocked"===t?r?"task 委派目标不在当前 workspace inventory 中,已被运行时策略阻止。":"The task delegation target is not in the current workspace inventory and was blocked by runtime policy.":r?`${e} 返回运行时控制状态:${t}。`:`${e} returned runtime control status: ${t}.`}(e,i,o);if("task"===e)return o?"委派任务已返回结果,我会基于这些证据继续推进。":"The delegated task returned; I'll keep going with that evidence.";const a=function summarizeToolOutput(e){if("string"==typeof e)return summarizeText(e);if(isRecord(e)){if("string"==typeof e.status)return summarizeText(e.status);if("string"==typeof e.summary)return summarizeText(e.summary)}}(t);return o?`${e} 已返回${a?`:${a}`:",我会继续判断下一步。"}`:`${e} returned${a?`: ${a}`:"; I'll decide the next step from here."}`}(e.toolId,e.output,e.error,e.controlStatus,t);if("agent.langgraph.invoke"===e.phase)return t?"我正在调用 workflow backend。":"I'm invoking the workflow backend.";if("agent.node.completed"===e.phase&&"string"==typeof e.nodeId)return t?`节点 ${e.nodeId} 已完成。`:`Node ${e.nodeId} is complete.`;if("inventory.repair"===e.phase&&"string"==typeof e.status){const r=isRecord(e.diagnostic)?e.diagnostic:{};return inventoryRepairMessage(e.status,readString(r.layer)??"selection",t)}}}(e.event,r):void 0}(r,e.get(r.requestId));if(i&&i!==t.get(r.requestId))return t.set(r.requestId,i),"runtime.request.failed"!==r.type&&"runtime.request.cancelled"!==r.type||(e.delete(r.requestId),t.delete(r.requestId)),function pruneRequestState(e,t){for(;e.size>200;){const r=e.keys().next().value;if(!r)break;e.delete(r),t.delete(r)}}(e,t),{message:i,style:n.style,model:n.model}}}}():void 0}export function createProgressNarrationEvent(e){if(!e.narrator||"runtime.progress.narration"===e.source.type)return;const t=readProgressPolicy(e.policy),r=!1===e.options?void 0:e.options,n=e.narrator.narrate(e.source,{style:r?.style??t.style,model:r?.model??t.model});return function isPromiseLike(e){return isRecord(e)&&"function"==typeof e.then}(n)?n.then(t=>toNarrationEvent(e.source,e.narrator,t)):toNarrationEvent(e.source,e.narrator,n)}export function createProgressNarrationCapability(e){const t=resolveProgressNarrator(e);if(t)return{id:"runtime.progress.narration",onEvent(r,n){try{const o=createProgressNarrationEvent({source:r,narrator:t,options:e.options,policy:e.policy});!function isRuntimeEventPromise(e){return isRecord(e)&&"function"==typeof e.then}(o)?o&&n(o):o.then(e=>{e&&n(e)}).catch(()=>{})}catch{return}}}}function toNarrationEvent(e,t,r){if(r?.message.trim())return{type:"runtime.progress.narration",requestId:e.requestId,sessionId:e.sessionId,agentId:e.agentId,message:r.message,provider:t.name,sourceEventTypes:r.sourceEventTypes??[e.type],sourceEventIds:r.sourceEventIds??(e.eventId?[e.eventId]:void 0),model:r.model,style:r.style}}function inventoryRepairMessage(e,t,r){return"repaired"===e?r?`${t} 选择已按 workspace inventory 修正。`:`${t} selection was repaired against the workspace inventory.`:r?`${t} 选择不在 workspace inventory 中,已被阻止。`:`${t} selection was blocked because it is outside the workspace inventory.`}function summarizeText(e){const t=e?.replace(/\s+/gu," ").trim();return t?t.length>120?`${t.slice(0,117)}...`:t:""}function readString(e){return"string"==typeof e&&e.trim()?e:void 0}function readProgressPolicy(e){const t=isRecord(e?.progress)?e.progress:{},r=isRecord(t.narration)?t.narration:{};return{enabled:"boolean"==typeof r.enabled?r.enabled:void 0,style:"string"==typeof r.style?r.style:void 0,model:"string"==typeof r.model?r.model:void 0}}function isRecord(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
export function createDelegationTraceProjection(e,t={}){return{traceType:"delegation",traceLabel:e,...t}}export function createPlanTraceProjection(e,t={}){return{traceType:"plan",traceLabel:e,...t}}export function projectRuntimeTrace(e){return e.events.map(projectEvent).filter(isTraceEntry)}export function projectRuntimeTraceSpans(e){const t=function createSpanBuilder(e){const t=`run:${e.requestId}`,r=[],o=new Map;return{ensureRoot(){if(o.has(t))return;const n={spanId:t,requestId:e.requestId,sessionId:e.sessionId,agentId:e.agentId,kind:"run",name:e.agentId,status:(a=e.state,"completed"===a?"completed":"failed"===a?"failed":"cancelled"===a?"blocked":"running"),startedAt:e.startedAt,completedAt:e.completedAt,startEventIndex:0,...e.parentRunId?{parentSpanId:`run:${e.parentRunId}`}:{},events:[]};var a;r.push(n),o.set(t,n)},markRoot(e,r,n,a){const i=o.get(t);i&&(addEvent(i,e,r),i.status=n,i.attributes=merge(i.attributes,a),"running"!==n&&close(i,e,r))},start(e,n,a,i,s,d){const p=createSpan(`${t}/${e}:${s}`,t,n,a,i,s,d);r.push(p),o.set(e,p)},complete(e,n,a,i){const s=o.get(e)??createSpan(`${t}/${e}:${a}`,t,"adapter",e,n,a);return o.has(e)||r.push(s),addEvent(s,n,a),s.attributes=merge(s.attributes,i),close(s,n,a),o.delete(e),s},fail(e,t,r,o){this.complete(e,t,r,o).status="failed"},event(e,o,n,a,i){const s=createSpan(`${t}/event:${a}`,t,e,o,n,a,i);s.status=function readBlockedStatus(e){return e.type.endsWith(".blocked")||e.type.includes(".approval.")?"blocked":void 0}(n)??"event",close(s,n,a),r.push(s)},closeRoot(){const r=o.get(t);r&&e.completedAt&&(r.completedAt=e.completedAt)},spans:()=>r}}(e);return t.ensureRoot(),e.events.forEach((e,r)=>function projectSpanEvent(e,t,r){return t.type.startsWith("runtime.request.")?function projectRequestSpanEvent(e,t,r){return"runtime.request.started"===t.type?e.markRoot(t,r,"running",{input:t.input}):"runtime.request.completed"===t.type?e.markRoot(t,r,"completed",{output:t.output}):"runtime.request.failed"===t.type?e.markRoot(t,r,"failed",{error:t.error}):"runtime.request.cancelled"===t.type?e.markRoot(t,r,"blocked",{reason:t.reason}):"runtime.execution.contract.failed"===t.type?projectSingleSpan(e,t,r,"quality",t.type,{reason:t.reason,missingEvidenceTools:t.missingEvidenceTools}):void 0}(e,t,r):"runtime.tool.direct.started"===t.type?e.start(`tool:${t.toolId}`,"tool",t.toolId,t,r,{toolId:t.toolId}):"runtime.tool.direct.completed"===t.type?e.complete(`tool:${t.toolId}`,t,r,{toolId:t.toolId,output:t.output}):"runtime.workflow.started"===t.type?e.start(`workflow:${t.workflowId}`,"workflow",t.workflowId,t,r,{workflowId:t.workflowId,adapter:t.adapter}):"runtime.workflow.completed"===t.type?e.complete(`workflow:${t.workflowId}`,t,r,{workflowId:t.workflowId,adapter:t.adapter}):t.type.startsWith("runtime.approval.")||t.type.startsWith("runtime.memory.approval.")?projectSingleSpan(e,t,r,"approval",t.type):t.type.startsWith("runtime.specDriven.phase.")?projectSingleSpan(e,t,r,"spec",function readPhaseName(e,t){return"phaseId"in e&&"string"==typeof e.phaseId?e.phaseId:t}(t,"phase")):t.type.startsWith("runtime.memory.")?projectSingleSpan(e,t,r,"memory",t.type):t.type.startsWith("runtime.quality.")?projectSingleSpan(e,t,r,"quality",t.type):"runtime.artifact.created"===t.type?projectSingleSpan(e,t,r,"artifact",t.artifact.id,{artifact:t.artifact}):"runtime.progress.narration"===t.type?projectSingleSpan(e,t,r,"progress",t.message,{provider:t.provider}):"runtime.adapter.event"===t.type?function projectAdapterSpanEvent(e,t,r){const o=isRecord(t.event)?t.event:void 0,n=readString(o?.phase)??"runtime.adapter.event",a=readTraceType(o?.traceType),i=readString(o?.traceLabel);return"delegation"===a&&i?.endsWith(".start")?e.start(delegationKey(o),"delegation",readString(o?.subagentType)??i,t,r,o):"delegation"===a&&i?.endsWith(".completed")?e.complete(delegationKey(o),t,r,o):"plan"===a&&i?projectSingleSpan(e,t,r,"plan",i,o):"agent.tool.start"===
|
|
1
|
+
export function createDelegationTraceProjection(e,t={}){return{traceType:"delegation",traceLabel:e,...t}}export function createPlanTraceProjection(e,t={}){return{traceType:"plan",traceLabel:e,...t}}export function projectRuntimeTrace(e){return e.events.map(projectEvent).filter(isTraceEntry)}export function projectRuntimeTraceSpans(e){const t=function createSpanBuilder(e){const t=`run:${e.requestId}`,r=[],o=new Map;return{ensureRoot(){if(o.has(t))return;const n={spanId:t,requestId:e.requestId,sessionId:e.sessionId,agentId:e.agentId,kind:"run",name:e.agentId,status:(a=e.state,"completed"===a?"completed":"failed"===a?"failed":"cancelled"===a?"blocked":"running"),startedAt:e.startedAt,completedAt:e.completedAt,startEventIndex:0,...e.parentRunId?{parentSpanId:`run:${e.parentRunId}`}:{},events:[]};var a;r.push(n),o.set(t,n)},markRoot(e,r,n,a){const i=o.get(t);i&&(addEvent(i,e,r),i.status=n,i.attributes=merge(i.attributes,a),"running"!==n&&close(i,e,r))},start(e,n,a,i,s,d){const p=createSpan(`${t}/${e}:${s}`,t,n,a,i,s,d);r.push(p),o.set(e,p)},complete(e,n,a,i){const s=o.get(e)??createSpan(`${t}/${e}:${a}`,t,"adapter",e,n,a);return o.has(e)||r.push(s),addEvent(s,n,a),s.attributes=merge(s.attributes,i),close(s,n,a),o.delete(e),s},fail(e,t,r,o){this.complete(e,t,r,o).status="failed"},event(e,o,n,a,i){const s=createSpan(`${t}/event:${a}`,t,e,o,n,a,i);s.status=function readBlockedStatus(e){return e.type.endsWith(".blocked")||e.type.includes(".approval.")?"blocked":void 0}(n)??"event",close(s,n,a),r.push(s)},closeRoot(){const r=o.get(t);r&&e.completedAt&&(r.completedAt=e.completedAt)},spans:()=>r}}(e);return t.ensureRoot(),e.events.forEach((e,r)=>function projectSpanEvent(e,t,r){return t.type.startsWith("runtime.request.")?function projectRequestSpanEvent(e,t,r){return"runtime.request.started"===t.type?e.markRoot(t,r,"running",{input:t.input}):"runtime.request.completed"===t.type?e.markRoot(t,r,"completed",{output:t.output}):"runtime.request.failed"===t.type?e.markRoot(t,r,"failed",{error:t.error}):"runtime.request.cancelled"===t.type?e.markRoot(t,r,"blocked",{reason:t.reason}):"runtime.execution.contract.failed"===t.type?projectSingleSpan(e,t,r,"quality",t.type,{reason:t.reason,missingEvidenceTools:t.missingEvidenceTools}):void 0}(e,t,r):"runtime.tool.direct.started"===t.type?e.start(`tool:${t.toolId}`,"tool",t.toolId,t,r,{toolId:t.toolId}):"runtime.tool.direct.completed"===t.type?e.complete(`tool:${t.toolId}`,t,r,{toolId:t.toolId,output:t.output}):"runtime.workflow.started"===t.type?e.start(`workflow:${t.workflowId}`,"workflow",t.workflowId,t,r,{workflowId:t.workflowId,adapter:t.adapter}):"runtime.workflow.completed"===t.type?e.complete(`workflow:${t.workflowId}`,t,r,{workflowId:t.workflowId,adapter:t.adapter}):t.type.startsWith("runtime.approval.")||t.type.startsWith("runtime.memory.approval.")?projectSingleSpan(e,t,r,"approval",t.type):t.type.startsWith("runtime.specDriven.phase.")?projectSingleSpan(e,t,r,"spec",function readPhaseName(e,t){return"phaseId"in e&&"string"==typeof e.phaseId?e.phaseId:t}(t,"phase")):t.type.startsWith("runtime.memory.")?projectSingleSpan(e,t,r,"memory",t.type):t.type.startsWith("runtime.quality.")?projectSingleSpan(e,t,r,"quality",t.type):"runtime.artifact.created"===t.type?projectSingleSpan(e,t,r,"artifact",t.artifact.id,{artifact:t.artifact}):"runtime.progress.narration"===t.type?projectSingleSpan(e,t,r,"progress",t.message,{provider:t.provider}):"runtime.adapter.event"===t.type?function projectAdapterSpanEvent(e,t,r){const o=isRecord(t.event)?t.event:void 0,n=readString(o?.phase)??"runtime.adapter.event",a=readTraceType(o?.traceType),i=readString(o?.traceLabel);return"delegation"===a&&i?.endsWith(".start")?e.start(delegationKey(o),"delegation",readString(o?.subagentType)??i,t,r,o):"delegation"===a&&i?.endsWith(".completed")?e.complete(delegationKey(o),t,r,o):"plan"===a&&i?projectSingleSpan(e,t,r,"plan",i,o):function isToolStartEvent(e){return"deepagents.tool_execution.start"===e?.eventType||"agent.tool.start"===e?.phase}(o)?e.start(`agent-tool:${readString(o?.toolId)??"unknown"}`,"tool",readString(o?.toolId)??n,t,r,o):function isToolResultEvent(e){return"deepagents.tool_execution.result"===e?.eventType||"agent.tool.result"===e?.phase}(o)?e.complete(`agent-tool:${readString(o?.toolId)??"unknown"}`,t,r,o):projectSingleSpan(e,t,r,"adapter",n,o)}(e,t,r):"runtime.inventory.repair"===t.type?projectSingleSpan(e,t,r,"adapter","runtime.inventory.repair",{status:t.status,...t.diagnostic}):"runtime.sandbox.decision"===t.type?projectSingleSpan(e,t,r,"tool",`sandbox:${t.toolId}`,{toolId:t.toolId,...t.decision}):"runtime.tool.failure"===t.type?e.fail(`tool:${t.toolId}`,t,r,{toolId:t.toolId,...t.failure}):"runtime.tool.circuit.opened"===t.type?projectSingleSpan(e,t,r,"tool",`circuit:${t.toolId}`,{toolId:t.toolId,reason:t.reason}):void 0}(t,e,r)),t.closeRoot(),t.spans()}export function projectEvent(e){return"runtime.request.started"===e.type||"runtime.request.completed"===e.type||"runtime.request.failed"===e.type?base(e,"request",e.type):"runtime.request.cancelled"===e.type?base(e,"request",e.type,{reason:e.reason}):"runtime.execution.contract.failed"===e.type?base(e,"request",e.type,{reason:e.reason,missingEvidenceTools:e.missingEvidenceTools}):"runtime.inventory.repair"===e.type?base(e,"adapter","runtime.inventory.repair",{status:e.status,...e.diagnostic}):"runtime.tool.direct.started"===e.type?base(e,"tool","runtime.tool.direct.started",{toolId:e.toolId}):"runtime.tool.direct.completed"===e.type?base(e,"tool","runtime.tool.direct.completed",{toolId:e.toolId}):"runtime.sandbox.decision"===e.type?base(e,"tool","runtime.sandbox.decision",{toolId:e.toolId,...e.decision}):"runtime.tool.failure"===e.type?base(e,"tool","runtime.tool.failure",{toolId:e.toolId,...e.failure}):"runtime.tool.circuit.opened"===e.type?base(e,"tool","runtime.tool.circuit.opened",{toolId:e.toolId,reason:e.reason}):"runtime.workflow.started"===e.type||"runtime.workflow.completed"===e.type?base(e,"workflow",e.type,{workflowId:e.workflowId,adapter:e.adapter}):function isSpecDrivenPhaseEvent(e){return e.type.startsWith("runtime.specDriven.phase.")}(e)?base(e,"spec",e.type,{phaseId:e.phaseId,..."workflowId"in e&&e.workflowId?{workflowId:e.workflowId}:{},..."reason"in e?{reason:e.reason}:{},..."artifact"in e&&e.artifact?{artifact:e.artifact}:{}}):"runtime.adapter.event"===e.type?function adapterTrace(e){const t=e.event;if(isRecord(t)&&"string"==typeof t.phase){const r=function semanticAdapterTrace(e,t){if("inventory.repair"===t.phase)return base(e,"adapter","runtime.inventory.repair",{status:t.status,...isRecord(t.diagnostic)?t.diagnostic:{}});const r=readTraceType(t.traceType),o=readString(t.traceLabel);return r&&o?base(e,r,o,t):void 0}(e,t);return r||base(e,"adapter",t.phase.startsWith("agent.")?t.phase:`adapter.${t.phase}`,t)}return base(e,"adapter","runtime.adapter.event",{event:t})}(e):"runtime.artifact.created"===e.type?base(e,"artifact","runtime.artifact.created",{artifact:e.artifact}):e.type.startsWith("runtime.memory.")?base(e,"memory",e.type):"runtime.progress.narration"===e.type?base(e,"progress",e.type,{message:e.message,provider:e.provider,sourceEventTypes:e.sourceEventTypes}):void 0}export function readPlanTodos(e){const t=function readPlanRecord(e){if(isRecord(e))return e;if("string"==typeof e)try{const t=JSON.parse(e);return isRecord(t)?t:void 0}catch{return}}(e),r=function readTodosArray(e){const t=isRecord(e?.args)?e.args:void 0;return Array.isArray(e?.todos)?e.todos:Array.isArray(t?.todos)?t.todos:[]}(t);return r.map(readTodo).filter(isPlanTodoItem)}function readTodo(e){if(isRecord(e)&&"string"==typeof e.content)return{content:e.content,status:"string"==typeof e.status?e.status:"pending"}}function isPlanTodoItem(e){return void 0!==e}function base(e,t,r,o){return{type:t,label:r,agentId:e.agentId,requestId:e.requestId,detail:o}}function isTraceEntry(e){return void 0!==e}function projectSingleSpan(e,t,r,o,n,a){return e.event(o,n,t,r,a)}function delegationKey(e){return`delegation:${readString(e?.subagentType)??readString(e?.toolId)??"task"}`}function createSpan(e,t,r,o,n,a,i){const s={spanId:e,parentSpanId:t,requestId:n.requestId,sessionId:n.sessionId,agentId:n.agentId,kind:r,name:o,status:"running",startedAt:n.emittedAt,startEventIndex:a,attributes:i,events:[]};return addEvent(s,n,a),s}function addEvent(e,t,r){e.events.push({index:r,eventId:t.eventId??`${t.requestId}:${r}`,type:t.type,emittedAt:t.emittedAt})}function close(e,t,r){e.status="failed"===e.status||"blocked"===e.status?e.status:"completed",e.completedAt=t.emittedAt,e.endEventIndex=r,e.durationMs=function durationMs(e,t){if(!e||!t)return;const r=Date.parse(t)-Date.parse(e);return Number.isFinite(r)&&r>=0?r:void 0}(e.startedAt,e.completedAt)}function merge(e,t){return t?{...e,...t}:e}function isRecord(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function readTraceType(e){const t=readString(e);return"request"===t||"tool"===t||"workflow"===t||"spec"===t||"adapter"===t||"memory"===t||"artifact"===t||"progress"===t||"plan"===t||"delegation"===t?t:void 0}function readString(e){return"string"==typeof e&&e.trim()?e:void 0}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
export function missingFinalDelta(e,t){return e?!t||e.includes(t)?"":t.startsWith(e)?t.slice(e.length):t:t}export function createRoleChunk(e,t){return createChunk(e,t,{role:"assistant"},null)}export function createContentChunk(e,t,n){return createChunk(e,t,{content:n},null)}export function createStopChunk(e,t){return createChunk(e,t,{},"stop")}export function writeRuntimeStreamEvent(e,t,n,r){const o=function readAdapterDelta(e){if("runtime.adapter.event"!==e.type||"object"!=typeof e.event||null===e.event)return;const t=e.event;return"agent.output.delta"
|
|
1
|
+
export function missingFinalDelta(e,t){return e?!t||e.includes(t)?"":t.startsWith(e)?t.slice(e.length):t:t}export function createRoleChunk(e,t){return createChunk(e,t,{role:"assistant"},null)}export function createContentChunk(e,t,n){return createChunk(e,t,{content:n},null)}export function createStopChunk(e,t){return createChunk(e,t,{},"stop")}export function writeRuntimeStreamEvent(e,t,n,r){const o=function readAdapterDelta(e){if("runtime.adapter.event"!==e.type||"object"!=typeof e.event||null===e.event)return;const t=e.event;return"deepagents.message.coordinator_delta"!==t.eventType&&"agent.output.delta"!==t.phase||"string"!=typeof t.text?void 0:t.text}(t);if(o)return writeChatSse(e,createContentChunk(n,r,o)),o;!function writeProgressEvent(e,t){const n=function readToolProgress(e){if("runtime.tool.direct.started"===e.type||"runtime.tool.direct.completed"===e.type)return{request_id:e.requestId,session_id:e.sessionId,agent_id:e.agentId,type:e.type,tool_id:e.toolId};if("runtime.adapter.event"!==e.type||"object"!=typeof e.event||null===e.event)return;const t=e.event,n=function readToolProgressType(e){return"deepagents.tool_execution.start"===e.eventType?"deepagents.tool_execution.start":"deepagents.tool_execution.result"===e.eventType?"deepagents.tool_execution.result":"agent.tool.start"===e.phase||"agent.tool.result"===e.phase?e.phase:void 0}(t),r="string"==typeof t.toolId?t.toolId:void 0;return n&&r?{request_id:e.requestId,session_id:e.sessionId,agent_id:e.agentId,type:n,tool_id:r,adapter:t.adapter}:void 0}(t);n&&writeSse(e,"stable_harness.tool.progress",n)}(e,t),function writeNarrationEvent(e,t){"runtime.progress.narration"===t.type&&writeSse(e,"stable_harness.progress.narration",{request_id:t.requestId,session_id:t.sessionId,agent_id:t.agentId,type:t.type,message:t.message,provider:t.provider,source_event_types:t.sourceEventTypes,source_event_ids:t.sourceEventIds,model:t.model,style:t.style})}(e,t)}export function writeSseHeaders(e,t){e.writeHead(200,{"content-type":"text/event-stream","cache-control":"no-cache",connection:"keep-alive",...t})}export function writeChatSse(e,t){e.write(`data: ${JSON.stringify(t)}\n\n`)}function createChunk(e,t,n,r){return{id:e,object:"chat.completion.chunk",created:Math.floor(Date.now()/1e3),model:t??"stable-harness",choices:[{index:0,delta:n,finish_reason:r}]}}function writeSse(e,t,n){e.write(`event: ${t}\n`),e.write(`data: ${JSON.stringify(n)}\n\n`)}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "stable-harness",
|
|
3
|
-
"version": "0.0.
|
|
3
|
+
"version": "0.0.46",
|
|
4
4
|
"type": "module",
|
|
5
5
|
"description": "Stable application runtime and operator control plane for agent workspaces.",
|
|
6
6
|
"license": "Apache-2.0",
|
|
@@ -79,7 +79,7 @@
|
|
|
79
79
|
],
|
|
80
80
|
"dependencies": {
|
|
81
81
|
"@easynet/better-call": "^0.1.60",
|
|
82
|
-
"@langchain/core": "^1.1.
|
|
82
|
+
"@langchain/core": "^1.1.46",
|
|
83
83
|
"@langchain/langgraph": "^1.3.0",
|
|
84
84
|
"@langchain/langgraph-api": "^1.2.1",
|
|
85
85
|
"@langchain/ollama": "^1.2.7",
|
|
@@ -92,8 +92,8 @@
|
|
|
92
92
|
"@stable-harness/protocols": "0.0.1",
|
|
93
93
|
"@stable-harness/tool-gateway": "0.0.1",
|
|
94
94
|
"@stable-harness/workspace-yaml": "0.0.1",
|
|
95
|
-
"deepagents": "^1.
|
|
96
|
-
"langchain": "^1.
|
|
95
|
+
"deepagents": "^1.10.1",
|
|
96
|
+
"langchain": "^1.4.0",
|
|
97
97
|
"yaml": "^2.8.2",
|
|
98
98
|
"zod": "^4.1.13"
|
|
99
99
|
},
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{realpathSync as e}from"node:fs";import t from"node:path";import{buildRuntimeSystemPrompt as r}from"@stable-harness/core";import{createBuiltinToolPolicyMiddleware as n,createObserverMiddleware as o}from"./internal/builtin-tool-policy.js";import{resolveFilesystemPermissions as s}from"./internal/builtin/permissions.js";import{createToolRepeatState as a}from"@stable-harness/core";import{buildGatewayTools as i,stringifyDeepAgentResult as p}from"./internal/gateway-tools.js";import{resolveDeepAgentsNativeMemories as c}from"./memory.js";import{buildDeepAgentRequest as d}from"./internal/messages.js";import{createRawToolCallParserMiddleware as l}from"./internal/raw-tool-call-parser.js";import{createBackendModel as u}from"./model-providers.js";import{createDeepAgentsRetryMiddleware as m}from"./retry-policy.js";import{streamDeepAgentResult as g}from"./internal/stream-events.js";export function createDeepAgentsAdapter(e={}){return{name:"deepagents",canRun:e=>"deepagents"===e.backend,async run(t){if(t.emit({type:"runtime.adapter.event",requestId:t.requestId,sessionId:t.sessionId,agentId:t.agent.id,event:{adapter:"deepagents",phase:"agent.handoff",modelRef:t.agent.modelRef,tools:t.agent.tools,subagents:t.agent.subagents}}),e.runner)return e.runner(t);const r=e.createDeepAgent?void 0:await async function loadDeepAgentsModule(){try{return await async function importOptionalPackage(e){return import(e)}("deepagents")}catch(e){throw new Error(`DeepAgents package is required for the default adapter path: ${function formatError(e){return e instanceof Error?e.message:String(e)}(e)}`)}}(),n=e.createDeepAgent??function readCreateDeepAgent(e){const t=e?.createDeepAgent;if("function"==typeof t)return t;throw new Error("DeepAgents package does not export createDeepAgent.")}(r),o=n(function buildDeepAgentParams(e,t,r){const n={...readDeepAgentsConfig(t),...readDeepAgentsConfig(e.agent.config.deepagents)},o=resolveDeepAgentsSkills(e,e.agent),a=n.permissions??s(e,e.agent),p=requestScopedRepeatState(e,e.agent.id);return pruneUndefined({name:e.agent.id,model:n.model??resolveAgentModel(e,e.agent),systemPrompt:buildSystemPrompt(e,e.agent),backend:n.backend??resolveDeepAgentsBackend(e,r,o),checkpointer:n.checkpointer,store:n.store,middleware:mergeMiddleware(e,e.agent,n.middleware,p),responseFormat:n.responseFormat,contextSchema:n.contextSchema,interruptOn:n.interruptOn,generalPurposeAgent:readBoolean(n.generalPurposeAgent),taskDescription:readString(n.taskDescription),permissions:a,tools:i(e,e.agent.id,e.agent.tools,resolveAgentRepairModel(e,e.agent,n),p),subagents:e.agent.subagents.map(t=>{const r=e.workspace.agents.get(t),n=readDeepAgentsConfig(r?.config.deepagents),o=n.permissions??s(e,r),a=scopedInput(e,r),p=requestScopedRepeatState(e,t);return pruneUndefined({name:t,description:r?.description??readString(r?.config.description)??r?.id,systemPrompt:buildSystemPrompt(e,r),model:n.model??(r?resolveAgentModel(e,r):void 0),middleware:mergeMiddleware(a,r,n.middleware,p),interruptOn:n.interruptOn,generalPurposeAgent:readBoolean(n.generalPurposeAgent),taskDescription:readString(n.taskDescription),permissions:o,responseFormat:n.responseFormat,tools:i(e,t,r?.tools??[],resolveAgentRepairModel(a,r,n),p),memory:resolveDeepAgentsMemory(e,r),skills:resolveDeepAgentsSkills(e,r)})}),memory:resolveDeepAgentsMemory(e,e.agent),skills:o})}(t,e.config,r)),a=d(t),c=function buildDeepAgentInvokeConfig(e){return pruneUndefined({recursionLimit:readNumber(readDeepAgentsConfig(e.config.deepagents).recursionLimit)??readNumber(e.config.recursionLimit)})}(t.agent);if(!0===t.request.metadata?.openaiStream&&o.streamEvents)
|
|
1
|
+
import{realpathSync as e}from"node:fs";import t from"node:path";import{buildRuntimeSystemPrompt as r}from"@stable-harness/core";import{createBuiltinToolPolicyMiddleware as n,createObserverMiddleware as o}from"./internal/builtin-tool-policy.js";import{resolveFilesystemPermissions as s}from"./internal/builtin/permissions.js";import{createToolRepeatState as a}from"@stable-harness/core";import{buildGatewayTools as i,stringifyDeepAgentResult as p}from"./internal/gateway-tools.js";import{resolveDeepAgentsNativeMemories as c}from"./memory.js";import{buildDeepAgentRequest as d}from"./internal/messages.js";import{createRawToolCallParserMiddleware as l}from"./internal/raw-tool-call-parser.js";import{createBackendModel as u}from"./model-providers.js";import{createDeepAgentsRetryMiddleware as m}from"./retry-policy.js";import{streamDeepAgentResult as g}from"./internal/stream-events.js";export function createDeepAgentsAdapter(e={}){return{name:"deepagents",canRun:e=>"deepagents"===e.backend,async run(t){if(t.emit({type:"runtime.adapter.event",requestId:t.requestId,sessionId:t.sessionId,agentId:t.agent.id,event:{adapter:"deepagents",phase:"agent.handoff",modelRef:t.agent.modelRef,tools:t.agent.tools,subagents:t.agent.subagents}}),e.runner)return e.runner(t);const r=e.createDeepAgent?void 0:await async function loadDeepAgentsModule(){try{return await async function importOptionalPackage(e){return import(e)}("deepagents")}catch(e){throw new Error(`DeepAgents package is required for the default adapter path: ${function formatError(e){return e instanceof Error?e.message:String(e)}(e)}`)}}(),n=e.createDeepAgent??function readCreateDeepAgent(e){const t=e?.createDeepAgent;if("function"==typeof t)return t;throw new Error("DeepAgents package does not export createDeepAgent.")}(r),o=n(function buildDeepAgentParams(e,t,r){const n={...readDeepAgentsConfig(t),...readDeepAgentsConfig(e.agent.config.deepagents)},o=resolveDeepAgentsSkills(e,e.agent),a=n.permissions??s(e,e.agent),p=requestScopedRepeatState(e,e.agent.id);return pruneUndefined({name:e.agent.id,model:n.model??resolveAgentModel(e,e.agent),systemPrompt:buildSystemPrompt(e,e.agent),backend:n.backend??resolveDeepAgentsBackend(e,r,o),checkpointer:n.checkpointer,store:n.store,middleware:mergeMiddleware(e,e.agent,n.middleware,p),responseFormat:n.responseFormat,contextSchema:n.contextSchema,interruptOn:n.interruptOn,generalPurposeAgent:readBoolean(n.generalPurposeAgent),taskDescription:readString(n.taskDescription),permissions:a,tools:i(e,e.agent.id,e.agent.tools,resolveAgentRepairModel(e,e.agent,n),p),subagents:e.agent.subagents.map(t=>{const r=e.workspace.agents.get(t),n=readDeepAgentsConfig(r?.config.deepagents),o=n.permissions??s(e,r),a=scopedInput(e,r),p=requestScopedRepeatState(e,t);return pruneUndefined({name:t,description:r?.description??readString(r?.config.description)??r?.id,systemPrompt:buildSystemPrompt(e,r),model:n.model??(r?resolveAgentModel(e,r):void 0),middleware:mergeMiddleware(a,r,n.middleware,p),interruptOn:n.interruptOn,generalPurposeAgent:readBoolean(n.generalPurposeAgent),taskDescription:readString(n.taskDescription),permissions:o,responseFormat:n.responseFormat,tools:i(e,t,r?.tools??[],resolveAgentRepairModel(a,r,n),p),memory:resolveDeepAgentsMemory(e,r),skills:resolveDeepAgentsSkills(e,r)})}),memory:resolveDeepAgentsMemory(e,e.agent),skills:o})}(t,e.config,r)),a=d(t),c=function buildDeepAgentInvokeConfig(e){return pruneUndefined({recursionLimit:readNumber(readDeepAgentsConfig(e.config.deepagents).recursionLimit)??readNumber(e.config.recursionLimit)})}(t.agent);if(!0===t.request.metadata?.openaiStream&&o.streamEvents){const e=await o.streamEvents(a,{version:"v3",...c});return g(t,e,p)}const l=await o.invoke(a,c);return p(l)}}}function buildSystemPrompt(e,t){const n=t?.systemPrompt??readString(t?.config.systemPrompt);return r({workspace:e.workspace,request:e.request,agent:t},n)}function resolveDeepAgentsMemory(e,t){const r=readDeepAgentsStringArray(t?.config,"memory");if(r)return r;const n=[...readAgentMemorySources(e.workspace.root,t),...c(e.workspace).map(e=>`/memories/${e.id}.md`)],o=[...new Set(n)];return o.length>0?o:void 0}function readAgentMemorySources(e,t){return(t?.memory??[]).flatMap(t=>"string"==typeof t&&t.trim()?[backendMemorySourcePath(e,t.trim())]:isRecord(t)&&"string"==typeof t.path&&t.path.trim()?[backendMemorySourcePath(e,t.path.trim())]:[])}function backendMemorySourcePath(e,r){if(r.startsWith("/"))return r;if(t.isAbsolute(r)){const n=t.relative(e,r);return n&&!n.startsWith("..")?`/${n.split(t.sep).join("/")}`:canonicalPath(r)}const n=r.split(t.sep).join("/");return n.startsWith("/")?n:`/${n}`}function resolveDeepAgentsSkills(e,r){const n=readDeepAgentsStringArray(r?.config,"skills");if(n)return n;const o=[...new Set((r?.skills??[]).map(t=>e.workspace.skills.get(t)?.path).filter(e=>"string"==typeof e&&e.trim().length>0).map(r=>function backendSkillSourcePath(e,r){const n=t.dirname(t.dirname(r)),o=t.relative(e,n);return!o||o.startsWith("..")||t.isAbsolute(o)?""===o?"/":canonicalPath(n):`/${o.split(t.sep).join("/")}`}(e.workspace.root,r)))];return o.length>0?o:void 0}function resolveDeepAgentsBackend(e,t,r){if(t?.FilesystemBackend&&r&&0!==r.length)return()=>new t.FilesystemBackend({rootDir:e.workspace.root})}function mergeMiddleware(e,t,r,s=a(e.workspace.runtime.toolGateway)){const i=Array.isArray(r)?r:[],p=scopedInput(e,t),c=new Set;return[o(p,{observedToolIds:c,repeatState:s}),n(p,{repeatState:s}),...m(e.workspace.runtime.retry),...i,l(p)]}function requestScopedRepeatState(e,t){const r=`deepagents.repeat.${t}`,n=e.requestState?.get(r);if(n)return n;const o=a(e.workspace.runtime.toolGateway);return e.requestState&&o&&e.requestState.set(r,o),o}function scopedInput(e,t){return t?{...e,agent:t}:e}function resolveAgentModel(e,t){const r=t.modelRef?e.workspace.models.get(t.modelRef):void 0;return r?u(r):void 0}function resolveAgentRepairModel(e,t,r){const n=r.model;if(isRepairModel(n))return n;if(!t)return;const o=resolveAgentModel(e,t);return isRepairModel(o)?o:void 0}function readDeepAgentsConfig(e){return isRecord(e)?e:{}}function readDeepAgentsStringArray(e,t){const r=isRecord(e)?e:{},n=readDeepAgentsConfig(r.deepagents),o="memory"===t?["memory","memorySources"]:["skills","skillSources"];for(const e of o){const t=readStringArray(n[e]);if(t)return t}return readStringArray(r[t])}function pruneUndefined(e){return Object.fromEntries(Object.entries(e).filter(([,e])=>void 0!==e))}function readString(e){return"string"==typeof e&&e.trim()?e:void 0}function readNumber(e){return"number"==typeof e&&Number.isFinite(e)?e:void 0}function readBoolean(e){return"boolean"==typeof e?e:void 0}function readStringArray(e){return Array.isArray(e)?e.filter(e=>"string"==typeof e):void 0}function canonicalPath(t){try{return e.native(t)}catch{return t}}function isRecord(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function isRepairModel(e){return"object"==typeof e&&null!==e&&"invoke"in e&&"function"==typeof e.invoke}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{ToolMessage as t}from"@langchain/core/messages";import{afterToolInvoke as e,beforeToolInvoke as o,createToolRepeatState as r}from"@stable-harness/core";import{filesystemBuiltinToolIds as
|
|
1
|
+
import{ToolMessage as t}from"@langchain/core/messages";import{afterToolInvoke as e,beforeToolInvoke as o,createToolRepeatState as r}from"@stable-harness/core";import{filesystemBuiltinToolIds as n,isFilesystemDisabled as i,isFilesystemTool as s,validateFilesystemBuiltinCall as a}from"./builtin/permissions.js";import{repairTaskCall as l}from"./builtin/task-inventory.js";import{repairBuiltinToolRequest as u}from"./builtin-call-repair.js";import{stringifyDeepAgentResult as c,toolControlProjection as d}from"./gateway-tools.js";import{isSuccessfulEvidenceOutput as p,observedToolEvidence as m,recordObservedToolEvidence as g}from"./gateway/tool-evidence.js";import{validateSkillFileBuiltinCall as f}from"./skill-file-policy.js";import{filterRepeatLimitedTools as v}from"./tool-repeat-visibility.js";import{traceProjectionForBuiltinTool as b}from"./trace-projection.js";const T=new Set(["write_todos","read_todos","task","execute",...n]);export function createBuiltinToolPolicyMiddleware(t,e={}){return{name:"StableHarnessBuiltinToolPolicy",async wrapModelCall(o,r){const n=Array.isArray(o.tools)?v(o.tools.filter(e=>!function hasHiddenBuiltins(t){return i(t)||!isTaskVisible(t)}(t)||isModelVisibleBuiltin(t,e.name)),e.repeatState):o.tools,s=function normalizeToolChoice(t,e,o){return"required"===e?o&&o.length>0?e:"auto":function isForcedHiddenTool(t,e){return"string"==typeof e?.function?.name&&!isModelVisibleBuiltin(t,e.function.name)}(t,e)?"auto":e}(t,o.toolChoice,n);return r({...o,tools:n,toolChoice:s})}}}export function createObserverMiddleware(n,i={}){const s=i.repeatState??r(n.workspace.runtime.toolGateway);return{name:"StableHarnessObserver",async wrapToolCall(r,d){const g=r.toolCall?.name;if(!g||!T.has(g))return d(r);const v=await u({toolId:g,request:r,workspaceRoot:n.workspace.root});emitToolEvent(n,g,"agent.tool.start",v.toolCall?.args);const b="task"===g?await l(n,v):{request:v},h=b.request,y=b.blocked;if(y)return emitToolEvent(n,g,"agent.tool.result",h.toolCall?.args,{output:y.content}),y;const k=a(n,g,h);if(k)return emitToolEvent(n,g,"agent.tool.result",h.toolCall?.args,{output:k.content}),k;const C=f(n,g,h);if(C)return emitToolEvent(n,g,"agent.tool.result",h.toolCall?.args,{output:C.content}),C;try{const a=s?o(g,h.toolCall?.args,s):void 0;if(a)return emitToolEvent(n,g,"agent.tool.result",h.toolCall?.args,{output:a.eventOutput}),builtinToolMessage(r,g,function modelOutputForRepeatedBuiltin(t,e){return"task"!==t?e:function readPreviousOutput(t){try{const e=JSON.parse(t);if(!isRecord(e)||"repeated_tool_call_limit"!==e.status||"string"!=typeof e.previousOutput)return;const o=e.previousOutput.trim();return o.length>0?o:void 0}catch{return}}(e)??e}(g,a.modelOutput));const l=await d(h),u=function observedToolOutput(t,e,o){return"write_todos"===t?JSON.stringify({status:"recorded",args:e.toolCall?.args}):c(o)}(g,h,l),m=s?e({toolId:g,args:h.toolCall?.args,output:u,successful:!(l instanceof t&&"error"===l.status)&&p(u),state:s}):{};return emitToolEvent(n,g,"agent.tool.result",h.toolCall?.args,{output:m.eventOutput??u}),i.observedToolIds?.add(g),void 0===m.modelOutput?l:builtinToolMessage(r,g,m.modelOutput)}catch(e){const o=function recoverableBuiltinToolError(e,o,r,n){const i=formatError(n);if("task"===o&&/repeat limit reached for tool/iu.test(i)){const o=function formatObservedEvidence(t){const e=m(t);if(0===e.length)return"";const o=e.map(t=>[`Agent: ${t.agentId}`,`Tool: ${t.toolId}`,t.output].join("\n")).join("\n\n---\n\n");return o.length>12e3?`${o.slice(0,12e3)}\n[truncated]`:o}(e);return new t({tool_call_id:r.toolCall?.id??"stable-harness-task-repeat-limit",name:"task",content:JSON.stringify({status:"delegated_task_repeat_limit",finalizationRequired:!0,instruction:"The delegated agent reached a configured tool repeat limit. Stop delegating this evidence need and do not send a synthesis task to another subagent for the same need. Finalize only from observedEvidence and other evidence that is already visible in this run. If the visible evidence is insufficient for a requested claim, report an explicit blocker or evidence gap instead of estimating, inventing, or using generic knowledge.",...o?{observedEvidence:o}:{},error:previewError(i)})})}if(/Received tool input did not match expected schema|Invalid input:/iu.test(i))return new t({tool_call_id:r.toolCall?.id??`stable-harness-${o}-argument-error`,name:o,status:"error",content:JSON.stringify({status:"tool_argument_error",toolId:o,instruction:"The upstream builtin tool rejected these arguments. Fix the tool arguments according to the tool schema, or choose a more appropriate available tool.",error:previewError(i)})})}(n,g,r,e);if(o)return emitToolEvent(n,g,"agent.tool.result",v.toolCall?.args,{output:o.content}),o;throw emitToolEvent(n,g,"agent.tool.result",v.toolCall?.args,{error:formatError(e)}),e}}}}function builtinToolMessage(e,o,r){return new t({tool_call_id:e.toolCall?.id??`stable-harness-${o}-repeat-guard`,name:o,content:r})}function emitToolEvent(t,e,o,r,n={}){"string"==typeof n.output&&g(t,t.agent.id,e,n.output),t.emit({type:"runtime.adapter.event",requestId:t.requestId,sessionId:t.sessionId,agentId:t.agent.id,event:{adapter:"deepagents",eventGroup:"tool_execution",eventType:"agent.tool.start"===o?"deepagents.tool_execution.start":"deepagents.tool_execution.result",phase:o,toolId:e,..."agent.tool.start"===o?{args:r}:{},...n,..."string"==typeof n.output?d(n.output):{},...b(e,o,r)}})}function isTaskVisible(t){const e=function readConfigRecord(t,e){const o=isRecord(t)?t:{};return isRecord(o[e])?o[e]:void 0}(t.agent.config,"builtinTools")?.modelExposed;return!1!==e&&(!Array.isArray(e)||e.includes("task"))}function isModelVisibleBuiltin(t,e){return(!i(t)||!s(e))&&("task"!==e||isTaskVisible(t))}function isRecord(t){return"object"==typeof t&&null!==t&&!Array.isArray(t)}function formatError(t){return t instanceof Error?t.message:String(t)}function previewError(t){const e=t.replace(/\s+/gu," ").trim();return e.length>800?`${e.slice(0,797)}...`:e}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{ToolMessage as t}from"@langchain/core/messages";import{tool as e}from"@langchain/core/tools";import{afterToolInvoke as o,beforeToolInvoke as r,createToolRepeatState as n,missingRequiredPlanContent as s,missingToolDependencyContent as a,toolInvocationEvents as i}from"@stable-harness/core";import{isSuccessfulEvidenceOutput as u,observedToolEvidence as l,recordObservedToolEvidence as c}from"./gateway/tool-evidence.js";import{emitStructuredToolFailure as d}from"./gateway/tool-failure-events.js";export function buildGatewayTools(l,c,p,f,g=n(l.workspace.runtime.toolGateway)){return l.toolGateway?p.flatMap(n=>{const p=l.toolGateway?.get(n);if(!p)return[];const m=l.workspace.tools.get(n),y=m?.schema??p.schema;return[e(async e=>async function invokeGuardedGatewayTool(e){emitToolResult(e.input,e.agentId,e.toolId,void 0);const n=i({request:e.input.request,getEvents:e.input.getEvents}),l=s({agent:e.input.agent,events:n,toolId:e.toolId});if(l)return emitToolResult(e.input,e.agentId,e.toolId,l),l;const c=a({agent:e.input.agent,events:n,toolId:e.toolId});if(c)return emitToolResult(e.input,e.agentId,e.toolId,c),c;const p=e.repeatState?r(e.toolId,e.args,e.repeatState):void 0;if(p)return emitToolResult(e.input,e.agentId,e.toolId,p.eventOutput),p.modelOutput;const f=await async function invokeGatewayTool(e,o,r,n,s){try{if(e.toolFailureTracker?.isCircuitOpen(r))throw new Error(`Tool circuit is open: ${r}`);const t=await e.toolGateway.invoke({toolId:r,args:n,repairModel:s,context:{workspaceRoot:e.workspace.root,requestId:e.requestId,sessionId:e.sessionId,agentId:o,requestInput:e.request.input,observedEvidence:formatObservedEvidenceForToolContext(e),approvalIds:readApprovalIds(e.request.metadata)}});return e.toolFailureTracker?.recordSuccess(r),t}catch(n){if(d(e,o,r,n),function isToolArgumentValidationError(t){return t instanceof Error&&"ToolArgumentValidationError"===t.name&&"string"==typeof t.toolId&&Array.isArray(t.issues)}(n))return new t({tool_call_id:`stable-harness-${r}-argument-guard`,name:r,status:"error",content:formatToolArgumentError(n)});if(e.workspace.runtime.retry?.tools?.enabled)throw n;return new t({tool_call_id:`stable-harness-${r}-execution-error`,name:r,status:"error",content:JSON.stringify({error:"tool_execution_failed",toolId:r,message:formatError(n),retry:"Use the error as evidence, adjust the tool arguments if possible, or return a final answer with the blocker."})})}}(e.input,e.agentId,e.toolId,e.args,e.repairModel),g=f instanceof t?String(f.content):stringifyDeepAgentResult(f.output),m=e.repeatState?o({toolId:e.toolId,args:e.args,output:g,successful:!(f instanceof t&&"error"===f.status)&&u(g),state:e.repeatState}):{};return emitToolResult(e.input,e.agentId,e.toolId,m.eventOutput??g),void 0!==m.modelOutput?m.modelOutput:f instanceof t?f:g}({input:l,agentId:c,toolId:n,args:e,repairModel:f,repeatState:g}),{name:n,description:buildToolDescription(m?.description??p.description??n,y,l.workspace.runtime.toolGateway,n),schema:{type:"object",additionalProperties:!0}})]}):[]}function emitToolResult(t,e,o,r){void 0!==r&&c(t,e,o,r),t.emit({type:"runtime.adapter.event",requestId:t.requestId,sessionId:t.sessionId,agentId:e,event:void 0===r?{adapter:"deepagents",phase:"agent.tool.start",toolId:o}:{adapter:"deepagents",phase:"agent.tool.result",toolId:o,output:previewToolOutput(r),evidenceOutput:r,...toolControlProjection(r)}})}export function stringifyDeepAgentResult(e){if(e instanceof t)return function stringifyToolMessageContent(t){return"string"==typeof t?t:JSON.stringify(t)}(e.content);if("string"==typeof e)return e;if(isRecord(e)){const t=e.structuredResponse??e.structured_response;if(void 0!==t)return"string"==typeof t?t:JSON.stringify(t);const o=(Array.isArray(e.messages)?e.messages:[]).at(-1);if(isRecord(o)&&"string"==typeof o.content)return o.content;const r=(isRecord(e.update)&&Array.isArray(e.update.messages)?e.update.messages:[]).at(-1);if(isRecord(r)&&isRecord(r.kwargs)&&"string"==typeof r.kwargs.content)return r.kwargs.content;if(isRecord(r)&&"string"==typeof r.content)return r.content}return JSON.stringify(e)}function buildToolDescription(t,e,o,r){const n=function toolRepeatPolicyDescription(t,e){const o=function repeatGuardConfig(t){return isRecord(t)&&isRecord(t.repeatGuard)?t.repeatGuard:{}}(t),r=function readPositiveIntegerMap(t){return isRecord(t)?new Map(Object.entries(t).map(([t,e])=>[t,readPositiveInteger(e)]).filter(t=>void 0!==t[1])):new Map}(o.maxSuccessfulCallsByTool).get(e)??readPositiveInteger(o.maxSuccessfulCallsPerTool);return void 0===r?"":`Stable runtime repeat policy: call this tool at most ${r} successful time(s) for this request. If more detail is needed, include the dimensions in the first call and synthesize after the result returns.`}(o,r),s=n?`${t}\n\n${n}`:t;return e?`${s}\n\nStable tool input schema:\n${previewToolOutput(JSON.stringify(e))}`:s}function readPositiveInteger(t){return"number"==typeof t&&Number.isInteger(t)&&t>0?t:void 0}function previewToolOutput(t){const e=t.replace(/\s+/gu," ").trim();return e.length>500?`${e.slice(0,497)}...`:e}export function toolControlProjection(t){const e=function parseJsonRecord(t){try{const e=JSON.parse(t);return isRecord(e)?e:void 0}catch{return}}(t);if("string"==typeof e?.status)return{controlStatus:e.status};const o=function readTextStatus(t){return String(t).match(/^Status:\s*([A-Za-z0-9_-]+)/imu)?.[1]}(t);return o?{controlStatus:o}:"string"==typeof e?.error?{controlStatus:e.error}:t.startsWith("Task delegation target is not in the workspace inventory")?{controlStatus:"task_inventory_blocked"}:{}}function readApprovalIds(t){const e=t?.approvalIds??t?.approvalId;return"string"==typeof e&&e.trim()?[e.trim()]:Array.isArray(e)?e.filter(t=>"string"==typeof t&&t.trim().length>0):void 0}function formatObservedEvidenceForToolContext(t){const e=l(t).map(t=>`Tool: ${t.toolId}\n${t.output}`).join("\n\n---\n\n");return e.length>12e3?`${e.slice(0,12e3)}\n[truncated]`:e}function formatToolArgumentError(t){return JSON.stringify({error:"tool_argument_validation_failed",toolId:t.toolId,issues:t.issues,retry:"Call the same tool again with arguments that satisfy the reported schema and semantic issues."})}function isRecord(t){return"object"==typeof t&&null!==t&&!Array.isArray(t)}function formatError(t){return t instanceof Error?t.message:String(t)}
|
|
1
|
+
import{ToolMessage as t}from"@langchain/core/messages";import{tool as e}from"@langchain/core/tools";import{afterToolInvoke as o,beforeToolInvoke as r,createToolRepeatState as n,missingRequiredPlanContent as s,missingToolDependencyContent as a,toolInvocationEvents as i}from"@stable-harness/core";import{isSuccessfulEvidenceOutput as u,observedToolEvidence as l,recordObservedToolEvidence as c}from"./gateway/tool-evidence.js";import{emitStructuredToolFailure as d}from"./gateway/tool-failure-events.js";export function buildGatewayTools(l,c,p,f,g=n(l.workspace.runtime.toolGateway)){return l.toolGateway?p.flatMap(n=>{const p=l.toolGateway?.get(n);if(!p)return[];const m=l.workspace.tools.get(n),y=m?.schema??p.schema;return[e(async e=>async function invokeGuardedGatewayTool(e){emitToolResult(e.input,e.agentId,e.toolId,void 0);const n=i({request:e.input.request,getEvents:e.input.getEvents}),l=s({agent:e.input.agent,events:n,toolId:e.toolId});if(l)return emitToolResult(e.input,e.agentId,e.toolId,l),l;const c=a({agent:e.input.agent,events:n,toolId:e.toolId});if(c)return emitToolResult(e.input,e.agentId,e.toolId,c),c;const p=e.repeatState?r(e.toolId,e.args,e.repeatState):void 0;if(p)return emitToolResult(e.input,e.agentId,e.toolId,p.eventOutput),p.modelOutput;const f=await async function invokeGatewayTool(e,o,r,n,s){try{if(e.toolFailureTracker?.isCircuitOpen(r))throw new Error(`Tool circuit is open: ${r}`);const t=await e.toolGateway.invoke({toolId:r,args:n,repairModel:s,context:{workspaceRoot:e.workspace.root,requestId:e.requestId,sessionId:e.sessionId,agentId:o,requestInput:e.request.input,observedEvidence:formatObservedEvidenceForToolContext(e),approvalIds:readApprovalIds(e.request.metadata)}});return e.toolFailureTracker?.recordSuccess(r),t}catch(n){if(d(e,o,r,n),function isToolArgumentValidationError(t){return t instanceof Error&&"ToolArgumentValidationError"===t.name&&"string"==typeof t.toolId&&Array.isArray(t.issues)}(n))return new t({tool_call_id:`stable-harness-${r}-argument-guard`,name:r,status:"error",content:formatToolArgumentError(n)});if(e.workspace.runtime.retry?.tools?.enabled)throw n;return new t({tool_call_id:`stable-harness-${r}-execution-error`,name:r,status:"error",content:JSON.stringify({error:"tool_execution_failed",toolId:r,message:formatError(n),retry:"Use the error as evidence, adjust the tool arguments if possible, or return a final answer with the blocker."})})}}(e.input,e.agentId,e.toolId,e.args,e.repairModel),g=f instanceof t?String(f.content):stringifyDeepAgentResult(f.output),m=e.repeatState?o({toolId:e.toolId,args:e.args,output:g,successful:!(f instanceof t&&"error"===f.status)&&u(g),state:e.repeatState}):{};return emitToolResult(e.input,e.agentId,e.toolId,m.eventOutput??g),void 0!==m.modelOutput?m.modelOutput:f instanceof t?f:g}({input:l,agentId:c,toolId:n,args:e,repairModel:f,repeatState:g}),{name:n,description:buildToolDescription(m?.description??p.description??n,y,l.workspace.runtime.toolGateway,n),schema:{type:"object",additionalProperties:!0}})]}):[]}function emitToolResult(t,e,o,r){void 0!==r&&c(t,e,o,r),t.emit({type:"runtime.adapter.event",requestId:t.requestId,sessionId:t.sessionId,agentId:e,event:void 0===r?{adapter:"deepagents",eventGroup:"tool_execution",eventType:"deepagents.tool_execution.start",phase:"agent.tool.start",toolId:o}:{adapter:"deepagents",eventGroup:"tool_execution",eventType:"deepagents.tool_execution.result",phase:"agent.tool.result",toolId:o,output:previewToolOutput(r),evidenceOutput:r,...toolControlProjection(r)}})}export function stringifyDeepAgentResult(e){if(e instanceof t)return function stringifyToolMessageContent(t){return"string"==typeof t?t:JSON.stringify(t)}(e.content);if("string"==typeof e)return e;if(isRecord(e)){const t=e.structuredResponse??e.structured_response;if(void 0!==t)return"string"==typeof t?t:JSON.stringify(t);const o=(Array.isArray(e.messages)?e.messages:[]).at(-1);if(isRecord(o)&&"string"==typeof o.content)return o.content;const r=(isRecord(e.update)&&Array.isArray(e.update.messages)?e.update.messages:[]).at(-1);if(isRecord(r)&&isRecord(r.kwargs)&&"string"==typeof r.kwargs.content)return r.kwargs.content;if(isRecord(r)&&"string"==typeof r.content)return r.content}return JSON.stringify(e)}function buildToolDescription(t,e,o,r){const n=function toolRepeatPolicyDescription(t,e){const o=function repeatGuardConfig(t){return isRecord(t)&&isRecord(t.repeatGuard)?t.repeatGuard:{}}(t),r=function readPositiveIntegerMap(t){return isRecord(t)?new Map(Object.entries(t).map(([t,e])=>[t,readPositiveInteger(e)]).filter(t=>void 0!==t[1])):new Map}(o.maxSuccessfulCallsByTool).get(e)??readPositiveInteger(o.maxSuccessfulCallsPerTool);return void 0===r?"":`Stable runtime repeat policy: call this tool at most ${r} successful time(s) for this request. If more detail is needed, include the dimensions in the first call and synthesize after the result returns.`}(o,r),s=n?`${t}\n\n${n}`:t;return e?`${s}\n\nStable tool input schema:\n${previewToolOutput(JSON.stringify(e))}`:s}function readPositiveInteger(t){return"number"==typeof t&&Number.isInteger(t)&&t>0?t:void 0}function previewToolOutput(t){const e=t.replace(/\s+/gu," ").trim();return e.length>500?`${e.slice(0,497)}...`:e}export function toolControlProjection(t){const e=function parseJsonRecord(t){try{const e=JSON.parse(t);return isRecord(e)?e:void 0}catch{return}}(t);if("string"==typeof e?.status)return{controlStatus:e.status};const o=function readTextStatus(t){return String(t).match(/^Status:\s*([A-Za-z0-9_-]+)/imu)?.[1]}(t);return o?{controlStatus:o}:"string"==typeof e?.error?{controlStatus:e.error}:t.startsWith("Task delegation target is not in the workspace inventory")?{controlStatus:"task_inventory_blocked"}:{}}function readApprovalIds(t){const e=t?.approvalIds??t?.approvalId;return"string"==typeof e&&e.trim()?[e.trim()]:Array.isArray(e)?e.filter(t=>"string"==typeof t&&t.trim().length>0):void 0}function formatObservedEvidenceForToolContext(t){const e=l(t).map(t=>`Tool: ${t.toolId}\n${t.output}`).join("\n\n---\n\n");return e.length>12e3?`${e.slice(0,12e3)}\n[truncated]`:e}function formatToolArgumentError(t){return JSON.stringify({error:"tool_argument_validation_failed",toolId:t.toolId,issues:t.issues,retry:"Call the same tool again with arguments that satisfy the reported schema and semantic issues."})}function isRecord(t){return"object"==typeof t&&null!==t&&!Array.isArray(t)}function formatError(t){return t instanceof Error?t.message:String(t)}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
import type { RuntimeAdapter } from "@stable-harness/core";
|
|
2
|
-
export declare function streamDeepAgentResult(input: Parameters<RuntimeAdapter["run"]>[0],
|
|
2
|
+
export declare function streamDeepAgentResult(input: Parameters<RuntimeAdapter["run"]>[0], run: unknown, stringify: (value: unknown) => string): Promise<string>;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
export async function streamDeepAgentResult(t,e,
|
|
1
|
+
export async function streamDeepAgentResult(e,t,a){const s=function readRunProjection(e){const t=readRecord(e);if(!t)return;const a={messages:readAsyncIterable(t.messages),toolCalls:readAsyncIterable(t.toolCalls??t.tool_calls),subagents:readAsyncIterable(t.subagents),values:readAsyncIterable(t.values),extensions:readExtensions(t.extensions),output:t.output};return a.messages||a.toolCalls||a.subagents||a.values||a.extensions||a.output?a:void 0}(t);if(!s)throw new Error("DeepAgents streamEvents(version: v3) did not expose v3 projections.");let n,o="";return await Promise.all([consumeMessages(e,s.messages,e.agent.id,e=>{o+=e}),consumeToolCalls(e,s.toolCalls,e.agent.id),consumeSubagents(e,s.subagents),consumeValues(e,s.values,e.agent.id),consumeExtensions(e,s.extensions,e.agent.id),readFinalOutput(s.output,a).then(e=>{n=e})]),n??o}async function consumeMessages(e,t,a,s){if(t)for await(const n of t)await consumeMessage(e,n,a,s)}async function consumeMessage(e,t,a,s){const n=readRecord(t);n?await Promise.all([consumeTextProjection(e,n.text??n.content,a,s),consumeReasoning(e,n.reasoning,a),consumeModelToolCalls(e,readAsyncIterable(n.toolCalls??n.tool_calls),a),emitMessageOutput(e,n,a),emitMessageUsage(e,n,a)]):await emitTextValue(e,t,a,s)}async function consumeTextProjection(e,t,a,s){if(isAsyncIterable(t))for await(const n of t)await emitTextValue(e,n,a,s);else await emitTextValue(e,await resolveValue(t),a,s)}async function emitTextValue(e,t,a,s){const n=readContentText(await resolveValue(t));n&&(emitAdapterEvent(e,"message","delta",{phase:"agent.message.delta",sourceAgentId:a,text:n}),a===e.agent.id&&(s?.(n),emitAdapterEvent(e,"message","coordinator_delta",{phase:"agent.output.delta",text:n})))}async function consumeReasoning(e,t,a){if(isAsyncIterable(t))for await(const s of t)emitReasoning(e,s,a);else emitReasoning(e,await resolveValue(t),a)}function emitReasoning(e,t,a){const s=readContentText(t);s&&emitAdapterEvent(e,"reasoning","delta",{phase:"agent.reasoning.delta",sourceAgentId:a,text:s})}async function consumeModelToolCalls(e,t,a){if(t)for await(const s of t){const t=readRecord(s)??{};emitAdapterEvent(e,"tool_call","delta",{phase:"agent.tool.call.delta",sourceAgentId:a,toolId:readString(t.name)??readString(t.toolId),toolCallId:readString(t.callId)??readString(t.id),args:await resolveValue(t.input??t.args),delta:await resolveValue(t.delta??t.argsDelta??t.arguments)})}}async function consumeToolCalls(e,t,a){if(!t)return;let s=0;for await(const n of t){s+=1;const t=readRecord(n)??{},o=readString(t.name)??readString(t.toolId)??`tool-${s}`,r=readString(t.callId)??readString(t.id)??`${a}:${o}:${s}`;emitAdapterEvent(e,"tool_execution","start",{phase:"agent.tool.start",sourceAgentId:a,toolId:o,toolCallId:r,args:await resolveValue(t.input??t.args),upstream:passthroughRecord(t)}),await consumeToolOutputDeltas(e,t,a,o,r),await emitToolResult(e,t,a,o,r)}}async function consumeToolOutputDeltas(e,t,a,s,n){const o=readAsyncIterable(t.outputDeltas??t.output_delta??t.outputChunks);if(o)for await(const t of o)emitAdapterEvent(e,"tool_execution","output_delta",{phase:"agent.tool.output.delta",sourceAgentId:a,toolId:s,toolCallId:n,delta:t})}async function consumeSubagents(e,t){if(!t)return;const a=[];let s=0;for await(const n of t)s+=1,a.push(consumeSubagent(e,n,s));await Promise.all(a)}async function consumeSubagent(e,t,a){const s=readRecord(t)??{},n=readString(s.name)??`subagent-${a}`,o=readString(s.callId)??readString(s.id)??`${n}:${a}`;emitAdapterEvent(e,"subagent","start",{phase:"agent.subagent.start",subagentId:n,callId:o,taskInput:await resolveValue(s.taskInput),namespace:s.namespace,upstream:passthroughRecord(s)});try{await Promise.all([consumeMessages(e,readAsyncIterable(s.messages),n),consumeToolCalls(e,readAsyncIterable(s.toolCalls??s.tool_calls),n),consumeSubagents(e,readAsyncIterable(s.subagents)),consumeValues(e,readAsyncIterable(s.values),n),consumeExtensions(e,readExtensions(s.extensions),n),resolveValue(s.output)]),emitAdapterEvent(e,"subagent","result",{phase:"agent.subagent.result",subagentId:n,callId:o,status:"completed"})}catch(t){emitAdapterEvent(e,"subagent","result",{phase:"agent.subagent.result",subagentId:n,callId:o,status:"failed",error:formatError(t)})}}async function consumeValues(e,t,a){if(t)for await(const s of t)emitAdapterEvent(e,"state","snapshot",{phase:"agent.state.snapshot",sourceAgentId:a,snapshot:s})}async function consumeExtensions(e,t,a){t&&await Promise.all(Object.entries(t).map(async([t,s])=>{for await(const n of s)emitAdapterEvent(e,"extension","event",{phase:"agent.extension",sourceAgentId:a,name:t,value:n})}))}async function emitToolResult(e,t,a,s,n){try{emitAdapterEvent(e,"tool_execution","result",{phase:"agent.tool.result",sourceAgentId:a,toolId:s,toolCallId:n,status:await resolveValue(t.status),output:await resolveValue(t.output),error:await resolveValue(t.error),upstream:passthroughRecord(t)})}catch(t){emitAdapterEvent(e,"tool_execution","result",{phase:"agent.tool.result",sourceAgentId:a,toolId:s,toolCallId:n,status:"failed",error:formatError(t)})}}async function readFinalOutput(e,t){const a=await resolveValue(e);if(void 0!==a)return t(a)||void 0}async function emitMessageOutput(e,t,a){"output"in t&&emitAdapterEvent(e,"message","output",{phase:"agent.message.output",sourceAgentId:a,output:await resolveValue(t.output),upstream:passthroughRecord(t)})}async function emitMessageUsage(e,t,a){if(!("usage"in t))return;const s=await resolveValue(t.usage);s&&emitAdapterEvent(e,"message","usage",{phase:"agent.message.usage",sourceAgentId:a,usage:s})}function readContentText(e){return"string"==typeof e?e||void 0:Array.isArray(e)&&e.map(e=>readString(readRecord(e)?.text)??("string"==typeof e?e:"")).join("")||void 0}function emitAdapterEvent(e,t,a,s){e.emit({type:"runtime.adapter.event",requestId:e.requestId,sessionId:e.sessionId,agentId:e.agent.id,event:{adapter:"deepagents",eventGroup:t,eventType:`deepagents.${t}.${a}`,...s}})}async function resolveValue(e){return await e}function readAsyncIterable(e){return isAsyncIterable(e)?e:void 0}function readExtensions(e){const t=readRecord(e);if(!t)return;const a=Object.entries(t).filter(e=>isAsyncIterable(e[1]));return a.length>0?Object.fromEntries(a):void 0}function passthroughRecord(e){return Object.fromEntries(Object.entries(e).filter(([,e])=>!isAsyncIterable(e)&&!function isPromiseLike(e){return isRecord(e)&&"function"==typeof e.then}(e)))}function readRecord(e){return isRecord(e)?e:void 0}function readString(e){return"string"==typeof e&&e.trim()?e:void 0}function formatError(e){return e instanceof Error?e.message:String(e)}function isAsyncIterable(e){return isRecord(e)&&"function"==typeof e[Symbol.asyncIterator]}function isRecord(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import type { RuntimeAdapterContext, RuntimeAdapterResult } from "@stable-harness/core";
|
|
2
2
|
export type DeepAgentFactory = (params?: Record<string, unknown>) => {
|
|
3
3
|
invoke(input: Record<string, unknown>, options?: Record<string, unknown>): Promise<unknown>;
|
|
4
|
-
streamEvents?(input: Record<string, unknown>, options?: Record<string, unknown>):
|
|
4
|
+
streamEvents?(input: Record<string, unknown>, options?: Record<string, unknown>): unknown;
|
|
5
5
|
};
|
|
6
6
|
export type DeepAgentsModule = {
|
|
7
7
|
createDeepAgent?: unknown;
|
|
@@ -11,12 +11,12 @@
|
|
|
11
11
|
"types": "dist/src/index.d.ts",
|
|
12
12
|
"peerDependencies": {
|
|
13
13
|
"@easynet/better-call": "^0.1.60",
|
|
14
|
-
"@langchain/core": "^1.1.
|
|
14
|
+
"@langchain/core": "^1.1.46",
|
|
15
15
|
"@langchain/ollama": "^1.2.7",
|
|
16
16
|
"@langchain/openai": "^1.4.5",
|
|
17
17
|
"@stable-harness/core": "0.0.1",
|
|
18
|
-
"deepagents": "^1.
|
|
19
|
-
"langchain": "^1.
|
|
18
|
+
"deepagents": "^1.10.1",
|
|
19
|
+
"langchain": "^1.4.0"
|
|
20
20
|
},
|
|
21
21
|
"peerDependenciesMeta": {
|
|
22
22
|
"deepagents": {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
export function assertExecutionContract(e){(function contractDisabled(e){const t=isRecord(e?.executionContract)?e.executionContract:void 0;return!1===t?.enabled})(e.metadata)||(function assertRequiredPlan(e){const t=readExecutionContract(e.agent);if(!t.requiresPlan)return;const n=readStringArray(t.planEvidenceTools);if(0===n.length)throw e.emit({type:"runtime.execution.contract.failed",requestId:e.requestId,sessionId:e.sessionId,agentId:e.agent.id,reason:"invalid_plan_contract"}),new Error("Execution contract requires plan evidence tools when requiresPlan is enabled");const r=e.store.getRun(e.requestId),o=new Set((r?.events??[]).flatMap(readEvidenceToolId));if(!n.some(e=>o.has(e)))throw e.emit({type:"runtime.execution.contract.failed",requestId:e.requestId,sessionId:e.sessionId,agentId:e.agent.id,reason:"missing_plan",missingEvidenceTools:n}),new Error(`Execution contract requires a planning checkpoint from one of: ${n.join(", ")}`)}(e),function assertRequiredEvidenceTools(e){const t=function readRequiredEvidenceTools(e){return readStringArray(readExecutionContract(e).requiredEvidenceTools)}(e.agent);if(0===t.length)return;const n=e.store.getRun(e.requestId),r=new Set((n?.events??[]).flatMap(readEvidenceToolId)),o=t.filter(e=>!r.has(e));if(0!==o.length)throw e.emit({type:"runtime.execution.contract.failed",requestId:e.requestId,sessionId:e.sessionId,agentId:e.agent.id,reason:"missing_required_evidence",missingEvidenceTools:o}),new Error(`Execution contract missing required evidence tools: ${o.join(", ")}`)}(e),function assertToolDependencies(e){const t=readExecutionContract(e.agent),n=isRecord(t.toolDependencies)?t.toolDependencies:{},r=Object.entries(n).map(([e,t])=>[e,readStringArray(t)]).filter(e=>e[1].length>0);if(0===r.length)return;const o=e.store.getRun(e.requestId),i=new Set((o?.events??[]).flatMap(readEvidenceToolId)),s=r.filter(([e])=>i.has(e)).flatMap(([e,t])=>t.filter(e=>!i.has(e)).map(t=>`${e} requires ${t}`));if(0!==s.length)throw e.emit({type:"runtime.execution.contract.failed",requestId:e.requestId,sessionId:e.sessionId,agentId:e.agent.id,reason:"missing_tool_dependency",missingEvidenceTools:s}),new Error(`Execution contract missing required tool dependencies: ${s.join(", ")}`)}(e))}function readExecutionContract(e){return isRecord(e.config.executionContract)?e.config.executionContract:{}}function readEvidenceToolId(e){return"runtime.tool.direct.completed"===e.type?[e.toolId]:"runtime.adapter.event"===e.type&&isRecord(e.event)
|
|
1
|
+
export function assertExecutionContract(e){(function contractDisabled(e){const t=isRecord(e?.executionContract)?e.executionContract:void 0;return!1===t?.enabled})(e.metadata)||(function assertRequiredPlan(e){const t=readExecutionContract(e.agent);if(!t.requiresPlan)return;const n=readStringArray(t.planEvidenceTools);if(0===n.length)throw e.emit({type:"runtime.execution.contract.failed",requestId:e.requestId,sessionId:e.sessionId,agentId:e.agent.id,reason:"invalid_plan_contract"}),new Error("Execution contract requires plan evidence tools when requiresPlan is enabled");const r=e.store.getRun(e.requestId),o=new Set((r?.events??[]).flatMap(readEvidenceToolId));if(!n.some(e=>o.has(e)))throw e.emit({type:"runtime.execution.contract.failed",requestId:e.requestId,sessionId:e.sessionId,agentId:e.agent.id,reason:"missing_plan",missingEvidenceTools:n}),new Error(`Execution contract requires a planning checkpoint from one of: ${n.join(", ")}`)}(e),function assertRequiredEvidenceTools(e){const t=function readRequiredEvidenceTools(e){return readStringArray(readExecutionContract(e).requiredEvidenceTools)}(e.agent);if(0===t.length)return;const n=e.store.getRun(e.requestId),r=new Set((n?.events??[]).flatMap(readEvidenceToolId)),o=t.filter(e=>!r.has(e));if(0!==o.length)throw e.emit({type:"runtime.execution.contract.failed",requestId:e.requestId,sessionId:e.sessionId,agentId:e.agent.id,reason:"missing_required_evidence",missingEvidenceTools:o}),new Error(`Execution contract missing required evidence tools: ${o.join(", ")}`)}(e),function assertToolDependencies(e){const t=readExecutionContract(e.agent),n=isRecord(t.toolDependencies)?t.toolDependencies:{},r=Object.entries(n).map(([e,t])=>[e,readStringArray(t)]).filter(e=>e[1].length>0);if(0===r.length)return;const o=e.store.getRun(e.requestId),i=new Set((o?.events??[]).flatMap(readEvidenceToolId)),s=r.filter(([e])=>i.has(e)).flatMap(([e,t])=>t.filter(e=>!i.has(e)).map(t=>`${e} requires ${t}`));if(0!==s.length)throw e.emit({type:"runtime.execution.contract.failed",requestId:e.requestId,sessionId:e.sessionId,agentId:e.agent.id,reason:"missing_tool_dependency",missingEvidenceTools:s}),new Error(`Execution contract missing required tool dependencies: ${s.join(", ")}`)}(e))}function readExecutionContract(e){return isRecord(e.config.executionContract)?e.config.executionContract:{}}function readEvidenceToolId(e){return"runtime.tool.direct.completed"===e.type?[e.toolId]:"runtime.adapter.event"===e.type&&isRecord(e.event)&&function isToolResultEvent(e){return"deepagents.tool_execution.result"===e.eventType||"agent.tool.result"===e.phase}(e.event)&&"string"==typeof e.event.toolId&&function isSuccessfulEvidenceEvent(e){const t=function readString(e){return"string"==typeof e&&e.length>0?e:void 0}(e.controlStatus)??function readOutputStatus(e){if("string"!=typeof e)return;const t=function parseJsonRecord(e){try{const t=JSON.parse(e);return isRecord(t)?t:void 0}catch{return}}(e);return"string"==typeof t?.status?t.status:e.match(/^Status:\s*([A-Za-z0-9_-]+)/imu)?.[1]}(e.output);return!t||/^(?:completed|success|ok|recorded)$/iu.test(t)}(e.event)?[e.event.toolId]:[]}function isRecord(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function readStringArray(e){return Array.isArray(e)?e.filter(e=>"string"==typeof e&&e.length>0):[]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
export function hasPlanningEvidence(t){return t.some(t=>{const e=readAdapterEvent(t);return!!e&&("plan"===e.traceType||String(e.traceLabel??"").startsWith("plan.")||"write_todos"===e.toolId&&String(e.phase??"").startsWith("agent.tool."))})}export function successfulEvidenceToolIds(t){const e=t.flatMap(t=>{if("runtime.tool.direct.completed"===t.type)return[t.toolId];const e=readAdapterEvent(t);return e&&"
|
|
1
|
+
export function hasPlanningEvidence(t){return t.some(t=>{const e=readAdapterEvent(t);return!!e&&("plan"===e.traceType||String(e.traceLabel??"").startsWith("plan.")||"write_todos"===e.toolId&&String(e.phase??"").startsWith("agent.tool."))})}export function successfulEvidenceToolIds(t){const e=t.flatMap(t=>{if("runtime.tool.direct.completed"===t.type)return[t.toolId];const e=readAdapterEvent(t);return isToolResultEvent(e)&&"string"==typeof e.toolId&&isSuccessfulEvidenceEvent(e)?[e.toolId]:[]});return[...new Set(e)]}export function successfulEvidenceOutputs(t){return successfulEvidenceItems(t).map(t=>t.output)}export function successfulEvidenceItems(t){return t.flatMap(t=>{if("runtime.tool.direct.completed"===t.type)return stringifyEvidence(t.output).map(e=>({source:t.toolId,output:e}));const e=readAdapterEvent(t);return isToolResultEvent(e)&&"string"==typeof e.toolId?!isSuccessfulEvidenceEvent(e)||function isPlanningTool(t){return/^(?:write_todos|read_todos)$/u.test(t)}(e.toolId)?[]:stringifyEvidence(e.evidenceOutput??e.output).filter(t=>function isUsableEvidenceOutput(t,e){return"task"!==t||!function looksLikeUnexecutedToolIntent(t){const e=t.trim();return!(e.length>4e3)&&[/\b(?:I need to|I will|I'll|I am going to|I'm going to|Let me)\s+(?:call|use|run|invoke|get|fetch|check)\b[\s\S]{0,1200}\b(?:tool|function|system_time|web_search|url_text_fetch|task)\b/iu,/(?:我需要|我要|我会|我将|让我|我来|接下来我(?:会|将)?)\s*(?:先)?(?:调用|使用|运行|执行|检查|获取|查看)\b[\s\S]{0,1200}\b(?:工具|函数|system_time|web_search|url_text_fetch|task)\b/iu,/```(?:json)?\s*(?:system_time|web_search|url_text_fetch|task)\s*```/iu].some(t=>t.test(e))}(e)&&!function looksLikeDelegatedCommentary(t){const e=t.trim();return!(e.length>8e3)&&[/(?:这篇文章|this article)[\s\S]{0,1200}(?:我认为|我认同|打动我|值得深入探讨|特别认同|what I find|I think|I agree)/iu,/(?:你还有什么|还想深入探讨|would you like|do you want).{0,120}[??]\s*$/iu].some(t=>t.test(e))}(e)}(e.toolId,t)).map(t=>({source:e.toolId,output:t})):[]})}export function controlBlockers(t){const e=function successfulEventIndexesBySource(t){const e=new Map;return t.forEach((t,n)=>{const o=function successfulEventSource(t){if("runtime.tool.direct.completed"===t.type)return t.toolId;const e=readAdapterEvent(t);return isToolResultEvent(e)&&"string"==typeof e.toolId&&isSuccessfulEvidenceEvent(e)?e.toolId:void 0}(t);o&&e.set(o,[...e.get(o)??[],n])}),e}(t);return t.flatMap((t,n)=>{const o=readAdapterEvent(t),r=readString(o?.controlStatus)??readOutputStatus(o?.output),s=readString(o?.toolId)??"tool";return r&&isBlockerStatus(r)?isResolvedByLaterCompletion(r)&&function completedAfter(t,e,n){return(t.get(e)??[]).some(t=>t>n)}(e,s,n)?[]:[`${s}:${r}`]:[]})}export function controlGaps(t){const e=new Set(successfulEvidenceItems(t).map(t=>t.source));return t.flatMap(t=>{const n=readAdapterEvent(t),o=readString(n?.controlStatus)??readOutputStatus(n?.output),r=readString(n?.toolId)??"tool";return o&&isGapStatus(o)?e.has(r)&&isResolvedByLaterCompletion(o)?[]:[`${r}:${o}`]:[]})}function stringifyEvidence(t){return"string"==typeof t?t.trim()?[t]:[]:null==t?[]:[JSON.stringify(t)]}function readAdapterEvent(t){return"runtime.adapter.event"===t.type&&isRecord(t.event)?t.event:void 0}function isSuccessfulEvidenceEvent(t){const e=readString(t.controlStatus)??readOutputStatus(t.output);return!e||/^(?:completed|success|ok|recorded)$/iu.test(e)}function isBlockerStatus(t){return/^(?:blocked|approval_required|schema_repair_failed|tool_argument_error|invalid_input)$/iu.test(t)}function isGapStatus(t){return/^(?:dependency_required|plan_required|repeated_tool_call_limit|duplicate_tool_call)$/iu.test(t)}function isResolvedByLaterCompletion(t){return isGapStatus(t)||isBlockerStatus(t)}function isToolResultEvent(t){return"deepagents.tool_execution.result"===t?.eventType||"agent.tool.result"===t?.phase}function readOutputStatus(t){if("string"!=typeof t)return;const e=function parseJsonRecord(t){try{const e=JSON.parse(t);return isRecord(e)?e:void 0}catch{return}}(t);return"string"==typeof e?.status?e.status:t.match(/^Status:\s*([A-Za-z0-9_-]+)/imu)?.[1]}function isRecord(t){return"object"==typeof t&&null!==t&&!Array.isArray(t)}function readString(t){return"string"==typeof t&&t.trim()?t:void 0}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
export function toolCallRecoveryEnabled(e){return!0===readToolCallRecovery(e).enabled}export function isRecoverableAdapterError(e,t){const o=readToolCallRecovery(t);if(!0!==o.enabled)return!1;const n=e instanceof Error?e.message:String(e);return readRegexps(o.adapterErrorPatterns,[/XML syntax error|tool.?call.*syntax|malformed.*(?:XML|tool)|Non string tool message content|repeat limit reached for tool/iu]).some(e=>e.test(n))}export function buildAdapterErrorRecoveryPrompt(e,t,o){const n=t instanceof Error?t.message:String(t),r=readToolCallRecovery(o).instruction;return recoverRequest(e,["Stable runtime recovery: the backend failed while parsing a tool call.",`Parser error: ${n}`,"string"==typeof r?r:"Continue the same user request using the backend's normal tool-calling mechanism, then return a final human-readable answer.","Do not print raw tool-call markup, JSON tool-call envelopes, or pseudo tool-call text in the final answer."])}export function buildResultRecoveryRequest(e){const t=readToolCallRecovery(e.policy);if(!0!==t.enabled)return;if(containsRawToolCallText(e.output,t)){const t=recentToolEvidence(e.events,1e3);return recoverRequest(e.request,["Stable runtime recovery: your previous final answer printed raw tool-call markup instead of executing the tool.","Continue the same user request by calling the available upstream tool normally when more evidence is required.","If you call a tool, the next assistant action must be the backend's structured tool call itself, with no prose before it.",...e.availableToolIds?.length?[`Available configured tools: ${e.availableToolIds.join(", ")}`,"Do not invent, print, or call tools that are not in this list."]:[],"If the conversation context already contains enough evidence to answer, synthesize the final answer from that context instead.","Do not print XML, JSON, markdown fences, pseudo tool-call text, plans, or future-intent text such as saying you will call or wait for a tool.",...t.length>0?["","Recent executed tool evidence:",...t]:[],"","Previous invalid final answer:",e.output])}if(containsToolExecutionErrorText(e.output,t)){const t=recentToolEvidence(e.events,1e3);return recoverRequest(e.request,["Stable runtime recovery: your previous final answer exposed a backend tool execution error instead of handling it.","Continue the same user request using the backend's normal structured tool-calling mechanism.","Do not retry the same invalid tool arguments. If the failed tool is not required to answer the user, synthesize the final answer from the available context instead.",...e.availableToolIds?.length?[`Available configured tools: ${e.availableToolIds.join(", ")}`,"Do not invent, print, or call tools that are not in this list."]:[],"Do not print tool error stacks, schema validation diagnostics, raw tool-call markup, JSON tool-call envelopes, or pseudo tool-call text in the final answer.",...t.length>0?["","Recent executed tool evidence:",...t]:[],"","Previous invalid final answer:",e.output])}const o=function lastConfiguredEventHint(e,t){const o=function readEventRecoveryHints(e){return(Array.isArray(e)?e:[]).flatMap(e=>isRecord(e)&&"string"==typeof e.instruction?[{..."string"==typeof e.toolId?{toolId:e.toolId}:{},..."string"==typeof e.phase?{phase:e.phase}:{},..."string"==typeof e.outputIncludes?{outputIncludes:e.outputIncludes}:{},..."string"==typeof e.outputMatches?{outputMatches:e.outputMatches}:{},instruction:e.instruction}]:[])}(t.eventRecoveryHints);if(0!==o.length)return e.flatMap(e=>function readMatchingHints(e,t){const o="runtime.adapter.event"===e.type&&isRecord(e.event)?e.event:void 0;return o?t.filter(e=>function eventMatchesHint(e,t){return(!t.toolId||e.toolId===t.toolId)&&(!t.phase||e.phase===t.phase)&&(t.outputIncludes?"string"==typeof e.output&&e.output.includes(t.outputIncludes):!t.outputMatches||"string"==typeof e.output&&new RegExp(t.outputMatches,"u").test(e.output))}(o,e)).map(e=>({output:"string"==typeof o.output?o.output:"Adapter event matched configured recovery hint.",instruction:e.instruction})):[]}(e,o)).at(-1)}(e.events,t);return o?recoverRequest(e.request,["Stable runtime recovery: a previous adapter event matched a configured recovery hint.",o.output,o.instruction]):void 0}export function buildExecutionContractRecoveryRequest(e){if(!0!==readToolCallRecovery(e.policy).enabled)return;const t=function lastMissingEvidenceTools(e){for(let t=e.length-1;t>=0;t-=1){const o=e[t];if("runtime.execution.contract.failed"===o?.type)return readStringArray(o.missingEvidenceTools)}return[]}(e.events);return 0!==t.length?recoverRequest(e.request,["Stable runtime recovery: the execution contract was not satisfied.",`Required evidence tool(s) were missing: ${t.join(", ")}`,"Continue the same user request by calling the missing required evidence tool(s) through the backend's normal structured tool-calling mechanism.","Do not produce a final answer until the required evidence tool call has executed and you have synthesized its result.","Do not print XML, JSON, markdown fences, pseudo tool-call text, plans, or future-intent text in the final answer."]):void 0}export function assertNoRawToolCallOutput(e,t){if(containsRawToolCallOutput(e,t))throw new Error(`Adapter returned raw tool-call text as the final answer after recovery. The backend must execute tools instead of printing tool-call markup. Output preview: ${previewOutput(e)}`)}export function containsRawToolCallOutput(e,t){const o=readToolCallRecovery(t);return!0===o.enabled&&containsRawToolCallText(e,o)}export function containsRecoverableResultOutput(e,t){const o=readToolCallRecovery(t);return!0===o.enabled&&containsRecoverableResultFailureText(e,o)}export function assertNoToolExecutionErrorOutput(e,t){const o=readToolCallRecovery(t);if(!0===o.enabled&&containsToolExecutionErrorText(e,o))throw new Error(`Adapter returned a tool execution error as the final answer after recovery. Output preview: ${previewOutput(e)}`)}export function rawToolCallFailureMessage(){return["The model attempted to call a tool but returned the tool call as text instead of executing it.","Please retry the request or use a model/backend configuration with reliable tool calling for this workspace."].join(" ")}export function buildEvidenceSynthesisOutput(e){const t=readToolCallRecovery(e.policy);if(!0!==t.enabled||!1===t.synthesizeFromEvidenceOnFailure||!containsRecoverableResultFailureText(e.output,t))return;const o=function latestDelegatedTaskReport(e){return e.flatMap(e=>{const t="runtime.adapter.event"===e.type&&isRecord(e.event)?e.event:void 0;if(!t||"agent.tool.result"!==t.phase||"task"!==t.toolId)return[];const o="string"==typeof t.output?t.output.trim():"";return function looksLikeFinalReport(e){const t=e.trim();return!(t.length<80)&&(/^#{1,3}\s+\S/mu.test(t)||/\n#{1,3}\s+\S/mu.test(t)||/\n-{3,}\n/u.test(t))}(o)?[o]:[]}).at(-1)||void 0}(e.events);if(o)return o;const n=recentToolEvidence(e.events,6e3);return 0!==n.length?"zh"==(/\p{Script=Han}/u.test(e.request.input)?"zh":"en")?function buildChineseEvidenceSynthesis(e,t){return["上游模型在已有工具证据后仍输出了伪工具调用;runtime 已拒绝该 raw 输出,并直接交付已执行工具返回的证据结果。","","已执行的工具证据:",...t,"",`被拒绝的最终输出预览:${previewRejectedOutput(e)}`].join("\n")}(e.output,n):function buildEnglishEvidenceSynthesis(e,t){return["The upstream model still returned pseudo tool-call text after tool evidence was available. The runtime rejected that raw output and is returning the executed tool evidence directly.","","Executed tool evidence:",...t,"",`Rejected final output preview: ${previewRejectedOutput(e)}`].join("\n")}(e.output,n):void 0}function previewOutput(e){const t=e.replace(/\s+/gu," ").trim();return t.length>300?`${t.slice(0,297)}...`:t}function previewRejectedOutput(e){return previewOutput(e).replace(/[<>]/gu,"")}export function rawToolCallOutputPreview(e){return previewOutput(e)}function recoverRequest(e,t){return{...e,input:[e.input,"",...t].join("\n"),metadata:{...e.metadata,stableHarnessRecovery:"tool_call"}}}function containsRawToolCallText(e,t){const o=readRegexps(t.rawOutputPatterns,[/\{\s*"name"\s*:\s*"[^"]+"\s*,\s*"arguments"\s*:/iu,/\{\s*"tool_name"\s*:\s*"[^"]+"\s*,\s*"parameters"\s*:/iu,/\{\s*"type"\s*:\s*"[^"]+"\s*,\s*"args"\s*:/iu,/^\s*[A-Za-z_][\w.-]*\s*\([^)]{0,2000}\)\s*$/iu,/^\s*[A-Za-z_][\w.-]*(?:_command|_tool|_analysis|_investigate|task)\s*$/iu,/```(?:json)?[\s\S]{0,4000}"(?:tool_name|tool|name|subagent_type)"\s*:/iu,/```(?:json)?[\s\S]{0,4000}"(?:tool_name|tool|name|subagent_type)"\s*:[\s\S]{0,4000}"(?:arguments|parameters|task)"\s*:/iu,/```(?:json)?[\s\S]{0,2000}"query"\s*:[\s\S]{0,2000}"(?:max_results|count|freshness|market)"\s*:/iu]);return!![/<\s*(?:tool_call|task)\b[^>]*>/iu,/<\s*\/\s*(?:tool_call|task)\s*>/iu,/<\s*\/?\s*tool_code\b[^>]*>/iu,/<\s*\/?\s*[A-Za-z_][\w.-]*(?:_command|_tool|_analysis|_investigate|_todos|task)\b[^>]*>/iu].some(t=>t.test(e))||function looksLikeStandaloneRecoveryCandidate(e){const t=e.trim();return t.length<=6e3||/^\s*(?:```|\{|\[|[A-Za-z_][\w.-]*\s*\()/u.test(t)}(e)&&(o.some(t=>t.test(e))||[/^[\s\S]{0,2400}\b(?:I need to|I will|I'll|I am going to|I'm going to)\s+(?:call|use|invoke|delegate)\b[\s\S]{0,1200}\b(?:tool|function|specialist|subagent)\b[\s\S]{0,400}$/iu,/^[\s\S]{0,2400}\b(?:I will|I'll|I am going to|I'm going to)\s+(?:investigate|gather|check)\b[\s\S]{0,1200}\b(?:evidence|cluster|system|results?)\b[\s\S]{0,400}$/iu,/^[\s\S]{0,2400}\b(?:waiting for|wait for)\b[\s\S]{0,1200}\b(?:tool|function|specialist|subagent)\b[\s\S]{0,400}$/iu,/^[\s\S]{0,2400}\b(?:Would you like me to|Do you want me to|Should I|I can help with)\b[\s\S]{0,1200}\?[\s\S]{0,400}$/iu,/^[\s\S]{0,2400}\bCould you please provide\b[\s\S]{0,1200}\b(?:tool|function|specialist|subagent|task)\b[\s\S]{0,400}$/iu,/^[\s\S]{0,2400}\b(?:I don't|I do not) have enough information\b[\s\S]{0,1200}\b(?:tool|function|specialist|subagent|task|context)\b[\s\S]{0,400}$/iu,/^[\s\S]{0,2400}\bLet me\s+(?:call|use|invoke|delegate|check|run|verify|gather|inspect)\b[\s\S]{0,1200}\b(?:tool|function|specialist|subagent|results?|data|evidence|commands?)\b[\s\S]{0,400}$/iu,/^[\s\S]{0,2400}(?:我需要|我要|我会|我将|让我|我来|接下来我(?:会|将)?)\s*(?:先)?(?:调用|使用|运行|执行|检查|读取|收集|调查|验证|查看)[\s\S]{0,1200}$/iu,/^[\s\S]{0,2400}(?:要不要|是否需要|需要我|你想让我)[\s\S]{0,1200}(?:继续|进一步|帮你|分析|检查)[\s\S]{0,1200}[??][\s\S]{0,400}$/iu].some(t=>t.test(e)))}function containsRecoverableResultFailureText(e,t){return containsRawToolCallText(e,t)||containsToolExecutionErrorText(e,t)}function containsToolExecutionErrorText(e,t){return readRegexps(t.toolFailureOutputPatterns,[/^Error invoking tool ['"][^'"]+['"] with kwargs /iu,/Received tool input did not match expected schema/iu,/ToolMessage.*status.*error/iu]).some(t=>t.test(e))}function recentToolEvidence(e,t){return e.flatMap(e=>{const o="runtime.adapter.event"===e.type&&isRecord(e.event)?e.event:void 0;return o&&"agent.tool.result"===o.phase&&"string"==typeof o.toolId?function isControlToolOutput(e){if("string"!=typeof e||!e.trim().startsWith("{"))return!1;try{const t=JSON.parse(e),o=isRecord(t)?t.status:void 0;return"duplicate_tool_call"===o||"repeated_tool_call_limit"===o||"tool_argument_error"===o}catch{return!1}}(o.output)?[]:[`- ${o.toolId}: ${formatToolEvidence(o,t)}`]:[]}).slice(-5)}function formatToolEvidence(e,t=1e3){return"string"==typeof e.output&&e.output.trim()?e.output.slice(0,t):"string"==typeof e.error&&e.error.trim()?`error: ${e.error.slice(0,t)}`:isRecord(e.args)?`completed with args: ${previewOutput(JSON.stringify(e.args))}`:"completed"}function readToolCallRecovery(e){if(!isRecord(e))return{};const t=isRecord(e.recovery)?e.recovery:{};return isRecord(t.toolCall)?t.toolCall:{}}function readRegexps(e,t){const o=(Array.isArray(e)?e:[]).filter(e=>"string"==typeof e&&e.length>0).map(e=>new RegExp(e,"iu"));return o.length>0?o:t}function readStringArray(e){return Array.isArray(e)?e.filter(e=>"string"==typeof e&&e.length>0):[]}function isRecord(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}
|
|
1
|
+
export function toolCallRecoveryEnabled(e){return!0===readToolCallRecovery(e).enabled}export function isRecoverableAdapterError(e,t){const o=readToolCallRecovery(t);if(!0!==o.enabled)return!1;const n=e instanceof Error?e.message:String(e);return readRegexps(o.adapterErrorPatterns,[/XML syntax error|tool.?call.*syntax|malformed.*(?:XML|tool)|Non string tool message content|repeat limit reached for tool/iu]).some(e=>e.test(n))}export function buildAdapterErrorRecoveryPrompt(e,t,o){const n=t instanceof Error?t.message:String(t),r=readToolCallRecovery(o).instruction;return recoverRequest(e,["Stable runtime recovery: the backend failed while parsing a tool call.",`Parser error: ${n}`,"string"==typeof r?r:"Continue the same user request using the backend's normal tool-calling mechanism, then return a final human-readable answer.","Do not print raw tool-call markup, JSON tool-call envelopes, or pseudo tool-call text in the final answer."])}export function buildResultRecoveryRequest(e){const t=readToolCallRecovery(e.policy);if(!0!==t.enabled)return;if(containsRawToolCallText(e.output,t)){const t=recentToolEvidence(e.events,1e3);return recoverRequest(e.request,["Stable runtime recovery: your previous final answer printed raw tool-call markup instead of executing the tool.","Continue the same user request by calling the available upstream tool normally when more evidence is required.","If you call a tool, the next assistant action must be the backend's structured tool call itself, with no prose before it.",...e.availableToolIds?.length?[`Available configured tools: ${e.availableToolIds.join(", ")}`,"Do not invent, print, or call tools that are not in this list."]:[],"If the conversation context already contains enough evidence to answer, synthesize the final answer from that context instead.","Do not print XML, JSON, markdown fences, pseudo tool-call text, plans, or future-intent text such as saying you will call or wait for a tool.",...t.length>0?["","Recent executed tool evidence:",...t]:[],"","Previous invalid final answer:",e.output])}if(containsToolExecutionErrorText(e.output,t)){const t=recentToolEvidence(e.events,1e3);return recoverRequest(e.request,["Stable runtime recovery: your previous final answer exposed a backend tool execution error instead of handling it.","Continue the same user request using the backend's normal structured tool-calling mechanism.","Do not retry the same invalid tool arguments. If the failed tool is not required to answer the user, synthesize the final answer from the available context instead.",...e.availableToolIds?.length?[`Available configured tools: ${e.availableToolIds.join(", ")}`,"Do not invent, print, or call tools that are not in this list."]:[],"Do not print tool error stacks, schema validation diagnostics, raw tool-call markup, JSON tool-call envelopes, or pseudo tool-call text in the final answer.",...t.length>0?["","Recent executed tool evidence:",...t]:[],"","Previous invalid final answer:",e.output])}const o=function lastConfiguredEventHint(e,t){const o=function readEventRecoveryHints(e){return(Array.isArray(e)?e:[]).flatMap(e=>isRecord(e)&&"string"==typeof e.instruction?[{..."string"==typeof e.toolId?{toolId:e.toolId}:{},..."string"==typeof e.phase?{phase:e.phase}:{},..."string"==typeof e.outputIncludes?{outputIncludes:e.outputIncludes}:{},..."string"==typeof e.outputMatches?{outputMatches:e.outputMatches}:{},instruction:e.instruction}]:[])}(t.eventRecoveryHints);if(0!==o.length)return e.flatMap(e=>function readMatchingHints(e,t){const o="runtime.adapter.event"===e.type&&isRecord(e.event)?e.event:void 0;return o?t.filter(e=>function eventMatchesHint(e,t){return(!t.toolId||e.toolId===t.toolId)&&(!t.phase||e.phase===t.phase)&&(t.outputIncludes?"string"==typeof e.output&&e.output.includes(t.outputIncludes):!t.outputMatches||"string"==typeof e.output&&new RegExp(t.outputMatches,"u").test(e.output))}(o,e)).map(e=>({output:"string"==typeof o.output?o.output:"Adapter event matched configured recovery hint.",instruction:e.instruction})):[]}(e,o)).at(-1)}(e.events,t);return o?recoverRequest(e.request,["Stable runtime recovery: a previous adapter event matched a configured recovery hint.",o.output,o.instruction]):void 0}export function buildExecutionContractRecoveryRequest(e){if(!0!==readToolCallRecovery(e.policy).enabled)return;const t=function lastMissingEvidenceTools(e){for(let t=e.length-1;t>=0;t-=1){const o=e[t];if("runtime.execution.contract.failed"===o?.type)return readStringArray(o.missingEvidenceTools)}return[]}(e.events);return 0!==t.length?recoverRequest(e.request,["Stable runtime recovery: the execution contract was not satisfied.",`Required evidence tool(s) were missing: ${t.join(", ")}`,"Continue the same user request by calling the missing required evidence tool(s) through the backend's normal structured tool-calling mechanism.","Do not produce a final answer until the required evidence tool call has executed and you have synthesized its result.","Do not print XML, JSON, markdown fences, pseudo tool-call text, plans, or future-intent text in the final answer."]):void 0}export function assertNoRawToolCallOutput(e,t){if(containsRawToolCallOutput(e,t))throw new Error(`Adapter returned raw tool-call text as the final answer after recovery. The backend must execute tools instead of printing tool-call markup. Output preview: ${previewOutput(e)}`)}export function containsRawToolCallOutput(e,t){const o=readToolCallRecovery(t);return!0===o.enabled&&containsRawToolCallText(e,o)}export function containsRecoverableResultOutput(e,t){const o=readToolCallRecovery(t);return!0===o.enabled&&containsRecoverableResultFailureText(e,o)}export function assertNoToolExecutionErrorOutput(e,t){const o=readToolCallRecovery(t);if(!0===o.enabled&&containsToolExecutionErrorText(e,o))throw new Error(`Adapter returned a tool execution error as the final answer after recovery. Output preview: ${previewOutput(e)}`)}export function rawToolCallFailureMessage(){return["The model attempted to call a tool but returned the tool call as text instead of executing it.","Please retry the request or use a model/backend configuration with reliable tool calling for this workspace."].join(" ")}export function buildEvidenceSynthesisOutput(e){const t=readToolCallRecovery(e.policy);if(!0!==t.enabled||!1===t.synthesizeFromEvidenceOnFailure||!containsRecoverableResultFailureText(e.output,t))return;const o=function latestDelegatedTaskReport(e){return e.flatMap(e=>{const t="runtime.adapter.event"===e.type&&isRecord(e.event)?e.event:void 0;if(!isToolResultEvent(t)||"task"!==t.toolId)return[];const o="string"==typeof t.output?t.output.trim():"";return function looksLikeFinalReport(e){const t=e.trim();return!(t.length<80)&&(/^#{1,3}\s+\S/mu.test(t)||/\n#{1,3}\s+\S/mu.test(t)||/\n-{3,}\n/u.test(t))}(o)?[o]:[]}).at(-1)||void 0}(e.events);if(o)return o;const n=recentToolEvidence(e.events,6e3);return 0!==n.length?"zh"==(/\p{Script=Han}/u.test(e.request.input)?"zh":"en")?function buildChineseEvidenceSynthesis(e,t){return["上游模型在已有工具证据后仍输出了伪工具调用;runtime 已拒绝该 raw 输出,并直接交付已执行工具返回的证据结果。","","已执行的工具证据:",...t,"",`被拒绝的最终输出预览:${previewRejectedOutput(e)}`].join("\n")}(e.output,n):function buildEnglishEvidenceSynthesis(e,t){return["The upstream model still returned pseudo tool-call text after tool evidence was available. The runtime rejected that raw output and is returning the executed tool evidence directly.","","Executed tool evidence:",...t,"",`Rejected final output preview: ${previewRejectedOutput(e)}`].join("\n")}(e.output,n):void 0}function previewOutput(e){const t=e.replace(/\s+/gu," ").trim();return t.length>300?`${t.slice(0,297)}...`:t}function previewRejectedOutput(e){return previewOutput(e).replace(/[<>]/gu,"")}export function rawToolCallOutputPreview(e){return previewOutput(e)}function recoverRequest(e,t){return{...e,input:[e.input,"",...t].join("\n"),metadata:{...e.metadata,stableHarnessRecovery:"tool_call"}}}function containsRawToolCallText(e,t){const o=readRegexps(t.rawOutputPatterns,[/\{\s*"name"\s*:\s*"[^"]+"\s*,\s*"arguments"\s*:/iu,/\{\s*"tool_name"\s*:\s*"[^"]+"\s*,\s*"parameters"\s*:/iu,/\{\s*"type"\s*:\s*"[^"]+"\s*,\s*"args"\s*:/iu,/^\s*[A-Za-z_][\w.-]*\s*\([^)]{0,2000}\)\s*$/iu,/^\s*[A-Za-z_][\w.-]*(?:_command|_tool|_analysis|_investigate|task)\s*$/iu,/```(?:json)?[\s\S]{0,4000}"(?:tool_name|tool|name|subagent_type)"\s*:/iu,/```(?:json)?[\s\S]{0,4000}"(?:tool_name|tool|name|subagent_type)"\s*:[\s\S]{0,4000}"(?:arguments|parameters|task)"\s*:/iu,/```(?:json)?[\s\S]{0,2000}"query"\s*:[\s\S]{0,2000}"(?:max_results|count|freshness|market)"\s*:/iu]);return!![/<\s*(?:tool_call|task)\b[^>]*>/iu,/<\s*\/\s*(?:tool_call|task)\s*>/iu,/<\s*\/?\s*tool_code\b[^>]*>/iu,/<\s*\/?\s*[A-Za-z_][\w.-]*(?:_command|_tool|_analysis|_investigate|_todos|task)\b[^>]*>/iu].some(t=>t.test(e))||function looksLikeStandaloneRecoveryCandidate(e){const t=e.trim();return t.length<=6e3||/^\s*(?:```|\{|\[|[A-Za-z_][\w.-]*\s*\()/u.test(t)}(e)&&(o.some(t=>t.test(e))||[/^[\s\S]{0,2400}\b(?:I need to|I will|I'll|I am going to|I'm going to)\s+(?:call|use|invoke|delegate)\b[\s\S]{0,1200}\b(?:tool|function|specialist|subagent)\b[\s\S]{0,400}$/iu,/^[\s\S]{0,2400}\b(?:I will|I'll|I am going to|I'm going to)\s+(?:investigate|gather|check)\b[\s\S]{0,1200}\b(?:evidence|cluster|system|results?)\b[\s\S]{0,400}$/iu,/^[\s\S]{0,2400}\b(?:waiting for|wait for)\b[\s\S]{0,1200}\b(?:tool|function|specialist|subagent)\b[\s\S]{0,400}$/iu,/^[\s\S]{0,2400}\b(?:Would you like me to|Do you want me to|Should I|I can help with)\b[\s\S]{0,1200}\?[\s\S]{0,400}$/iu,/^[\s\S]{0,2400}\bCould you please provide\b[\s\S]{0,1200}\b(?:tool|function|specialist|subagent|task)\b[\s\S]{0,400}$/iu,/^[\s\S]{0,2400}\b(?:I don't|I do not) have enough information\b[\s\S]{0,1200}\b(?:tool|function|specialist|subagent|task|context)\b[\s\S]{0,400}$/iu,/^[\s\S]{0,2400}\bLet me\s+(?:call|use|invoke|delegate|check|run|verify|gather|inspect)\b[\s\S]{0,1200}\b(?:tool|function|specialist|subagent|results?|data|evidence|commands?)\b[\s\S]{0,400}$/iu,/^[\s\S]{0,2400}(?:我需要|我要|我会|我将|让我|我来|接下来我(?:会|将)?)\s*(?:先)?(?:调用|使用|运行|执行|检查|读取|收集|调查|验证|查看)[\s\S]{0,1200}$/iu,/^[\s\S]{0,2400}(?:要不要|是否需要|需要我|你想让我)[\s\S]{0,1200}(?:继续|进一步|帮你|分析|检查)[\s\S]{0,1200}[??][\s\S]{0,400}$/iu].some(t=>t.test(e)))}function containsRecoverableResultFailureText(e,t){return containsRawToolCallText(e,t)||containsToolExecutionErrorText(e,t)}function containsToolExecutionErrorText(e,t){return readRegexps(t.toolFailureOutputPatterns,[/^Error invoking tool ['"][^'"]+['"] with kwargs /iu,/Received tool input did not match expected schema/iu,/ToolMessage.*status.*error/iu]).some(t=>t.test(e))}function recentToolEvidence(e,t){return e.flatMap(e=>{const o="runtime.adapter.event"===e.type&&isRecord(e.event)?e.event:void 0;return isToolResultEvent(o)&&"string"==typeof o.toolId?function isControlToolOutput(e){if("string"!=typeof e||!e.trim().startsWith("{"))return!1;try{const t=JSON.parse(e),o=isRecord(t)?t.status:void 0;return"duplicate_tool_call"===o||"repeated_tool_call_limit"===o||"tool_argument_error"===o}catch{return!1}}(o.output)?[]:[`- ${o.toolId}: ${formatToolEvidence(o,t)}`]:[]}).slice(-5)}function isToolResultEvent(e){return"deepagents.tool_execution.result"===e?.eventType||"agent.tool.result"===e?.phase}function formatToolEvidence(e,t=1e3){return"string"==typeof e.output&&e.output.trim()?e.output.slice(0,t):"string"==typeof e.error&&e.error.trim()?`error: ${e.error.slice(0,t)}`:isRecord(e.args)?`completed with args: ${previewOutput(JSON.stringify(e.args))}`:"completed"}function readToolCallRecovery(e){if(!isRecord(e))return{};const t=isRecord(e.recovery)?e.recovery:{};return isRecord(t.toolCall)?t.toolCall:{}}function readRegexps(e,t){const o=(Array.isArray(e)?e:[]).filter(e=>"string"==typeof e&&e.length>0).map(e=>new RegExp(e,"iu"));return o.length>0?o:t}function readStringArray(e){return Array.isArray(e)?e.filter(e=>"string"==typeof e&&e.length>0):[]}function isRecord(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
export function createToolRepeatState(e){if(function repeatGuardEnabled(e){return!0===repeatGuardConfig(e).enabled}(e))return{successfulCalls:new Map,duplicateCallCounts:new Map,latestSuccessfulOutputByTool:new Map,successfulToolCounts:new Map,toolCallCounts:new Map,maxDuplicateCallsPerTool:readPositiveInteger(repeatGuardConfig(e).maxDuplicateCallsPerTool)??3,maxCallsPerTool:readPositiveInteger(repeatGuardConfig(e).maxCallsPerTool),maxSuccessfulCallsPerTool:readPositiveInteger(repeatGuardConfig(e).maxSuccessfulCallsPerTool),maxCallsByTool:readPositiveIntegerMap(repeatGuardConfig(e).maxCallsByTool),maxSuccessfulCallsByTool:readPositiveIntegerMap(repeatGuardConfig(e).maxSuccessfulCallsByTool),returnPreviousOutputOnRepeatLimit:!0===repeatGuardConfig(e).returnPreviousOutputOnRepeatLimit}}export function beforeToolInvoke(e,t,o){const n=o.toolCallCounts.get(e)??0;o.toolCallCounts.set(e,n+1);const r=o.maxCallsByTool.get(e)??o.maxCallsPerTool;if(void 0!==r&&n>=r){const t=o.latestSuccessfulOutputByTool.get(e),n=repeatedToolCallLimitContent(e,t);return{eventOutput:n,modelOutput:repeatLimitModelOutput(n,t,o)}}const l=o.maxSuccessfulCallsByTool.get(e)??o.maxSuccessfulCallsPerTool;if(void 0!==l&&(o.successfulToolCounts.get(e)??0)>=l){const t=o.latestSuccessfulOutputByTool.get(e),n=repeatedToolCallLimitContent(e,t);return{eventOutput:n,modelOutput:repeatLimitModelOutput(n,t,o)}}const
|
|
1
|
+
export function createToolRepeatState(e){if(function repeatGuardEnabled(e){return!0===repeatGuardConfig(e).enabled}(e))return{successfulCalls:new Map,duplicateCallCounts:new Map,latestSuccessfulOutputByTool:new Map,successfulToolCounts:new Map,toolCallCounts:new Map,maxDuplicateCallsPerTool:readPositiveInteger(repeatGuardConfig(e).maxDuplicateCallsPerTool)??3,maxCallsPerTool:readPositiveInteger(repeatGuardConfig(e).maxCallsPerTool),maxSuccessfulCallsPerTool:readPositiveInteger(repeatGuardConfig(e).maxSuccessfulCallsPerTool),maxCallsByTool:readPositiveIntegerMap(repeatGuardConfig(e).maxCallsByTool),maxSuccessfulCallsByTool:readPositiveIntegerMap(repeatGuardConfig(e).maxSuccessfulCallsByTool),returnPreviousOutputOnRepeatLimit:!0===repeatGuardConfig(e).returnPreviousOutputOnRepeatLimit}}export function beforeToolInvoke(e,t,o){const n=o.toolCallCounts.get(e)??0;o.toolCallCounts.set(e,n+1);const r=o.maxCallsByTool.get(e)??o.maxCallsPerTool;if(void 0!==r&&n>=r){const t=o.latestSuccessfulOutputByTool.get(e),n=repeatedToolCallLimitContent(e,t);return{eventOutput:n,modelOutput:repeatLimitModelOutput(n,t,o)}}const l=o.maxSuccessfulCallsByTool.get(e)??o.maxSuccessfulCallsPerTool;if(void 0!==l&&(o.successfulToolCounts.get(e)??0)>=l){const t=o.latestSuccessfulOutputByTool.get(e),n=repeatedToolCallLimitContent(e,t);return{eventOutput:n,modelOutput:repeatLimitModelOutput(n,t,o)}}const s=stableToolCallKey(e,t),u=o.successfulCalls.get(s);if(void 0!==u){const t=o.duplicateCallCounts.get(s)??0;if(o.duplicateCallCounts.set(s,t+1),void 0!==o.maxDuplicateCallsPerTool&&t>=o.maxDuplicateCallsPerTool){const t=repeatedToolCallLimitContent(e);return{eventOutput:t,modelOutput:t}}const n=function duplicateToolCallContent(e,t){return JSON.stringify({status:"duplicate_tool_call",toolId:e,instruction:"This agent already completed an equivalent tool call. Use the prior evidence instead of calling the tool again.",previousOutput:t})}(e,u);return{eventOutput:n,modelOutput:u}}}export function afterToolInvoke(e){return e.successful?(e.state.successfulCalls.set(stableToolCallKey(e.toolId,e.args),e.output),e.state.latestSuccessfulOutputByTool.set(e.toolId,e.output),e.state.successfulToolCounts.set(e.toolId,(e.state.successfulToolCounts.get(e.toolId)??0)+1),{}):{}}export function isToolRepeatLimitReached(e,t){if(!t)return!1;const o=t.maxCallsByTool.get(e)??t.maxCallsPerTool;if(void 0!==o&&(t.toolCallCounts.get(e)??0)>=o)return!0;const n=t.maxSuccessfulCallsByTool.get(e)??t.maxSuccessfulCallsPerTool;return void 0!==n&&(t.successfulToolCounts.get(e)??0)>=n}export function missingRequiredPlanContent(e){const t=readRecord(e.agent.config.executionContract);if(!0!==t.requiresPlan)return"";const o=readStringArray(t.planEvidenceTools);if(0===o.length||o.includes(e.toolId))return"";const n=new Set(e.events.flatMap(readEvidenceToolId));return o.some(e=>n.has(e))?"":["Status: plan_required",`Evidence tool: ${e.toolId}`,`Blocker: execution contract requires a planning checkpoint from one of: ${o.join(", ")} before evidence tools run.`,"Instruction: call the planning tool first, then retry this atomic evidence tool with repaired arguments."].join("\n")}export function missingToolDependencyContent(e){const t=readRecord(e.agent.config.executionContract),o=readStringArray(readRecord(t.toolDependencies)[e.toolId]);if(0===o.length)return"";const n=new Set(e.events.flatMap(readEvidenceToolId)),r=o.filter(e=>!n.has(e));return 0===r.length?"":["Status: dependency_required",`Evidence tool: ${e.toolId}`,`Blocker: this atomic evidence tool requires completed dependency evidence from: ${r.join(", ")}.`,"Instruction: complete the dependency tool first, evaluate it, then retry this atomic evidence tool."].join("\n")}export function toolInvocationEvents(e){const t=e.getEvents?.();return t??[]}function repeatGuardConfig(e){const t=readRecord(e);return readRecord(t.repeatGuard)}function readPositiveInteger(e){return"number"==typeof e&&Number.isInteger(e)&&e>0?e:void 0}function readPositiveIntegerMap(e){const t=readRecord(e);return new Map(Object.entries(t).map(([e,t])=>[e,readPositiveInteger(t)]).filter(e=>void 0!==e[1]))}function repeatLimitModelOutput(e,t,o){return o.returnPreviousOutputOnRepeatLimit&&void 0!==t&&0!==t.trim().length?t:e}function repeatedToolCallLimitContent(e,t){return JSON.stringify({status:"repeated_tool_call_limit",toolId:e,instruction:"This tool reached the configured repeat limit for this request. Do not call this tool or a substitute tool for the same evidence need again. Use previousOutput and the collected evidence to produce the final answer now, or report the remaining gap explicitly.",...void 0!==t?{previousOutput:t}:{}})}function stableToolCallKey(e,t){return`${e}:${stableJson(t)}`}function stableJson(e){return Array.isArray(e)?`[${e.map(stableJson).join(",")}]`:isRecord(e)?`{${Object.keys(e).sort().map(t=>`${JSON.stringify(t)}:${stableJson(e[t])}`).join(",")}}`:JSON.stringify(e)}function readEvidenceToolId(e){return"runtime.tool.direct.completed"===e.type?[e.toolId]:"runtime.adapter.event"===e.type&&isRecord(e.event)&&function isToolResultEvent(e){return"deepagents.tool_execution.result"===e.eventType||"agent.tool.result"===e.phase}(e.event)&&"string"==typeof e.event.toolId&&function isSuccessfulEvidenceEvent(e){const t=function readString(e){return"string"==typeof e&&e.length>0?e:void 0}(e.controlStatus)??function readOutputStatus(e){if("string"!=typeof e)return;const t=function parseJsonRecord(e){try{const t=JSON.parse(e);return isRecord(t)?t:void 0}catch{return}}(e);return"string"==typeof t?.status?t.status:e.match(/^Status:\s*([A-Za-z0-9_-]+)/imu)?.[1]}(e.output);return!t||/^(?:completed|success|ok|recorded)$/iu.test(t)}(e.event)?[e.event.toolId]:[]}function readRecord(e){return isRecord(e)?e:{}}function readStringArray(e){return Array.isArray(e)?e.filter(e=>"string"==typeof e&&e.length>0):[]}function isRecord(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
export function resolveProgressNarrator(e){if(!1===e.options)return;const t=readProgressPolicy(e.policy);return e.options?.enabled??t.enabled?e.options?.provider??function createTemplateProgressNarrator(){const e=new Map,t=new Map;return{name:"template",narrate(r,n){var o;"runtime.request.started"===r.type&&(e.set(r.requestId,{language:(o=r.input??"",/\p{Script=Han}/u.test(o)?"zh":void 0),input:r.input}),t.delete(r.requestId));const i=function templateMessage(e,t){const r="zh"===t?.language;return"runtime.request.started"===e.type?r?`我开始处理这个请求:${summarizeText(e.input)}`:`I'm starting on this request: ${summarizeText(e.input)}`:"runtime.request.completed"===e.type?r?"我已经完成执行链,正在交付最终结果。":"I've finished the execution chain and am returning the final result.":"runtime.request.failed"===e.type?r?"执行链失败了,我会保留具体错误方便定位。":"The execution chain failed; I'm keeping the concrete error visible for diagnosis.":"runtime.request.cancelled"===e.type?r?"这个请求已取消,后续执行会停止。":"The request was cancelled, so the remaining execution will stop.":"runtime.tool.direct.started"===e.type?r?`我正在运行 ${e.toolId}。`:`I'm running ${e.toolId}.`:"runtime.tool.direct.completed"===e.type?r?`${e.toolId} 已返回结果,我会继续使用这份证据。`:`${e.toolId} returned; I'll keep using that evidence.`:"runtime.workflow.started"===e.type?r?`我正在启动 workflow ${e.workflowId}。`:`I'm starting workflow ${e.workflowId}.`:"runtime.workflow.completed"===e.type?r?`workflow ${e.workflowId} 已完成。`:`Workflow ${e.workflowId} is complete.`:"runtime.specDriven.phase.started"===e.type?r?`我正在进入 spec-driven 阶段 ${e.phaseId}。`:`I'm starting spec-driven phase ${e.phaseId}.`:"runtime.specDriven.phase.blocked"===e.type?r?`spec-driven 阶段 ${e.phaseId} 被 gate 阻塞。`:`Spec-driven phase ${e.phaseId} is blocked by a gate.`:"runtime.specDriven.phase.completed"===e.type?r?`spec-driven 阶段 ${e.phaseId} 已完成。`:`Spec-driven phase ${e.phaseId} is complete.`:"runtime.specDriven.phase.verified"===e.type?r?`spec-driven 阶段 ${e.phaseId} 已验证。`:`Spec-driven phase ${e.phaseId} is verified.`:"runtime.artifact.created"===e.type?r?"我已经保存一份运行产物。":"I've saved a runtime artifact.":"runtime.execution.contract.failed"===e.type?r?"运行证据没有满足执行契约,我会进入恢复或失败路径。":"The run evidence did not satisfy the execution contract, so I'll recover or fail explicitly.":"runtime.inventory.repair"===e.type?inventoryRepairMessage(e.status,e.diagnostic.layer,r):"runtime.skill.candidate.created"===e.type?r?`我发现一个可沉淀的 skill 候选:${e.name}。`:`I found a reusable skill candidate: ${e.name}.`:e.type.startsWith("runtime.memory.")?function memoryMessage(e,t){return"runtime.memory.lifecycle"===e.type?t?`我进入记忆阶段:${e.hook}。`:`I'm in the memory lifecycle phase: ${e.hook}.`:"runtime.memory.recall.completed"===e.type?t?`我召回了 ${e.recordIds.length} 条相关记忆。`:`I recalled ${e.recordIds.length} relevant memory records.`:"runtime.memory.candidate.submitted"===e.type?t?"我提交了一条候选记忆。":"I submitted a memory candidate.":"runtime.memory.approval.requested"===e.type?t?"我提交了记忆审批请求。":"I requested memory approval.":"runtime.memory.plugin.started"===e.type?t?`我正在运行记忆插件 ${e.provider}。`:`I'm running memory plugin ${e.provider}.`:"runtime.memory.plugin.completed"===e.type?t?`记忆插件 ${e.provider} 已完成。`:`Memory plugin ${e.provider} completed.`:"runtime.memory.plugin.failed"===e.type?t?`记忆插件 ${e.provider} 失败了;主任务会继续,不把它当成执行结果。`:`Memory plugin ${e.provider} failed; the main task will continue without treating it as the result.`:"runtime.memory.maintenance.started"===e.type?t?`我正在维护 ${e.target} 记忆。`:`I'm maintaining ${e.target} memory.`:"runtime.memory.maintenance.completed"===e.type?t?`${e.target} 记忆维护完成。`:`${e.target} memory maintenance completed.`:"runtime.memory.maintenance.failed"===e.type?t?`${e.target} 记忆维护失败。`:`${e.target} memory maintenance failed.`:void 0}(e,r):"runtime.adapter.event"===e.type?function adapterMessage(e,t){if(isRecord(e)){if("agent.handoff"===e.phase)return t?"我把请求交给上游 agent backend,让它负责规划和执行。":"I'm handing the request to the upstream agent backend for planning and execution.";if("agent.tool.start"===e.phase&&"string"==typeof e.toolId)return function toolStartMessage(e,t,r){if("task"===e){const e=function readTaskTarget(e){const t=isRecord(e)?e:{};return readString(t.subagent_type)??readString(t.subagentType)}(t),n=function readDescription(e){const t=isRecord(e)?e:{};return summarizeText(readString(t.description)??readString(t.task))}(t);if(e&&n)return r?`我正在请求 task 工具委派给 ${e}:${n}`:`I'm asking the task tool to delegate to ${e}: ${n}`;if(e)return r?`我正在请求 task 工具委派给 ${e}。`:`I'm asking the task tool to delegate to ${e}.`}return r?`我正在运行 ${e} 收集证据。`:`I'm running ${e} to gather evidence.`}(e.toolId,e.args,t);if("agent.tool.result"===e.phase&&"string"==typeof e.toolId)return function toolResultMessage(e,t,r,n,o){if(r)return o?`${e} 返回错误:${summarizeText(String(r))}`:`${e} returned an error: ${summarizeText(String(r))}`;const i="string"==typeof n?n:function readToolControlStatus(e){const t=function parseToolOutputRecord(e){if(isRecord(e))return e;if("string"==typeof e)try{const t=JSON.parse(e);return isRecord(t)?t:void 0}catch{return}}(e);return"string"==typeof t?.status?t.status:"string"==typeof t?.error?t.error:"string"==typeof e&&e.startsWith("Task delegation target is not in the workspace inventory")?"task_inventory_blocked":void 0}(t);if(i)return function toolControlMessage(e,t,r){return"duplicate_tool_call"===t?r?`${e} 重复调用已复用已有证据。`:`${e} repeated an equivalent call, so the existing evidence was reused.`:"repeated_tool_call_limit"===t?r?`${e} 出现重复调用循环,我会基于已有证据继续收敛。`:`${e} entered a repeated-call loop, so I'll continue from the evidence already collected.`:"tool_argument_error"===t||"tool_argument_validation_failed"===t?r?`${e} 参数被工具 schema 拒绝,我会让 agent 修正参数或改用合适工具。`:`${e} arguments were rejected by the tool schema; I'll have the agent repair them or choose a suitable tool.`:"task_inventory_blocked"===t?r?"task 委派目标不在当前 workspace inventory 中,已被运行时策略阻止。":"The task delegation target is not in the current workspace inventory and was blocked by runtime policy.":r?`${e} 返回运行时控制状态:${t}。`:`${e} returned runtime control status: ${t}.`}(e,i,o);if("task"===e)return o?"委派任务已返回结果,我会基于这些证据继续推进。":"The delegated task returned; I'll keep going with that evidence.";const a=function summarizeToolOutput(e){if("string"==typeof e)return summarizeText(e);if(isRecord(e)){if("string"==typeof e.status)return summarizeText(e.status);if("string"==typeof e.summary)return summarizeText(e.summary)}}(t);return o?`${e} 已返回${a?`:${a}`:",我会继续判断下一步。"}`:`${e} returned${a?`: ${a}`:"; I'll decide the next step from here."}`}(e.toolId,e.output,e.error,e.controlStatus,t);if("agent.langgraph.invoke"===e.phase)return t?"我正在调用 workflow backend。":"I'm invoking the workflow backend.";if("agent.node.completed"===e.phase&&"string"==typeof e.nodeId)return t?`节点 ${e.nodeId} 已完成。`:`Node ${e.nodeId} is complete.`;if("inventory.repair"===e.phase&&"string"==typeof e.status){const r=isRecord(e.diagnostic)?e.diagnostic:{};return inventoryRepairMessage(e.status,readString(r.layer)??"selection",t)}}}(e.event,r):void 0}(r,e.get(r.requestId));if(i&&i!==t.get(r.requestId))return t.set(r.requestId,i),"runtime.request.failed"!==r.type&&"runtime.request.cancelled"!==r.type||(e.delete(r.requestId),t.delete(r.requestId)),function pruneRequestState(e,t){for(;e.size>200;){const r=e.keys().next().value;if(!r)break;e.delete(r),t.delete(r)}}(e,t),{message:i,style:n.style,model:n.model}}}}():void 0}export function createProgressNarrationEvent(e){if(!e.narrator||"runtime.progress.narration"===e.source.type)return;const t=readProgressPolicy(e.policy),r=!1===e.options?void 0:e.options,n=e.narrator.narrate(e.source,{style:r?.style??t.style,model:r?.model??t.model});return function isPromiseLike(e){return isRecord(e)&&"function"==typeof e.then}(n)?n.then(t=>toNarrationEvent(e.source,e.narrator,t)):toNarrationEvent(e.source,e.narrator,n)}export function createProgressNarrationCapability(e){const t=resolveProgressNarrator(e);if(t)return{id:"runtime.progress.narration",onEvent(r,n){try{const o=createProgressNarrationEvent({source:r,narrator:t,options:e.options,policy:e.policy});!function isRuntimeEventPromise(e){return isRecord(e)&&"function"==typeof e.then}(o)?o&&n(o):o.then(e=>{e&&n(e)}).catch(()=>{})}catch{return}}}}function toNarrationEvent(e,t,r){if(r?.message.trim())return{type:"runtime.progress.narration",requestId:e.requestId,sessionId:e.sessionId,agentId:e.agentId,message:r.message,provider:t.name,sourceEventTypes:r.sourceEventTypes??[e.type],sourceEventIds:r.sourceEventIds??(e.eventId?[e.eventId]:void 0),model:r.model,style:r.style}}function inventoryRepairMessage(e,t,r){return"repaired"===e?r?`${t} 选择已按 workspace inventory 修正。`:`${t} selection was repaired against the workspace inventory.`:r?`${t} 选择不在 workspace inventory 中,已被阻止。`:`${t} selection was blocked because it is outside the workspace inventory.`}function summarizeText(e){const t=e?.replace(/\s+/gu," ").trim();return t?t.length>120?`${t.slice(0,117)}...`:t:""}function readString(e){return"string"==typeof e&&e.trim()?e:void 0}function readProgressPolicy(e){const t=isRecord(e?.progress)?e.progress:{},r=isRecord(t.narration)?t.narration:{};return{enabled:"boolean"==typeof r.enabled?r.enabled:void 0,style:"string"==typeof r.style?r.style:void 0,model:"string"==typeof r.model?r.model:void 0}}function isRecord(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}
|
|
1
|
+
export function resolveProgressNarrator(e){if(!1===e.options)return;const t=readProgressPolicy(e.policy);return e.options?.enabled??t.enabled?e.options?.provider??function createTemplateProgressNarrator(){const e=new Map,t=new Map;return{name:"template",narrate(r,n){var o;"runtime.request.started"===r.type&&(e.set(r.requestId,{language:(o=r.input??"",/\p{Script=Han}/u.test(o)?"zh":void 0),input:r.input}),t.delete(r.requestId));const i=function templateMessage(e,t){const r="zh"===t?.language;return"runtime.request.started"===e.type?r?`我开始处理这个请求:${summarizeText(e.input)}`:`I'm starting on this request: ${summarizeText(e.input)}`:"runtime.request.completed"===e.type?r?"我已经完成执行链,正在交付最终结果。":"I've finished the execution chain and am returning the final result.":"runtime.request.failed"===e.type?r?"执行链失败了,我会保留具体错误方便定位。":"The execution chain failed; I'm keeping the concrete error visible for diagnosis.":"runtime.request.cancelled"===e.type?r?"这个请求已取消,后续执行会停止。":"The request was cancelled, so the remaining execution will stop.":"runtime.tool.direct.started"===e.type?r?`我正在运行 ${e.toolId}。`:`I'm running ${e.toolId}.`:"runtime.tool.direct.completed"===e.type?r?`${e.toolId} 已返回结果,我会继续使用这份证据。`:`${e.toolId} returned; I'll keep using that evidence.`:"runtime.workflow.started"===e.type?r?`我正在启动 workflow ${e.workflowId}。`:`I'm starting workflow ${e.workflowId}.`:"runtime.workflow.completed"===e.type?r?`workflow ${e.workflowId} 已完成。`:`Workflow ${e.workflowId} is complete.`:"runtime.specDriven.phase.started"===e.type?r?`我正在进入 spec-driven 阶段 ${e.phaseId}。`:`I'm starting spec-driven phase ${e.phaseId}.`:"runtime.specDriven.phase.blocked"===e.type?r?`spec-driven 阶段 ${e.phaseId} 被 gate 阻塞。`:`Spec-driven phase ${e.phaseId} is blocked by a gate.`:"runtime.specDriven.phase.completed"===e.type?r?`spec-driven 阶段 ${e.phaseId} 已完成。`:`Spec-driven phase ${e.phaseId} is complete.`:"runtime.specDriven.phase.verified"===e.type?r?`spec-driven 阶段 ${e.phaseId} 已验证。`:`Spec-driven phase ${e.phaseId} is verified.`:"runtime.artifact.created"===e.type?r?"我已经保存一份运行产物。":"I've saved a runtime artifact.":"runtime.execution.contract.failed"===e.type?r?"运行证据没有满足执行契约,我会进入恢复或失败路径。":"The run evidence did not satisfy the execution contract, so I'll recover or fail explicitly.":"runtime.inventory.repair"===e.type?inventoryRepairMessage(e.status,e.diagnostic.layer,r):"runtime.skill.candidate.created"===e.type?r?`我发现一个可沉淀的 skill 候选:${e.name}。`:`I found a reusable skill candidate: ${e.name}.`:e.type.startsWith("runtime.memory.")?function memoryMessage(e,t){return"runtime.memory.lifecycle"===e.type?t?`我进入记忆阶段:${e.hook}。`:`I'm in the memory lifecycle phase: ${e.hook}.`:"runtime.memory.recall.completed"===e.type?t?`我召回了 ${e.recordIds.length} 条相关记忆。`:`I recalled ${e.recordIds.length} relevant memory records.`:"runtime.memory.candidate.submitted"===e.type?t?"我提交了一条候选记忆。":"I submitted a memory candidate.":"runtime.memory.approval.requested"===e.type?t?"我提交了记忆审批请求。":"I requested memory approval.":"runtime.memory.plugin.started"===e.type?t?`我正在运行记忆插件 ${e.provider}。`:`I'm running memory plugin ${e.provider}.`:"runtime.memory.plugin.completed"===e.type?t?`记忆插件 ${e.provider} 已完成。`:`Memory plugin ${e.provider} completed.`:"runtime.memory.plugin.failed"===e.type?t?`记忆插件 ${e.provider} 失败了;主任务会继续,不把它当成执行结果。`:`Memory plugin ${e.provider} failed; the main task will continue without treating it as the result.`:"runtime.memory.maintenance.started"===e.type?t?`我正在维护 ${e.target} 记忆。`:`I'm maintaining ${e.target} memory.`:"runtime.memory.maintenance.completed"===e.type?t?`${e.target} 记忆维护完成。`:`${e.target} memory maintenance completed.`:"runtime.memory.maintenance.failed"===e.type?t?`${e.target} 记忆维护失败。`:`${e.target} memory maintenance failed.`:void 0}(e,r):"runtime.adapter.event"===e.type?function adapterMessage(e,t){if(isRecord(e)){if("agent.handoff"===e.phase)return t?"我把请求交给上游 agent backend,让它负责规划和执行。":"I'm handing the request to the upstream agent backend for planning and execution.";if(function isToolStartEvent(e){return"deepagents.tool_execution.start"===e.eventType||"agent.tool.start"===e.phase}(e)&&"string"==typeof e.toolId)return function toolStartMessage(e,t,r){if("task"===e){const e=function readTaskTarget(e){const t=isRecord(e)?e:{};return readString(t.subagent_type)??readString(t.subagentType)}(t),n=function readDescription(e){const t=isRecord(e)?e:{};return summarizeText(readString(t.description)??readString(t.task))}(t);if(e&&n)return r?`我正在请求 task 工具委派给 ${e}:${n}`:`I'm asking the task tool to delegate to ${e}: ${n}`;if(e)return r?`我正在请求 task 工具委派给 ${e}。`:`I'm asking the task tool to delegate to ${e}.`}return r?`我正在运行 ${e} 收集证据。`:`I'm running ${e} to gather evidence.`}(e.toolId,e.args,t);if(function isToolResultEvent(e){return"deepagents.tool_execution.result"===e.eventType||"agent.tool.result"===e.phase}(e)&&"string"==typeof e.toolId)return function toolResultMessage(e,t,r,n,o){if(r)return o?`${e} 返回错误:${summarizeText(String(r))}`:`${e} returned an error: ${summarizeText(String(r))}`;const i="string"==typeof n?n:function readToolControlStatus(e){const t=function parseToolOutputRecord(e){if(isRecord(e))return e;if("string"==typeof e)try{const t=JSON.parse(e);return isRecord(t)?t:void 0}catch{return}}(e);return"string"==typeof t?.status?t.status:"string"==typeof t?.error?t.error:"string"==typeof e&&e.startsWith("Task delegation target is not in the workspace inventory")?"task_inventory_blocked":void 0}(t);if(i)return function toolControlMessage(e,t,r){return"duplicate_tool_call"===t?r?`${e} 重复调用已复用已有证据。`:`${e} repeated an equivalent call, so the existing evidence was reused.`:"repeated_tool_call_limit"===t?r?`${e} 出现重复调用循环,我会基于已有证据继续收敛。`:`${e} entered a repeated-call loop, so I'll continue from the evidence already collected.`:"tool_argument_error"===t||"tool_argument_validation_failed"===t?r?`${e} 参数被工具 schema 拒绝,我会让 agent 修正参数或改用合适工具。`:`${e} arguments were rejected by the tool schema; I'll have the agent repair them or choose a suitable tool.`:"task_inventory_blocked"===t?r?"task 委派目标不在当前 workspace inventory 中,已被运行时策略阻止。":"The task delegation target is not in the current workspace inventory and was blocked by runtime policy.":r?`${e} 返回运行时控制状态:${t}。`:`${e} returned runtime control status: ${t}.`}(e,i,o);if("task"===e)return o?"委派任务已返回结果,我会基于这些证据继续推进。":"The delegated task returned; I'll keep going with that evidence.";const a=function summarizeToolOutput(e){if("string"==typeof e)return summarizeText(e);if(isRecord(e)){if("string"==typeof e.status)return summarizeText(e.status);if("string"==typeof e.summary)return summarizeText(e.summary)}}(t);return o?`${e} 已返回${a?`:${a}`:",我会继续判断下一步。"}`:`${e} returned${a?`: ${a}`:"; I'll decide the next step from here."}`}(e.toolId,e.output,e.error,e.controlStatus,t);if("agent.langgraph.invoke"===e.phase)return t?"我正在调用 workflow backend。":"I'm invoking the workflow backend.";if("agent.node.completed"===e.phase&&"string"==typeof e.nodeId)return t?`节点 ${e.nodeId} 已完成。`:`Node ${e.nodeId} is complete.`;if("inventory.repair"===e.phase&&"string"==typeof e.status){const r=isRecord(e.diagnostic)?e.diagnostic:{};return inventoryRepairMessage(e.status,readString(r.layer)??"selection",t)}}}(e.event,r):void 0}(r,e.get(r.requestId));if(i&&i!==t.get(r.requestId))return t.set(r.requestId,i),"runtime.request.failed"!==r.type&&"runtime.request.cancelled"!==r.type||(e.delete(r.requestId),t.delete(r.requestId)),function pruneRequestState(e,t){for(;e.size>200;){const r=e.keys().next().value;if(!r)break;e.delete(r),t.delete(r)}}(e,t),{message:i,style:n.style,model:n.model}}}}():void 0}export function createProgressNarrationEvent(e){if(!e.narrator||"runtime.progress.narration"===e.source.type)return;const t=readProgressPolicy(e.policy),r=!1===e.options?void 0:e.options,n=e.narrator.narrate(e.source,{style:r?.style??t.style,model:r?.model??t.model});return function isPromiseLike(e){return isRecord(e)&&"function"==typeof e.then}(n)?n.then(t=>toNarrationEvent(e.source,e.narrator,t)):toNarrationEvent(e.source,e.narrator,n)}export function createProgressNarrationCapability(e){const t=resolveProgressNarrator(e);if(t)return{id:"runtime.progress.narration",onEvent(r,n){try{const o=createProgressNarrationEvent({source:r,narrator:t,options:e.options,policy:e.policy});!function isRuntimeEventPromise(e){return isRecord(e)&&"function"==typeof e.then}(o)?o&&n(o):o.then(e=>{e&&n(e)}).catch(()=>{})}catch{return}}}}function toNarrationEvent(e,t,r){if(r?.message.trim())return{type:"runtime.progress.narration",requestId:e.requestId,sessionId:e.sessionId,agentId:e.agentId,message:r.message,provider:t.name,sourceEventTypes:r.sourceEventTypes??[e.type],sourceEventIds:r.sourceEventIds??(e.eventId?[e.eventId]:void 0),model:r.model,style:r.style}}function inventoryRepairMessage(e,t,r){return"repaired"===e?r?`${t} 选择已按 workspace inventory 修正。`:`${t} selection was repaired against the workspace inventory.`:r?`${t} 选择不在 workspace inventory 中,已被阻止。`:`${t} selection was blocked because it is outside the workspace inventory.`}function summarizeText(e){const t=e?.replace(/\s+/gu," ").trim();return t?t.length>120?`${t.slice(0,117)}...`:t:""}function readString(e){return"string"==typeof e&&e.trim()?e:void 0}function readProgressPolicy(e){const t=isRecord(e?.progress)?e.progress:{},r=isRecord(t.narration)?t.narration:{};return{enabled:"boolean"==typeof r.enabled?r.enabled:void 0,style:"string"==typeof r.style?r.style:void 0,model:"string"==typeof r.model?r.model:void 0}}function isRecord(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
export function createDelegationTraceProjection(e,t={}){return{traceType:"delegation",traceLabel:e,...t}}export function createPlanTraceProjection(e,t={}){return{traceType:"plan",traceLabel:e,...t}}export function projectRuntimeTrace(e){return e.events.map(projectEvent).filter(isTraceEntry)}export function projectRuntimeTraceSpans(e){const t=function createSpanBuilder(e){const t=`run:${e.requestId}`,r=[],o=new Map;return{ensureRoot(){if(o.has(t))return;const n={spanId:t,requestId:e.requestId,sessionId:e.sessionId,agentId:e.agentId,kind:"run",name:e.agentId,status:(a=e.state,"completed"===a?"completed":"failed"===a?"failed":"cancelled"===a?"blocked":"running"),startedAt:e.startedAt,completedAt:e.completedAt,startEventIndex:0,...e.parentRunId?{parentSpanId:`run:${e.parentRunId}`}:{},events:[]};var a;r.push(n),o.set(t,n)},markRoot(e,r,n,a){const i=o.get(t);i&&(addEvent(i,e,r),i.status=n,i.attributes=merge(i.attributes,a),"running"!==n&&close(i,e,r))},start(e,n,a,i,s,d){const p=createSpan(`${t}/${e}:${s}`,t,n,a,i,s,d);r.push(p),o.set(e,p)},complete(e,n,a,i){const s=o.get(e)??createSpan(`${t}/${e}:${a}`,t,"adapter",e,n,a);return o.has(e)||r.push(s),addEvent(s,n,a),s.attributes=merge(s.attributes,i),close(s,n,a),o.delete(e),s},fail(e,t,r,o){this.complete(e,t,r,o).status="failed"},event(e,o,n,a,i){const s=createSpan(`${t}/event:${a}`,t,e,o,n,a,i);s.status=function readBlockedStatus(e){return e.type.endsWith(".blocked")||e.type.includes(".approval.")?"blocked":void 0}(n)??"event",close(s,n,a),r.push(s)},closeRoot(){const r=o.get(t);r&&e.completedAt&&(r.completedAt=e.completedAt)},spans:()=>r}}(e);return t.ensureRoot(),e.events.forEach((e,r)=>function projectSpanEvent(e,t,r){return t.type.startsWith("runtime.request.")?function projectRequestSpanEvent(e,t,r){return"runtime.request.started"===t.type?e.markRoot(t,r,"running",{input:t.input}):"runtime.request.completed"===t.type?e.markRoot(t,r,"completed",{output:t.output}):"runtime.request.failed"===t.type?e.markRoot(t,r,"failed",{error:t.error}):"runtime.request.cancelled"===t.type?e.markRoot(t,r,"blocked",{reason:t.reason}):"runtime.execution.contract.failed"===t.type?projectSingleSpan(e,t,r,"quality",t.type,{reason:t.reason,missingEvidenceTools:t.missingEvidenceTools}):void 0}(e,t,r):"runtime.tool.direct.started"===t.type?e.start(`tool:${t.toolId}`,"tool",t.toolId,t,r,{toolId:t.toolId}):"runtime.tool.direct.completed"===t.type?e.complete(`tool:${t.toolId}`,t,r,{toolId:t.toolId,output:t.output}):"runtime.workflow.started"===t.type?e.start(`workflow:${t.workflowId}`,"workflow",t.workflowId,t,r,{workflowId:t.workflowId,adapter:t.adapter}):"runtime.workflow.completed"===t.type?e.complete(`workflow:${t.workflowId}`,t,r,{workflowId:t.workflowId,adapter:t.adapter}):t.type.startsWith("runtime.approval.")||t.type.startsWith("runtime.memory.approval.")?projectSingleSpan(e,t,r,"approval",t.type):t.type.startsWith("runtime.specDriven.phase.")?projectSingleSpan(e,t,r,"spec",function readPhaseName(e,t){return"phaseId"in e&&"string"==typeof e.phaseId?e.phaseId:t}(t,"phase")):t.type.startsWith("runtime.memory.")?projectSingleSpan(e,t,r,"memory",t.type):t.type.startsWith("runtime.quality.")?projectSingleSpan(e,t,r,"quality",t.type):"runtime.artifact.created"===t.type?projectSingleSpan(e,t,r,"artifact",t.artifact.id,{artifact:t.artifact}):"runtime.progress.narration"===t.type?projectSingleSpan(e,t,r,"progress",t.message,{provider:t.provider}):"runtime.adapter.event"===t.type?function projectAdapterSpanEvent(e,t,r){const o=isRecord(t.event)?t.event:void 0,n=readString(o?.phase)??"runtime.adapter.event",a=readTraceType(o?.traceType),i=readString(o?.traceLabel);return"delegation"===a&&i?.endsWith(".start")?e.start(delegationKey(o),"delegation",readString(o?.subagentType)??i,t,r,o):"delegation"===a&&i?.endsWith(".completed")?e.complete(delegationKey(o),t,r,o):"plan"===a&&i?projectSingleSpan(e,t,r,"plan",i,o):"agent.tool.start"===
|
|
1
|
+
export function createDelegationTraceProjection(e,t={}){return{traceType:"delegation",traceLabel:e,...t}}export function createPlanTraceProjection(e,t={}){return{traceType:"plan",traceLabel:e,...t}}export function projectRuntimeTrace(e){return e.events.map(projectEvent).filter(isTraceEntry)}export function projectRuntimeTraceSpans(e){const t=function createSpanBuilder(e){const t=`run:${e.requestId}`,r=[],o=new Map;return{ensureRoot(){if(o.has(t))return;const n={spanId:t,requestId:e.requestId,sessionId:e.sessionId,agentId:e.agentId,kind:"run",name:e.agentId,status:(a=e.state,"completed"===a?"completed":"failed"===a?"failed":"cancelled"===a?"blocked":"running"),startedAt:e.startedAt,completedAt:e.completedAt,startEventIndex:0,...e.parentRunId?{parentSpanId:`run:${e.parentRunId}`}:{},events:[]};var a;r.push(n),o.set(t,n)},markRoot(e,r,n,a){const i=o.get(t);i&&(addEvent(i,e,r),i.status=n,i.attributes=merge(i.attributes,a),"running"!==n&&close(i,e,r))},start(e,n,a,i,s,d){const p=createSpan(`${t}/${e}:${s}`,t,n,a,i,s,d);r.push(p),o.set(e,p)},complete(e,n,a,i){const s=o.get(e)??createSpan(`${t}/${e}:${a}`,t,"adapter",e,n,a);return o.has(e)||r.push(s),addEvent(s,n,a),s.attributes=merge(s.attributes,i),close(s,n,a),o.delete(e),s},fail(e,t,r,o){this.complete(e,t,r,o).status="failed"},event(e,o,n,a,i){const s=createSpan(`${t}/event:${a}`,t,e,o,n,a,i);s.status=function readBlockedStatus(e){return e.type.endsWith(".blocked")||e.type.includes(".approval.")?"blocked":void 0}(n)??"event",close(s,n,a),r.push(s)},closeRoot(){const r=o.get(t);r&&e.completedAt&&(r.completedAt=e.completedAt)},spans:()=>r}}(e);return t.ensureRoot(),e.events.forEach((e,r)=>function projectSpanEvent(e,t,r){return t.type.startsWith("runtime.request.")?function projectRequestSpanEvent(e,t,r){return"runtime.request.started"===t.type?e.markRoot(t,r,"running",{input:t.input}):"runtime.request.completed"===t.type?e.markRoot(t,r,"completed",{output:t.output}):"runtime.request.failed"===t.type?e.markRoot(t,r,"failed",{error:t.error}):"runtime.request.cancelled"===t.type?e.markRoot(t,r,"blocked",{reason:t.reason}):"runtime.execution.contract.failed"===t.type?projectSingleSpan(e,t,r,"quality",t.type,{reason:t.reason,missingEvidenceTools:t.missingEvidenceTools}):void 0}(e,t,r):"runtime.tool.direct.started"===t.type?e.start(`tool:${t.toolId}`,"tool",t.toolId,t,r,{toolId:t.toolId}):"runtime.tool.direct.completed"===t.type?e.complete(`tool:${t.toolId}`,t,r,{toolId:t.toolId,output:t.output}):"runtime.workflow.started"===t.type?e.start(`workflow:${t.workflowId}`,"workflow",t.workflowId,t,r,{workflowId:t.workflowId,adapter:t.adapter}):"runtime.workflow.completed"===t.type?e.complete(`workflow:${t.workflowId}`,t,r,{workflowId:t.workflowId,adapter:t.adapter}):t.type.startsWith("runtime.approval.")||t.type.startsWith("runtime.memory.approval.")?projectSingleSpan(e,t,r,"approval",t.type):t.type.startsWith("runtime.specDriven.phase.")?projectSingleSpan(e,t,r,"spec",function readPhaseName(e,t){return"phaseId"in e&&"string"==typeof e.phaseId?e.phaseId:t}(t,"phase")):t.type.startsWith("runtime.memory.")?projectSingleSpan(e,t,r,"memory",t.type):t.type.startsWith("runtime.quality.")?projectSingleSpan(e,t,r,"quality",t.type):"runtime.artifact.created"===t.type?projectSingleSpan(e,t,r,"artifact",t.artifact.id,{artifact:t.artifact}):"runtime.progress.narration"===t.type?projectSingleSpan(e,t,r,"progress",t.message,{provider:t.provider}):"runtime.adapter.event"===t.type?function projectAdapterSpanEvent(e,t,r){const o=isRecord(t.event)?t.event:void 0,n=readString(o?.phase)??"runtime.adapter.event",a=readTraceType(o?.traceType),i=readString(o?.traceLabel);return"delegation"===a&&i?.endsWith(".start")?e.start(delegationKey(o),"delegation",readString(o?.subagentType)??i,t,r,o):"delegation"===a&&i?.endsWith(".completed")?e.complete(delegationKey(o),t,r,o):"plan"===a&&i?projectSingleSpan(e,t,r,"plan",i,o):function isToolStartEvent(e){return"deepagents.tool_execution.start"===e?.eventType||"agent.tool.start"===e?.phase}(o)?e.start(`agent-tool:${readString(o?.toolId)??"unknown"}`,"tool",readString(o?.toolId)??n,t,r,o):function isToolResultEvent(e){return"deepagents.tool_execution.result"===e?.eventType||"agent.tool.result"===e?.phase}(o)?e.complete(`agent-tool:${readString(o?.toolId)??"unknown"}`,t,r,o):projectSingleSpan(e,t,r,"adapter",n,o)}(e,t,r):"runtime.inventory.repair"===t.type?projectSingleSpan(e,t,r,"adapter","runtime.inventory.repair",{status:t.status,...t.diagnostic}):"runtime.sandbox.decision"===t.type?projectSingleSpan(e,t,r,"tool",`sandbox:${t.toolId}`,{toolId:t.toolId,...t.decision}):"runtime.tool.failure"===t.type?e.fail(`tool:${t.toolId}`,t,r,{toolId:t.toolId,...t.failure}):"runtime.tool.circuit.opened"===t.type?projectSingleSpan(e,t,r,"tool",`circuit:${t.toolId}`,{toolId:t.toolId,reason:t.reason}):void 0}(t,e,r)),t.closeRoot(),t.spans()}export function projectEvent(e){return"runtime.request.started"===e.type||"runtime.request.completed"===e.type||"runtime.request.failed"===e.type?base(e,"request",e.type):"runtime.request.cancelled"===e.type?base(e,"request",e.type,{reason:e.reason}):"runtime.execution.contract.failed"===e.type?base(e,"request",e.type,{reason:e.reason,missingEvidenceTools:e.missingEvidenceTools}):"runtime.inventory.repair"===e.type?base(e,"adapter","runtime.inventory.repair",{status:e.status,...e.diagnostic}):"runtime.tool.direct.started"===e.type?base(e,"tool","runtime.tool.direct.started",{toolId:e.toolId}):"runtime.tool.direct.completed"===e.type?base(e,"tool","runtime.tool.direct.completed",{toolId:e.toolId}):"runtime.sandbox.decision"===e.type?base(e,"tool","runtime.sandbox.decision",{toolId:e.toolId,...e.decision}):"runtime.tool.failure"===e.type?base(e,"tool","runtime.tool.failure",{toolId:e.toolId,...e.failure}):"runtime.tool.circuit.opened"===e.type?base(e,"tool","runtime.tool.circuit.opened",{toolId:e.toolId,reason:e.reason}):"runtime.workflow.started"===e.type||"runtime.workflow.completed"===e.type?base(e,"workflow",e.type,{workflowId:e.workflowId,adapter:e.adapter}):function isSpecDrivenPhaseEvent(e){return e.type.startsWith("runtime.specDriven.phase.")}(e)?base(e,"spec",e.type,{phaseId:e.phaseId,..."workflowId"in e&&e.workflowId?{workflowId:e.workflowId}:{},..."reason"in e?{reason:e.reason}:{},..."artifact"in e&&e.artifact?{artifact:e.artifact}:{}}):"runtime.adapter.event"===e.type?function adapterTrace(e){const t=e.event;if(isRecord(t)&&"string"==typeof t.phase){const r=function semanticAdapterTrace(e,t){if("inventory.repair"===t.phase)return base(e,"adapter","runtime.inventory.repair",{status:t.status,...isRecord(t.diagnostic)?t.diagnostic:{}});const r=readTraceType(t.traceType),o=readString(t.traceLabel);return r&&o?base(e,r,o,t):void 0}(e,t);return r||base(e,"adapter",t.phase.startsWith("agent.")?t.phase:`adapter.${t.phase}`,t)}return base(e,"adapter","runtime.adapter.event",{event:t})}(e):"runtime.artifact.created"===e.type?base(e,"artifact","runtime.artifact.created",{artifact:e.artifact}):e.type.startsWith("runtime.memory.")?base(e,"memory",e.type):"runtime.progress.narration"===e.type?base(e,"progress",e.type,{message:e.message,provider:e.provider,sourceEventTypes:e.sourceEventTypes}):void 0}export function readPlanTodos(e){const t=function readPlanRecord(e){if(isRecord(e))return e;if("string"==typeof e)try{const t=JSON.parse(e);return isRecord(t)?t:void 0}catch{return}}(e),r=function readTodosArray(e){const t=isRecord(e?.args)?e.args:void 0;return Array.isArray(e?.todos)?e.todos:Array.isArray(t?.todos)?t.todos:[]}(t);return r.map(readTodo).filter(isPlanTodoItem)}function readTodo(e){if(isRecord(e)&&"string"==typeof e.content)return{content:e.content,status:"string"==typeof e.status?e.status:"pending"}}function isPlanTodoItem(e){return void 0!==e}function base(e,t,r,o){return{type:t,label:r,agentId:e.agentId,requestId:e.requestId,detail:o}}function isTraceEntry(e){return void 0!==e}function projectSingleSpan(e,t,r,o,n,a){return e.event(o,n,t,r,a)}function delegationKey(e){return`delegation:${readString(e?.subagentType)??readString(e?.toolId)??"task"}`}function createSpan(e,t,r,o,n,a,i){const s={spanId:e,parentSpanId:t,requestId:n.requestId,sessionId:n.sessionId,agentId:n.agentId,kind:r,name:o,status:"running",startedAt:n.emittedAt,startEventIndex:a,attributes:i,events:[]};return addEvent(s,n,a),s}function addEvent(e,t,r){e.events.push({index:r,eventId:t.eventId??`${t.requestId}:${r}`,type:t.type,emittedAt:t.emittedAt})}function close(e,t,r){e.status="failed"===e.status||"blocked"===e.status?e.status:"completed",e.completedAt=t.emittedAt,e.endEventIndex=r,e.durationMs=function durationMs(e,t){if(!e||!t)return;const r=Date.parse(t)-Date.parse(e);return Number.isFinite(r)&&r>=0?r:void 0}(e.startedAt,e.completedAt)}function merge(e,t){return t?{...e,...t}:e}function isRecord(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function readTraceType(e){const t=readString(e);return"request"===t||"tool"===t||"workflow"===t||"spec"===t||"adapter"===t||"memory"===t||"artifact"===t||"progress"===t||"plan"===t||"delegation"===t?t:void 0}function readString(e){return"string"==typeof e&&e.trim()?e:void 0}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
export function computeToolCallMetrics(t){const e=function createCounters(){return{toolStarted:0,toolCompleted:0,toolFailures:0,inventoryRepairs:0,inventoryRepairBlocks:0,argumentFailureCount:0,transientFailureCount:0,controlFailureCount:0,businessFailureCount:0,circuitOpenCount:0,firstAttemptArgumentValidityRate:void 0,schemaRepairFailureRate:void 0,repairRate:void 0,failureRate:void 0,perTool:new Map}}();for(const o of t)applyEvent(e,o);return{...e,firstAttemptArgumentValidityRate:rate(e.toolStarted-e.argumentFailureCount,e.toolStarted),schemaRepairFailureRate:rate(e.argumentFailureCount,e.toolStarted),repairRate:rate(e.inventoryRepairs,e.toolStarted+e.inventoryRepairs),failureRate:rate(e.toolFailures,e.toolStarted),perTool:Object.fromEntries([...e.perTool.entries()])}}function applyEvent(t,e){"runtime.tool.direct.started"===e.type?(t.toolStarted+=1,perTool(t,e.toolId).started+=1):"runtime.tool.direct.completed"===e.type?(t.toolCompleted+=1,perTool(t,e.toolId).completed+=1):"runtime.tool.failure"===e.type?function applyFailure(t,e){t.toolFailures+=1,perTool(t,e.toolId).failures+=1,"transient"===e.failure.kind&&(t.transientFailureCount+=1),"control"===e.failure.kind&&(t.controlFailureCount+=1),"business"===e.failure.kind&&(t.businessFailureCount+=1),"invalid_input"!==e.failure.reason&&"schema_repair_failed"!==e.failure.reason||(t.argumentFailureCount+=1)}(t,e):"runtime.tool.circuit.opened"===e.type?(t.circuitOpenCount+=1,perTool(t,e.toolId).circuitOpen+=1):"runtime.inventory.repair"===e.type?function applyInventoryRepair(t,e){if("repaired"===e.status){t.inventoryRepairs+=1;for(const o of[e.diagnostic.originalId,e.diagnostic.repairedId].filter(isString))perTool(t,o).inventoryRepairs+=1}else t.inventoryRepairBlocks+=1}(t,e):"runtime.adapter.event"===e.type&&function applyAdapterEvent(t,e){(function isRecord(t){return"object"==typeof t&&null!==t&&!Array.isArray(t)})(e)&&("agent.tool.start"===
|
|
1
|
+
export function computeToolCallMetrics(t){const e=function createCounters(){return{toolStarted:0,toolCompleted:0,toolFailures:0,inventoryRepairs:0,inventoryRepairBlocks:0,argumentFailureCount:0,transientFailureCount:0,controlFailureCount:0,businessFailureCount:0,circuitOpenCount:0,firstAttemptArgumentValidityRate:void 0,schemaRepairFailureRate:void 0,repairRate:void 0,failureRate:void 0,perTool:new Map}}();for(const o of t)applyEvent(e,o);return{...e,firstAttemptArgumentValidityRate:rate(e.toolStarted-e.argumentFailureCount,e.toolStarted),schemaRepairFailureRate:rate(e.argumentFailureCount,e.toolStarted),repairRate:rate(e.inventoryRepairs,e.toolStarted+e.inventoryRepairs),failureRate:rate(e.toolFailures,e.toolStarted),perTool:Object.fromEntries([...e.perTool.entries()])}}function applyEvent(t,e){"runtime.tool.direct.started"===e.type?(t.toolStarted+=1,perTool(t,e.toolId).started+=1):"runtime.tool.direct.completed"===e.type?(t.toolCompleted+=1,perTool(t,e.toolId).completed+=1):"runtime.tool.failure"===e.type?function applyFailure(t,e){t.toolFailures+=1,perTool(t,e.toolId).failures+=1,"transient"===e.failure.kind&&(t.transientFailureCount+=1),"control"===e.failure.kind&&(t.controlFailureCount+=1),"business"===e.failure.kind&&(t.businessFailureCount+=1),"invalid_input"!==e.failure.reason&&"schema_repair_failed"!==e.failure.reason||(t.argumentFailureCount+=1)}(t,e):"runtime.tool.circuit.opened"===e.type?(t.circuitOpenCount+=1,perTool(t,e.toolId).circuitOpen+=1):"runtime.inventory.repair"===e.type?function applyInventoryRepair(t,e){if("repaired"===e.status){t.inventoryRepairs+=1;for(const o of[e.diagnostic.originalId,e.diagnostic.repairedId].filter(isString))perTool(t,o).inventoryRepairs+=1}else t.inventoryRepairBlocks+=1}(t,e):"runtime.adapter.event"===e.type&&function applyAdapterEvent(t,e){(function isRecord(t){return"object"==typeof t&&null!==t&&!Array.isArray(t)})(e)&&(function isToolStart(t){return"deepagents.tool_execution.start"===t.eventType||"agent.tool.start"===t.phase}(e)&&"string"==typeof e.toolId?(t.toolStarted+=1,perTool(t,e.toolId).started+=1):function isToolResult(t){return"deepagents.tool_execution.result"===t.eventType||"agent.tool.result"===t.phase}(e)&&"string"==typeof e.toolId&&(t.toolCompleted+=1,perTool(t,e.toolId).completed+=1))}(t,e.event)}function perTool(t,e){const o=t.perTool.get(e);if(o)return o;const r={started:0,completed:0,failures:0,inventoryRepairs:0,circuitOpen:0};return t.perTool.set(e,r),r}function rate(t,e){return e>0?t/e:void 0}function isString(t){return"string"==typeof t&&t.length>0}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
export function missingFinalDelta(e,t){return e?!t||e.includes(t)?"":t.startsWith(e)?t.slice(e.length):t:t}export function createRoleChunk(e,t){return createChunk(e,t,{role:"assistant"},null)}export function createContentChunk(e,t,n){return createChunk(e,t,{content:n},null)}export function createStopChunk(e,t){return createChunk(e,t,{},"stop")}export function writeRuntimeStreamEvent(e,t,n,r){const o=function readAdapterDelta(e){if("runtime.adapter.event"!==e.type||"object"!=typeof e.event||null===e.event)return;const t=e.event;return"agent.output.delta"
|
|
1
|
+
export function missingFinalDelta(e,t){return e?!t||e.includes(t)?"":t.startsWith(e)?t.slice(e.length):t:t}export function createRoleChunk(e,t){return createChunk(e,t,{role:"assistant"},null)}export function createContentChunk(e,t,n){return createChunk(e,t,{content:n},null)}export function createStopChunk(e,t){return createChunk(e,t,{},"stop")}export function writeRuntimeStreamEvent(e,t,n,r){const o=function readAdapterDelta(e){if("runtime.adapter.event"!==e.type||"object"!=typeof e.event||null===e.event)return;const t=e.event;return"deepagents.message.coordinator_delta"!==t.eventType&&"agent.output.delta"!==t.phase||"string"!=typeof t.text?void 0:t.text}(t);if(o)return writeChatSse(e,createContentChunk(n,r,o)),o;!function writeProgressEvent(e,t){const n=function readToolProgress(e){if("runtime.tool.direct.started"===e.type||"runtime.tool.direct.completed"===e.type)return{request_id:e.requestId,session_id:e.sessionId,agent_id:e.agentId,type:e.type,tool_id:e.toolId};if("runtime.adapter.event"!==e.type||"object"!=typeof e.event||null===e.event)return;const t=e.event,n=function readToolProgressType(e){return"deepagents.tool_execution.start"===e.eventType?"deepagents.tool_execution.start":"deepagents.tool_execution.result"===e.eventType?"deepagents.tool_execution.result":"agent.tool.start"===e.phase||"agent.tool.result"===e.phase?e.phase:void 0}(t),r="string"==typeof t.toolId?t.toolId:void 0;return n&&r?{request_id:e.requestId,session_id:e.sessionId,agent_id:e.agentId,type:n,tool_id:r,adapter:t.adapter}:void 0}(t);n&&writeSse(e,"stable_harness.tool.progress",n)}(e,t),function writeNarrationEvent(e,t){"runtime.progress.narration"===t.type&&writeSse(e,"stable_harness.progress.narration",{request_id:t.requestId,session_id:t.sessionId,agent_id:t.agentId,type:t.type,message:t.message,provider:t.provider,source_event_types:t.sourceEventTypes,source_event_ids:t.sourceEventIds,model:t.model,style:t.style})}(e,t)}export function writeSseHeaders(e,t){e.writeHead(200,{"content-type":"text/event-stream","cache-control":"no-cache",connection:"keep-alive",...t})}export function writeChatSse(e,t){e.write(`data: ${JSON.stringify(t)}\n\n`)}function createChunk(e,t,n,r){return{id:e,object:"chat.completion.chunk",created:Math.floor(Date.now()/1e3),model:t??"stable-harness",choices:[{index:0,delta:n,finish_reason:r}]}}function writeSse(e,t,n){e.write(`event: ${t}\n`),e.write(`data: ${JSON.stringify(n)}\n\n`)}
|