stable-harness 0.0.19 → 0.0.21
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/docs/guides/operator-runbook.md +6 -0
- package/package.json +1 -1
- package/packages/adapter-deepagents/dist/src/internal/builtin-tool-policy.js +1 -1
- package/packages/adapter-deepagents/dist/src/internal/gateway/tool-evidence.d.ts +10 -0
- package/packages/adapter-deepagents/dist/src/internal/gateway/tool-evidence.js +1 -0
- package/packages/adapter-deepagents/dist/src/internal/gateway-tools.d.ts +0 -6
- package/packages/adapter-deepagents/dist/src/internal/gateway-tools.js +1 -1
- package/packages/core/dist/execution-contract.js +1 -1
- package/packages/core/dist/quality/event-evidence.d.ts +1 -0
- package/packages/core/dist/quality/event-evidence.js +1 -1
- package/packages/core/dist/quality/execution-review.js +1 -1
- package/packages/core/dist/quality/profile.js +1 -1
- package/packages/core/dist/quality/recovery-policy.d.ts +1 -0
- package/packages/core/dist/quality/recovery-policy.js +1 -1
- package/packages/core/dist/quality/runtime.js +1 -1
- package/packages/core/dist/quality/types.d.ts +1 -0
|
@@ -20,6 +20,12 @@ npm run release:pack
|
|
|
20
20
|
npm run release:smoke
|
|
21
21
|
```
|
|
22
22
|
|
|
23
|
+
Stable Harness publishes compiled npm artifacts only. The package must not
|
|
24
|
+
include TypeScript sources, source maps, source-map content markers, tests,
|
|
25
|
+
scripts, examples, benchmarks, or development-only source directories. The
|
|
26
|
+
release package may include compiled JavaScript, declaration files, package
|
|
27
|
+
metadata, docs, README, NOTICE, and LICENSE.
|
|
28
|
+
|
|
23
29
|
`release:smoke` installs the packed package into an isolated temporary project,
|
|
24
30
|
initializes a workspace, and runs a CLI tool call. It catches missing published
|
|
25
31
|
dependencies that monorepo tests can hide.
|
package/package.json
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{realpathSync as e}from"node:fs";import{repairCallSelection as t}from"@botbotgo/better-call";import{ToolMessage as o}from"@langchain/core/messages";import{normalizeArgsRecord as n}from"./builtin-args.js";import{repairBuiltinToolRequest as r}from"./builtin-call-repair.js";import{afterToolInvoke as i,beforeToolInvoke as a,createToolRepeatState as s,
|
|
1
|
+
import{realpathSync as e}from"node:fs";import{repairCallSelection as t}from"@botbotgo/better-call";import{ToolMessage as o}from"@langchain/core/messages";import{normalizeArgsRecord as n}from"./builtin-args.js";import{repairBuiltinToolRequest as r}from"./builtin-call-repair.js";import{afterToolInvoke as i,beforeToolInvoke as a,createToolRepeatState as s,stringifyDeepAgentResult as l,toolControlProjection as u}from"./gateway-tools.js";import{observedToolEvidence as c,recordObservedToolEvidence as d}from"./gateway/tool-evidence.js";import{validateSkillFileBuiltinCall as g}from"./skill-file-policy.js";import{filterRepeatLimitedTools as p}from"./tool-repeat-visibility.js";import{traceProjectionForBuiltinTool as f}from"./trace-projection.js";const m=new Set(["ls","read_file","write_file","edit_file","glob","grep"]),h=new Set(["write_todos","read_todos","task","execute",...m]);export function createBuiltinToolPolicyMiddleware(e,t={}){return{name:"StableHarnessBuiltinToolPolicy",async wrapModelCall(o,n){const r=Array.isArray(o.tools)?p(o.tools.filter(t=>!function hasHiddenBuiltins(e){return isFilesystemDisabled(e)||!isTaskVisible(e)}(e)||isModelVisibleBuiltin(e,t.name)),t.repeatState):o.tools,i=function normalizeToolChoice(e,t,o){return"required"===t?o&&o.length>0?t:"auto":function isForcedHiddenTool(e,t){return"string"==typeof t?.function?.name&&!isModelVisibleBuiltin(e,t.function.name)}(e,t)?"auto":t}(e,o.toolChoice,r);return n({...o,tools:r,toolChoice:i})}}}export function validateFilesystemBuiltinCall(e,t,n){if(isFilesystemDisabled(e)&&m.has(t))return new o({tool_call_id:n.toolCall?.id??`stable-harness-${t}-policy`,name:t,content:`Filesystem builtin tool '${t}' is disabled for this agent. Do not retry filesystem tools; use the agent's registered workspace tools and already collected evidence instead.`})}export function createObserverMiddleware(e,u={}){const d=u.repeatState??s(e.workspace.runtime.toolGateway);return{name:"StableHarnessObserver",async wrapToolCall(s,p){const f=s.toolCall?.name;if(!f||!h.has(f))return p(s);const m=await r({toolId:f,request:s,workspaceRoot:e.workspace.root});emitToolEvent(e,f,"agent.tool.start",m.toolCall?.args);const y="task"===f?await async function repairTaskCall(e,r){const i=function allowedTaskTypes(e){const t=readConfigRecord(e.agent.config,"deepagents");if(!0===t?.generalPurposeAgent)return;const o=readConfigRecord(e.agent.config,"builtinTools")?.modelExposed;return!1===o?[]:Array.isArray(o)?o.includes("task")?e.agent.subagents:[]:0===e.agent.subagents.length?[]:void 0}(e);if(void 0===i)return{request:r};const a=n(r.toolCall?.args),s=function readTaskSubagentType(e){const t=isRecord(e)?e:{};return readString(t.subagent_type)??readString(t.subagentType)}(a);if(s&&i.includes(s))return{request:r};const l=await t({call:{id:s,args:a},candidates:taskCallCandidates(e,i),mode:"repair"});if(l.ok){const e={...a,...l.args,subagent_type:l.candidateId};return{request:{...r,toolCall:{...r.toolCall,args:e}}}}const u=s?`: ${s}`:"",c=i.length>0?i.join(", "):"none";return{request:r,blocked:new o({tool_call_id:r.toolCall?.id??"stable-harness-task-policy",name:"task",status:"error",content:[`Task delegation target is not in the workspace inventory${u}. Allowed task targets: ${c}.`,"Retry with an allowed target only when that target semantically owns the original user request.","Do not substitute another specialist just to continue the same evidence need; synthesize from already collected evidence when no allowed target is a semantic match."].join(" ")})}}(e,m):{request:m},b=y.request,v=y.blocked;if(v)return emitToolEvent(e,f,"agent.tool.result",b.toolCall?.args,{output:v.content}),v;const w=validateFilesystemBuiltinCall(e,f,b);if(w)return emitToolEvent(e,f,"agent.tool.result",b.toolCall?.args,{output:w.content}),w;const k=g(e,f,b);if(k)return emitToolEvent(e,f,"agent.tool.result",b.toolCall?.args,{output:k.content}),k;try{const t=d?a(f,b.toolCall?.args,d):void 0;if(t)return emitToolEvent(e,f,"agent.tool.result",b.toolCall?.args,{output:t.eventOutput}),builtinToolMessage(s,f,t.modelOutput);const o=await p(b),n=function observedToolOutput(e,t,o){return"write_todos"===e?JSON.stringify({status:"recorded",args:t.toolCall?.args}):l(o)}(f,b,o),r=d?i(f,b.toolCall?.args,n,o,d):{};return emitToolEvent(e,f,"agent.tool.result",b.toolCall?.args,{output:r.eventOutput??n}),u.observedToolIds?.add(f),void 0===r.modelOutput?o:builtinToolMessage(s,f,r.modelOutput)}catch(t){const n=function recoverableBuiltinToolError(e,t,n,r){const i=formatError(r);if("task"===t&&/repeat limit reached for tool/iu.test(i)){const t=function formatObservedEvidence(e){const t=c(e);if(0===t.length)return"";const o=t.map(e=>[`Agent: ${e.agentId}`,`Tool: ${e.toolId}`,e.output].join("\n")).join("\n\n---\n\n");return o.length>12e3?`${o.slice(0,12e3)}\n[truncated]`:o}(e);return new o({tool_call_id:n.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.",...t?{observedEvidence:t}:{},error:previewError(i)})})}if(/Received tool input did not match expected schema|Invalid input:/iu.test(i))return new o({tool_call_id:n.toolCall?.id??`stable-harness-${t}-argument-error`,name:t,status:"error",content:JSON.stringify({status:"tool_argument_error",toolId:t,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)})})}(e,f,s,t);if(n)return emitToolEvent(e,f,"agent.tool.result",m.toolCall?.args,{output:n.content}),n;throw emitToolEvent(e,f,"agent.tool.result",m.toolCall?.args,{error:formatError(t)}),t}}}}function builtinToolMessage(e,t,n){return new o({tool_call_id:e.toolCall?.id??`stable-harness-${t}-repeat-guard`,name:t,content:n})}export function resolveFilesystemPermissions(e,t){const o=readConfigRecord(t?.config,"builtinTools"),n=[];if(n.push(...function skillReadPermissions(e,t){const o=[...new Set((t?.skills??[]).flatMap(t=>function skillReadPaths(e,t){return t?[...new Set([t,canonicalPath(t),backendSkillPath(e,t)])].flatMap(e=>function skillReadPathCandidates(e){const t=e.replace(/\/+$/u,""),o=t.endsWith("/SKILL.md")?t.slice(0,-9):t,n=function parentPath(e){const t=e.lastIndexOf("/");return t>0?e.slice(0,t):void 0}(o);return[t,o,`${o}/**`,...n?[n,`${n}/**`]:[]]}(e)):[]}(e.workspace.root,e.workspace.skills.get(t)?.path)).filter(e=>e.startsWith("/")))];return o.length>0?[{operations:["read"],paths:o,mode:"allow"}]:[]}(e,t)),!1!==o?.filesystem){if(deepagentsMemoryWritable(e))return n.length>0?n:void 0}else n.push({operations:["read"],paths:["/memories/**"],mode:"allow"}),n.push({operations:["read","write"],paths:["/**"],mode:"deny"});return deepagentsMemoryWritable(e)||n.push({operations:["write"],paths:["/memories/**"],mode:"deny"}),n.length>0?n:void 0}function emitToolEvent(e,t,o,n,r={}){"string"==typeof r.output&&d(e,e.agent.id,t,r.output),e.emit({type:"runtime.adapter.event",requestId:e.requestId,sessionId:e.sessionId,agentId:e.agent.id,event:{adapter:"deepagents",phase:o,toolId:t,..."agent.tool.start"===o?{args:n}:{},...r,..."string"==typeof r.output?u(r.output):{},...f(t,o,n)}})}function backendSkillPath(e,t){const o=function pathRelative(e,t){const o=e.split("/").filter(Boolean),n=t.split("/").filter(Boolean);if(!(n.length<o.length)){for(let e=0;e<o.length;e+=1)if(o[e]!==n[e])return;return n.slice(o.length).join("/")}}(e,t);return void 0===o?t:`/${o.split("/").filter(Boolean).join("/")}`}function canonicalPath(t){try{return e.native(t)}catch{return t}}function deepagentsMemoryWritable(e){const t=readConfigRecord(e.workspace.runtime.memory,"deepagentsMem");return!1!==t?.write}function taskCallCandidates(e,t){return t.map(t=>({id:t,description:e.workspace.agents.get(t)?.description,schema:{type:"object",properties:{subagent_type:{type:"string"},subagentType:{type:"string"},description:{type:"string"}},required:["description"],additionalProperties:!0}}))}function isFilesystemDisabled(e){const t=readConfigRecord(e.agent.config,"builtinTools");return!1===t?.filesystem}function isTaskVisible(e){const t=readConfigRecord(e.agent.config,"builtinTools")?.modelExposed;return!1!==t&&(!Array.isArray(t)||t.includes("task"))}function isModelVisibleBuiltin(e,t){return(!isFilesystemDisabled(e)||!function isFilesystemTool(e){return"string"==typeof e&&m.has(e)}(t))&&("task"!==t||isTaskVisible(e))}function readConfigRecord(e,t){const o=isRecord(e)?e:{};return isRecord(o[t])?o[t]:void 0}function readString(e){return"string"==typeof e&&e.trim()?e:void 0}function isRecord(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function formatError(e){return e instanceof Error?e.message:String(e)}function previewError(e){const t=e.replace(/\s+/gu," ").trim();return t.length>800?`${t.slice(0,797)}...`:t}
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
import type { RuntimeAdapter } from "@stable-harness/core";
|
|
2
|
+
export type ObservedToolEvidence = {
|
|
3
|
+
agentId: string;
|
|
4
|
+
toolId: string;
|
|
5
|
+
output: string;
|
|
6
|
+
};
|
|
7
|
+
export declare function observedToolEvidence(input: Parameters<RuntimeAdapter["run"]>[0]): ObservedToolEvidence[];
|
|
8
|
+
export declare function recordObservedToolEvidence(input: Parameters<RuntimeAdapter["run"]>[0], agentId: string, toolId: string, output: string): void;
|
|
9
|
+
export declare function isControlOnlyOutput(output: string): boolean;
|
|
10
|
+
export declare function isSuccessfulEvidenceOutput(output: string): boolean;
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
const e="deepagents.observedToolEvidence";export function observedToolEvidence(t){const r=t.requestState?.get(e);return Array.isArray(r)?r:[]}export function recordObservedToolEvidence(t,r,o,n){if(!t.requestState||!isSuccessfulEvidenceOutput(n)||isControlOnlyOutput(n))return;const s=observedToolEvidence(t);t.requestState.set(e,[...s,{agentId:r,toolId:o,output:n}].slice(-12))}export function isControlOnlyOutput(e){return/"status"\s*:\s*"(?:duplicate_tool_call|repeated_tool_call_limit|tool_argument_error|delegated_task_repeat_limit|invalid_input|blocked|failed|error|plan_required|dependency_required)"|Status:\s*(?:invalid_input|blocked|failed|error|plan_required|dependency_required)\b|Filesystem builtin tool .* is disabled/iu.test(e)}export function isSuccessfulEvidenceOutput(e){const t=function parseJsonRecord(e){try{const t=JSON.parse(e);return function isRecord(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}(t)?t:void 0}catch{return}}(e),r="string"==typeof t?.status?t.status:function readTextStatus(e){return String(e).match(/^Status:\s*([A-Za-z0-9_-]+)/imu)?.[1]}(e);return!r||/^(?:completed|success|ok|recorded)$/iu.test(r)}
|
|
@@ -13,12 +13,6 @@ export type ToolRepeatState = {
|
|
|
13
13
|
maxCallsByTool: Map<string, number>;
|
|
14
14
|
maxSuccessfulCallsByTool: Map<string, number>;
|
|
15
15
|
};
|
|
16
|
-
export type ObservedToolEvidence = {
|
|
17
|
-
agentId: string;
|
|
18
|
-
toolId: string;
|
|
19
|
-
output: string;
|
|
20
|
-
};
|
|
21
|
-
export declare function observedToolEvidence(input: Parameters<RuntimeAdapter["run"]>[0]): ObservedToolEvidence[];
|
|
22
16
|
export declare function buildGatewayTools(input: Parameters<RuntimeAdapter["run"]>[0], agentId: string, toolIds: string[], repairModel?: RuntimeToolRepairModel, repeatState?: ToolRepeatState | undefined): import("@langchain/core/tools").DynamicTool<string | ToolMessage<import("@langchain/core/messages").MessageStructure<import("@langchain/core/messages").MessageToolSet>>, unknown>[];
|
|
23
17
|
export declare function createToolRepeatState(config: unknown): ToolRepeatState | undefined;
|
|
24
18
|
export declare function beforeToolInvoke(toolId: string, args: unknown, state: ToolRepeatState): {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{ToolMessage as e}from"@langchain/core/messages";import{tool as t}from"@langchain/core/tools";
|
|
1
|
+
import{ToolMessage as e}from"@langchain/core/messages";import{tool as t}from"@langchain/core/tools";import{isSuccessfulEvidenceOutput as o,observedToolEvidence as r,recordObservedToolEvidence as n}from"./gateway/tool-evidence.js";export function buildGatewayTools(o,n,s,a,i=createToolRepeatState(o.workspace.runtime.toolGateway)){return o.toolGateway?s.flatMap(s=>{const l=o.toolGateway?.get(s);if(!l)return[];const u=o.workspace.tools.get(s),c=u?.schema??l.schema;return[t(async t=>async function invokeGuardedGatewayTool(t){emitToolResult(t.input,t.agentId,t.toolId,void 0);const o=function missingRequiredPlanContent(e,t){const o=readRecord(e.agent.config.executionContract);if(!0!==o?.requiresPlan)return"";const n=readStringArray(o.planEvidenceTools);if(0===n.length||n.includes(t))return"";const s=new Set(r(e).map(e=>e.toolId));return n.some(e=>s.has(e))?"":["Status: plan_required",`Evidence tool: ${t}`,`Blocker: execution contract requires a planning checkpoint from one of: ${n.join(", ")} before evidence tools run.`,"Instruction: call the planning tool first, then retry this atomic evidence tool with repaired arguments."].join("\n")}(t.input,t.toolId);if(o)return emitToolResult(t.input,t.agentId,t.toolId,o),o;const n=function missingToolDependencyContent(e,t){const o=readRecord(e.agent.config.executionContract),n=readStringArray(readRecord(o.toolDependencies)[t]);if(0===n.length)return"";const s=new Set(r(e).map(e=>e.toolId)),a=n.filter(e=>!s.has(e));return 0===a.length?"":["Status: dependency_required",`Evidence tool: ${t}`,`Blocker: this atomic evidence tool requires completed dependency evidence from: ${a.join(", ")}.`,"Instruction: complete the dependency tool first, evaluate it, then retry this atomic evidence tool."].join("\n")}(t.input,t.toolId);if(n)return emitToolResult(t.input,t.agentId,t.toolId,n),n;const s=t.repeatState?beforeToolInvoke(t.toolId,t.args,t.repeatState):void 0;if(s)return emitToolResult(t.input,t.agentId,t.toolId,s.eventOutput),s.modelOutput;const a=await async function invokeGatewayTool(t,o,r,n,s){try{return await t.toolGateway.invoke({toolId:r,args:n,repairModel:s,context:{workspaceRoot:t.workspace.root,requestId:t.requestId,sessionId:t.sessionId,agentId:o,requestInput:t.request.input,observedEvidence:formatObservedEvidenceForToolContext(t)}})}catch(o){if(function isToolArgumentValidationError(e){return e instanceof Error&&"ToolArgumentValidationError"===e.name&&"string"==typeof e.toolId&&Array.isArray(e.issues)}(o))return new e({tool_call_id:`stable-harness-${r}-argument-guard`,name:r,status:"error",content:formatToolArgumentError(o)});if(t.workspace.runtime.retry?.tools?.enabled)throw o;return new e({tool_call_id:`stable-harness-${r}-execution-error`,name:r,status:"error",content:JSON.stringify({error:"tool_execution_failed",toolId:r,message:formatError(o),retry:"Use the error as evidence, adjust the tool arguments if possible, or return a final answer with the blocker."})})}}(t.input,t.agentId,t.toolId,t.args,t.repairModel),i=a instanceof e?String(a.content):stringifyDeepAgentResult(a.output),l=t.repeatState?afterToolInvoke(t.toolId,t.args,i,a,t.repeatState):{};return emitToolResult(t.input,t.agentId,t.toolId,l.eventOutput??i),void 0!==l.modelOutput?l.modelOutput:a instanceof e?a:i}({input:o,agentId:n,toolId:s,args:t,repairModel:a,repeatState:i}),{name:s,description:buildToolDescription(u?.description??l.description??s,c,o.workspace.runtime.toolGateway,s),schema:{type:"object",additionalProperties:!0}})]}):[]}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)}}function repeatGuardConfig(e){return isRecord(e)&&isRecord(e.repeatGuard)?e.repeatGuard:{}}function readPositiveInteger(e){return"number"==typeof e&&Number.isInteger(e)&&e>0?e:void 0}function readPositiveIntegerMap(e){return isRecord(e)?new Map(Object.entries(e).map(([e,t])=>[e,readPositiveInteger(t)]).filter(e=>void 0!==e[1])):new Map}export function beforeToolInvoke(e,t,o){const r=o.toolCallCounts.get(e)??0;o.toolCallCounts.set(e,r+1);const n=o.maxCallsByTool.get(e)??o.maxCallsPerTool;if(void 0!==n&&r>=n){const t=repeatedToolCallLimitContent(e,o.latestSuccessfulOutputByTool.get(e));return{eventOutput:t,modelOutput:t}}const s=o.maxSuccessfulCallsByTool.get(e)??o.maxSuccessfulCallsPerTool;if(void 0!==s&&(o.successfulToolCounts.get(e)??0)>=s){const t=repeatedToolCallLimitContent(e,o.latestSuccessfulOutputByTool.get(e));return{eventOutput:t,modelOutput:t}}const a=stableToolCallKey(e,t),i=o.successfulCalls.get(a);if(void 0!==i){const t=o.duplicateCallCounts.get(a)??0;if(o.duplicateCallCounts.set(a,t+1),void 0!==o.maxDuplicateCallsPerTool&&t>=o.maxDuplicateCallsPerTool){const t=repeatedToolCallLimitContent(e);return{eventOutput:t,modelOutput:t}}const r=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,i);return{eventOutput:r,modelOutput:i}}}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 r=t.maxSuccessfulCallsByTool.get(e)??t.maxSuccessfulCallsPerTool;return void 0!==r&&(t.successfulToolCounts.get(e)??0)>=r}export function afterToolInvoke(t,r,n,s,a){return s instanceof e&&"error"===s.status?{}:o(n)?(a.successfulCalls.set(stableToolCallKey(t,r),n),a.latestSuccessfulOutputByTool.set(t,n),a.successfulToolCounts.set(t,(a.successfulToolCounts.get(t)??0)+1),{}):{}}function emitToolResult(e,t,o,r){void 0!==r&&n(e,t,o,r),e.emit({type:"runtime.adapter.event",requestId:e.requestId,sessionId:e.sessionId,agentId:t,event:void 0===r?{adapter:"deepagents",phase:"agent.tool.start",toolId:o}:{adapter:"deepagents",phase:"agent.tool.result",toolId:o,output:previewToolOutput(r),...toolControlProjection(r)}})}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}:{}})}export function stringifyDeepAgentResult(t){if(t instanceof e)return function stringifyToolMessageContent(e){return"string"==typeof e?e:JSON.stringify(e)}(t.content);if("string"==typeof t)return t;if(isRecord(t)){const e=t.structuredResponse??t.structured_response;if(void 0!==e)return"string"==typeof e?e:JSON.stringify(e);const o=(Array.isArray(t.messages)?t.messages:[]).at(-1);if(isRecord(o)&&"string"==typeof o.content)return o.content;const r=(isRecord(t.update)&&Array.isArray(t.update.messages)?t.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(t)}function buildToolDescription(e,t,o,r){const n=function toolRepeatPolicyDescription(e,t){const o=repeatGuardConfig(e),r=readPositiveIntegerMap(o.maxSuccessfulCallsByTool).get(t)??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?`${e}\n\n${n}`:e;return t?`${s}\n\nStable tool input schema:\n${previewToolOutput(JSON.stringify(t))}`:s}function previewToolOutput(e){const t=e.replace(/\s+/gu," ").trim();return t.length>500?`${t.slice(0,497)}...`:t}export function toolControlProjection(e){const t=function parseJsonRecord(e){try{const t=JSON.parse(e);return isRecord(t)?t:void 0}catch{return}}(e);if("string"==typeof t?.status)return{controlStatus:t.status};const o=function readTextStatus(e){return String(e).match(/^Status:\s*([A-Za-z0-9_-]+)/imu)?.[1]}(e);return o?{controlStatus:o}:"string"==typeof t?.error?{controlStatus:t.error}:e.startsWith("Task delegation target is not in the workspace inventory")?{controlStatus:"task_inventory_blocked"}:{}}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 formatObservedEvidenceForToolContext(e){const t=r(e).map(e=>`Tool: ${e.toolId}\n${e.output}`).join("\n\n---\n\n");return t.length>12e3?`${t.slice(0,12e3)}\n[truncated]`:t}function formatToolArgumentError(e){return JSON.stringify({error:"tool_argument_validation_failed",toolId:e.toolId,issues:e.issues,retry:"Call the same tool again with arguments that satisfy the reported schema and semantic issues."})}function isRecord(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function readRecord(e){return isRecord(e)?e:{}}function readStringArray(e){return Array.isArray(e)?e.filter(e=>"string"==typeof e&&e.length>0):[]}function formatError(e){return e instanceof Error?e.message:String(e)}
|
|
@@ -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 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)?"agent.tool.result"!==e.event.phase||"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
|
+
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)?"agent.tool.result"!==e.event.phase||"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,4 +1,5 @@
|
|
|
1
1
|
import type { RuntimeEvent } from "../types.js";
|
|
2
2
|
export declare function hasPlanningEvidence(events: RuntimeEvent[]): boolean;
|
|
3
3
|
export declare function successfulEvidenceToolIds(events: RuntimeEvent[]): string[];
|
|
4
|
+
export declare function successfulEvidenceOutputs(events: RuntimeEvent[]): string[];
|
|
4
5
|
export declare function controlBlockers(events: RuntimeEvent[]): string[];
|
|
@@ -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&&"agent.tool.result"===e.phase&&"string"==typeof e.toolId&&function
|
|
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&&"agent.tool.result"===e.phase&&"string"==typeof e.toolId&&isSuccessfulEvidenceEvent(e)?[e.toolId]:[]});return[...new Set(e)]}export function successfulEvidenceOutputs(t){return t.flatMap(t=>{if("runtime.tool.direct.completed"===t.type)return stringifyEvidence(t.output);const e=readAdapterEvent(t);return e&&"agent.tool.result"===e.phase&&"string"==typeof e.toolId?!isSuccessfulEvidenceEvent(e)||function isPlanningTool(t){return/^(?:write_todos|read_todos)$/u.test(t)}(e.toolId)?[]:stringifyEvidence(e.output):[]})}export function controlBlockers(t){return t.flatMap(t=>{const e=readAdapterEvent(t),r=readString(e?.controlStatus)??readOutputStatus(e?.output);return r&&function isBlockerStatus(t){return/^(?:blocked|approval_required|schema_repair_failed|tool_argument_error|invalid_input)$/iu.test(t)}(r)?[`${readString(e?.toolId)??"tool"}:${r}`]:[]})}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 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
|
-
import{controlBlockers as e,successfulEvidenceToolIds as
|
|
1
|
+
import{controlBlockers as e,successfulEvidenceOutputs as n,successfulEvidenceToolIds as t}from"./event-evidence.js";const r=/(?<![\w.])(?:\d{1,3}(?:,\d{3})+|\d+)(?:\.\d+)?[%kKmMbBtTxX]?(?!\w)/gu;export function reviewExecutionEvidence(e,n){if(!n.enabled||!n.executionReview.enabled)return{verdict:"pass",issues:[]};const t=[...blockerIssues(e,n),...emptyFinalIssues(e,n),...toolEvidenceIssues(e,n),...ungroundedNumberIssues(e,n)];return 0===t.length?{verdict:"pass",issues:[]}:{verdict:t.some(e=>!e.recoverable)?"blocked":"continue_react",issues:t}}function ungroundedNumberIssues(e,t){if(!t.executionReview.rejectUngroundedNumbers||!e.output?.text.trim())return[];const r=numberSet(n(e.events).join("\n"));if(0===r.size)return[];const s=[...numberSet(e.output.text)].filter(e=>!function isSupportedNumber(e,n){if(n.has(e))return!0;const t=Number.parseFloat(e);if(!Number.isFinite(t))return!1;for(const e of n){const n=Number.parseFloat(e);if(Number.isFinite(n)&&Math.abs(n-t)<=roundingTolerance(t))return!0}return!1}(e,r));return 0===s.length?[]:[{code:"ungrounded_numeric_claim",message:`Final answer contains numeric claims not found in successful tool evidence: ${s.slice(0,12).join(", ")}`,recoverable:!1}]}function numberSet(e){const n=new Set;for(const t of e.matchAll(r)){const e=normalizeNumber(t[0]);e&&n.add(e)}return n}function normalizeNumber(e){const n=e.replace(/,/gu,"").replace(/^\+/u,"").replace(/[%kKmMbBtTxX]$/u,"").trim();if(n){if(/^\d+$/u.test(n)){const e=Number.parseInt(n,10);if(e>=1&&e<=20)return;return String(e)}return/^\d+\.\d+$/u.test(n)?n.replace(/0+$/u,"").replace(/\.$/u,""):void 0}}function roundingTolerance(e){return Math.abs(e)>=1e3?1:Math.abs(e)>=100?.1:Math.abs(e)>=10?.05:.005}function blockerIssues(n,t){return t.executionReview.stopOnBlocker?e(n.events).map(e=>({code:"control_blocker",message:`Execution produced a control blocker: ${e}`,recoverable:!1})):[]}function emptyFinalIssues(e,n){return!n.executionReview.rejectEmptyFinal||e.output?.text.trim()?[]:[{code:"empty_final_answer",message:"The final answer is empty.",recoverable:!0}]}function toolEvidenceIssues(e,n){return!n.executionReview.requireToolEvidence||t(e.events).length>0?[]:[{code:"missing_tool_evidence",message:"No successful tool or delegated-task evidence was observed.",recoverable:!0}]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
export function resolveQualityPolicy(e,n){const r=n.config.quality??e.quality,
|
|
1
|
+
export function resolveQualityPolicy(e,n){const r=n.config.quality??e.quality,o=function readProfile(e){const n="string"==typeof e?e:isRecord(e)?e.profile:void 0;return"fast"===n||"balanced"===n||"strict"===n?n:"off"}(r),i=function profileDefaults(e,n){const r=n.tools.length>0||n.subagents.length>0||(n.skills?.length??0)>0;return"off"===e?function disabledPolicy(e){return{enabled:!1,profile:e,reviewer:{mode:"deterministic"},planningReview:{enabled:!1,requirePlan:!1},executionReview:{enabled:!1,requireToolEvidence:!1,rejectEmptyFinal:!1,stopOnBlocker:!1,rejectUngroundedNumbers:!1},recovery:{enabled:!1,maxLoops:0}}}(e):{enabled:!0,profile:e,planningReview:{enabled:"fast"!==e,requirePlan:"fast"!==e&&r},executionReview:{enabled:!0,requireToolEvidence:"strict"===e&&r,rejectEmptyFinal:!0,stopOnBlocker:!0,rejectUngroundedNumbers:"strict"===e},recovery:{enabled:"fast"!==e,maxLoops:"strict"===e?3:2}}}(o,n),t=isRecord(r)?r:{},a=function readReviewer(e){const n=isRecord(e.reviewer)?e.reviewer:e,r="llm"===n.mode||"string"==typeof n.modelRef?"llm":"deterministic",o=isRecord(n.prompts)?n.prompts:{},i=readString(n.modelRef);return{mode:r,...i?{modelRef:i}:{},...readString(n.planningPrompt)??readString(o.planning)?{planningPrompt:readString(n.planningPrompt)??readString(o.planning)}:{},...readString(n.executionPrompt)??readString(o.execution)?{executionPrompt:readString(n.executionPrompt)??readString(o.execution)}:{}}}(t);return{enabled:i.enabled,profile:o,...a?{reviewer:a}:{},planningReview:{enabled:readBoolean(t.planningReview,"enabled")??i.planningReview.enabled,requirePlan:readBoolean(t.planningReview,"requirePlan")??i.planningReview.requirePlan},executionReview:{enabled:readBoolean(t.executionReview,"enabled")??i.executionReview.enabled,requireToolEvidence:readBoolean(t.executionReview,"requireToolEvidence")??i.executionReview.requireToolEvidence,rejectEmptyFinal:readBoolean(t.executionReview,"rejectEmptyFinal")??i.executionReview.rejectEmptyFinal,stopOnBlocker:readBoolean(t.executionReview,"stopOnBlocker")??i.executionReview.stopOnBlocker,rejectUngroundedNumbers:readBoolean(t.executionReview,"rejectUngroundedNumbers")??i.executionReview.rejectUngroundedNumbers},recovery:{enabled:readBoolean(t.recovery,"enabled")??i.recovery.enabled,maxLoops:readPositiveInteger(t.recovery,"maxLoops")??i.recovery.maxLoops}}}function readString(e){return"string"==typeof e&&e.trim()?e.trim():void 0}function readBoolean(e,n){const r=isRecord(e)?e:{};return"boolean"==typeof r[n]?r[n]:void 0}function readPositiveInteger(e,n){const r=(isRecord(e)?e:{})[n];return"number"==typeof r&&Number.isInteger(r)&&r>0?r:void 0}function isRecord(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
export function buildQualityRecoveryRequest(e){if(!e.policy.recovery.enabled||"pass"===e.result.verdict||"blocked"===e.result.verdict)return;const n="planning"===e.phase?function planningLines(e){return["Stable runtime quality review: the previous plan was not ready to execute.",...issueLines(e.result),inventoryLine("Available configured tools",e.availableToolIds),inventoryLine("Available configured subagents",e.availableSubagentIds),"Revise the plan using only the declared inventory, then continue through the backend's normal planning and tool-calling flow.","Do not invent tools, subagents, or a separate planning language."].filter(e=>e.length>0)}(e):function executionLines(e){return["Stable runtime quality review: the execution evidence is not sufficient for a final answer.",...issueLines(e.result),inventoryLine("Available configured tools",e.availableToolIds),inventoryLine("Available configured subagents",e.availableSubagentIds),"Continue from the current state using ReAct: inspect the evidence gap, choose
|
|
1
|
+
export function buildQualityRecoveryRequest(e){if(!e.policy.recovery.enabled||"pass"===e.result.verdict||"blocked"===e.result.verdict)return;const n="planning"===e.phase?function planningLines(e){return["Stable runtime quality review: the previous plan was not ready to execute.",...issueLines(e.result),inventoryLine("Available configured tools",e.availableToolIds),inventoryLine("Available configured subagents",e.availableSubagentIds),"Revise the plan using only the declared inventory, then continue through the backend's normal planning and tool-calling flow.","Do not invent tools, subagents, or a separate planning language."].filter(e=>e.length>0)}(e):function executionLines(e){return["Stable runtime quality review: the execution evidence is not sufficient for a final answer.",...issueLines(e.result),inventoryLine("Available configured tools",e.availableToolIds),inventoryLine("Available configured subagents",e.availableSubagentIds),...(n=e.observedEvidence??[],0===n.length?[]:["Completed observed evidence available for synthesis:",...n.slice(-8).map((e,n)=>`Evidence ${n+1}: ${function compact(e){const n=e.replace(/\s+/gu," ").trim();return n.length>900?`${n.slice(0,897)}...`:n}(e)}`)]),"Continue from the current state using ReAct: inspect the evidence gap, then either synthesize directly from completed observed evidence or choose one remaining declared tool/subagent action.","Do not call tools that already produced completed evidence or a repeat-limit control result for the same evidence need.","Preserve blockers explicitly instead of converting control states into unsupported factual answers."].filter(e=>e.length>0);var n}(e);return{...e.request,input:[e.request.input,"",...n].join("\n"),metadata:{...e.request.metadata,stableHarnessRecovery:`quality_${e.phase}`}}}function issueLines(e){return e.issues.map(e=>`- ${e.code}: ${e.message}`)}function inventoryLine(e,n){return n.length>0?`${e}: ${n.join(", ")}`:""}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{successfulEvidenceOutputs as e}from"./event-evidence.js";import{buildQualityRecoveryRequest as i}from"./recovery-policy.js";import{reviewExecutionEvidence as t}from"./execution-review.js";import{reviewWithLlm as n}from"./llm-review.js";import{reviewPlanningEvidence as r}from"./planning-review.js";export async function recoverQualityReview(e,i,t,n){if(!n.enabled)return t;let r=i,s=t;for(let i=0;i<n.recovery.maxLoops+1;i+=1){const t=await emitPlanningReview(e,r,s,n);if("blocked"===t.verdict)return qualityFailureOutput("planning",t);const u=buildQualityRecovery(e,r,t,"planning",n,i);if(u){r=u,s=await e.runAdapter(r);continue}const a=await emitExecutionReview(e,r,s,n),o=buildQualityRecovery(e,r,a,"execution",n,i);if(!o)return"pass"===a.verdict?s:qualityFailureOutput("execution",a);r=o,s=await e.runAdapter(r)}return qualityFailureOutput("execution",{verdict:"blocked",issues:[{code:"quality_recovery_exhausted",message:`Quality recovery exceeded maxLoops=${n.recovery.maxLoops}.`,recoverable:!1}]})}function emitPlanningReview(e,i,t,n){return emitReview(e,"planning",r,i,t,n)}function emitExecutionReview(e,i,n,r){return emitReview(e,"execution",t,i,n,r)}async function emitReview(e,i,t,r,s,u){const a={...reviewInputFor(e,r),output:s},o="planning"===i?u.planningReview.enabled:u.executionReview.enabled;if(!o)return t(a,u);const c=t(a,u),l=await n({phase:i,review:a,policy:u,model:e.reviewModel}),d="pass"===c.verdict?l??c:c;return o&&function emitReviewEvent(e,i,t){"planning"!==i?e.emit({type:"runtime.quality.execution.reviewed",requestId:e.requestId,sessionId:e.sessionId,agentId:e.agent.id,verdict:t.verdict,issues:t.issues}):e.emit({type:"runtime.quality.planning.reviewed",requestId:e.requestId,sessionId:e.sessionId,agentId:e.agent.id,verdict:t.verdict,issues:t.issues})}(e,i,d),d}function buildQualityRecovery(t,n,r,s,u,a){if(a>=u.recovery.maxLoops)return;const o=i({request:n,result:r,phase:s,policy:u,availableToolIds:t.agent.tools,availableSubagentIds:t.agent.subagents,observedEvidence:"execution"===s?e(t.getEvents()):[]});return o&&t.emit({type:"runtime.quality.recovery.started",requestId:t.requestId,sessionId:t.sessionId,agentId:t.agent.id,phase:s,attempt:a+1,verdict:r.verdict}),o}function reviewInputFor(e,i){return{workspace:e.workspace,agent:e.agent,request:i,events:e.getEvents()}}function qualityFailureOutput(e,i){return{text:[`Stable runtime quality review blocked final delivery during ${e}.`,"",...i.issues.length>0?i.issues.map(e=>`- ${e.code}: ${e.message}`):["- quality_review_failed: Quality review did not pass."]].join("\n")}}
|