@humain/humain-code 0.4.6 → 0.4.7
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +15 -0
- package/dist/bun/sandbox-env-setup.js +8 -0
- package/dist/bun/sandbox-env-setup.js.map +1 -1
- package/dist/bundle/agent-monitor.js +1 -1
- package/dist/bundle/chunks/{anthropic-messages-OHNAMPAM.js → anthropic-messages-YMPB2HJ7.js} +14 -13
- package/dist/bundle/chunks/{azure-openai-responses-FREWTLSS.js → azure-openai-responses-PDHOT7UC.js} +2 -2
- package/dist/bundle/chunks/bedrock-converse-stream.js +35 -35
- package/dist/bundle/chunks/{chunk-UTMYL2YO.js → chunk-2W5PWUPO.js} +10 -10
- package/dist/bundle/chunks/{chunk-DUZY4PDA.js → chunk-3E4SMILM.js} +33 -29
- package/dist/bundle/chunks/{chunk-UU4WS4BQ.js → chunk-3TYF6GG6.js} +319 -321
- package/dist/bundle/chunks/{chunk-FP2SXW5M.js → chunk-DAJJK7AP.js} +472 -458
- package/dist/bundle/chunks/{chunk-JQZ7BIAI.js → chunk-F7UMX5BV.js} +25 -22
- package/dist/bundle/chunks/{chunk-E7WGCXWK.js → chunk-GUUAEK6G.js} +1 -1
- package/dist/bundle/chunks/{chunk-4X774RBJ.js → chunk-GVVRXZHN.js} +4 -4
- package/dist/bundle/chunks/{chunk-H5CZL7M5.js → chunk-KRMTBTWU.js} +1 -1
- package/dist/bundle/chunks/{chunk-ICLZNV4V.js → chunk-LQ4S7CRR.js} +79 -67
- package/dist/bundle/chunks/{chunk-KLIRQQH5.js → chunk-OTXURGIO.js} +1 -1
- package/dist/bundle/chunks/{chunk-OXJXKCLB.js → chunk-PMISFIBM.js} +1 -1
- package/dist/bundle/chunks/{chunk-LFXFQLII.js → chunk-ROSZII6E.js} +1 -1
- package/dist/bundle/chunks/{chunk-E22S6D55.js → chunk-SWRU4BOC.js} +1 -1
- package/dist/bundle/chunks/{chunk-VQTXF23B.js → chunk-TIAXGIMN.js} +1 -1
- package/dist/bundle/chunks/{chunk-3ZI2TEVB.js → chunk-UZ5FVVCP.js} +1 -1
- package/dist/bundle/chunks/{chunk-BBBBZ5HY.js → chunk-XRMWWXLF.js} +3 -3
- package/dist/bundle/chunks/{chunk-2NX3BVH6.js → chunk-Z5LYSSTY.js} +2 -2
- package/dist/bundle/chunks/{cli-5YRA5PFB.js → cli-ZKT34WPW.js} +2 -2
- package/dist/bundle/chunks/{compat-LJ4ZIVJZ.js → compat-VPRCBNVL.js} +8 -8
- package/dist/bundle/chunks/{dist-UAQRGPZO.js → dist-4KCNJLEA.js} +153 -143
- package/dist/bundle/chunks/{dist-QHFJK4TH.js → dist-N7XDUAAO.js} +4 -4
- package/dist/bundle/chunks/{easter-egg-3d-ARXMB2RN.js → easter-egg-3d-5KKDWEIA.js} +1 -1
- package/dist/bundle/chunks/{execute-MFIDTEMB.js → execute-OSBDNQU5.js} +1 -1
- package/dist/bundle/chunks/{extract-EWN2GRAC.js → extract-56PXVZVW.js} +2 -2
- package/dist/bundle/chunks/{host-3OGMFGBY.js → host-2ARI7PQ5.js} +1 -1
- package/dist/bundle/chunks/mistral-conversations-XA2ZGSAH.js +43 -0
- package/dist/bundle/chunks/{openai-codex-responses-5AJAJHTK.js → openai-codex-responses-Y6NRWMOI.js} +2 -2
- package/dist/bundle/chunks/{openai-completions-65RRYKEQ.js → openai-completions-FY77MIZH.js} +6 -6
- package/dist/bundle/chunks/{openai-responses-72W3PGZ7.js → openai-responses-LNSCERKH.js} +2 -2
- package/dist/bundle/chunks/{pi-messages-RLLYRBDT.js → pi-messages-LYJZPRST.js} +7 -6
- package/dist/bundle/chunks/{runtime-HBWXEJT3.js → runtime-JFLZUNYP.js} +1 -1
- package/dist/bundle/chunks/{virtual-modules-LWYOTTHQ.js → virtual-modules-F76HZAGG.js} +2 -2
- package/dist/bundle/cli-runtime.js +2 -2
- package/dist/bundle/flow/package.json +1 -1
- package/dist/bundle/index.js +5 -5
- package/dist/bundle/rpc-entry.js +2 -2
- package/dist/core/tools/renderers/write.d.ts +2 -2
- package/dist/core/tools/renderers/write.d.ts.map +1 -1
- package/dist/core/tools/renderers/write.js +120 -15
- package/dist/core/tools/renderers/write.js.map +1 -1
- package/dist/humain/bedrock-provider/vendor/index.bundle.mjs +27 -28
- package/dist/humain/flow-loader.d.ts.map +1 -1
- package/dist/humain/flow-loader.js +30 -2
- package/dist/humain/flow-loader.js.map +1 -1
- package/dist/modes/interactive/components/assistant-message.d.ts.map +1 -1
- package/dist/modes/interactive/components/assistant-message.js +2 -0
- package/dist/modes/interactive/components/assistant-message.js.map +1 -1
- package/dist/modes/interactive/components/mermaid.d.ts.map +1 -1
- package/dist/modes/interactive/components/mermaid.js +4 -0
- package/dist/modes/interactive/components/mermaid.js.map +1 -1
- package/dist/modes/interactive/components/tool-execution.d.ts.map +1 -1
- package/dist/modes/interactive/components/tool-execution.js +4 -0
- package/dist/modes/interactive/components/tool-execution.js.map +1 -1
- package/dist/modes/interactive/interactive-mode.d.ts.map +1 -1
- package/dist/modes/interactive/interactive-mode.js +5 -0
- package/dist/modes/interactive/interactive-mode.js.map +1 -1
- package/dist/utils/child-process.d.ts +8 -0
- package/dist/utils/child-process.d.ts.map +1 -1
- package/dist/utils/child-process.js +65 -4
- package/dist/utils/child-process.js.map +1 -1
- package/dist/utils/windows-path.d.ts +9 -0
- package/dist/utils/windows-path.d.ts.map +1 -0
- package/dist/utils/windows-path.js +31 -0
- package/dist/utils/windows-path.js.map +1 -0
- package/docs/tui.md +1 -1
- package/npm-shrinkwrap.json +6 -6
- package/package.json +2 -2
- package/dist/bundle/chunks/mistral-conversations-5HCMHK6E.js +0 -43
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
import { createRequire as __piCreateRequire } from "node:module"; const require = __piCreateRequire(import.meta.url);
|
|
2
|
-
import"./chunk-
|
|
3
|
-
import"./chunk-
|
|
4
|
-
import{FLOW_DIGEST_PATTERN,FLOW_ID_PATTERN,FLOW_MODEL_ID_PATTERN,FLOW_ROLES,FlowContractError,FlowCountSchema,FlowDigestSchema,FlowFailureClassSchema,FlowIdSchema,FlowMicrousdSchema,FlowModelRefSchema,FlowPositiveIntSchema,FlowProfileRefSchema,FlowReasonClassSchema,FlowRoleSchema,FlowSizeSchema,FlowTimestampSchema,StrictObject,canonicalFlowJson,canonicalWithout,compileFlow,hasDuplicateModels,lit,parseFlowData,partialByRole,verifyFlowDigest}from"./chunk-
|
|
5
|
-
import"./chunk-BRXQUQSC.js";import"./chunk-
|
|
2
|
+
import"./chunk-XRMWWXLF.js";import{FLOW_MESSAGE_MAX_LENGTH,assertDhRetryAdmission,checkDhControlFence,dhCanonicalText,discoverAgents,getFlowChildLaunchHost,getFlowControlHost,getFlowTraceProducer,parseDhControlDelivery,parseFlowControlCommandV1,parseFlowControlReceiptV1,parseFlowMessageReceiptV1,parseFlowStatusV1,renderTaskWithContext,resolveDhEffectiveTerminals}from"./chunk-DAJJK7AP.js";import"./chunk-UZ5FVVCP.js";import"./chunk-KRMTBTWU.js";import"./chunk-UBQSONVR.js";
|
|
3
|
+
import"./chunk-ROSZII6E.js";import"./chunk-3TYF6GG6.js";import"./chunk-Z5LYSSTY.js";import"./chunk-F7UMX5BV.js";import"./chunk-PMISFIBM.js";import"./chunk-GUUAEK6G.js";import{ScrollView,matchesKey,mixColors,styleText,truncateToWidth,visibleWidth,wrapTextWithAnsi}from"./chunk-LQ4S7CRR.js";import"./chunk-SCIGZFN5.js";import"./chunk-KQM7ZGL6.js";import"./chunk-CIA6V3BP.js";import"./chunk-XQZG5HPT.js";import"./chunk-FACBDLFU.js";
|
|
4
|
+
import{FLOW_DIGEST_PATTERN,FLOW_ID_PATTERN,FLOW_MODEL_ID_PATTERN,FLOW_ROLES,FlowContractError,FlowCountSchema,FlowDigestSchema,FlowFailureClassSchema,FlowIdSchema,FlowMicrousdSchema,FlowModelRefSchema,FlowPositiveIntSchema,FlowProfileRefSchema,FlowReasonClassSchema,FlowRoleSchema,FlowSizeSchema,FlowTimestampSchema,StrictObject,canonicalFlowJson,canonicalWithout,compileFlow,hasDuplicateModels,lit,parseFlowData,partialByRole,verifyFlowDigest}from"./chunk-TIAXGIMN.js";import{getAgentDir}from"./chunk-3E4SMILM.js";
|
|
5
|
+
import"./chunk-BRXQUQSC.js";import"./chunk-OTXURGIO.js";import"./chunk-DBL35X7L.js";import"./chunk-GVVRXZHN.js";import"./chunk-WPLW452J.js";import"./chunk-YURQPD6Y.js";import"./chunk-AKA7HNO3.js";import"./chunk-QMUIATLD.js";import{typebox_exports}from"./chunk-BHM75BJJ.js";import"./chunk-JXWJOIH4.js";import{resolve}from"node:path";var FlowProfileError=class extends Error{code;path;constructor(code,message,path){super(message),this.name="FlowProfileError",this.code=code,path!==void 0&&(this.path=path)}};import{stripVTControlCharacters}from"node:util";var CONTROL=/[\u0000-\u001f\u007f-\u009f\u061c\u200e\u200f\u202a-\u202e\u2066-\u2069]/g;function sanitizeForDisplay(text2){return stripVTControlCharacters(text2).replace(CONTROL,"")}var clean=sanitizeForDisplay,fmtRef=r=>clean(`${r.provider}/${r.model}`);function summarizeProfile(p){let lines=[`${clean(p.id)} (${p.kind}) ${clean(p.label)}`,`version: ${p.version}`,`digest: ${p.digest}`];p.description!==void 0&&lines.push(`description: ${clean(p.description)}`),p.direct!==void 0&&lines.push(`model\
|
|
6
6
|
: ${fmtRef(p.direct.model)}`,`fallbacks: ${p.direct.fallbacks.map(fmtRef).join(", ")||"none"}`);for(let[role,b]of Object.entries(p.roles??{}))lines.push(`role ${role}: ${fmtRef(b.primary)} [${b.effort}] backups: ${b.backups.map(fmtRef).join(", ")||"none"}`);return lines.push(`limits: ${Object.entries(p.limits).map(([k,v])=>`${k}=${v}`).join(" ")}`),lines.push(`spend: runCapMicrousd=${p.spend.runCapMicrousd} warnAtPct=${p.spend.warnAtPct}`),lines.join(`
|
|
7
7
|
`)}var CLOSE="Close",BACK="Back",MAX_BACKUPS=8,InvalidInput=class extends Error{};function parseRef(text2){let i=text2.indexOf("/"),provider=text2.slice(0,i).trim(),model=text2.slice(i+1).trim();if(i<1||model==="")throw new InvalidInput(`Invalid model ref (expected provider/model): ${clean(text2)}`);return{provider,model}}function parseInteger(text2,label3){let n=Number(text2.trim());if(!/^\d+$/.test(text2.trim())||!Number.isSafeInteger(n))throw new InvalidInput(`${label3} must be an integer`);return n}
|
|
8
8
|
async function editRole(ctx,draft){let roles=draft.roles;if(roles===void 0)return;let role=await ctx.ui.select("Role",Object.keys(roles));if(role===void 0||!Object.hasOwn(roles,role))return;let current2=roles[role];if(current2===void 0)return;let primaryText=await ctx.ui.input(`Primary model (current: ${fmtRef(current2.primary)}; empty = keep)`);if(primaryText===void 0)return;let backupsText=await ctx.ui.input(`Fallbacks (comma-separated provider/model, max ${MAX_BACKUPS}; current: ${current2.backups.
|
|
@@ -875,11 +875,12 @@ id}${row.mr?` \xB7 MR ${row.mr}`:""}`,mark=row.outcome==="pending"?"\u25CC":row.
|
|
|
875
875
|
nested??[]){let existing=view.nested.get(snapshot.taskId);if(snapshot.changed){if(existing){Object.assign(existing,{agent:snapshot.agent,depth:snapshot.depth,turns:snapshot.turns,exitCode:snapshot.exitCode,finished:snapshot.finished,costUsd:snapshot.costUsd,latestText:snapshot.latestText,lastChangedAt:now});continue}if(view.nested.set(snapshot.taskId,{taskId:snapshot.taskId,agent:snapshot.agent,depth:snapshot.depth,turns:snapshot.turns,exitCode:snapshot.exitCode,finished:snapshot.finished,costUsd:snapshot.
|
|
876
876
|
costUsd,latestText:snapshot.latestText,firstSeenAt:now,lastChangedAt:now}),view.nested.size>32){let oldest;for(let row of view.nested.values())(!oldest||row.firstSeenAt<oldest.firstSeenAt)&&(oldest=row);oldest&&view.nested.delete(oldest.taskId)}}}}function applyWarnings(view,warnings,now,log){for(let warning of warnings)view.warning={text:warning.text,at:now,kind:warning.kind},!(view.lastLoggedWarning?.text===warning.text&&now-view.lastLoggedWarning.at<300*1e3)&&(log(warning.text.replace(/\s+/g,
|
|
877
877
|
" ").trim()),view.lastLoggedWarning={text:warning.text,at:now})}var fmtElapsed=formatDuration;function formatFlowSummary(input,width,theme,truncate3){let cost=input.costUsd===void 0?"cost unknown":`$${input.costUsd.toFixed(4)}`,now=input.alert?.text??(input.now?`Now: ${input.now.label} \xB7 ${input.now.model} \xB7 ${input.now.detail}`:`Now: ${input.phase}`);return[["accent",`HUMAIN Code / Flow \xB7 ${input.phase} \xB7 ${fmtElapsed(input.elapsedMs)} \xB7 ${cost}`],["muted",`${input.running} runni\
|
|
878
|
-
ng \xB7 ${input.ended} ended \xB7 ${input.failed} failed \xB7 ${input.cancelled} cancelled${input.ciPending>0?` \xB7 ${input.ciPending} CI pending`:""}`],[input.alert?.token??"text"
|
|
879
|
-
return text2.length<=maxLength?text2:maxLength<=0?"":maxLength===1?"\u2026":`${text2.slice(0,maxLength-1)}\u2026`}function formatProgressLine(view,now,indent,theme=plainTheme){if(!view.lastProgressDetail)return;let prefix=`${indent}\u21B3 progress ${fmtElapsed(now-view.lastProgressAt)} ago: `,suffix=[view.loopSuspects>0?`${view.loopSuspects} loop-suspect calls`:"",view.duplicateSnapshots>0?`${view.duplicateSnapshots}
|
|
880
|
-
detail=singleLine(view.lastProgressDetail),available=Math.max(0,120-prefix.length-suffix.length);return theme.fg("muted",`${prefix}${truncate(detail,available)}${suffix}`.slice(0,120))}var SPINNER_FRAMES=["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"];function spinnerFrame(now){return SPINNER_FRAMES[Math.floor(now/80)%SPINNER_FRAMES.length]}function formatNestedWorkerRows(view,now,parentDepth,theme=plainTheme){
|
|
881
|
-
...view.nested.values()].sort((a,b)=>a.firstSeenAt-b.firstSeenAt).map(row=>{let running=row.exitCode===-1&&!row.finished,mark=row.exitCode===-1?row.finished?"\u2713":spinnerFrame(now):row.exitCode===0?"\u2713":"\u2717",markToken=running?"accent":mark==="\u2717"?"error":"muted",agent=truncate(singleLine(row.agent),20).padEnd(20),metrics=` t${row.turns} $${row.costUsd.toFixed(4)} latest: `,fixedLen=indent.length+mark.length+1+agent.length+metrics.length,
|
|
882
|
-
Math.max(0,120-fixedLen));return styleSegments([["text",indent],[markToken,mark],["text"," "],["text",agent],["muted",metrics],["text",latest]],120,theme)})}function formatWarningLine(view,now,indent,theme=plainTheme){if(!view.warning)return;let prefix=`${indent}\u26A0 `,suffix=` (${fmtElapsed(now-view.warning.at)} ago)`,text2=singleLine(view.warning.text);return theme.fg("warning",`${prefix}${truncate(text2,Math.max(0,120-prefix.length-suffix.length))}${suffix}`.
|
|
878
|
+
ng \xB7 ${input.ended} ended \xB7 ${input.failed} failed \xB7 ${input.cancelled} cancelled${input.ciPending>0?` \xB7 ${input.ciPending} CI pending`:""}`],[input.alert?.token??"text",`${now}${!input.alert&&input.now?.backup?` \xB7 ${input.now.backup}`:""}`],["dim","/flow-status details \xB7 /flow-cancel \xB7 /omsg"]].map(([token,line])=>theme.fg(token,stripVTControlCharacters5(truncate3(sanitizeControlChars(redactCredentials(line)),width))))}function singleLine(text2){return sanitizeControlChars(
|
|
879
|
+
redactCredentials(text2)).replace(/\s+/g," ").trim()}function truncate(text2,maxLength){return text2.length<=maxLength?text2:maxLength<=0?"":maxLength===1?"\u2026":`${text2.slice(0,maxLength-1)}\u2026`}function formatProgressLine(view,now,indent,theme=plainTheme){if(!view.lastProgressDetail)return;let prefix=`${indent}\u21B3 progress ${fmtElapsed(now-view.lastProgressAt)} ago: `,suffix=[view.loopSuspects>0?`${view.loopSuspects} loop-suspect calls`:"",view.duplicateSnapshots>0?`${view.duplicateSnapshots}\
|
|
880
|
+
duplicate snapshots`:""].filter(Boolean).map(text2=>` \xB7 ${text2}`).join(""),detail=singleLine(view.lastProgressDetail),available=Math.max(0,120-prefix.length-suffix.length);return theme.fg("muted",`${prefix}${truncate(detail,available)}${suffix}`.slice(0,120))}var SPINNER_FRAMES=["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"];function spinnerFrame(now){return SPINNER_FRAMES[Math.floor(now/80)%SPINNER_FRAMES.length]}function formatNestedWorkerRows(view,now,parentDepth,theme=plainTheme){
|
|
881
|
+
let indent=" ".repeat(2+parentDepth);return[...view.nested.values()].sort((a,b)=>a.firstSeenAt-b.firstSeenAt).map(row=>{let running=row.exitCode===-1&&!row.finished,mark=row.exitCode===-1?row.finished?"\u2713":spinnerFrame(now):row.exitCode===0?"\u2713":"\u2717",markToken=running?"accent":mark==="\u2717"?"error":"muted",agent=truncate(singleLine(row.agent),20).padEnd(20),metrics=` t${row.turns} $${row.costUsd.toFixed(4)} latest: `,fixedLen=indent.length+mark.length+1+agent.length+metrics.length,
|
|
882
|
+
latest=truncate(singleLine(row.latestText),Math.max(0,120-fixedLen));return styleSegments([["text",indent],[markToken,mark],["text"," "],["text",agent],["muted",metrics],["text",latest]],120,theme)})}function formatWarningLine(view,now,indent,theme=plainTheme){if(!view.warning)return;let prefix=`${indent}\u26A0 `,suffix=` (${fmtElapsed(now-view.warning.at)} ago)`,text2=singleLine(view.warning.text);return theme.fg("warning",`${prefix}${truncate(text2,Math.max(0,120-prefix.length-suffix.length))}${suffix}`.
|
|
883
|
+
slice(0,120))}var CLEAN_FLUSH_REPORT={ok:!0,batches:0,acknowledged:0,failed:0,derivedStale:0},ZERO_QUEUE_STATS={enqueued:0,acknowledged:0,duplicates:0,batches:0,retries:0,failed:0,derivedStale:0};function telemetryWarning(report){let lines=[];return(!report.ok||report.failed>0)&&lines.push(`telemetry: ${report.failed} record(s) could not be written to the ledger \u2014 ${report.error??"see run.log"}`),report.derivedStale>0&&lines.push(`telemetry: ${report.derivedStale} record(s) are durable but the derived-vi\
|
|
883
884
|
ew refresh failed; derived views are stale until the next successful write \u2014 ${report.staleReason??"see run.log"}`),lines}function telemetryHealthy(report){return report.ok&&report.failed===0&&report.derivedStale===0}function verificationVerdictFor(input){if(input.blocked)return"NOT RUN (blocked: every lead stopped at a stop condition or precondition)";if(!input.dispatchOk)return"NOT RUN (no lead succeeded)";if(input.verificationTargetBlocked){let reason=input.verificationTargetBlocked;return/^claimed changes (outside candidate|not observed in candidate)/.test(reason)?`BLOCKED (${reason})`:`BLOCKED (ambiguous verification target: ${reason})`}if(input.verificationSkipped)return input.filesChangedCount===0?"N/\
|
|
884
885
|
A (no files changed \u2014 report-only goal)":"SKIPPED (no files changed)";if(input.verificationTimedOut)return"QA TIMED OUT (QA dispatch did not complete)";if(input.verificationProviderStall)return"QA PROVIDER STALL (QA dispatch did not complete)";if(input.passedVerification)return"PASS";let checks=input.failedChecks??[];return checks.length>0?`FAIL (${checks.join(", ")})`:"FAIL (unparsed)"}var shortId2=id2=>id2?id2.slice(0,12):"none",BANNER_WORD={complete:"complete",partial:"partial",blocked:"\
|
|
885
886
|
BLOCKED",failed:"FAILED",cancelled:"cancelled"};function buildRunSummary(report,audience="diagnostic",options={}){let verdict=verificationVerdictFor({blocked:report.blocked,dispatchOk:report.verificationDispatchOk,verificationSkipped:report.verificationSkipped,filesChangedCount:report.filesChangedCount,passedVerification:report.passedVerification,verificationTimedOut:report.verificationTimedOut,verificationProviderStall:report.verificationProviderStall,failedChecks:report.failedChecks,verificationTargetBlocked:report.
|
|
@@ -919,13 +920,14 @@ OW \xB7 ${input.stage}`,motion:input.stage==="starting"?"sweep":"pulse"}}functio
|
|
|
919
920
|
e blocked");for(let check2 of result.externalChecks)check2.outcome!=="success"&&unfinished.push(`External check ${check2.outcome}: ${check2.provider} ${check2.id}`);return result.codeVerification==="pass"&&(result.liveQa.verdict==="pass"||result.liveQa.verdict==="not_requested")&&(!result.acceptance||result.acceptance.overall==="pass")&&result.externalChecks.every(check2=>check2.outcome==="success")?terminal("verified","VERIFIED COMPLETE","verified complete","success","Requested scope complete. \
|
|
920
921
|
Required checks passed.","Review the changes and evidence. Nothing was committed.","settle"):terminal("unverified","UNVERIFIED","verification incomplete","warning",unfinished.join("; ")||"Verification did not finish","Inspect the run log; run the project checks before relying on these changes.")}function isFlowCommandText(text2){return/^\s*\/flow(\s|$)/.test(text2)}function flowMotionEnabled(env){return(env.HUMAIN_TERMINAL_REDUCED_MOTION===void 0||["","0","false"].includes(env.HUMAIN_TERMINAL_REDUCED_MOTION))&&
|
|
921
922
|
!env.NO_COLOR&&env.TERM!=="dumb"}function clean4(text2){return sanitizeControlChars(redactCredentials(text2)).replace(/\s+/g," ").trim()}function verificationEvidence(result){let lines=[`Code verification: ${result.codeVerification.replaceAll("_"," ")}`,`Live QA: ${result.liveQa.verdict.replaceAll("_"," ")}`];result.acceptance&&lines.push(`Acceptance: ${result.acceptance.overall} (${result.acceptance.criteria.length} criteria)`);for(let check2 of result.externalChecks)lines.push(`CI ${check2.provider} ${check2.id}: ${check2.outcome}`);
|
|
922
|
-
return lines.map(clean4)}function flowBadge(p,elapsedMs,costUsd,costComplete=!0){return clean4(`${p.badge} \xB7 ${fmtElapsed(elapsedMs)}${costUsd===void 0?"":` \xB7 $${costUsd.toFixed(4)}${costComplete?"":"+"}`}`)}function liveBodyLines(s,p){return[`${clean4(s.phase)} \xB7 ${s.running} running \xB7 ${s.ended} ended \xB7 ${s.failed} failed \xB7 ${s.cancelled} cancelled${s.ciPending>0?` \xB7 ${s.ciPending} CI pending`:""}`,s.alert?
|
|
923
|
-
|
|
924
|
-
|
|
925
|
-
{...line,text:clean4(line.text)});if(width<20)return[theme.fg(p.tone,label3),...lines.map(line=>theme.fg(line.token??(line.text.startsWith("Result:")?p.tone:"text"),line.text))].slice(0,4).map(line=>fitBoardLine(line,width));let brightness=Number.isFinite(frame.brightness)?Math.min(1,Math.max(0,
|
|
926
|
-
brightness,"srgb"):void 0,border=text2=>color?styleText(text2,{fg:color},"truecolor"):theme.fg(p.tone,text2),fittedBadge=truncateToWidth(label3,width-6,"\u2026"),titleWidth=width-7-visibleWidth(fittedBadge),title=runTitle&&titleWidth>0?truncateToWidth(` FLOW \xB7 ${clean4(runTitle)} `,titleWidth,
|
|
927
|
-
let cells=Math.min(6,dashCount),start=Math.round(Math.min(1,Math.max(0,frame.sweepAt))*(dashCount-cells)),highlight="\u2500".repeat(cells);dashes=border("\u2500".repeat(start))+theme.fg("text",theme.bold?theme.bold(highlight):highlight)+border("\u2500".repeat(dashCount-start-cells))}else dashes=
|
|
928
|
-
token??(line.text.startsWith("Result:")?p.tone:/^(Checks:|Open:|Next:|Log:|Exit status|\/flow-status)/.test(line.text)?"muted":"text");return border("\u2502 ")+theme.fg(token,truncateToWidth(line.text,width-4,"\u2026",!0))+border("
|
|
923
|
+
return lines.map(clean4)}function flowBadge(p,elapsedMs,costUsd,costComplete=!0){return clean4(`${p.badge} \xB7 ${fmtElapsed(elapsedMs)}${costUsd===void 0?"":` \xB7 $${costUsd.toFixed(4)}${costComplete?"":"+"}`}`)}function liveBodyLines(s,p){return[`${p.key==="starting"?`${spinnerFrame(s.elapsedMs)} Starting \xB7 `:""}${clean4(s.phase)} \xB7 ${s.running} running \xB7 ${s.ended} ended \xB7 ${s.failed} failed \xB7 ${s.cancelled} cancelled${s.ciPending>0?` \xB7 ${s.ciPending} CI pending`:""}`,s.alert?
|
|
924
|
+
{text:clean4(s.alert.text),token:s.alert.token}:p.key==="awaiting_input"?"Waiting for your confirmation in the dialog":s.now?`Now: ${s.now.label} \xB7 ${s.now.model} \xB7 ${s.now.detail}`:`Latest: ${s.latest}`,...s.now?.backup&&!s.alert?[{text:clean4(s.now.backup),token:"muted"}]:[],"/flow-status details \xB7 /flow-cancel \xB7 /omsg"].map(line=>typeof line=="string"?clean4(line):line)}function finalBodyLines(s,p){let first=items=>`${items[0]}${items.length>1?` (+${items.length-1} more)`:""}`;return[
|
|
925
|
+
`Result: ${p.detail}${s.replacedAttempts?.length?` \xB7 ${first(s.replacedAttempts)}`:""}`,[s.verification.length?`Checks: ${first(s.verification)}`:"",s.openItems.length?`Open: ${first(s.openItems)}`:"",`Changed: ${s.changedFiles===void 0?"not attributed":s.changedFiles.length?`${s.changedFiles.length} files: ${s.changedFiles.slice(0,3).join(", ")}${s.changedFiles.length>3?` (+${s.changedFiles.length-3} more)`:""}`:"no run-attributed files"}`].filter(Boolean).join(" \xB7 "),`Next: ${p.nextAction}\
|
|
926
|
+
\xB7 Log: ${s.runLog}`].map(clean4)}function renderFlowFrame(width,theme,p,badge,body,frame,runTitle){let label3=clean4(badge),lines=body.map(line=>typeof line=="string"?{text:clean4(line),token:void 0}:{...line,text:clean4(line.text)});if(width<20)return[theme.fg(p.tone,label3),...lines.map(line=>theme.fg(line.token??(line.text.startsWith("Result:")?p.tone:"text"),line.text))].slice(0,4).map(line=>fitBoardLine(line,width));let brightness=Number.isFinite(frame.brightness)?Math.min(1,Math.max(0,
|
|
927
|
+
frame.brightness)):1,foreground=theme.colors?.[p.tone],background=theme.colors?.customMessageBg,color=brightness<1&&foreground&&background&&theme.getColorMode?.()==="truecolor"?mixColors(background,foreground,brightness,"srgb"):void 0,border=text2=>color?styleText(text2,{fg:color},"truecolor"):theme.fg(p.tone,text2),fittedBadge=truncateToWidth(label3,width-6,"\u2026"),titleWidth=width-7-visibleWidth(fittedBadge),title=runTitle&&titleWidth>0?truncateToWidth(` FLOW \xB7 ${clean4(runTitle)} `,titleWidth,
|
|
928
|
+
"\u2026"):width>=visibleWidth(label3)+visibleWidth(" HUMAIN / FLOW ")+7?" HUMAIN / FLOW ":"",dashCount=width-6-visibleWidth(fittedBadge)-visibleWidth(title),dashes;if(frame.sweepAt!==void 0&&dashCount>0){let cells=Math.min(6,dashCount),start=Math.round(Math.min(1,Math.max(0,frame.sweepAt))*(dashCount-cells)),highlight="\u2500".repeat(cells);dashes=border("\u2500".repeat(start))+theme.fg("text",theme.bold?theme.bold(highlight):highlight)+border("\u2500".repeat(dashCount-start-cells))}else dashes=
|
|
929
|
+
border("\u2500".repeat(dashCount));return[border("\u256D\u2500")+(title?theme.fg(p.tone,title):"")+dashes+border(" ")+theme.fg(p.tone,fittedBadge)+border(" \u2500\u256E"),...lines.slice(0,3).filter((line,index)=>index<2||line.token==="muted").map(line=>{let token=line.token??(line.text.startsWith("Result:")?p.tone:/^(Checks:|Open:|Next:|Log:|Exit status|\/flow-status)/.test(line.text)?"muted":"text");return border("\u2502 ")+theme.fg(token,truncateToWidth(line.text,width-4,"\u2026",!0))+border("\
|
|
930
|
+
\u2502")}),border("\u2570\u2500")+(lines.length>2?theme.fg("muted",truncateToWidth(` ${lines.at(-1)?.text} `,width-4,"\u2026",!0)):border("\u2500".repeat(width-4)))+border("\u2500\u256F")].map(line=>fitBoardLine(line,width))}import{closeSync as closeSync11,constants as constants7,existsSync as existsSync5,fstatSync as fstatSync10,openSync as openSync11,readSync as readSync10,writeSync as writeSync3}from"node:fs";var DEFAULT_HEAD_BYTES=8*1024,DEFAULT_TAIL_BYTES=56*1024,encoder=new TextEncoder,decoder=new TextDecoder,MAX_CHILD_STDERR_DISK_BYTES=8*1024*1024,CAP_HEAD_BYTES=64*1024,CAP_MARKER_RESERVE_BYTES=512;function concatBytes(left,right){let joined=new Uint8Array(left.length+right.length);return joined.set(left),joined.set(right,left.length),joined}function byteLength(text2){return encoder.encode(text2).length}var BoundedCapture=class{headLimit;tailLimit;head=new Uint8Array(0);tail=new Uint8Array(0);totalBytes=0;tailLineAligned=!1;credentialContext=new ElidedCredentialContext;constructor(headBytes=DEFAULT_HEAD_BYTES,tailBytes=DEFAULT_TAIL_BYTES){
|
|
929
931
|
this.headLimit=Math.max(0,Math.trunc(headBytes)),this.tailLimit=Math.max(0,Math.trunc(tailBytes))}get elidedBytes(){return Math.max(0,this.totalBytes-this.head.length-this.tail.length)}append(chunk){let bytes=encoder.encode(chunk);this.totalBytes+=bytes.length;let headBytes=Math.min(this.headLimit-this.head.length,bytes.length);headBytes>0&&(this.head=concatBytes(this.head,bytes.subarray(0,headBytes)),this.credentialContext.append(bytes.subarray(0,headBytes)));let tailInput=bytes.subarray(Math.max(
|
|
930
932
|
0,headBytes));if(tailInput.length===0)return;if(this.tailLimit===0){this.credentialContext.append(tailInput),this.tailLineAligned=tailInput[tailInput.length-1]===10;return}if(this.tail.length===this.tailLimit&&tailInput.length<=this.tailLimit){this.credentialContext.append(this.tail.subarray(0,tailInput.length)),this.tailLineAligned=this.tail[tailInput.length-1]===10,this.tail.copyWithin(0,tailInput.length),this.tail.set(tailInput,this.tail.length-tailInput.length);return}let joinedTail=concatBytes(
|
|
931
933
|
this.tail,tailInput),discarded=Math.max(0,joinedTail.length-this.tailLimit);this.credentialContext.append(joinedTail.subarray(0,discarded)),discarded>0&&(this.tailLineAligned=joinedTail[discarded-1]===10),this.tail=joinedTail.slice(discarded)}text(){return this.elidedBytes===0?decoder.decode(concatBytes(this.head,this.tail)):decoder.decode(this.head)+`
|
|
@@ -938,10 +940,10 @@ position),position);if(n<=0)throw new Error("stderr file changed while scanning
|
|
|
938
940
|
`;return`${head.toString("utf8")}${marker}${tail.toString("utf8")}`}finally{closeSync11(fd)}}var REDACTED="[redacted]";function redactUserText(value){if(Array.isArray(value)){let mapped=value.map(redactUserText);return mapped.some((item,i)=>item!==value[i])?mapped:value}if(!value||typeof value!="object")return value;let record2=value,userMessage=record2.role==="user",changes={};for(let[key,item]of Object.entries(record2)){let next=userMessage&&key==="content"?REDACTED:record2.type==="queue_update"&&Array.isArray(item)&&(key==="steering"||key==="followUp")?item.map(()=>REDACTED):redactUserText(
|
|
939
941
|
item);next!==item&&(changes[key]=next)}return Object.keys(changes).length>0?{...record2,...changes}:value}function trimEventForLog(event2){if(event2=redactUserText(event2),!event2||typeof event2!="object"||event2.type!=="tool_execution_update")return event2;let partialResult=event2.partialResult;if(!partialResult||typeof partialResult!="object")return event2;let details=partialResult.details;if(!details||typeof details!="object")return event2;let results=details.results;return Array.isArray(results)?
|
|
940
942
|
{...event2,partialResult:{...partialResult,details:{...details,results:results.map(result=>{if(!result||typeof result!="object")return result;let{messages:_messages,...trimmedResult}=result;return trimmedResult})}}}:event2}function wasPipeTruncated(stderr){return stderr.length===65536?!0:stderr.includes("file://")&&!/\bNode\.js v\d/.test(stderr)&&!/(?:\r?\n)$/.test(stderr)}function truncateSummary(summary,maxLen,suffix){let limit=Math.max(0,Math.trunc(maxLen)),trimmed=summary.trim();return suffix?
|
|
941
|
-
limit<=suffix.length?suffix.slice(0,limit):trimmed.length+suffix.length<=limit?`${trimmed}${suffix}`:`${trimmed.slice(0,limit-suffix.length).trimEnd()}${suffix}`:trimmed.slice(0,limit).trim()}function summarizeStderr(stderr,maxLen=160){let lines=redactCredentials(stderr,void 0,stderr.length).split(/\r?\n/),marker=[...lines].reverse().find(line=>line.trim().startsWith("[orchestrator
|
|
942
|
-
fallback=[...lines].reverse().find(line=>line.trim().length>0&&line.length<=400&&!line.trim().startsWith("file://")),hasBundledLine=lines.some(line=>byteLength(line)>400),summary=marker?.trim()||errorLine?.trim()||fallback?.trim()||(hasBundledLine?`(diagnostic buried in ${byteLength(stderr)} bytes of bundled runtime output; see stderr log)`:""),truncation=wasPipeTruncated(stderr)?
|
|
943
|
-
return input.cancelled?{status:"cancelled",effectiveExitCode:137,note:input.stderrSummary||void 0}:input.timedOut||input.exitCode===124?{status:"timed_out",effectiveExitCode:input.exitCode,note:input.stderrSummary||void 0}:input.exitCode===0?input.lastStopReason==="error"||input.lastStopReason==="aborted"?{status:"failed",effectiveExitCode:1,note:input.
|
|
944
|
-
input.hasFinalText&&input.lastStopReason==="stop"?{status:"completed_after_process_error",effectiveExitCode:0,note:`completed; process exited ${input.exitCode} after settle: ${input.stderrSummary}`}:{status:"failed",effectiveExitCode:input.exitCode,note:input.stderrSummary||void 0}}var RECON_QUESTIONS=["Identify the affected files, functions, and call sites this task must touch or reference. List exact paths and symbols.","Identify existing tests that already cover this area, and note any gaps a fix or feature would need to close.","Identify conventions, patterns, and prior art already established in this codebase for this kind of change.","Identify the external interfaces, dependencies, or callers that this change could impact.","Identify likely risks and edge cases based\
|
|
943
|
+
limit<=suffix.length?suffix.slice(0,limit):trimmed.length+suffix.length<=limit?`${trimmed}${suffix}`:`${trimmed.slice(0,limit-suffix.length).trimEnd()}${suffix}`:trimmed.slice(0,limit).trim()}function summarizeStderr(stderr,maxLen=160){let lines=redactCredentials(stderr,void 0,stderr.length).split(/\r?\n/),marker=lines.find(line=>/^\s*\[orchestrator\] (?:all candidates unavailable\b|no compatible Bedrock route\b)/.test(line))??[...lines].reverse().find(line=>line.trim().startsWith("[orchestrator\
|
|
944
|
+
]")),errorLine=lines.find(line=>line.length<=400&&/^\s*(?:[A-Za-z]*Error|Uncaught [A-Za-z]*Error|error)\b.*:/.test(line)),fallback=[...lines].reverse().find(line=>line.trim().length>0&&line.length<=400&&!line.trim().startsWith("file://")),hasBundledLine=lines.some(line=>byteLength(line)>400),summary=marker?.trim()||errorLine?.trim()||fallback?.trim()||(hasBundledLine?`(diagnostic buried in ${byteLength(stderr)} bytes of bundled runtime output; see stderr log)`:""),truncation=wasPipeTruncated(stderr)?
|
|
945
|
+
" [stderr truncated by child pipe]":"";return truncateSummary(sanitizeControlChars(summary),maxLen,truncation)}function classifyDispatchOutcome(input){return input.cancelled?{status:"cancelled",effectiveExitCode:137,note:input.stderrSummary||void 0}:input.timedOut||input.exitCode===124?{status:"timed_out",effectiveExitCode:input.exitCode,note:input.stderrSummary||void 0}:input.exitCode===0?input.lastStopReason==="error"||input.lastStopReason==="aborted"?{status:"failed",effectiveExitCode:1,note:input.
|
|
946
|
+
stderrSummary||`final turn ended in ${input.lastStopReason}`}:{status:"completed",effectiveExitCode:0}:!input.spawnFailed&&input.sawAgentSettled&&input.hasFinalText&&input.lastStopReason==="stop"?{status:"completed_after_process_error",effectiveExitCode:0,note:`completed; process exited ${input.exitCode} after settle: ${input.stderrSummary}`}:{status:"failed",effectiveExitCode:input.exitCode,note:input.stderrSummary||void 0}}var RECON_QUESTIONS=["Identify the affected files, functions, and call sites this task must touch or reference. List exact paths and symbols.","Identify existing tests that already cover this area, and note any gaps a fix or feature would need to close.","Identify conventions, patterns, and prior art already established in this codebase for this kind of change.","Identify the external interfaces, dependencies, or callers that this change could impact.","Identify likely risks and edge cases based\
|
|
945
947
|
on how this code currently behaves."];function readOnlyReconPrompt(goal,question){return["Read-only reconnaissance for the following task. Do not implement anything yet.","",`Task goal: ${goal}`,"",question,"","Do not edit, commit, push, switch branches, stash, or otherwise modify the working tree in any way. Investigate and report your findings as plain text only."].join(`
|
|
946
948
|
`)}function reconWorkerCount(method,complexity,taskClass){if(complexity<method.min_complexity||taskClass&&method.skip_for_task_classes.includes(taskClass))return 0;let band=method.workers_by_complexity.find(({min,max})=>complexity>=min&&complexity<=max);return Math.max(0,band?.workers??0)}function planReconTasks(input){let{method,complexity,taskClass,goal,runId}=input,count3=reconWorkerCount(method,complexity,taskClass);return RECON_QUESTIONS.slice(0,count3).map((question,index)=>({taskId:`${runId}\
|
|
947
949
|
-recon-${index}`,capability:method.worker_capability,stage:"recon",task:readOnlyReconPrompt(goal,question),tools:["read","grep","find","ls"]}))}var TRUNCATION_MARKER="\u2026[truncated]";function truncate2(text2,maxChars){let limit=Math.max(0,Math.trunc(maxChars));if(text2.length<=limit)return text2;if(limit===0)return"";if(TRUNCATION_MARKER.length>=limit)return TRUNCATION_MARKER.slice(0,limit);let budget=limit-TRUNCATION_MARKER.length,kept="";for(let char of text2){let next=kept+char;if(next.length>
|
|
@@ -1165,33 +1167,34 @@ d");let event2=emitter.emit(input);return input.kind==="size_decided"?decidedSiz
|
|
|
1165
1167
|
roles?.[role],bound2=binding?[binding.primary,...binding.backups].map(qualified):[],unique=[...knownModels].filter(id3=>id3.slice(id3.indexOf("/")+1)===model);return knownModels.has(model)?model:dispatched!==void 0&&dispatchedBare===model&&knownModels.has(dispatched)?dispatched:bound2.find(id3=>id3.slice(id3.indexOf("/")+1)===model)??(unique.length===1?unique[0]:void 0)},resolveDispatched=(role,model)=>{let canonical=resolveCanonical(role,model);return canonical===void 0&&knownModels.add(model),
|
|
1166
1168
|
canonical??model},nestedModelRef=(role,model)=>{let unknown={provider:"unknown",model:"unknown"};if(!model)return unknown;let canonical=resolveCanonical(role,model);if(canonical!==void 0)return modelRef(canonical);let ref=modelRef(model),key=exactPriceKey(ref.provider,ref.model);return key===void 0?unknown:{provider:ref.provider,model:key}},routeBinding=(role,dispatched,nested)=>{let binding=admission.profile.roles?.[role],matches=ref=>dispatched===qualified(ref),primary=!!binding&&matches(binding.
|
|
1167
1169
|
primary),label3=primary?"primary":nested?"lead_selected":"backup",backupAt=!primary&&!nested&&binding?binding.backups.findIndex(matches):-1;return{effort:binding?.effort??"medium",binding:label3,backupIndex:Math.min(7,Math.max(0,backupAt))}},nestedRoleFor=agent=>{try{return flowRoleForCapability(roleForAgentName(agent),admission.profile)}catch{return"worker"}},record2=input=>{try{let result=ledger.record(input);return result.persisted||console.warn("[orchestrator] Flow usage persistence failed; \
|
|
1168
|
-
spend ledger incomplete"),result}catch(error){throw failed=!0,error}finally{notifyStop()}},recordExternalCostRows=rows=>{let num=v=>typeof v=="number"&&Number.isSafeInteger(v)&&v>=0?v:0;for(let row of rows){let recordId=typeof row.record_id=="string"?row.record_id:void 0;if(!recordId)continue;let reported=typeof row.cost_usd=="number"&&Number.isFinite(row.
|
|
1169
|
-
cost=reported??estimated,countersValid=[row.input_tokens,row.output_tokens,row.cached_input_tokens,row.cache_write_tokens].every(v=>typeof v=="number"&&Number.isSafeInteger(v)&&v>=0),unknownCost=typeof row.cost_source=="string"&&row.cost_source.startsWith("unknown")||cost===void 0&&!countersValid,base={taskId:telemetryTaskId(typeof row.task_id=="string"?
|
|
1170
|
-
unknown",model:"unknown"},durationMs:num(row.duration_ms)},input=usageOrUnknown({...base,requestId:requestIdFor([runId,"live-qa",recordId]),usage:{input:num(row.input_tokens),output:num(row.output_tokens),cacheRead:num(row.cached_input_tokens),cacheWrite:num(row.cache_write_tokens),...cost!==void 0?{cost:{total:cost}}:{}},costBasis:reported!==void 0?
|
|
1171
|
-
[runId,"live-qa",recordId,"incomplete"]),model:{provider:"unknown",model:"unknown"},usage:{input:0,output:0,cacheRead:0,cacheWrite:0},unknownCost:!0}))}},finalize=(outcome,failureClass,incomplete=!1)=>closing||(emit({kind:"run_settled",payload:{outcome:stopped()?"budget_stopped":outcome,...stopped()?{failureClass:"budget_stop"}:failureClass?{failureClass}:
|
|
1172
|
-
"direct"],totals:ledger.totals()}}),closing=emitter.settle().finally(()=>{closed=!0,durable.close()}),closing);return replay.some(event2=>event2.kind==="run_started")||emit({kind:"run_started",payload:{mode:admission.mode,surface:admission.surface,admissionDigest:admission.admissionDigest,inputsCount:admission.inputs.length,goalSha256:createHash13("sha256").
|
|
1173
|
-
capability,admission.profile),stopDispatch(){dispatchStopped=!0},status(){let cap=admission.spendCapMicrousd;return{mode:admission.mode,size:decidedSize??admission.sizeOverride??"medium",budgetPct:cap>0?Math.min(100,ledger.spentMicrousd/cap*100):0,warnings:[...ledger.state==="stop"?["budget_stop"]:[],...ledger.persistFailed?["internal"]:[]]}},recordExternalCostRows,
|
|
1174
|
-
()=>{producers.delete(drained),release()}},get stopped(){return stopped()},get healthy(){return!failed&&!ledger.persistFailed},beginAttempt(nativeTaskId,capability,model,routeReason2){assertCanDispatch();let taskId=telemetryTaskId(nativeTaskId),role=flowRoleForCapability(capability,admission.profile),attempt=(attempts.get(taskId)??0)+1;attempts.set(taskId,attempt);
|
|
1175
|
-
provider!==route.provider||prevRoute.model!==route.model),binding=admission.profile.roles?.[role],substituted=!prevRoute&&!!binding&&dispatched!==qualified(binding.primary)&&(routeReason2!==void 0||binding.backups.some(b=>dispatched===qualified(b)));attempt>1&&prevRoute&&fellBack?emit({kind:"fallback",payload:{taskId,role,from:prevRoute,to:route,reasonClass:lastFailure.
|
|
1176
|
-
primary)),to:route,reasonClass:routeReason2??"config_invalid"}}),substituted&&substitutedTasks.add(taskId),lastFailure.delete(taskId),attempt>1&&emit({kind:"attempt",payload:{taskId,role,attempt,state:"retried"}});let started=emit({kind:"attempt",payload:{taskId,role,attempt,state:"started"}});assertCanDispatch();let{effort:effort2,binding:boundAs,backupIndex}=routeBinding(
|
|
1177
|
-
started.eventId]}),lastRoute.set(taskId,route);let turnIndex=0,compactionIndex=0,nestedOrdinals=new Map,finished=!1,ownUnknownCost=!1,sawOwnUsage=!1,nestedOverflow=!1,nestedHigh=new Map,nestedEmitted=new Map,nestedUnknown=new Map,nestedDispatched=new Map,nestedTasks=new Map,markNestedOverflow=()=>{nestedOverflow||(nestedOverflow=!0,record2({...usageOrUnknown({requestId:requestIdFor(
|
|
1178
|
-
costBasis:"reported",usage:{input:0,output:0,cacheRead:0,cacheWrite:0},unknownCost:!0}),causes:[started.eventId]}))},emitVerdict=(n,verdict)=>{n.verdicted||n.role!=="reviewer"&&n.role!=="security_reviewer"||(n.verdicted=!0,emit({kind:"verdict",payload:{stage:"review",taskId:n.taskId,verdict:verdict==="PASS"?"pass":verdict==="FAIL"?"fail":"blocked",findingsCount:verdict==="PASS"?0:
|
|
1179
|
-
taskId,role:n.role,attempt:n.attempt,state,...failureClass?{failureClass}:{}},causes:[n.started.eventId]})};return{get unknownCost(){return ownUnknownCost},get nestedOverflow(){return nestedOverflow},markNestedOverflow,onStop(listener){return listeners.add(listener),stopped()&&listener(),()=>{listeners.delete(listener)}},recordUsage(usage,durationMs,servedModel=dispatched,source="
|
|
1180
|
-
"compaction"?["compaction",String(compactionIndex++)]:[String(turnIndex++)]]),inputs=usageRowsOrUnknown({requestId,taskId,role,model:knownModelRef(resolveCanonical(role,servedModel,dispatched)??servedModel),usage,durationMs,costBasis:"reported"});return inputs.some(input=>input.payload.costMicrousd===null)&&(ownUnknownCost=!0),inputs.map(input=>record2({...input,causes:[started.
|
|
1181
|
-
u.cost===void 0&&!completeCounters(u),hasUsage=!!(u.turns||u.input||u.output||u.cacheRead||u.cacheWrite||u.cost),hasRow=!!call.usageIncomplete||terminalUnproven||hasUsage||call.terminal&&completeCounters(u);if(!hasRow&&!call.model&&!call.terminal)continue;if(!nestedTasks.has(call.key)&&nestedTasks.size>=maxNestedKeys){markNestedOverflow();continue}let nestedRole=nestedRoleFor(
|
|
1182
|
-
call.model);call.model?.includes("/")&&dispatchedAs===void 0&&ref.provider!=="unknown"&&nestedDispatched.set(call.key,call.model);let n=nestedTasks.get(call.key);if(!n){let nestedTaskId=telemetryTaskId(JSON.stringify([nativeTaskId,attempt,call.toolCallId,call.taskId])),callAttempt=call.attempt,nestedAttemptNo=callAttempt!==void 0&&Number.isSafeInteger(callAttempt)&&callAttempt>=
|
|
1183
|
-
state:"started"},causes:[started.eventId]});emit({kind:"route_bound",payload:{taskId:nestedTaskId,role:nestedRole,model:ref,...routeBinding(nestedRole,ref.provider==="unknown"?"":qualified(ref),!0)},causes:[nestedStarted.eventId]}),n={taskId:nestedTaskId,role:nestedRole,attempt:nestedAttemptNo,started:nestedStarted,lastAt:call.startedAt,unknown:!1,ended:!1,verdicted:!1},nestedTasks.
|
|
1184
|
-
String(attempt),"nested",call.key,call.agent??"",...suffix]),lowerBound=u.cost!==void 0&&(!!call.usageIncomplete||hasInvalidCounter(u)),unknownEvidence=!!call.usageIncomplete&&u.cost===void 0||!call.costReported&&u.cost===void 0&&!completeCounters(u),p=usageOrUnknown({requestId:rowId(String(ordinal)),taskId:n.taskId,role:n.role,model:ref,durationMs:0,costBasis:"reported",...unknownEvidence?
|
|
1185
|
-
output??0:validOrZero2(u.output),cacheRead:unknownEvidence?u.cacheRead??0:validOrZero2(u.cacheRead),cacheWrite:unknownEvidence?u.cacheWrite??0:validOrZero2(u.cacheWrite),...u.cost===void 0||unknownEvidence?{}:{cost:{total:u.cost}}}}).payload,reportedMicro=u.cost!==void 0&&u.cost>0?Math.max(1,Math.round(u.cost*1e6)):0,high=nestedHigh.get(call.key)??{input:0,output:0,cacheRead:0,cacheWrite:0,
|
|
1186
|
-
{input:0,output:0,cacheRead:0,cacheWrite:0},emitDelta={inputTokens:Math.max(0,p.inputTokens-emitted.input),outputTokens:Math.max(0,p.outputTokens-emitted.output),cacheReadTokens:Math.max(0,p.cacheReadTokens-emitted.cacheRead),cacheWriteTokens:Math.max(0,p.cacheWriteTokens-emitted.cacheWrite)},delta={...p,inputTokens:Math.max(0,p.inputTokens-high.input),outputTokens:Math.max(0,p.outputTokens-
|
|
1187
|
-
high.cacheWrite),costMicrousd:p.costMicrousd===null?null:Math.max(0,reportedMicro-high.cost)},turnsNow=validCounter(u.turns)?u.turns:void 0,deltaTurns=turnsNow===void 0?void 0:Math.max(1,turnsNow-high.turns),deltaPrice=(provider,model2)=>{let price=priceFor(provider,model2);if(price===void 0||price==="free"||!price.tier)return price;let turns=deltaTurns??1,sum=delta.inputTokens+
|
|
1188
|
-
moved=!!delta.inputTokens||!!delta.outputTokens||!!delta.cacheReadTokens||!!delta.cacheWriteTokens||!!delta.costMicrousd,bookRow=payload=>{nestedOrdinals.set(call.key,(nestedOrdinals.get(call.key)??0)+1),nestedEmitted.set(call.key,{input:emitted.input+payload.inputTokens,output:emitted.output+payload.outputTokens,cacheRead:emitted.cacheRead+payload.cacheReadTokens,cacheWrite:emitted.
|
|
1189
|
-
Math.max(0,Math.round(at-n.lastAt)):0;at!==void 0&&(n.lastAt=at),record2({kind:"request_usage",payload:{...payload,durationMs},causes:[started.eventId]})};if(p.costMicrousd!==null){if(moved||!nestedHigh.has(call.key)){let known=usageOrUnknown({requestId:p.requestId,taskId:n.taskId,role:n.role,model:ref,durationMs:0,costBasis:"reported",price:deltaPrice,usage:{input:delta.inputTokens,
|
|
1190
|
-
{cost:{total:(delta.costMicrousd??0)/1e6}}}});bookRow({...known.payload,...emitDelta}),nestedHigh.set(call.key,{input:high.input+delta.inputTokens,output:high.output+delta.outputTokens,cacheRead:high.cacheRead+delta.cacheReadTokens,cacheWrite:high.cacheWrite+delta.cacheWriteTokens,cost:Math.max(high.cost,reportedMicro,high.cost+(known.payload.costMicrousd??0)),turns:Math.max(high.turns,
|
|
1191
|
-
"incomplete"),taskId:n.taskId,role:n.role,model:{provider:"unknown",model:"unknown"},durationMs:0,costBasis:"reported",usage:{input:0,output:0,cacheRead:0,cacheWrite:0},unknownCost:!0})))}else n.unknown=!0,flags.open||(flags.open=!0,bookRow({...delta,...emitDelta}));nestedUnknown.set(call.key,flags)}if(call.terminal&&!n.ended){let ok2=!!call.succeeded&&call.stopReason!=="
|
|
1192
|
-
n,"failed",/time-?out|timed out/i.test(call.stopReason??"")?"timeout":"provider_error")}call.reviewVerdict!==void 0&&emitVerdict(n,call.reviewVerdict)}},finish(state,failureClass){if(finished||closed)return;finished=!0;let missingOwnUsage=state!=="succeeded"&&!sawOwnUsage;(ownUnknownCost||nestedOverflow)&&state!=="cancelled"&&(state="failed",failureClass
|
|
1193
|
-
-usage"]),taskId,role,model:route,durationMs:0,usage:{input:0,output:0,cacheRead:0,cacheWrite:0},unknownCost:!0}),causes:[started.eventId]}));for(let n of nestedTasks.values())n.ended||(state==="cancelled"?nestedAttempt(n,"cancelled"):nestedAttempt(n,"failed",failureClass??"internal")),emitVerdict(n,
|
|
1194
|
-
return dispatchStopped=!0,settling??=(async()=>{for(;producers.size;)await Promise.all(producers);let override=late?.();await finalize(override?.outcome??outcome,override?override.failureClass:failureClass)})(),settling},settleIncomplete(){return dispatchStopped=!0,finalize(
|
|
1170
|
+
spend ledger incomplete"),result.recorded&&input.payload.costMicrousd===null&&console.warn("[orchestrator] provider usage incomplete; request cost unknown (not free)"),result}catch(error){throw failed=!0,error}finally{notifyStop()}},recordExternalCostRows=rows=>{let num=v=>typeof v=="number"&&Number.isSafeInteger(v)&&v>=0?v:0;for(let row of rows){let recordId=typeof row.record_id=="string"?row.record_id:void 0;if(!recordId)continue;let reported=typeof row.cost_usd=="number"&&Number.isFinite(row.
|
|
1171
|
+
cost_usd)?row.cost_usd:void 0,estimated=typeof row.estimatedCostUsd=="number"&&Number.isFinite(row.estimatedCostUsd)?row.estimatedCostUsd:void 0,cost=reported??estimated,countersValid=[row.input_tokens,row.output_tokens,row.cached_input_tokens,row.cache_write_tokens].every(v=>typeof v=="number"&&Number.isSafeInteger(v)&&v>=0),unknownCost=typeof row.cost_source=="string"&&row.cost_source.startsWith("unknown")||cost===void 0&&!countersValid,base={taskId:telemetryTaskId(typeof row.task_id=="string"?
|
|
1172
|
+
row.task_id:recordId),role:"qa",model:typeof row.provider=="string"&&typeof row.model=="string"?modelRef(`${row.provider}/${row.model}`):{provider:"unknown",model:"unknown"},durationMs:num(row.duration_ms)},input=usageOrUnknown({...base,requestId:requestIdFor([runId,"live-qa",recordId]),usage:{input:num(row.input_tokens),output:num(row.output_tokens),cacheRead:num(row.cached_input_tokens),cacheWrite:num(row.cache_write_tokens),...cost!==void 0?{cost:{total:cost}}:{}},costBasis:reported!==void 0?
|
|
1173
|
+
"reported":"estimated",...unknownCost?{unknownCost:!0}:{}});record2(input),row.cost_complete===!1&&record2(usageOrUnknown({...base,requestId:requestIdFor([runId,"live-qa",recordId,"incomplete"]),model:{provider:"unknown",model:"unknown"},usage:{input:0,output:0,cacheRead:0,cacheWrite:0},unknownCost:!0}))}},finalize=(outcome,failureClass,incomplete=!1)=>closing||(emit({kind:"run_settled",payload:{outcome:stopped()?"budget_stopped":outcome,...stopped()?{failureClass:"budget_stop"}:failureClass?{failureClass}:
|
|
1174
|
+
{},settledCleanly:!incomplete&&!failed&&!ledger.persistFailed&&outcome!=="interrupted",retryOffer:outcome==="succeeded"&&!stopped()?[]:["flow","direct"],totals:ledger.totals()}}),closing=emitter.settle().finally(()=>{closed=!0,durable.close()}),closing);return replay.some(event2=>event2.kind==="run_started")||emit({kind:"run_started",payload:{mode:admission.mode,surface:admission.surface,admissionDigest:admission.admissionDigest,inputsCount:admission.inputs.length,goalSha256:createHash13("sha256").
|
|
1175
|
+
update(opts.goal).digest("hex")}}),{emitter,ledger,ledgerPath:durable.path,emit,assertCanDispatch,roleForCapability:capability=>flowRoleForCapability(capability,admission.profile),stopDispatch(){dispatchStopped=!0},status(){let cap=admission.spendCapMicrousd;return{mode:admission.mode,size:decidedSize??admission.sizeOverride??"medium",budgetPct:cap>0?Math.min(100,ledger.spentMicrousd/cap*100):0,warnings:[...ledger.state==="stop"?["budget_stop"]:[],...ledger.persistFailed?["internal"]:[]]}},recordExternalCostRows,
|
|
1176
|
+
registerProducer(){assertCanDispatch();let release,drained=new Promise(resolve11=>{release=resolve11});return producers.add(drained),()=>{producers.delete(drained),release()}},get stopped(){return stopped()},get healthy(){return!failed&&!ledger.persistFailed},beginAttempt(nativeTaskId,capability,model,routeReason2){assertCanDispatch();let taskId=telemetryTaskId(nativeTaskId),role=flowRoleForCapability(capability,admission.profile),attempt=(attempts.get(taskId)??0)+1;attempts.set(taskId,attempt);
|
|
1177
|
+
let dispatched=resolveDispatched(role,model),route=knownModelRef(dispatched),prevRoute=lastRoute.get(taskId),fellBack=!!prevRoute&&(prevRoute.provider!==route.provider||prevRoute.model!==route.model),binding=admission.profile.roles?.[role],substituted=!prevRoute&&!!binding&&dispatched!==qualified(binding.primary)&&(routeReason2!==void 0||binding.backups.some(b=>dispatched===qualified(b)));attempt>1&&prevRoute&&fellBack?emit({kind:"fallback",payload:{taskId,role,from:prevRoute,to:route,reasonClass:lastFailure.
|
|
1178
|
+
get(taskId)??"provider_error"}}):substituted&&binding&&emit({kind:"fallback",payload:{taskId,role,from:modelRef(qualified(binding.primary)),to:route,reasonClass:routeReason2??"config_invalid"}}),substituted&&substitutedTasks.add(taskId),lastFailure.delete(taskId),attempt>1&&emit({kind:"attempt",payload:{taskId,role,attempt,state:"retried"}});let started=emit({kind:"attempt",payload:{taskId,role,attempt,state:"started"}});assertCanDispatch();let{effort:effort2,binding:boundAs,backupIndex}=routeBinding(
|
|
1179
|
+
role,dispatched,!1);emit({kind:"route_bound",payload:{taskId,role,model:route,effort:effort2,binding:boundAs,backupIndex},causes:[started.eventId]}),lastRoute.set(taskId,route);let turnIndex=0,compactionIndex=0,nestedOrdinals=new Map,finished=!1,ownUnknownCost=!1,sawOwnUsage=!1,nestedOverflow=!1,nestedHigh=new Map,nestedEmitted=new Map,nestedUnknown=new Map,nestedDispatched=new Map,nestedTasks=new Map,markNestedOverflow=()=>{nestedOverflow||(nestedOverflow=!0,record2({...usageOrUnknown({requestId:requestIdFor(
|
|
1180
|
+
[runId,taskId,String(attempt),"nested-overflow"]),taskId,role,model:{provider:"unknown",model:"unknown"},durationMs:0,costBasis:"reported",usage:{input:0,output:0,cacheRead:0,cacheWrite:0},unknownCost:!0}),causes:[started.eventId]}))},emitVerdict=(n,verdict)=>{n.verdicted||n.role!=="reviewer"&&n.role!=="security_reviewer"||(n.verdicted=!0,emit({kind:"verdict",payload:{stage:"review",taskId:n.taskId,verdict:verdict==="PASS"?"pass":verdict==="FAIL"?"fail":"blocked",findingsCount:verdict==="PASS"?0:
|
|
1181
|
+
1},causes:[n.started.eventId]}))},nestedAttempt=(n,state,failureClass)=>{n.ended=!0,emit({kind:"attempt",payload:{taskId:n.taskId,role:n.role,attempt:n.attempt,state,...failureClass?{failureClass}:{}},causes:[n.started.eventId]})};return{get unknownCost(){return ownUnknownCost},get nestedOverflow(){return nestedOverflow},markNestedOverflow,onStop(listener){return listeners.add(listener),stopped()&&listener(),()=>{listeners.delete(listener)}},recordUsage(usage,durationMs,servedModel=dispatched,source="\
|
|
1182
|
+
assistant"){source==="assistant"&&(sawOwnUsage=!0);let requestId=requestIdFor([runId,taskId,String(attempt),...source==="compaction"?["compaction",String(compactionIndex++)]:[String(turnIndex++)]]),inputs=usageRowsOrUnknown({requestId,taskId,role,model:knownModelRef(resolveCanonical(role,servedModel,dispatched)??servedModel),usage,durationMs,costBasis:"reported"});return inputs.some(input=>input.payload.costMicrousd===null)&&(ownUnknownCost=!0),inputs.map(input=>record2({...input,causes:[started.
|
|
1183
|
+
eventId]})).at(-1)},recordNested(calls){for(let call of calls){let u=call.usage,terminalUnproven=call.terminal&&!call.costReported&&u.cost===void 0&&!completeCounters(u),hasUsage=!!(u.turns||u.input||u.output||u.cacheRead||u.cacheWrite||u.cost),hasRow=!!call.usageIncomplete||terminalUnproven||hasUsage||call.terminal&&completeCounters(u);if(!hasRow&&!call.model&&!call.terminal)continue;if(!nestedTasks.has(call.key)&&nestedTasks.size>=maxNestedKeys){markNestedOverflow();continue}let nestedRole=nestedRoleFor(
|
|
1184
|
+
call.agent),dispatchedAs=nestedDispatched.get(call.key),ref=nestedModelRef(nestedRole,call.model&&dispatchedAs?dispatchedAs:call.model);call.model?.includes("/")&&dispatchedAs===void 0&&ref.provider!=="unknown"&&nestedDispatched.set(call.key,call.model);let n=nestedTasks.get(call.key);if(!n){let nestedTaskId=telemetryTaskId(JSON.stringify([nativeTaskId,attempt,call.toolCallId,call.taskId])),callAttempt=call.attempt,nestedAttemptNo=callAttempt!==void 0&&Number.isSafeInteger(callAttempt)&&callAttempt>=
|
|
1185
|
+
1?callAttempt:1,nestedStarted=emit({kind:"attempt",payload:{taskId:nestedTaskId,role:nestedRole,attempt:nestedAttemptNo,state:"started"},causes:[started.eventId]});emit({kind:"route_bound",payload:{taskId:nestedTaskId,role:nestedRole,model:ref,...routeBinding(nestedRole,ref.provider==="unknown"?"":qualified(ref),!0)},causes:[nestedStarted.eventId]}),n={taskId:nestedTaskId,role:nestedRole,attempt:nestedAttemptNo,started:nestedStarted,lastAt:call.startedAt,unknown:!1,ended:!1,verdicted:!1},nestedTasks.
|
|
1186
|
+
set(call.key,n)}if(hasRow){let ordinal=nestedOrdinals.get(call.key)??0,rowId=(...suffix)=>requestIdFor([runId,taskId,String(attempt),"nested",call.key,call.agent??"",...suffix]),lowerBound=u.cost!==void 0&&(!!call.usageIncomplete||hasInvalidCounter(u)),unknownEvidence=!!call.usageIncomplete&&u.cost===void 0||!call.costReported&&u.cost===void 0&&!completeCounters(u),p=usageOrUnknown({requestId:rowId(String(ordinal)),taskId:n.taskId,role:n.role,model:ref,durationMs:0,costBasis:"reported",...unknownEvidence?
|
|
1187
|
+
{unknownCost:!0}:{},usage:{input:unknownEvidence?u.input??0:validOrZero2(u.input),output:unknownEvidence?u.output??0:validOrZero2(u.output),cacheRead:unknownEvidence?u.cacheRead??0:validOrZero2(u.cacheRead),cacheWrite:unknownEvidence?u.cacheWrite??0:validOrZero2(u.cacheWrite),...u.cost===void 0||unknownEvidence?{}:{cost:{total:u.cost}}}}).payload,reportedMicro=u.cost!==void 0&&u.cost>0?Math.max(1,Math.round(u.cost*1e6)):0,high=nestedHigh.get(call.key)??{input:0,output:0,cacheRead:0,cacheWrite:0,
|
|
1188
|
+
cost:0,turns:0},flags=nestedUnknown.get(call.key)??{open:!1,marked:!1},emitted=nestedEmitted.get(call.key)??{input:0,output:0,cacheRead:0,cacheWrite:0},emitDelta={inputTokens:Math.max(0,p.inputTokens-emitted.input),outputTokens:Math.max(0,p.outputTokens-emitted.output),cacheReadTokens:Math.max(0,p.cacheReadTokens-emitted.cacheRead),cacheWriteTokens:Math.max(0,p.cacheWriteTokens-emitted.cacheWrite)},delta={...p,inputTokens:Math.max(0,p.inputTokens-high.input),outputTokens:Math.max(0,p.outputTokens-
|
|
1189
|
+
high.output),cacheReadTokens:Math.max(0,p.cacheReadTokens-high.cacheRead),cacheWriteTokens:Math.max(0,p.cacheWriteTokens-high.cacheWrite),costMicrousd:p.costMicrousd===null?null:Math.max(0,reportedMicro-high.cost)},turnsNow=validCounter(u.turns)?u.turns:void 0,deltaTurns=turnsNow===void 0?void 0:Math.max(1,turnsNow-high.turns),deltaPrice=(provider,model2)=>{let price=priceFor(provider,model2);if(price===void 0||price==="free"||!price.tier)return price;let turns=deltaTurns??1,sum=delta.inputTokens+
|
|
1190
|
+
delta.cacheReadTokens+delta.cacheWriteTokens;return turns===1||sum/turns>price.tier.inputTokensAbove?price:{...price,tier:void 0}},moved=!!delta.inputTokens||!!delta.outputTokens||!!delta.cacheReadTokens||!!delta.cacheWriteTokens||!!delta.costMicrousd,bookRow=payload=>{nestedOrdinals.set(call.key,(nestedOrdinals.get(call.key)??0)+1),nestedEmitted.set(call.key,{input:emitted.input+payload.inputTokens,output:emitted.output+payload.outputTokens,cacheRead:emitted.cacheRead+payload.cacheReadTokens,cacheWrite:emitted.
|
|
1191
|
+
cacheWrite+payload.cacheWriteTokens});let at=call.endedAt??call.updatedAt,durationMs=at!==void 0&&n.lastAt!==void 0?Math.max(0,Math.round(at-n.lastAt)):0;at!==void 0&&(n.lastAt=at),record2({kind:"request_usage",payload:{...payload,durationMs},causes:[started.eventId]})};if(p.costMicrousd!==null){if(moved||!nestedHigh.has(call.key)){let known=usageOrUnknown({requestId:p.requestId,taskId:n.taskId,role:n.role,model:ref,durationMs:0,costBasis:"reported",price:deltaPrice,usage:{input:delta.inputTokens,
|
|
1192
|
+
output:delta.outputTokens,cacheRead:delta.cacheReadTokens,cacheWrite:delta.cacheWriteTokens,...u.cost===void 0?{}:{cost:{total:(delta.costMicrousd??0)/1e6}}}});bookRow({...known.payload,...emitDelta}),nestedHigh.set(call.key,{input:high.input+delta.inputTokens,output:high.output+delta.outputTokens,cacheRead:high.cacheRead+delta.cacheReadTokens,cacheWrite:high.cacheWrite+delta.cacheWriteTokens,cost:Math.max(high.cost,reportedMicro,high.cost+(known.payload.costMicrousd??0)),turns:Math.max(high.turns,
|
|
1193
|
+
turnsNow??0)})}flags.open=!1,lowerBound&&!flags.marked&&(flags.marked=!0,n.unknown=!0,record2(usageOrUnknown({requestId:rowId("incomplete"),taskId:n.taskId,role:n.role,model:{provider:"unknown",model:"unknown"},durationMs:0,costBasis:"reported",usage:{input:0,output:0,cacheRead:0,cacheWrite:0},unknownCost:!0})))}else n.unknown=!0,flags.open||(flags.open=!0,bookRow({...delta,...emitDelta}));nestedUnknown.set(call.key,flags)}if(call.terminal&&!n.ended){let ok2=!!call.succeeded&&call.stopReason!=="\
|
|
1194
|
+
error"&&call.stopReason!=="aborted";n.unknown?nestedAttempt(n,"failed","config_invalid"):ok2?nestedAttempt(n,"succeeded"):nestedAttempt(n,"failed",/time-?out|timed out/i.test(call.stopReason??"")?"timeout":"provider_error")}call.reviewVerdict!==void 0&&emitVerdict(n,call.reviewVerdict)}},finish(state,failureClass){if(finished||closed)return;finished=!0;let missingOwnUsage=state!=="succeeded"&&!sawOwnUsage;(ownUnknownCost||nestedOverflow)&&state!=="cancelled"&&(state="failed",failureClass!=="budg\
|
|
1195
|
+
et_stop"&&(failureClass=nestedOverflow?"config_invalid":"provider_error")),missingOwnUsage&&(ownUnknownCost=!0,record2({...usageOrUnknown({requestId:requestIdFor([runId,taskId,String(attempt),"missing-usage"]),taskId,role,model:route,durationMs:0,usage:{input:0,output:0,cacheRead:0,cacheWrite:0},unknownCost:!0}),causes:[started.eventId]}));for(let n of nestedTasks.values())n.ended||(state==="cancelled"?nestedAttempt(n,"cancelled"):nestedAttempt(n,"failed",failureClass??"internal")),emitVerdict(n,
|
|
1196
|
+
"INVALID");lastFailure.set(taskId,state==="failed"?failureClass:void 0),emit({kind:"attempt",payload:{taskId,role,attempt,state,...failureClass?{failureClass}:{}},causes:[started.eventId]})}}},settle(outcome,failureClass,late){return dispatchStopped=!0,settling??=(async()=>{for(;producers.size;)await Promise.all(producers);let override=late?.();await finalize(override?.outcome??outcome,override?override.failureClass:failureClass)})(),settling},settleIncomplete(){return dispatchStopped=!0,finalize(
|
|
1197
|
+
"interrupted","cancelled",!0)},flushSync:()=>{closed||durable.flushSync()}}}catch(error){throw durable.close(),error}}import{createHash as createHash14}from"node:crypto";function roundHalfEven(x){let floor=Math.floor(x),diff=x-floor;return diff<.5?floor:diff>.5?floor+1:floor%2===0?floor:floor+1}function topologyFor(complexity,coupling=.5,parallelizable=.5){if(complexity<=3||coupling>=.8)return{depth:1,leads:0,workers:1,shape:"direct"};if(complexity<=6)return{depth:2,leads:1,workers:Math.max(1,Math.min(4,roundHalfEven(1+3*parallelizable))),shape:"single_lead"};let leads=Math.max(2,Math.min(4,roundHalfEven(2+2*parallelizable))),workers=Math.max(leads,Math.min(10,roundHalfEven(
|
|
1195
1198
|
complexity*parallelizable+leads)));return{depth:complexity<9?3:4,leads,workers,shape:"multi_lead"}}var QUALITY_FLOOR=.95,COST_AGGRESSIVENESS=.7,RISK_QUALITY_FLOOR_DELTA={low:0,medium:.02,high:.04,critical:.045},ROUTING_MODE="recommend",MAX_EFFORT="high",MAX_DEPTH=4,MIN_WORKERS=1,MAX_WORKERS=8,MIN_SAMPLES=12,EFFORTS=["minimal","low","standard","high","maximum"],DEFAULT_EFFORT={implementation_fast:"low",implementation_strong:"standard"},HIGH_RISK=new Set(["high","critical"]),DEFAULT_PACKAGES=[{capability:"implementation_fast",effort:"low",verification_depth:"targeted"},{capability:"implementati\
|
|
1196
1199
|
on_fast",effort:"standard",verification_depth:"targeted"},{capability:"implementation_fast",effort:"high",verification_depth:"broad"},{capability:"implementation_strong",effort:"standard",verification_depth:"broad"},{capability:"implementation_strong",effort:"high",verification_depth:"full"}];function effortIndex(effort2){return EFFORTS.indexOf(effort2)}function roundTo(x,digits){return Number(x.toFixed(digits))}function defaultPackageFor(complexity,risk){let capability=HIGH_RISK.has(risk)||complexity>=
|
|
1197
1200
|
8?"implementation_strong":"implementation_fast",effort2=DEFAULT_EFFORT[capability];risk==="critical"?effort2="high":complexity<=3&&risk==="low"&&(effort2="low"),effortIndex(effort2)>effortIndex(MAX_EFFORT)&&(effort2=MAX_EFFORT);let verification_depth=risk==="critical"?"full":risk==="high"||complexity>=7?"broad":"targeted";return{capability,effort:effort2,verification_depth}}function recommendPackage(qualityFloor){let smallPenalty=Math.max(0,MIN_SAMPLES-0)/MIN_SAMPLES*.025,best,feasibleBest;for(let pkg of DEFAULT_PACKAGES){
|
|
@@ -1625,15 +1628,16 @@ return{error:`--context ${raw}: ${err.message}`}}let source={label:contextFileLa
|
|
|
1625
1628
|
ound in the current session."};if(budgetLeft<=0)omittedCount++;else{let rendered=formatContextSource({label:LAST_REPLY_LABEL,content:text2}),cost=rendered.length+providedContextSeparatorLength(renderedSources.length);cost>budgetLeft?omittedCount++:(renderedSources.push(rendered),budgetLeft-=cost)}}return{block:assembleProvidedContextBlock(renderedSources,omittedCount)}}function redactingCtx(ctx){if(!ctx.ui)return ctx;let redact=v=>typeof v=="string"?redactDollarAmounts(v):Array.isArray(v)?v.map(
|
|
1626
1629
|
x=>typeof x=="string"?redactDollarAmounts(x):x):v,wrapUi=ui=>new Proxy(ui,{get(target,prop){let value=Reflect.get(target,prop,target);if(typeof value!="function")return value;let fn=value;return prop==="notify"?(message,...rest)=>fn.call(target,redact(message),...rest):prop==="setStatus"||prop==="setWidget"?(key,content,...rest)=>fn.call(target,key,redact(content),...rest):fn.bind(target)}});return new Proxy(ctx,{get(target,prop){let value=Reflect.get(target,prop,target);return prop==="ui"?wrapUi(
|
|
1627
1630
|
value):value}})}function postRunMessage(pi,runId,outcome,content,costUsd,result,hideCost){try{pi?.sendMessage({customType:"orchestrator-run",content:hideCost?redactDollarAmounts(content):content,display:!0,details:hideCost?{runId,outcome,result}:{runId,outcome,costUsd,result}},{triggerTurn:!1})}catch(err){console.warn(`[orchestrator] could not post run ${runId} summary to chat: ${err?.message??err}`)}}function newFlowRunId(){return`ht-orch-${Date.now()}-${Math.random().toString(36).slice(2,8)}`}
|
|
1628
|
-
async function startFlowExecution(request,ctx,deps){let{recovery}=request,pi=deps.pi,usage=usageText(deps.profilesPath),ownedSession,ownedRun=null,executionStarted=!1,refusalClass="config_invalid",refusalAdmission,refusalAdmissionFile,sentinel,cleanup=async(outcome="interrupted",failureClass)=>{sentinel?.close(),sentinel=void 0;let settleError;try{if(ownedSession){safeUi(()=>ownedSession.
|
|
1629
|
-
resolve11=>{release=resolve11}));sealing.then(ok2=>{unsealedEarly||=!ok2&&!released},()=>{unsealedEarly||=!released});try{if(ownedSession.flowTelemetry)try{await ownedSession.flowTelemetry.settle(outcome,failureClass,()=>(unsealedEarly||ownedSession.diagnosticsFailed?.())&&executionStarted?{outcome:"interrupted",failureClass:"internal"}:void 0),settledCleanly=ownedSession.flowTelemetry.
|
|
1630
|
-
if(executionStarted&&!sealed)throw new Error("Run diagnostics remain unsealed")}if(settleError)throw settleError}finally{try{ownedRun&&(safeUi(()=>ownedRun.activity?.close()),deps.runRegistry.release(ownedRun))}finally{try{ownedSession?.finish()}finally{recovery?.claim.release()}}}};try{let parsed=recovery?{...structuredClone(recovery.plan.snapshot.args),goal:recovery.plan.
|
|
1631
|
-
recovery&&(ctx.mode!=="tui"||!ctx.hasUI)){ctx.ui.notify("Confirmation unavailable; nothing dispatched.","warning");return}let flagError=parsed.literalGoal&&parsed.flowAdmission!==void 0?null:unappliedGoalFlagError(parsed.goal,parsed.force);if(flagError){ctx.ui.notify(flagError,"error");return}if(!parsed.goal){ctx.ui.notify(usage,"warning");return}if(parsed.unknownFlags.
|
|
1631
|
+
async function startFlowExecution(request,ctx,deps){let{recovery}=request,pi=deps.pi,usage=usageText(deps.profilesPath),ownedSession,ownedRun=null,executionStarted=!1,refusalClass="config_invalid",refusalAdmission,refusalAdmissionFile,sentinel,starting;safeUi(()=>{ctx.mode==="tui"&&!deps.runRegistry.active()&&(starting=deps.flowStage?.startStarting?.(ctx.ui))});let cleanup=async(outcome="interrupted",failureClass)=>{sentinel?.close(),sentinel=void 0;let settleError;try{if(ownedSession){safeUi(()=>ownedSession.
|
|
1632
|
+
close());let settledCleanly=!0,release,released=!1,unsealedEarly=!1,sealing=ownedSession.sealDiagnostics(new Promise(resolve11=>{release=resolve11}));sealing.then(ok2=>{unsealedEarly||=!ok2&&!released},()=>{unsealedEarly||=!released});try{if(ownedSession.flowTelemetry)try{await ownedSession.flowTelemetry.settle(outcome,failureClass,()=>(unsealedEarly||ownedSession.diagnosticsFailed?.())&&executionStarted?{outcome:"interrupted",failureClass:"internal"}:void 0),settledCleanly=ownedSession.flowTelemetry.
|
|
1633
|
+
healthy}catch(error){settledCleanly=!1,settleError=error}}finally{released=!0,release(settledCleanly)}let sealed=await sealing;if(executionStarted&&!sealed)throw new Error("Run diagnostics remain unsealed")}if(settleError)throw settleError}finally{try{ownedRun&&(safeUi(()=>ownedRun.activity?.close()),deps.runRegistry.release(ownedRun))}finally{try{ownedSession?.finish()}finally{recovery?.claim.release()}}}};try{let parsed=recovery?{...structuredClone(recovery.plan.snapshot.args),goal:recovery.plan.
|
|
1634
|
+
snapshot.goal}:request.args;if(refusalAdmissionFile=parsed.flowAdmission===void 0?void 0:resolve8(process.cwd(),parsed.flowAdmission),recovery&&(ctx.mode!=="tui"||!ctx.hasUI)){ctx.ui.notify("Confirmation unavailable; nothing dispatched.","warning");return}let flagError=parsed.literalGoal&&parsed.flowAdmission!==void 0?null:unappliedGoalFlagError(parsed.goal,parsed.force);if(flagError){ctx.ui.notify(flagError,"error");return}if(!parsed.goal){ctx.ui.notify(usage,"warning");return}if(parsed.unknownFlags.
|
|
1635
|
+
length>0){ctx.ui.notify(`Unknown flag(s): ${parsed.unknownFlags.join(", ")}
|
|
1632
1636
|
${usage}`,"error");return}let childLimits=parseSentinelChildEnv(deps.env);if(!childLimits.ok){ctx.ui.notify(childLimits.error,"error");return}let alreadyActive=deps.runRegistry.active();if(alreadyActive){refusalClass="internal",ctx.ui.notify(`An orchestration is already running (${alreadyActive.session.runId}). Wait for it to finish; its log is ${alreadyActive.session.file("run.log")}.`,"warning");return}let providedContextResult=recovery?{block:recovery.plan.snapshot.providedContext}:loadProvidedContext(
|
|
1633
|
-
process.cwd(),parsed.contextFiles,parsed.withLastReply,ctx);if("error"in providedContextResult){ctx.ui.notify(providedContextResult.error,"error");return}let providedContext=providedContextResult.block
|
|
1637
|
+
process.cwd(),parsed.contextFiles,parsed.withLastReply,ctx);if("error"in providedContextResult){ctx.ui.notify(providedContextResult.error,"error");return}let providedContext=providedContextResult.block;starting?.step("resolving checkout");let candidate=resolveCandidate({invocationCwd:process.cwd(),candidate:recovery?recovery.plan.snapshot.checkout.root:parsed.candidate},REAL_CANDIDATE_SEAMS);if(!candidate.ok){ctx.ui.notify(`${candidate.reason}
|
|
1634
1638
|
Nothing was dispatched.`,"error");return}let selection=candidate.selection,savedCwd=recovery?.plan.snapshot.dispatchCwd;if(savedCwd!==void 0&&selection.root!==null){let resumed=resolveSavedDispatchCwd(selection.root,savedCwd,REAL_CANDIDATE_SEAMS);if(!resumed.ok){ctx.ui.notify(`${resumed.reason}
|
|
1635
|
-
Nothing was dispatched.`,"error");return}selection={...selection,dispatchCwd:resumed.dispatchCwd,explicit:parsed.candidate!==void 0}}let runCwd=selection.dispatchCwd
|
|
1636
|
-
without a frozen admission under the startup --flow-admission.
|
|
1639
|
+
Nothing was dispatched.`,"error");return}selection={...selection,dispatchCwd:resumed.dispatchCwd,explicit:parsed.candidate!==void 0}}let runCwd=selection.dispatchCwd;starting?.step("resolving admission");let admissionSource,runCtx=ctx,useAdmissionCtx=source=>{source.kind==="file"&&source.admission.surface==="web"&&(runCtx=redactingCtx(ctx))},approvedInputs=[],startupFile=recovery?deps.startupFlowAdmission?.():void 0;if(recovery&&startupFile!==void 0&&recovery.plan.snapshot.admissionDigest===void 0){
|
|
1640
|
+
runCtx.ui.notify(`Cannot recover a run without a frozen admission under the startup --flow-admission.
|
|
1637
1641
|
Nothing was dispatched.`,"error");return}if(recovery&&(recovery.plan.snapshot.admissionDigest!==void 0||parsed.flowAdmission!==void 0||existsSync8(join19(runDir(deps.stateRoot,recovery.plan.snapshot.rootRunId),FLOW_ADMISSION_FILE)))){let frozen=loadFrozenAdmission(runDir(deps.stateRoot,recovery.plan.snapshot.rootRunId),{cwd:runCwd,...parsed.flowAdmission!==void 0?{admissionDir:dirname13(resolve8(process.cwd(),parsed.flowAdmission))}:{}},recovery.plan.snapshot.admissionDigest);if(!frozen.ok){runCtx.
|
|
1638
1642
|
ui.notify(`Cannot recover frozen admission: ${frozen.message}
|
|
1639
1643
|
Nothing was dispatched.`,"error");return}if(startupFile!==void 0){let startup=await resolveAdmissionSource({admissionFile:startupFile,cwd:process.cwd(),config:deps.flowAdmission??{flowDir:""}});if(!startup.ok){runCtx.ui.notify(`${startup.message}
|
|
@@ -1645,26 +1649,26 @@ Nothing was dispatched.`,"error");return}if(admissionSource=picked.source,useAdm
|
|
|
1645
1649
|
Nothing was dispatched.`,"error");return}approvedInputs=loaded.inputs}}else if(parsed.flowAdmission!==void 0){runCtx.ui.notify(`--flow-admission is not available for this run.
|
|
1646
1650
|
Nothing was dispatched.`,"error");return}if(admissionSource?.kind==="file"){let{runId:runId2,profile}=admissionSource.admission;refusalAdmission={runId:runId2,profile:{id:profile.id,version:profile.version,digest:profile.digest}}}let hasContext=parsed.contextFiles.length>0||parsed.withLastReply||approvedInputs.length>0;if(!recovery&&!hasContext&&!parsed.force&&goalRefersToMissingContext(parsed.goal)){runCtx.ui.notify('This goal looks short and refers to something outside itself (a lettered/numbe\
|
|
1647
1651
|
red item, "the above", "as discussed", or similar) that the dispatched agents will not have. '+(parsed.literalGoal?"Under --flow-admission the goal is taken literally and --force/--context are not applied: make the goal self-contained or attach approved inputs to the admission.":"Attach it with --context <file> (repeatable) or --with-last-reply, or skip this check with --force."),"warning");return}let frozenProfile=admissionSource===void 0?void 0:admissionSource.kind==="file"?admissionSource.admission.
|
|
1648
|
-
profile:admissionSource.resolved.profile
|
|
1649
|
-
|
|
1652
|
+
profile:admissionSource.resolved.profile;starting?.step("resolving models");let resolved2=await deps.resolveAdapter(ctx,parsed.models,frozenProfile),adapter=resolved2.adapter;if(recovery?.plan.currentBindings){let expected=recovery.plan.currentBindings;if([...new Set([...Object.keys(expected),...Object.keys(adapter)])].some(capability=>expected[capability]!==(adapter[capability]&&recoveryBindingDescription(adapter[capability])))){runCtx.ui.notify("Recovery bindings changed; run /flow-continue fo\
|
|
1653
|
+
r a fresh preview and confirmation.","warning");return}}let overrideErrors=userLayerWarnings(resolved2);if(overrideErrors.length>0||resolved2.profiles.problems.length>0){runCtx.ui.notify(`Model configuration is invalid \u2014 nothing was dispatched:
|
|
1650
1654
|
${[...resolved2.profiles.problems,...overrideErrors].map(w=>`- ${w}`).join(`
|
|
1651
1655
|
`)}
|
|
1652
1656
|
|
|
1653
1657
|
Fix with /flow-models set <capability|tier> <alias>, or /flow-models list to see aliases.`,"error");return}let residencyFailures=frozenProfile?resolved2.residentModels?.length?residencyRefusals(resolved2,frozenProfile):["no resident model set was resolved for the frozen profile"]:[];if(residencyFailures.length>0){runCtx.ui.notify(`Frozen profile ${frozenProfile.id} cannot run this configuration \u2014 nothing was dispatched:
|
|
1654
1658
|
${residencyFailures.map(f=>`- ${f}`).join(`
|
|
1655
1659
|
`)}`,"error");return}for(let w of resolved2.warnings)runCtx.ui.notify(w,"warning");for(let n of resolved2.profiles.notes)runCtx.ui.notify(n,"info");goalExpectsInteraction(parsed.goal)&&runCtx.ui.notify("Heads-up: dispatched agents run non-interactively and cannot ask you questions mid-run. They are instructed to make the conservative choice and list open questions in their final report, which is shown when the run completes.","warning");let mode=ctx.mode,runId=recovery?.childRunId??(admissionSource?.
|
|
1656
|
-
kind==="file"?admissionSource.admission.runId:newFlowRunId()),session=ownedSession=deps.createSession(runId,runCtx,parsed.goal,runCwd);session.applySentinelLimits?.(childLimits.limits);for(let w of childLimits.warnings)session.log(w),runCtx.ui.notify(w,"warning");let claimed=ownedRun=deps.runRegistry.claim(session,{profile:resolved2.profileName,policy_id:policyIdFor(resolved2.profileName,adapter)},resolved2.table,resolved2.sources,resolved2.candidates||resolved2.residentModels?
|
|
1657
|
-
candidates,policyCandidates:resolved2.policyCandidates,reviewCandidates:resolved2.reviewCandidates,modelHealth:new ModelHealth,policy:resolved2.policy,residentModels:resolved2.residentModels}:void 0);if(!claimed){refusalClass="internal",runCtx.ui.notify(`An orchestration is already running (${deps.runRegistry.active().session.runId}). Wait for it to finish; its log is ${deps.runRegistry.active().session.file("run.log")}.`,"warning");return}let admission;if(admissionSource){
|
|
1658
|
-
kind==="file"?admissionSource.admission:admissionFor(admissionSource,runId,deps.flowAdmission)}catch(error){if(!(error instanceof FlowProfileError))throw error;runCtx.ui.notify(`${renderFlowProfileError(error)}
|
|
1660
|
+
kind==="file"?admissionSource.admission.runId:newFlowRunId()),session=ownedSession=deps.createSession(runId,runCtx,parsed.goal,runCwd);starting?.step("preparing run"),session.applySentinelLimits?.(childLimits.limits);for(let w of childLimits.warnings)session.log(w),runCtx.ui.notify(w,"warning");let claimed=ownedRun=deps.runRegistry.claim(session,{profile:resolved2.profileName,policy_id:policyIdFor(resolved2.profileName,adapter)},resolved2.table,resolved2.sources,resolved2.candidates||resolved2.residentModels?
|
|
1661
|
+
{candidates:resolved2.candidates,policyCandidates:resolved2.policyCandidates,reviewCandidates:resolved2.reviewCandidates,modelHealth:new ModelHealth,policy:resolved2.policy,residentModels:resolved2.residentModels}:void 0);if(!claimed){refusalClass="internal",runCtx.ui.notify(`An orchestration is already running (${deps.runRegistry.active().session.runId}). Wait for it to finish; its log is ${deps.runRegistry.active().session.file("run.log")}.`,"warning");return}let admission;if(admissionSource){
|
|
1662
|
+
try{admission=admissionSource.kind==="file"?admissionSource.admission:admissionFor(admissionSource,runId,deps.flowAdmission)}catch(error){if(!(error instanceof FlowProfileError))throw error;runCtx.ui.notify(`${renderFlowProfileError(error)}
|
|
1659
1663
|
Nothing was dispatched.`,"error");return}let path=session.file(FLOW_ADMISSION_FILE),written=writeAdmissionAtomic(path,admission);if(!written.ok){refusalClass="internal",runCtx.ui.notify(`${written.message}
|
|
1660
1664
|
Nothing was dispatched.`,"error");return}if(approvedInputs.length>0){let approvedFile=writeApprovedInputsFile(session.file(FLOW_APPROVED_INPUTS_FILE),approvedInputs);if(!approvedFile.ok){refusalClass="internal",runCtx.ui.notify(`${approvedFile.message}
|
|
1661
1665
|
Nothing was dispatched.`,"error");return}}session.log(`admission: profile ${admission.profile.id} v${admission.profile.version} ${admission.profile.digest} frozen in ${FLOW_ADMISSION_FILE}`)}executionStarted=!0;let runPromise=(async()=>{let cwd=runCwd,hideCost=admission?.surface==="web";session.hideCost=hideCost;let finalResult,changedFiles,elapsedMs,terminal={outcome:"failed",title:"Orchestration crashed",body:`See ${session.file("run.log")}`},failureClass;safeUi(()=>pi?.events.emit("orchestrat\
|
|
1662
|
-
or:run-start",{runId,mode,goal:parsed.goal})),safeUi(()=>{let source=session;mode==="tui"&&typeof source.flowLiveState=="function"&&typeof source.flowLiveSnapshot=="function"&&deps.flowStage?.startRun(runCtx.ui,source)});try{if(admission&&(session.flowTelemetry=openRunTelemetry({admission,admittedRunDir:recovery?runDir(deps.stateRoot,recovery.plan.snapshot.rootRunId):session.dir,goal:parsed.goal,writeFrame:deps.flowEventFrameWriter}),session.flowTelemetry.assertCanDispatch()),session.
|
|
1663
|
-
{...parsed,models:{...parsed.models,profile:resolved2.profileName}},providedContext,Object.fromEntries(Object.entries(adapter).map(([capability,binding])=>[capability,recoveryBindingDescription(binding)])),recovery||admission?{...recovery?recoveryChildEvidence(recovery.plan,recovery.reconciled):{},...admission?{admissionDigest:admission.admissionDigest}:{}}:void 0),recovery){let recorder=session.recovery;if(!recorder)throw new Error("Recovery evidence unavailable; nothing
|
|
1664
|
-
recovery.plan,deps.stateRoot,runCwd,recovery.reconciled,[runId],deps.scanLineage),recorder.setRecoveryParent(recovery.plan.snapshot),recorder.setRecoveryReconciliation(recovery.reconciled),recorder.onLaunched=owner=>addClaimWorker(deps.stateRoot,recovery.plan.snapshot.rootRunId,recovery.claim.token,owner),recorder.update(s=>{Object.assign(s,recoveryChildEvidence(recovery.plan,recovery.reconciled))});let decisions=redactCredentials(JSON.stringify({parentRunId:recovery.plan.
|
|
1665
|
-
plan.snapshot.rootRunId,actions:recovery.plan.actions,reconciled:[...recovery.reconciled],reconciledAttempts:[...recovery.reconciled].map(logicalTaskId=>({logicalTaskId,nativeAttemptId:recovery.plan.snapshot.tasks[logicalTaskId]?.task.taskId})),confirmedAt:new Date().toISOString()}));if(Buffer.byteLength(decisions)>4*1024*1024||!session.writeDiagnostic("recovery-decisions.json",decisions))throw new Error("Recovery decisions persistence failed; nothing dispatched");
|
|
1666
|
-
snapshot.runId)}session.recovery?.rootRunId&&(sentinel=startOwnerSentinel(lineageMarker({rootRunId:session.recovery.rootRunId,runId,logicalTaskId:"owner",attemptId:runId}))),claimed.activity=flowActivityFor(deps.getFlowTraceProducer,runCtx,runId,deps.getFlowChildLaunchHost,{getHost:deps.getFlowControlHost,runCancellation:session.cancellation}),claimed.activity?.liveControl||(session.log("Flow controls unknown: trusted qualified root unavailable; controls
|
|
1667
|
-
activity&&safeUi(()=>runCtx.ui.notify("Flow controls unavailable: trusted qualified root missing; controls disabled.","warning"))),deps.recordEvent("candidate_selected",{run_id:runId,invocation_cwd:process.cwd(),root:selection.root,explicit:selection.explicit}),selection.explicit&&session.log(`candidate: ${selection.root}`),session.log(`policy: ${claimed.tags.policy_id}`),session.log(`models (profile "${resolved2.profileName}"):
|
|
1666
|
+
or:run-start",{runId,mode,goal:parsed.goal})),safeUi(()=>{let source=session;mode==="tui"&&typeof source.flowLiveState=="function"&&typeof source.flowLiveSnapshot=="function"&&deps.flowStage?.startRun(runCtx.ui,source)}),starting?.close();try{if(admission&&(session.flowTelemetry=openRunTelemetry({admission,admittedRunDir:recovery?runDir(deps.stateRoot,recovery.plan.snapshot.rootRunId):session.dir,goal:parsed.goal,writeFrame:deps.flowEventFrameWriter}),session.flowTelemetry.assertCanDispatch()),session.
|
|
1667
|
+
initializeRecovery?.({...parsed,models:{...parsed.models,profile:resolved2.profileName}},providedContext,Object.fromEntries(Object.entries(adapter).map(([capability,binding])=>[capability,recoveryBindingDescription(binding)])),recovery||admission?{...recovery?recoveryChildEvidence(recovery.plan,recovery.reconciled):{},...admission?{admissionDigest:admission.admissionDigest}:{}}:void 0),recovery){let recorder=session.recovery;if(!recorder)throw new Error("Recovery evidence unavailable; nothing di\
|
|
1668
|
+
spatched");prepareRecovery(recovery.plan,deps.stateRoot,runCwd,recovery.reconciled,[runId],deps.scanLineage),recorder.setRecoveryParent(recovery.plan.snapshot),recorder.setRecoveryReconciliation(recovery.reconciled),recorder.onLaunched=owner=>addClaimWorker(deps.stateRoot,recovery.plan.snapshot.rootRunId,recovery.claim.token,owner),recorder.update(s=>{Object.assign(s,recoveryChildEvidence(recovery.plan,recovery.reconciled))});let decisions=redactCredentials(JSON.stringify({parentRunId:recovery.plan.
|
|
1669
|
+
snapshot.runId,rootRunId:recovery.plan.snapshot.rootRunId,actions:recovery.plan.actions,reconciled:[...recovery.reconciled],reconciledAttempts:[...recovery.reconciled].map(logicalTaskId=>({logicalTaskId,nativeAttemptId:recovery.plan.snapshot.tasks[logicalTaskId]?.task.taskId})),confirmedAt:new Date().toISOString()}));if(Buffer.byteLength(decisions)>4*1024*1024||!session.writeDiagnostic("recovery-decisions.json",decisions))throw new Error("Recovery decisions persistence failed; nothing dispatched");
|
|
1670
|
+
recovery.claim.admit(recovery.plan.snapshot.runId)}session.recovery?.rootRunId&&(sentinel=startOwnerSentinel(lineageMarker({rootRunId:session.recovery.rootRunId,runId,logicalTaskId:"owner",attemptId:runId}))),claimed.activity=flowActivityFor(deps.getFlowTraceProducer,runCtx,runId,deps.getFlowChildLaunchHost,{getHost:deps.getFlowControlHost,runCancellation:session.cancellation}),claimed.activity?.liveControl||(session.log("Flow controls unknown: trusted qualified root unavailable; controls disabl\
|
|
1671
|
+
ed."),deps.getFlowControlHost&&claimed.activity&&safeUi(()=>runCtx.ui.notify("Flow controls unavailable: trusted qualified root missing; controls disabled.","warning"))),deps.recordEvent("candidate_selected",{run_id:runId,invocation_cwd:process.cwd(),root:selection.root,explicit:selection.explicit}),selection.explicit&&session.log(`candidate: ${selection.root}`),session.log(`policy: ${claimed.tags.policy_id}`),session.log(`models (profile "${resolved2.profileName}"):
|
|
1668
1672
|
${formatAdapterTable(resolved2).map(l=>` ${l}`).join(`
|
|
1669
1673
|
`)}`);for(let n of resolved2.notes)session.log(`note: ${n}`);let orchestrationDeps={...recovery?{recovery:recovery.plan,reconciledRecoveryTasks:recovery.reconciled}:{},scanLineage:deps.scanLineage,triageTask:(id2,goal,...rest)=>(session.flowTelemetry?.assertCanDispatch(),deps.triageTask(id2,attachApprovedInputs(goal,approvedInputs),...rest)),planRun:deps.planRun,recordEvent:deps.recordEvent,recordOutcome:deps.recordOutcome,captureDispatchCost:deps.captureDispatchCost,dispatchParallel:(dispatchCwd,id2,tasks,adapterArg,ctxArg,run)=>(session.
|
|
1670
1674
|
flowTelemetry?.assertCanDispatch(),deps.dispatchParallel(dispatchCwd,id2,tasks.map(task=>({...task,task:attachApprovedInputs(task.task,approvedInputs)})),adapterArg,ctxArg,run)),...admission?{admission,approvedInputs}:{},escalation:createEscalationGate(payload=>{session.flowTelemetry?.emit({kind:"escalated",payload}),deps.onEscalated?.(payload)},admission?.profile.sizing?.maxEscalations??1),onSizeDecided:decision=>{let{size,source,ruleScore,thresholds}=decision;session.flowTelemetry?.emit({kind:"\
|
|
@@ -1684,7 +1688,7 @@ truncateMarked(terminal.body,RUN_RESULT_LIMITS.stringChars)].slice(-RUN_RESULT_L
|
|
|
1684
1688
|
profile.version,digest:admission.profile.digest}}),"internal");let event2={runId,mode,...terminal,notificationHandled:!1};safeUi(()=>{mode==="tui"&&finalResult&&deps.flowStage?.finishRun({goal:parsed.goal,elapsedMs:elapsedMs??session.terminalTiming().elapsed_ms,costUsd:finalResult.cost.usd,costComplete:finalResult.cost.complete,changedFiles,verification:verificationEvidence(finalResult),openItems:finalResult.openItems,runLog:finalResult.runLog},presentResult(finalResult,{declinedAtGate:session.confirmationDeclined}))}),
|
|
1685
1689
|
session.flowTelemetry?.stopped&&(failureClass="budget_stop"),safeUi(()=>pi?.events.emit("orchestrator:run-end",event2)),mode==="tui"&&!event2.notificationHandled&¬ifyTerminal(event2.title,event2.body),!recovery&&pi&&safeUi(()=>{offerRetry({outcome:terminal.outcome,failureClass:terminal.outcome==="failed"?failureClass??"internal":failureClass,hasUI:ctx.hasUI&&parsed.flowAdmission===void 0,ui:ctx.ui,retryFlow:async()=>{if(deps.isFlowDisabled?deps.isFlowDisabled():deps.env.HUMAIN_TERMINAL_FLOW_DISABLED===
|
|
1686
1690
|
"1"){runCtx.ui.notify("Flow disabled","error");return}await startFlowExecution(request,ctx,deps)},retryDirect:async()=>pi.sendUserMessage(parsed.goal,{deliverAs:"followUp"})}).catch(()=>safeUi(()=>ctx.ui.notify("Flow retry failed","error")))})}}return terminal.outcome==="completed"&&failureClass!=="budget_stop"})(),settled=runPromise.then(()=>{});session.runPromise=settled,settled.catch(err=>{console.error(`[orchestrator] run ${runId} background task rejected unexpectedly: ${err?.stack??err}`)}),
|
|
1687
|
-
(mode==="print"||mode==="json"||deps.env.HUMAIN_ORCHESTRATOR_FOREGROUND==="1")&&(await runPromise.catch(()=>!1)||markHeadlessFailure(mode))}catch(error){throw refusalClass="internal",error}finally{if(
|
|
1691
|
+
(mode==="print"||mode==="json"||deps.env.HUMAIN_ORCHESTRATOR_FOREGROUND==="1")&&(await runPromise.catch(()=>!1)||markHeadlessFailure(mode))}catch(error){throw refusalClass="internal",error}finally{if(starting?.close(),!executionStarted){markHeadlessFailure(ctx.mode);try{await cleanup()}finally{await emitRefusalSettled(join19(deps.stateRoot,"runs"),deps.flowEventFrameWriter,()=>refusalIdentity({admission:refusalAdmission,admissionFile:refusalAdmissionFile}),refusalClass)}}}}function registerOrchestrateCommand(pi,deps){
|
|
1688
1692
|
let command={description:`Plan and dispatch a hierarchical agent run. Args: <goal> [--task-class T] [--complexity N] [--risk low|medium|high|critical] [--profile ID | --flow-admission FILE] [--lead-size small|standard|large] [--cheap ALIAS] [--mid ALIAS] [--premium ALIAS] [--frontier ALIAS] [--model <capability>=ALIAS] [--effort LEVEL] [--quality-floor F] [--cost-aggressiveness C] [--max-retries R] [--context FILE ...] [--with-last-reply] [--force]
|
|
1689
1693
|
|
|
1690
1694
|
With no triage flags, an LLM triage call (cheapest configured model) auto-fills task_class, complexity, and risk from the goal text. Models: flags > profile (orchestrator-profiles.json) > cost-tier resolver. See /flow-models.`,handler:async(args2,ctx)=>{let cliAdmission,refused=!1,refuse=async message=>{refused=!0,markHeadlessFailure(ctx.mode);try{ctx.ui.notify(`${message}
|
|
@@ -1720,12 +1724,14 @@ env??process.env,p.file.workflow_mode);return`workflow mode: ${wf.mode} (source:
|
|
|
1720
1724
|
`),resolved2.warnings.length>0?"warning":"info"),resolved2},handler=SUBCOMMANDS2[sub];if(!handler){ctx.ui.notify(`Unknown subcommand "${sub}".
|
|
1721
1725
|
${modelsUsage}`,"error");return}await handler({ctx,sub,positional,rest,parsed,deps,modelsUsage,showResolved})}})}var FlowAnimator=class{opts;timers;now;timer;armed=!1;disposed=!1;visual={brightness:1,sweepAt:void 0};constructor(opts){this.opts=opts,this.now=opts.now??Date.now,this.timers=opts.timers??{setInterval:(fn,ms)=>{let handle=setInterval(fn,ms);return handle.unref?.(),handle},clearInterval:id2=>clearInterval(id2)}}play(motion){if(this.disposed)return;if(this.stop(),!this.opts.motion||motion==="none"){this.update(1,void 0);return}let start=this.now();this.update(motion==="settle"?.4:1,motion==="swee\
|
|
1722
1726
|
p"?0:void 0),!this.disposed&&(this.timer=this.timers.setInterval(()=>{if(!this.disposed)if(motion==="sweep"){let at=Math.min(1,Math.max(0,(this.now()-start)/700));this.update(1,at),at===1&&!this.disposed&&this.play("pulse")}else if(motion==="pulse"){let phase=(this.now()-start)%3e3/3e3;this.update(.7+.3*Math.cos(phase*2*Math.PI),void 0)}else this.stop(),this.update(1,void 0)},motion==="sweep"?70:motion==="pulse"?40:600),this.armed=!0)}frame(){return{...this.visual}}get active(){return this.armed}dispose(){
|
|
1723
|
-
this.disposed||(this.disposed=!0,this.stop(),this.visual={brightness:1,sweepAt:void 0})}stop(){this.armed&&this.timers.clearInterval(this.timer),this.armed=!1,this.timer=void 0}update(brightness,sweepAt){if(!(this.visual.brightness===brightness&&this.visual.sweepAt===sweepAt)){this.visual={brightness,sweepAt};try{this.opts.onFrame()}catch{this.dispose()}}}};var FlowStage=class{opts;ui;unsubscribe;source;final;presentation=FLOW_READY;animator;activated=!1;requestRender;constructor(opts={}){this.opts=opts}bindTyping(ui){safeUi(()=>this.unsubscribe?.()),this.unsubscribe=void 0,this.ui=ui,safeUi(()=>{typeof ui.onEditorChange=="function"&&(this.unsubscribe=ui.onEditorChange(text2=>{this.source||this.accent(isFlowCommandText(text2)?FLOW_READY:this.final?this.presentation:void 0)}))})}
|
|
1724
|
-
|
|
1725
|
-
|
|
1726
|
-
this.
|
|
1727
|
-
|
|
1728
|
-
|
|
1727
|
+
this.disposed||(this.disposed=!0,this.stop(),this.visual={brightness:1,sweepAt:void 0})}stop(){this.armed&&this.timers.clearInterval(this.timer),this.armed=!1,this.timer=void 0}update(brightness,sweepAt){if(!(this.visual.brightness===brightness&&this.visual.sweepAt===sweepAt)){this.visual={brightness,sweepAt};try{this.opts.onFrame()}catch{this.dispose()}}}};var FlowStage=class{opts;ui;unsubscribe;source;startingSource;final;presentation=FLOW_READY;animator;activated=!1;requestRender;constructor(opts={}){this.opts=opts}bindTyping(ui){safeUi(()=>this.unsubscribe?.()),this.unsubscribe=void 0,this.ui=ui,safeUi(()=>{typeof ui.onEditorChange=="function"&&(this.unsubscribe=ui.onEditorChange(text2=>{this.source||this.accent(isFlowCommandText(text2)?FLOW_READY:this.final?this.presentation:void 0)}))})}startStarting(ui){if(this.source)return;let startedAt=(this.
|
|
1728
|
+
opts.now??Date.now)(),phase="loading context",source={flowLiveState:()=>({stage:"starting",awaitingInput:!1,cancelling:!1}),flowLiveSnapshot:()=>({goal:"",phase,elapsedMs:(this.opts.now??Date.now)()-startedAt,costUsd:void 0,running:0,ended:0,failed:0,cancelled:0,ciPending:0,now:void 0,alert:void 0,finished:0,total:0,latest:phase,pendingChecks:0})};return this.startingSource=source,this.mountRun(ui,source),safeUi(()=>this.requestRender?.(!0)),{step:text2=>{phase=text2,this.owns(source)&&this.refresh()},
|
|
1729
|
+
close:()=>{this.owns(source)&&(this.animator?.dispose(),this.animator=void 0,this.requestRender=void 0,this.source=void 0,this.startingSource=void 0,this.presentation=FLOW_READY,this.accent(void 0),safeUi(()=>this.ui?.setWidget("orchestrator",void 0)))}}}startRun(ui,source){if(this.source&&this.source===this.startingSource){this.ui=ui,this.source=source,this.startingSource=void 0,this.refresh();return}this.mountRun(ui,source)}mountRun(ui,source){this.animator?.dispose(),this.requestRender=void 0,
|
|
1730
|
+
this.ui=ui,this.source=source,this.final=void 0,this.presentation=presentLive(source.flowLiveState());let animator=new FlowAnimator({...this.opts,motion:flowMotionEnabled(this.opts.env??process.env),onFrame:()=>safeUi(()=>this.requestRender?.())});this.animator=animator,safeUi(()=>ui.setWidget("orchestrator",(tui,theme)=>(this.requestRender=force=>force?tui.renderNow():tui.requestRender(),{invalidate(){},render:width=>{if(this.animator!==animator)return[];let p=this.presentation,final=this.final,
|
|
1731
|
+
snapshot=final??this.source?.flowLiveSnapshot();return snapshot?renderFlowFrame(width,theme,p,flowBadge(p,snapshot.elapsedMs,snapshot.costUsd,final?.costComplete),"costComplete"in snapshot?finalBodyLines(snapshot,p):liveBodyLines(snapshot,p),animator.frame(),snapshot.title):[]},dispose:()=>{animator.dispose(),this.animator===animator&&(this.requestRender=void 0)}}))),this.accent(this.presentation),this.activated=this.presentation.motion==="sweep",animator.play(this.presentation.motion)}refresh(){
|
|
1732
|
+
if(!this.source)return;let p=presentLive(this.source.flowLiveState()),previous=this.presentation;if(this.presentation=p,p.key!==previous.key){this.accent(p);let motion=p.motion==="sweep"&&this.activated?"pulse":p.motion;motion==="sweep"&&(this.activated=!0),motion==="pulse"&&(previous.motion==="sweep"||previous.motion==="pulse")||this.animator?.play(motion)}safeUi(()=>this.requestRender?.())}finishRun(final,p){if(!this.source)return;let snapshot=this.source.flowLiveSnapshot();this.final={...final,
|
|
1733
|
+
title:final.title??snapshot.title,replacedAttempts:final.replacedAttempts??snapshot.replacedAttempts},this.source=void 0,this.presentation=p,this.animator?.play(p.motion),this.accent(p),safeUi(()=>this.requestRender?.())}owns(source){return this.source===source}holdsWidget(){return this.source!==void 0||this.final!==void 0}reset(){this.animator?.dispose(),this.animator=void 0,this.activated=!1,this.requestRender=void 0,this.source=void 0,this.startingSource=void 0,this.final=void 0,this.presentation=
|
|
1734
|
+
FLOW_READY,safeUi(()=>this.unsubscribe?.()),this.unsubscribe=void 0,this.accent(void 0),safeUi(()=>this.ui?.setWidget("orchestrator",void 0)),this.ui=void 0}accent(p){safeUi(()=>{typeof this.ui?.setEditorAccent=="function"&&this.ui.setEditorAccent(p?{color:p.tone,label:p.inputLabel}:void 0)})}},flowStage=new FlowStage;import{createHash as createHash16,randomUUID as randomUUID5}from"node:crypto";import{closeSync as closeSync15,constants as constants10,fstatSync as fstatSync14,fsyncSync as fsyncSync5,ftruncateSync as ftruncateSync2,linkSync as linkSync4,lstatSync as lstatSync13,mkdirSync as mkdirSync6,openSync as openSync15,readSync as readSync13,renameSync as renameSync4,unlinkSync as unlinkSync5,writeFileSync as writeFileSync4}from"node:fs";import{basename as basename7,dirname as dirname14,join as join20,resolve as resolve9}from"node:path";var OWNER_FILE=".diagnostics-owner.json",SEAL_FILE=".diagnostics-sealed.json",PROTOCOL="ht-run-diagnostics-v1",SEAL_DRAIN_TIMEOUT_MS=2e3,owners2=new Map,protectedNames=new Set(contract_default.never_archive_files);function syncDirectory3(dir){let fd=openSync15(dir,constants10.O_RDONLY|constants10.O_NOFOLLOW);try{fsyncSync5(fd)}finally{closeSync15(fd)}}function assertSafeDiagnosticName(name){if(!name||basename7(name)!==name||/[/\\\0]/.test(name)||name.startsWith(".")||name.endsWith(".gz")||protectedNames.
|
|
1729
1735
|
has(name))throw new Error(`unsafe diagnostic name: ${name}`)}function publish(dir,name,value){let tmp=join20(dir,`.${name}.${randomUUID5()}.tmp`),fd=openSync15(tmp,"wx",384);try{try{writeFileSync4(fd,JSON.stringify(value)),fsyncSync5(fd)}finally{closeSync15(fd)}linkSync4(tmp,join20(dir,name)),syncDirectory3(dir)}finally{unlinkSync5(tmp)}}var RunDiagnostics=class{dir;owner;snapshotDirectoryIdentity;files=new Map;attempts=new Map;childStderrFinal=new Map;leases=new Set;accepting=!0;failed=!1;drained;sealing;get isFailed(){
|
|
1730
1736
|
return this.failed}constructor(dir,runId){if(this.dir=dir,basename7(dir)!==runId||runId.startsWith(".")||/[/\\\0]/.test(runId))throw new Error("invalid run id");mkdirSync6(dirname14(dir),{recursive:!0});for(let p of[dirname14(dir),dirname14(dirname14(dir))])if(!lstatSync13(p).isDirectory())throw new Error(`unsafe diagnostic directory: ${p}`);mkdirSync6(dir,{mode:448});let st=lstatSync13(dir);this.snapshotDirectoryIdentity={dev:st.dev,ino:st.ino},this.verifySnapshotDirectory(),this.owner={format_version:1,
|
|
1731
1737
|
protocol:PROTOCOL,run_id:runId,owner_id:randomUUID5()},publish(dir,OWNER_FILE,this.owner),syncDirectory3(dirname14(dir)),owners2.set(resolve9(dir),this)}write(name,text2,append=!1){return this.accepting&&this.writeOwned(name,text2,append)}verifySnapshotDirectory(){let st=lstatSync13(this.dir);if(!st.isDirectory()||!process.getuid||st.uid!==process.getuid()||(st.mode&18)!==0)throw new Error("unsafe diagnostic directory");if(st.dev!==this.snapshotDirectoryIdentity.dev||st.ino!==this.snapshotDirectoryIdentity.
|
|
@@ -1809,16 +1815,16 @@ release}}catch(err){let message=`stderr for ${stderrName} fell back to a private
|
|
|
1809
1815
|
try{rmSync7(dir,{recursive:!0,force:!0})}catch{}}}}function finishTrace(attempt,outcome,failure){try{attempt?.finish(outcome,failure)}catch{}}function traceCancel(attempt,fn){try{attempt&&fn(attempt)}catch{}}async function runSubagentProcess(opts){let clock=opts.clock??{now:()=>Date.now(),setTimeout:(callback,ms)=>globalThis.setTimeout(callback,ms),clearTimeout:handle=>globalThis.clearTimeout(handle)};if(opts.evidenceAttemptId&&!opts.spawnChild)throw new Error("evidence dispatch disabled: runtim\
|
|
1810
1816
|
e executable/import isolation is not established");let session=opts.session,flowTelemetry=opts.flowTelemetry??session?.flowTelemetry;flowTelemetry?.assertCanDispatch();let recordEvent2=opts.recordEvent??(()=>{}),envGetter=opts.env;try{session?.cancellation.throwIfCancelled(),opts.cancellation?.throwIfCancelled()}catch(err){let scope=session?.cancellation.isCancelled?"whole-run":"selected";traceCancel(opts.traceAttempt,a=>a.cancelRequested?.({scope,reason:"run_cancelled"})),finishTrace(opts.traceAttempt,
|
|
1811
1817
|
"cancelled"),traceCancel(opts.traceAttempt,a=>a.cancelObserved?.({scope,state:"applied",reason:"cancelled_before_spawn"}));try{opts.traceAttempt?.observeClose?.()}catch{}throw err}let taskId=opts.taskId??`${opts.agentName}-${clock.now()}`,safeTaskId=taskId.replace(/[^a-zA-Z0-9._-]+/g,"_"),attempt=session?.diagnostics.claimAttempt(safeTaskId)??1,eventsName=`${safeTaskId}.events.jsonl`,stderrName=attempt===1?`${safeTaskId}.stderr.log`:`${safeTaskId}.attempt-${attempt}.stderr.log`;if(session){try{session.
|
|
1812
|
-
writeDiagnostic(`${safeTaskId}.prompt.md`,opts.task)}catch{}session.startDispatch(taskId,opts.label??opts.agentName,opts.model,opts.depth??0,opts.agentName===NO_PERSONA?void 0:opts.agentName,opts.capability)}let personaResolution=resolvePersona({cwd:opts.cwd,agentName:opts.agentName,noPersonaSentinel:NO_PERSONA,discoverAgents:opts.discoverAgentsFn??discoverAgents,tmpPrefix:PERSONA_TMP_PREFIX});if(personaResolution.error&&session){session.log(`persona resolution for ${opts.agentName}
|
|
1813
|
-
error}`);try{session.writeDiagnostic(`${safeTaskId}.persona-error.log`,personaResolution.error)}catch{}}let tools=opts.tools&&opts.tools.length>0?opts.tools:personaResolution.tools;if(opts.agentName!==NO_PERSONA&&(personaResolution.error||!tools?.length)){let message=`persona ${opts.agentName} unavailable: ${personaResolution.error??"no tool allow-list"}`;personaResolution.cleanup(),session?.endDispatch(taskId,1,0,message),finishTrace(opts.traceAttempt,"failed",{code:"
|
|
1814
|
-
opts.traceAttempt?.observeClose?.()}catch{}throw new Error(message)}let personaCanMutate=personaCanMutateFor(tools),args2=buildChildArgs({model:opts.model,effort:opts.effort,promptPath:personaResolution.promptPath,tools}),promptLine=rpcPromptLine(renderTaskWithContext(opts.task,void 0));opts.evidenceAttemptId&&args2.push("--no-approve","--no-context-files","--offline","-e",fileURLToPath5(new URL(`./evidence-guard${extname(fileURLToPath5(import.meta.url))}`,import.meta.
|
|
1815
|
-
evidenceGuardReady=!1,evidenceModels=new Set,evidenceUsageComplete=!0,startedAt=clock.now(),flowAttempt=flowTelemetry?.beginAttempt(opts.flowTaskId??taskId,opts.capability??"worker",opts.model,opts.flowRouteReason),lastUsageAt=startedAt,approvedInputsFile=session?join22(session.dir,FLOW_APPROVED_INPUTS_FILE):void 0,hasApprovedInputs=approvedInputsFile!==void 0&&lstatSync14(approvedInputsFile,{throwIfNoEntry:!1})?.isFile(),releaseProducer=flowTelemetry?.registerProducer(),
|
|
1816
|
-
(resolve11,reject)=>{(async()=>{let invocation=orchCliInvocation(args2),env=buildChildEnv(envGetter(),{cwd:opts.cwd,trace:opts.traceAttempt?.env,trustedAgentsDir:getFlowAgentsDir(),...opts.residentModels?{residentModels:opts.residentModels}:{},...hasApprovedInputs?{approvedInputsFile}:{}});env.HUMAIN_ORCHESTRATOR_KILL_GRACE_MS=String(dispatchChildKillGraceMs());let marker=session?.recovery?.markerForAttempt?.(taskId);marker&&(env[LINEAGE_ENV]=marker),opts.
|
|
1817
|
-
opts.cwd,env.HUMAIN_ORCHESTRATOR_EVIDENCE_ATTEMPT=opts.evidenceAttemptId);let buffer="",stdoutCapture=new BoundedCapture,stderrCapture=new BoundedCapture,events=new ChildEventAccumulator,nestedCost=new NestedCostTracker,telemetryTracker=new DispatchTelemetryTracker,spentSoFar=()=>events.usage.cost+nestedCost.total(),nestedProviderErrors=[],lastNestedProviderError=new Map,timedOut=!1,cancelledByListener=!1,signalled=!1,signalledScopes=new Set,
|
|
1818
|
-
launchRegistrationFailed,settled=!1,promptSent=!1,turnActive=!1,unregisterLive,startupTimer,steerSeq=0,pendingSteers=new Map,resolveSteer=(id2,accepted)=>{let done=pendingSteers.get(id2);pendingSteers.delete(id2),done?.(accepted)},rejectPendingSteers=()=>{for(let id2 of[...pendingSteers.keys()])resolveSteer(id2,!1)},clearStartupTimer=()=>{startupTimer!==void 0&&(clock.clearTimeout(startupTimer),startupTimer=void 0)},processClosed=!1,processExited=!1,
|
|
1819
|
-
pendingResult&&(timeoutTimer!==void 0&&(clock.clearTimeout(timeoutTimer),timeoutTimer=void 0),resolve11({...pendingResult,processTerminationConfirmed:processExited||processClosed||spawnFailed&&proc?.pid===void 0}),pendingResult=void 0)},controlTarget,selectedCancellation=opts.cancellation??new RunCancellation,timeoutTimer,removeCancellationListener,removeSpendListener,progressTracker,dispatchStartedAt=startedAt,toolCalls=0,effectObservationComplete=!0,
|
|
1820
|
-
assistantTurns=0,interruptionNote,armTimer=()=>{},handleExpiry=()=>{},handleSpendCap=()=>{},postEndGraceTimer,exitDrainTimer,postEndGraceExpired=!1,postEndGraceMs=DEFAULT_POST_END_GRACE_MS,armPostEndGrace=()=>{},cancelPostEndGrace=()=>{},handlePostEndGraceExpired=()=>{},assistantTexts=[],cleanupPrompt=()=>{personaResolution.cleanup()},recordInterruption=reason=>{if(interruptionNote)return interruptionNote;let now=clock.now();return progressTracker||
|
|
1821
|
-
opts.capability,envGetter()),dispatchStartedAt)),interruption=buildInterruptionReport({taskId,reason,startedAt:dispatchStartedAt,now,turns:assistantTurns,toolCalls,partialText:assistantTexts[assistantTexts.length-1]??"",tracker:progressTracker}),interruptionNote=renderInterruptionReport(interruption),stderrCapture.append(`
|
|
1818
|
+
writeDiagnostic(`${safeTaskId}.prompt.md`,opts.task)}catch{}session.startDispatch(taskId,opts.label??opts.agentName,opts.model,opts.depth??0,opts.agentName===NO_PERSONA?void 0:opts.agentName,opts.capability,opts.replacement)}let personaResolution=resolvePersona({cwd:opts.cwd,agentName:opts.agentName,noPersonaSentinel:NO_PERSONA,discoverAgents:opts.discoverAgentsFn??discoverAgents,tmpPrefix:PERSONA_TMP_PREFIX});if(personaResolution.error&&session){session.log(`persona resolution for ${opts.agentName}\
|
|
1819
|
+
failed: ${personaResolution.error}`);try{session.writeDiagnostic(`${safeTaskId}.persona-error.log`,personaResolution.error)}catch{}}let tools=opts.tools&&opts.tools.length>0?opts.tools:personaResolution.tools;if(opts.agentName!==NO_PERSONA&&(personaResolution.error||!tools?.length)){let message=`persona ${opts.agentName} unavailable: ${personaResolution.error??"no tool allow-list"}`;personaResolution.cleanup(),session?.endDispatch(taskId,1,0,message),finishTrace(opts.traceAttempt,"failed",{code:"\
|
|
1820
|
+
persona_unavailable"});try{opts.traceAttempt?.observeClose?.()}catch{}throw new Error(message)}let personaCanMutate=personaCanMutateFor(tools),args2=buildChildArgs({model:opts.model,effort:opts.effort,promptPath:personaResolution.promptPath,tools}),promptLine=rpcPromptLine(renderTaskWithContext(opts.task,void 0));opts.evidenceAttemptId&&args2.push("--no-approve","--no-context-files","--offline","-e",fileURLToPath5(new URL(`./evidence-guard${extname(fileURLToPath5(import.meta.url))}`,import.meta.
|
|
1821
|
+
url)));let evidenceUnsupported=new Set,evidenceGuardReady=!1,evidenceModels=new Set,evidenceUsageComplete=!0,startedAt=clock.now(),flowAttempt=flowTelemetry?.beginAttempt(opts.flowTaskId??taskId,opts.capability??"worker",opts.model,opts.flowRouteReason),lastUsageAt=startedAt,approvedInputsFile=session?join22(session.dir,FLOW_APPROVED_INPUTS_FILE):void 0,hasApprovedInputs=approvedInputsFile!==void 0&&lstatSync14(approvedInputsFile,{throwIfNoEntry:!1})?.isFile(),releaseProducer=flowTelemetry?.registerProducer(),
|
|
1822
|
+
childOwnsProducer=!1;return new Promise((resolve11,reject)=>{(async()=>{let invocation=orchCliInvocation(args2),env=buildChildEnv(envGetter(),{cwd:opts.cwd,trace:opts.traceAttempt?.env,trustedAgentsDir:getFlowAgentsDir(),...opts.residentModels?{residentModels:opts.residentModels}:{},...hasApprovedInputs?{approvedInputsFile}:{}});env.HUMAIN_ORCHESTRATOR_KILL_GRACE_MS=String(dispatchChildKillGraceMs());let marker=session?.recovery?.markerForAttempt?.(taskId);marker&&(env[LINEAGE_ENV]=marker),opts.
|
|
1823
|
+
evidenceAttemptId&&(env.HUMAIN_ORCHESTRATOR_EVIDENCE_CANDIDATE=opts.cwd,env.HUMAIN_ORCHESTRATOR_EVIDENCE_ATTEMPT=opts.evidenceAttemptId);let buffer="",stdoutCapture=new BoundedCapture,stderrCapture=new BoundedCapture,events=new ChildEventAccumulator,nestedCost=new NestedCostTracker,telemetryTracker=new DispatchTelemetryTracker,spentSoFar=()=>events.usage.cost+nestedCost.total(),nestedProviderErrors=[],lastNestedProviderError=new Map,timedOut=!1,cancelledByListener=!1,signalled=!1,signalledScopes=new Set,
|
|
1824
|
+
timeoutReason,toolInFlight,interruption,spawnFailed=!1,launchRegistrationFailed,settled=!1,promptSent=!1,turnActive=!1,unregisterLive,startupTimer,steerSeq=0,pendingSteers=new Map,resolveSteer=(id2,accepted)=>{let done=pendingSteers.get(id2);pendingSteers.delete(id2),done?.(accepted)},rejectPendingSteers=()=>{for(let id2 of[...pendingSteers.keys()])resolveSteer(id2,!1)},clearStartupTimer=()=>{startupTimer!==void 0&&(clock.clearTimeout(startupTimer),startupTimer=void 0)},processClosed=!1,processExited=!1,
|
|
1825
|
+
terminationGraceExpired=!1,pendingResult,deliverResult=()=>{pendingResult&&(timeoutTimer!==void 0&&(clock.clearTimeout(timeoutTimer),timeoutTimer=void 0),resolve11({...pendingResult,processTerminationConfirmed:processExited||processClosed||spawnFailed&&proc?.pid===void 0}),pendingResult=void 0)},controlTarget,selectedCancellation=opts.cancellation??new RunCancellation,timeoutTimer,removeCancellationListener,removeSpendListener,progressTracker,dispatchStartedAt=startedAt,toolCalls=0,effectObservationComplete=!0,
|
|
1826
|
+
stdoutClosed=!1,toolExecutionsStarted=0,nestedActivity=!1,assistantTurns=0,interruptionNote,armTimer=()=>{},handleExpiry=()=>{},handleSpendCap=()=>{},postEndGraceTimer,exitDrainTimer,postEndGraceExpired=!1,postEndGraceMs=DEFAULT_POST_END_GRACE_MS,armPostEndGrace=()=>{},cancelPostEndGrace=()=>{},handlePostEndGraceExpired=()=>{},assistantTexts=[],cleanupPrompt=()=>{personaResolution.cleanup()},recordInterruption=reason=>{if(interruptionNote)return interruptionNote;let now=clock.now();return progressTracker||
|
|
1827
|
+
(progressTracker=new DispatchProgressTracker(resolveDispatchTimeoutPolicy(opts.capability,envGetter()),dispatchStartedAt)),interruption=buildInterruptionReport({taskId,reason,startedAt:dispatchStartedAt,now,turns:assistantTurns,toolCalls,partialText:assistantTexts[assistantTexts.length-1]??"",tracker:progressTracker}),interruptionNote=renderInterruptionReport(interruption),stderrCapture.append(`
|
|
1822
1828
|
${interruptionNote}`),interruptionNote},diagnosticWriter,stderrPrefix="",stderrTarget,settledFileBytes,noteWriteBytes,currentStderrFileBytes=()=>{if(!stderrTarget)return 0;try{return statSync7(stderrTarget.path).size}catch{return 0}},finish=processExitCode=>{if(settled)return;let cancelled=cancelledByListener||session?.cancellation.isCancelled===!0||opts.cancellation?.isCancelled===!0;cancelledByListener=cancelled,cancelled&&session?.log(recordInterruption("cancelled")),settled=!0,unregisterLive?.(),
|
|
1823
1829
|
rejectPendingSteers(),clearStartupTimer(),removeSpendListener?.(),timeoutTimer!==void 0&&(clock.clearTimeout(timeoutTimer),timeoutTimer=void 0),exitDrainTimer!==void 0&&clearTimeout(exitDrainTimer),cancelPostEndGrace(),cleanupPrompt();let fileBytes=currentStderrFileBytes();settledFileBytes===void 0&&(settledFileBytes=fileBytes);let fileText=fileBytes>0?readStderrFileBounded(stderrTarget.path):"",rawStderr=stderrCapture.text()+(fileText?`
|
|
1824
1830
|
${fileText}`:""),stderrSummary=summarizeStderr(rawStderr),finalText=assistantTexts.length>0?assistantTexts[assistantTexts.length-1]:"",outcome=classifyDispatchOutcome({exitCode:processExitCode,sawAgentSettled:events.sawAgentSettled,sawAgentEnd:events.sawAgentEnd,hasFinalText:!!finalText,lastStopReason:events.stopReason,timedOut,cancelled,spawnFailed,stderrSummary});flowAttempt?.finish(outcome.status==="cancelled"?"cancelled":outcome.effectiveExitCode===0?"succeeded":"failed",flowTelemetry?.stopped?
|
|
@@ -1848,8 +1854,8 @@ append(eventsName,`${JSON.stringify(trimEventForLog(event2))}
|
|
|
1848
1854
|
lastNestedProviderError.get(worker.taskId)!==worker.errorMessage&&(lastNestedProviderError.set(worker.taskId,worker.errorMessage),nestedProviderErrors.push({message:worker.errorMessage.slice(0,16384),timestamp:new Date(now).toISOString()})):lastNestedProviderError.delete(worker.taskId);if(opts.evidenceAttemptId&&(event2.type==="task_evidence_guard_ready"&&event2.attemptId===opts.evidenceAttemptId&&(evidenceGuardReady=!0),(event2.type==="auto_retry_start"||event2.type==="auto_compaction_start")&&
|
|
1849
1855
|
evidenceUnsupported.add(event2.type),event2.type==="tool_execution_start"&&!["read","edit","write"].includes(String(event2.toolName))&&evidenceUnsupported.add("unsupported_tool"),event2.type==="message_end"&&event2.message?.role==="assistant")){let message=event2.message;evidenceModels.add(`${message.provider??"unknown"}/${message.responseModel??message.model??"unknown"}`);let expected=opts.model.slice(opts.model.indexOf("/")+1);(message.model!==expected||message.responseModel!==void 0&&message.
|
|
1850
1856
|
responseModel!==expected||message.provider!==opts.model.split("/")[0])&&evidenceUnsupported.add("model_identity_mismatch"),["input","output","cacheRead","cacheWrite"].every(key=>typeof message.usage?.[key]=="number"&&Number.isSafeInteger(message.usage[key])&&message.usage[key]>=0)||(evidenceUsageComplete=!1,evidenceUnsupported.add("incomplete_usage")),(message.stopReason==="error"||message.stopReason==="aborted")&&evidenceUnsupported.add("unsuccessful_turn")}let delta=events.absorb(event2);if(session?.
|
|
1851
|
-
onChildEvent(taskId,event2,delta),delta.turn
|
|
1852
|
-
[provider ${delta.turn.errorKind}] ${delta.turn.errorMessage}`),delta.turn.text&&assistantTexts.push(delta.turn.text),recordFlowUsage(event2,now),
|
|
1857
|
+
onChildEvent(taskId,event2,delta),delta.turn){if(assistantTurns+=1,delta.turn.errorMessage&&delta.turn.errorKind&&stderrCapture.append(`
|
|
1858
|
+
[provider ${delta.turn.errorKind}] ${delta.turn.errorMessage}`),delta.turn.text&&assistantTexts.push(delta.turn.text),recordFlowUsage(event2,now),delta.turn.hadUsage){let verdict=session?.spendCaps.observe(taskId,opts.capability??"unknown",spentSoFar()+(opts.spendCapOffsetUsd??0))??"ok";verdict!=="ok"&&handleSpendCap(verdict==="stop"&&delta.turn.stopReason==="stop"?"warn":verdict)}stopOnUnknownCost(event2,delta.turn.stopReason)}if(event2.type==="compaction_end"&&(recordFlowUsage(event2,now),stopOnUnknownCost(
|
|
1853
1859
|
event2,void 0)),delta.turn?.hadUsage&&telemetryTracker.observeContextTokens(event2.message?.usage?.totalTokens),event2.type==="tool_execution_start"&&typeof event2.toolName=="string"&&telemetryTracker.observeToolCall(event2.toolName,event2.args),nestedCost.observe(event2,now)){nestedActivity=!0,session?.setNestedCost(taskId,nestedCost.total());let verdict=session?.spendCaps.observe(taskId,opts.capability??"unknown",spentSoFar()+(opts.spendCapOffsetUsd??0))??"ok";verdict!=="ok"&&handleSpendCap(verdict)}
|
|
1854
1860
|
if(event2.toolName==="subagent"&&flowAttempt?.recordNested(nestedCost.entries()),event2.toolName==="subagent"&&stopOnNestedOverflow(),flowTelemetry?.stopped&&POST_END_GRACE_CANCEL_TYPES.has(event2.type??"")&&handleSpendCap("stop"),delta.ended||delta.turn&&delta.turn.stopReason==="error")armPostEndGrace(postEndGraceMs);else if(event2.type==="auto_retry_start"){let retryError=event2.errorMessage;if(!cancelledByListener&&events.stopReason==="error"&&typeof retryError=="string"&&isQuotaError(retryError)){
|
|
1855
1861
|
stderrCapture.append(`
|
|
@@ -1893,16 +1899,17 @@ let results=Array.isArray(e.result?.details?.results)?e.result.details.results:[
|
|
|
1893
1899
|
errorMessage.slice(0,LAST_ERROR_MESSAGE_HEAD_LIMIT))}}}return{toolCalls,toolInFlight:inFlight.size>0,lastErrorMessage,lastAssistantText:lastAssistantText2,finishedWorkers,unfinishedWorkers:[...pendingSubagent.values()].flat(),subagentCalls}}var ORCHESTRATOR_LINE_RE=/^\s*(\[orchestrator\]|⚠|taskId:|elapsedMs:|sinceLastProgressMs:|turns:|toolCalls:|repeatedToolCalls:|lastProgress:|nestedWorkers:|verified:|partialText:)/,INTERRUPTION_REPORT_START_RE=/^\s*UNVERIFIED PARTIAL WORK\b/;function providerText(stderr,errorMessage){let lines=[];for(let raw of stderr.split(/\r?\n/)){if(INTERRUPTION_REPORT_START_RE.test(raw))break;raw.trim()&&!ORCHESTRATOR_LINE_RE.test(raw)&&lines.push(raw)}return[...lines,errorMessage??""].filter(Boolean).join(
|
|
1894
1900
|
`
|
|
1895
1901
|
`)}function attemptSignals(input){return{...input}}function attemptSignalsFromScan(attempt,scan,cancelled){return attemptSignals({exitCode:attempt.exitCode,outcome:attempt.outcome,stderr:attempt.stderr??"",errorMessage:scan.lastErrorMessage,stopReason:attempt.stopReason,timeoutReason:attempt.timeoutReason,toolInFlight:scan.toolInFlight,cancelled})}function classifyFailure(s){if(s.cancelled||s.outcome==="cancelled")return"cancelled";if(s.exitCode===0&&(s.outcome==="completed"||s.outcome==="comple\
|
|
1896
|
-
ted_after_process_error"))return"ok";if(s.stopReason==="spend_cap")return"task";let text2=providerText(s.stderr,s.errorMessage);return isQuotaError(text2)?s.outcome==="timed_out"?"task":"quota":isTransientProviderError(text2)?"transient":s.outcome==="timed_out"&&s.timeoutReason==="inactivity"&&!s.toolInFlight?"stall":"task"}function telemetryFailureClass(cls,timedOut){switch(cls){case"
|
|
1897
|
-
return cls}}function failureReason(s,max=160){let lines=providerText(redactCredentials(s.stderr),s.errorMessage===void 0?void 0:redactCredentials(s.errorMessage)).split(`
|
|
1898
|
-
`),hit=lines.find(l=>isQuotaError(l)||isTransientProviderError(l))??lines.find(l=>l.trim())??"",fallback=s.outcome==="timed_out"?`timed out (${s.timeoutReason??"unknown"})`:`exit ${s.exitCode}`;return sanitizeControlChars(hit.trim()||fallback).slice(0,max)}function hadRealWork(scan,filesChanged,minToolCalls){return filesChanged.length>0||scan.finishedWorkers.length>0||scan.toolCalls>=minToolCalls}function failoverConfig(rule=METHOD.rules.model_failover){return{unhealthyMs:rule.unhealthy_ms,sameModelRetryDelayMs:rule.same_model_retry_delay_ms,waitScheduleMs:[...rule.wait_schedule_ms],maxWaitMs:rule.max_wait_ms,maxSwitches:rule.max_switches,realWorkMinToolCalls:rule.real_work_min_tool_calls}}function initialState(candidates,start=0){return{candidates,current:start,attempted:[start],quotaFailed:[],sameModelRetried:!1,switches:0,waitIndex:0,waitedMs:0}}function pickCandidate(state,isHealthy){
|
|
1899
|
-
let index=state.candidates.findIndex((model,i)=>!state.attempted.includes(i)&&!state.quotaFailed.includes(model)&&isHealthy(model));return index<0?null:index}function waitOrGiveUp(state,cfg){if(state.candidates.length>0&&state.candidates.every(model=>state.quotaFailed.includes(model)))return{kind:"give-up",reason:
|
|
1900
|
-
length-1)];return{kind:"wait",delayMs:Math.min(planned,remaining)}}function nextStep(state,failure,realWork,isHealthy,cfg){
|
|
1901
|
-
cfg)}function applyStep(state,step){switch(step.kind){case"retry-same":return{...state,sameModelRetried:!0};case"switch":return{...state,current:step.index,attempted:[...state.attempted,step.index],switches:state.switches+1,sameModelRetried:!1};case"
|
|
1902
|
+
ted_after_process_error"))return"ok";if(s.stopReason==="spend_cap")return"task";if(s.stopReason==="unknown_cost")return"unknown_cost";let text2=providerText(s.stderr,s.errorMessage);return isQuotaError(text2)?s.outcome==="timed_out"?"task":"quota":isTransientProviderError(text2)?"transient":s.outcome==="timed_out"&&s.timeoutReason==="inactivity"&&!s.toolInFlight?"stall":"task"}function telemetryFailureClass(cls,timedOut){switch(cls){case"unknown_cost":return"transient";case"transient":return timedOut?
|
|
1903
|
+
"provider_stall":"transient";case"stall":return"provider_stall";case"ok":return"task";default:return cls}}function failureReason(s,max=160){if(s.stopReason==="unknown_cost")return"provider usage incomplete; request cost unknown (not free)".slice(0,max);let lines=providerText(redactCredentials(s.stderr),s.errorMessage===void 0?void 0:redactCredentials(s.errorMessage)).split(`
|
|
1904
|
+
`),hit=lines.find(l=>isQuotaError(l)||isTransientProviderError(l))??lines.find(l=>l.trim())??"",fallback=s.outcome==="timed_out"?`timed out (${s.timeoutReason??"unknown"})`:`exit ${s.exitCode}`;return sanitizeControlChars(hit.trim()||fallback).slice(0,max)}function hadRealWork(scan,filesChanged,minToolCalls){return filesChanged.length>0||scan.finishedWorkers.length>0||scan.toolCalls>=minToolCalls}function failoverConfig(rule=METHOD.rules.model_failover){return{unhealthyMs:rule.unhealthy_ms,sameModelRetryDelayMs:rule.same_model_retry_delay_ms,waitScheduleMs:[...rule.wait_schedule_ms],maxWaitMs:rule.max_wait_ms,maxSwitches:rule.max_switches,realWorkMinToolCalls:rule.real_work_min_tool_calls}}function initialState(candidates,start=0){return{candidates,current:start,attempted:[start],quotaFailed:[],unknownCostFailed:[],sameModelRetried:!1,switches:0,waitIndex:0,waitedMs:0}}function pickCandidate(state,isHealthy){
|
|
1905
|
+
let index=state.candidates.findIndex((model,i)=>!state.attempted.includes(i)&&!state.quotaFailed.includes(model)&&!state.unknownCostFailed.includes(model)&&isHealthy(model));return index<0?null:index}function waitOrGiveUp(state,cfg){if(state.candidates.length>0&&state.candidates.every(model=>state.quotaFailed.includes(model)||state.unknownCostFailed.includes(model)))return{kind:"give-up",reason:state.unknownCostFailed.length?"unknown-cost-exhausted":"quota-exhausted"};let remaining=cfg.maxWaitMs-
|
|
1906
|
+
state.waitedMs;if(remaining<=0)return{kind:"give-up",reason:"max-wait"};let planned=cfg.waitScheduleMs[Math.min(state.waitIndex,cfg.waitScheduleMs.length-1)];return{kind:"wait",delayMs:Math.min(planned,remaining)}}function nextStep(state,failure,realWork,isHealthy,cfg){let candidateFailure=failure==="quota"||failure==="unknown_cost";if(!candidateFailure&&realWork&&!state.sameModelRetried)return{kind:"retry-same",delayMs:cfg.sameModelRetryDelayMs};if(!candidateFailure&&state.switches>=cfg.maxSwitches)
|
|
1907
|
+
return{kind:"give-up",reason:"max-switches"};let index=pickCandidate(state,isHealthy);return index!==null?{kind:"switch",index}:candidateFailure?{kind:"give-up",reason:failure==="unknown_cost"?"unknown-cost-exhausted":"quota-exhausted"}:waitOrGiveUp(state,cfg)}function applyStep(state,step){switch(step.kind){case"retry-same":return{...state,sameModelRetried:!0};case"switch":return{...state,current:step.index,attempted:[...state.attempted,step.index],switches:state.switches+1,sameModelRetried:!1};case"\
|
|
1908
|
+
wait":return{...state,attempted:[],waitIndex:state.waitIndex+1,waitedMs:state.waitedMs+step.delayMs};case"give-up":return state}}function resumeAfterWait(state,index){return{...state,current:index,attempted:[index],sameModelRetried:!1}}async function dispatchWithFailover(task,candidates,deps){if(candidates.length===0)throw new Error(`dispatchWithFailover: no candidate models for ${task.taskId}`);let healthy=m=>deps.health.isHealthy(m),start=candidates.findIndex(healthy),state=initialState(candidates,start>=0?start:0),prompt=task.prompt,spent=0,files=new Set,filesUnknown=!1,attempts=[],switches=[],waitedMs=0;for(;;){let model=candidates[state.current],snap=deps.snapshot(),n=attempts.length+1,delayMs=waitedMs;waitedMs=0;let result=await deps.
|
|
1902
1909
|
runAttempt(model,prompt,n,spent,delayMs,attempts.at(-1)?.record);spent+=result.costUsd+(result.nestedCostUsd??0);let scan=scanEvents(deps.readEvents(result)),signals=attemptSignalsFromScan(result,scan,deps.isCancelled()),cls=classifyFailure(signals),observed=deps.changedSince(snap),changed=observed??[];for(let f of changed)files.add(f);let realWork=observed===null||hadRealWork(scan,changed,deps.config.realWorkMinToolCalls);observed===null&&(filesUnknown=!0);let reason=cls==="ok"?"":failureReason(
|
|
1903
1910
|
signals),observation=result.effectObservation,effectSafe=observation?.complete===!0&&observation.toolExecutionsStarted===0&&observation.nestedActivity===!1&&observed!==null&&changed.length===0&&scan.toolCalls===0&&!scan.toolInFlight&&!scan.subagentCalls.length&&!scan.finishedWorkers.length&&!scan.unfinishedWorkers.length&&(result.nestedCostUsd??0)===0;attempts.push({model,result,record:{model,cls,reason,costUsd:result.costUsd+(result.nestedCostUsd??0),realWork,effectSafe}});let done=(exhausted,r=result)=>({
|
|
1904
1911
|
result:r,attempts,switches,finalModel:model,finalScan:scan,exhausted});if(cls==="cancelled")return done(!1);if(result.processTerminationConfirmed===!1)return done(!0,{...result,exitCode:-1,stderr:`[orchestrator] termination_unconfirmed; automatic retry blocked
|
|
1905
|
-
${result.stderr}`});if(cls==="ok"||cls==="task")return done(!1);deps.health.markUnhealthy(model,cls,deps.config.unhealthyMs),deps.recordEvent("model_unhealthy",{task_id:task.taskId,model,class:cls,for_ms:deps.config.unhealthyMs,reason}),cls==="quota"&&(state={...state,quotaFailed:[...state.quotaFailed,model]}),realWork&&(prompt=`${task.prompt}
|
|
1912
|
+
${result.stderr}`});if(cls==="ok"||cls==="task")return done(!1);deps.health.markUnhealthy(model,cls,deps.config.unhealthyMs),deps.recordEvent("model_unhealthy",{task_id:task.taskId,model,class:cls,for_ms:deps.config.unhealthyMs,reason}),cls==="quota"&&(state={...state,quotaFailed:[...state.quotaFailed,model]}),cls==="unknown_cost"&&(state={...state,unknownCostFailed:[...state.unknownCostFailed,model]}),realWork&&(prompt=`${task.prompt}
|
|
1906
1913
|
|
|
1907
1914
|
${buildHandoff({taskId:task.taskId,attempt:n+1,previousModel:model,failureClass:cls,reason,filesChanged:[...files],filesUnknown,scan,redact:deps.redact})}`);let missingRoute=deps.requireCompatibleBedrock&&cls==="quota"&&billingRouteFor(model)==="subscription"&&!candidates.some(candidate=>candidate.startsWith("amazon-bedrock/")),diagnostic=missingRoute?`no compatible Bedrock route for ${model} after quota exhaustion`:null,step=missingRoute?{kind:"give-up",reason:"max-wait"}:nextStep(state,cls,realWork,
|
|
1908
1915
|
healthy,deps.config),resumed=!1;for(;step.kind==="wait";){if(deps.log(`${task.taskId}: no healthy candidate; waiting ${Math.round(step.delayMs/1e3)}s before retrying the list`),await deps.sleep(step.delayMs),waitedMs+=step.delayMs,state=applyStep(state,step),deps.isCancelled())return done(!1);let index=pickCandidate(state,healthy);index!==null?(state=resumeAfterWait(state,index),step={kind:"switch",index},resumed=!0):step=waitOrGiveUp(state,deps.config)}if(step.kind==="give-up"){let summary=attempts.
|
|
@@ -1948,42 +1955,44 @@ pids,CANCEL_CONFIRM_TIMEOUT_MS),descendants.terminate()]);return childrenGone&&d
|
|
|
1948
1955
|
this.liveChildren.get(native)(text2):Promise.resolve(!1)},emitMessage:payload=>this.emitMessageSafe(payload),holding:()=>this.pendingLeadMessages.length>0||this.leadDraining,hold:pending=>this.cancellation.isCancelled||this.closed||this.flowTelemetry?.stopped||this.pendingLeadMessages.length>=32?!1:(this.pendingLeadMessages.push(pending),!0)}}}flowRoleOf(taskId){let d=this.dispatches.get(taskId);if(d?.capability&&this.flowTelemetry?.roleForCapability)try{return this.flowTelemetry.roleForCapability(
|
|
1949
1956
|
d.capability)}catch{}let role=roleForAgentName(d?.agentName);return FLOW_ROLES.find(known=>known===role)??"worker"}currentLead(){for(let[taskId,steer]of[...this.liveChildren].reverse()){let role=this.flowRoleOf(taskId);if(role==="lead"||role==="lead_large")return{steer,role}}}emitMessageSafe(payload){try{let out=this.flowTelemetry?.emit({kind:"message",payload});out instanceof Promise&&out.catch(()=>{})}catch{}}async drainLeadMessages(){if(!this.leadDraining){this.leadDraining=!0;try{for(await Promise.
|
|
1950
1957
|
resolve();;){let lead=this.currentLead();if(this.cancellation.isCancelled||this.closed||!lead)return;let next=this.pendingLeadMessages.shift();if(!next)return;let{text:text2,...event2}=next,ok2=await lead.steer(text2).catch(()=>!1);this.emitMessageSafe({...event2,targetRole:lead.role,disposition:ok2?"live":"rejected"})}}finally{this.leadDraining=!1}}}registerLiveChild(taskId,steer){return this.liveChildren.set(taskId,steer),this.pendingLeadMessages.length&&this.drainLeadMessages(),()=>{this.liveChildren.
|
|
1951
|
-
get(taskId)===steer&&this.liveChildren.delete(taskId)}}flowControlStatus(){let telemetry=this.flowTelemetry?.status()??{mode:"auto",size:"medium",budgetPct:0,warnings:[]},agents=[...this.dispatches.values()].slice(-64).map(d=>({taskId:telemetryTaskId(d.taskId),role:this.flowRoleOf(d.taskId),model:flowEventModelRef(d.model),state:d.status==="running"?"running":d.status==="done"?"succeeded":d.status==="failed"?"failed":"cancelled"}));return{runId:this.runId,mode:telemetry.
|
|
1952
|
-
state:this.closed?"settled":this.cancellation.isCancelled?"cancelling":this.pauseGate.paused?"paused":this.flowStageKind==="starting"&&agents.length===0?"starting":"running",stage:this.flowStageKind==="starting"?"sizing":this.flowStageKind==="verifying"?"qa":"implementing",agents,budgetPct:telemetry.budgetPct,warnings:telemetry.warnings}}file(name){return join23(this.dir,name)}writeDiagnostic(name,text2){return this.diagnostics.write(name,text2)}setTitle(text2){let title=sanitizeControlChars(
|
|
1953
|
-
text2.trim().replace(/\s+/g," ")));if(!title)throw new Error("Usage: /flow-title <title>");if(!this.writeDiagnostic("title.json",JSON.stringify({title})))throw new Error("Could not save flow title.");this.title=title,this.render()}diagnosticsFailed(){return this.diagnostics.isFailed}async sealDiagnostics(terminal=Promise.resolve(!1)){this.controlAttempts.size&&await this.drainControlAttempts();let sealed=await this.diagnostics.seal(terminal);return sealed||safeUi2(()=>this.ctx.
|
|
1954
|
-
|
|
1955
|
-
void 0&&(this.sentinelDeadlineTimer=setDeadlineTimer(()=>{this.log(`SENTINEL_CHILD_DEADLINE_AT_MS reached (${limits.deadlineAtMs}); aborting run`),this.cancel("signal")},limits.deadlineAtMs,{unref:!0}))}enforceSentinelCost(){if(this.sentinelMaxCostUsd===void 0||this.cancellation.isCancelled)return;let spent=this.totalCost()+this.estimatedCost();spent<=this.sentinelMaxCostUsd||(this.log(`SENTINEL_CHILD_MAX_COST_USD exceeded ($${spent.toFixed(4)} > $${this.sentinelMaxCostUsd});
|
|
1956
|
-
cancel("signal"))}cancel(reason="user"){this.cancellation.isCancelled||(this._cancelReason=reason,this.rejectPendingLeadMessages(),this.phase="cancelling",this.log(`cancellation requested (${reason})`),this.cancellation.cancel(),this.render())}rejectPendingLeadMessages(){for(let{text:_text,...event2}of this.pendingLeadMessages.splice(0))this.emitMessageSafe({...event2,targetRole:"lead",disposition:"rejected"})}log(line){this.latestActivity=line;let stamped=`${new Date().toISOString()}
|
|
1957
|
-
this.diagnostics.write("run.log",`${stamped}
|
|
1958
|
+
get(taskId)===steer&&this.liveChildren.delete(taskId)}}flowControlStatus(){let telemetry=this.flowTelemetry?.status()??{mode:"auto",size:"medium",budgetPct:0,warnings:[]},agents=[...this.dispatches.values()].filter(d=>!d.supersededBy).slice(-64).map(d=>({taskId:telemetryTaskId(d.taskId),role:this.flowRoleOf(d.taskId),model:flowEventModelRef(d.model),state:d.status==="running"?"running":d.status==="done"?"succeeded":d.status==="failed"?"failed":"cancelled"}));return{runId:this.runId,mode:telemetry.
|
|
1959
|
+
mode,size:telemetry.size,state:this.closed?"settled":this.cancellation.isCancelled?"cancelling":this.pauseGate.paused?"paused":this.flowStageKind==="starting"&&agents.length===0?"starting":"running",stage:this.flowStageKind==="starting"?"sizing":this.flowStageKind==="verifying"?"qa":"implementing",agents,budgetPct:telemetry.budgetPct,warnings:telemetry.warnings}}file(name){return join23(this.dir,name)}writeDiagnostic(name,text2){return this.diagnostics.write(name,text2)}setTitle(text2){let title=sanitizeControlChars(
|
|
1960
|
+
redactCredentials(text2.trim().replace(/\s+/g," ")));if(!title)throw new Error("Usage: /flow-title <title>");if(!this.writeDiagnostic("title.json",JSON.stringify({title})))throw new Error("Could not save flow title.");this.title=title,this.render()}diagnosticsFailed(){return this.diagnostics.isFailed}async sealDiagnostics(terminal=Promise.resolve(!1)){this.controlAttempts.size&&await this.drainControlAttempts();let sealed=await this.diagnostics.seal(terminal);return sealed||safeUi2(()=>this.ctx.
|
|
1961
|
+
ui.notify(`Diagnostics remain UNSEALED and archive-ineligible: producer drain/terminal acknowledgement did not complete or sealing failed. Raw diagnostics retained: ${this.dir}`,"warning")),sealed}terminalTiming(){return{started_at:this.startedAtIso,finished_at:new Date().toISOString(),elapsed_ms:Math.max(0,Math.round(performance.now()-this.startedMono)),elapsed_source:"monotonic"}}sentinelMaxCostUsd;sentinelDeadlineTimer;applySentinelLimits(limits){this.sentinelMaxCostUsd=limits.maxCostUsd,limits.
|
|
1962
|
+
deadlineAtMs!==void 0&&(this.sentinelDeadlineTimer=setDeadlineTimer(()=>{this.log(`SENTINEL_CHILD_DEADLINE_AT_MS reached (${limits.deadlineAtMs}); aborting run`),this.cancel("signal")},limits.deadlineAtMs,{unref:!0}))}enforceSentinelCost(){if(this.sentinelMaxCostUsd===void 0||this.cancellation.isCancelled)return;let spent=this.totalCost()+this.estimatedCost();spent<=this.sentinelMaxCostUsd||(this.log(`SENTINEL_CHILD_MAX_COST_USD exceeded ($${spent.toFixed(4)} > $${this.sentinelMaxCostUsd}); abor\
|
|
1963
|
+
ting run`),this.cancel("signal"))}cancel(reason="user"){this.cancellation.isCancelled||(this._cancelReason=reason,this.rejectPendingLeadMessages(),this.phase="cancelling",this.log(`cancellation requested (${reason})`),this.cancellation.cancel(),this.render())}rejectPendingLeadMessages(){for(let{text:_text,...event2}of this.pendingLeadMessages.splice(0))this.emitMessageSafe({...event2,targetRole:"lead",disposition:"rejected"})}log(line){this.latestActivity=line;let stamped=`${new Date().toISOString()}\
|
|
1964
|
+
${line}`;try{this.diagnostics.write("run.log",`${stamped}
|
|
1958
1965
|
`,!0)}catch{}}setPhase(phase,notify=!0){this.phase=phase,this.log(`phase: ${phase}`),notify&&safeUi2(()=>this.ctx.ui.notify(`[${fmtElapsed(Date.now()-this.startedAt)}] ${phase}`,"info")),safeUi2(()=>this.render())}setFlowStage(kind){this.flowStageKind=kind,this.render()}setAwaitingInput(waiting){this.awaitingInput=waiting,this.render()}get confirmationDeclined(){return this.declinedAtGate}recordDeclined(){this.declinedAtGate=!0}flowLiveState(){return{stage:this.flowStageKind,awaitingInput:this.awaitingInput,
|
|
1959
|
-
cancelling:this.cancellation.isCancelled}}flowLiveSnapshot(){let summary=this.summaryInput(this.closedAt??Date.now());return{...summary,title:this.title,goal:this.goal,finished:[...this.dispatches.values()].filter(d
|
|
1960
|
-
set(taskId,{taskId,label:label3,agentName,capability,model,startedAt:now,turns:0,toolCalls:0,lastActivity:"starting",activityTail:["starting"],costUsd:0,nestedCostUsd:0,status:"running"
|
|
1961
|
-
|
|
1962
|
-
|
|
1963
|
-
|
|
1964
|
-
push(changed),d.activityTail.length>MAX_ACTIVITY_TAIL&&d.activityTail.splice(0,d.activityTail.length-MAX_ACTIVITY_TAIL)),this.scheduleRender()}endDispatch(taskId,exitCode,costUsd,note,usageReported=!0){
|
|
1965
|
-
note));d.lastActivity=diagnostic??(d.status==="cancelled"?"cancelled by user":exitCode===0?"finished":`exit ${exitCode}`),this.log(`dispatch ${taskId} ${d.status} in ${fmtElapsed(d.endedAt-d.startedAt)}
|
|
1966
|
-
this.enforceSentinelCost(),this.scheduleRender())}totalCost(){let c=0;for(let d of this.dispatches.values())c+=d.costUsd+d.nestedCostUsd;return c+this.externalCostUsd}externalCostUsd=0;externalEstimatedUsd=0;externalHasEstimate=!1;externalHasReported=!1;externalUsageUnknown=!1;addExternalCost(usd,complete,estimatedUsd=0,basis=complete?
|
|
1967
|
-
complete=!1,basis=(reported??0)>0||(estimated??0)>0?"partial":"unknown"),usd=reported??0,estimatedUsd=estimated??0,this.externalCostUsd+=usd,this.externalHasReported||=basis==="reported"||usd>0,this.externalEstimatedUsd+=estimatedUsd,this.externalHasEstimate||=basis==="estimated"||estimatedUsd>0,(basis==="partial"||basis==="unknown"||!complete&&
|
|
1968
|
-
for(let d of this.dispatches.values())if(d.endedAt===void 0||d.usageUnreported)return!1;return!0}estimatedCost(){return this.externalEstimatedUsd}costBasis(){let dispatches=[...this.dispatches.values()],hasUnknown=this.externalUsageUnknown||dispatches.some(d=>d.endedAt===void 0||d.usageUnreported),hasKnown=this.externalHasReported||this.externalHasEstimate||
|
|
1969
|
-
"estimated":"reported"}scheduleRender(){this.renderTimer||(this.renderTimer=setTimeout(()=>{this.renderTimer=void 0,this.render()},250))}setPendingChecks(rows){this.pendingChecks=rows.slice(0,MAX_PENDING_CHECKS).map(row=>({...row})),this.render()}summaryInput(now){let dispatches=[...this.dispatches.values()]
|
|
1970
|
-
find(d=>d.progress.warning)?.progress.warning;return{phase:this.phase,elapsedMs:now-this.startedAt,costUsd:this.totalCost()||void 0,running:running.length,ended:dispatches.filter(d=>d.status==="done").length,failed:dispatches.filter(d=>d.status==="failed").length,cancelled:dispatches.filter(d=>d.status==="cancelled").
|
|
1971
|
-
|
|
1972
|
-
holdsWidget()||(safeUi2(()=>{let theme=this.ctx.ui.theme??plainTheme,ciPending=this.pendingChecks.filter(row=>row.outcome==="pending").length;this.ctx.ui.setStatus("orchestrator",styleSegments([["muted","HUMAIN Code - Flow "],["accent",sanitizeControlChars(
|
|
1973
|
-
|
|
1966
|
+
cancelling:this.cancellation.isCancelled}}flowLiveSnapshot(){let summary=this.summaryInput(this.closedAt??Date.now());return{...summary,title:this.title,goal:this.goal,finished:[...this.dispatches.values()].filter(d=>!d.supersededBy&&d.status!=="running").length,total:[...this.dispatches.values()].filter(d=>!d.supersededBy).length,latest:this.latestActivity,pendingChecks:summary.ciPending,replacedAttempts:[...this.dispatches.values()].filter(d=>d.supersededBy).map(d=>`${d.label} replaced by ${d.
|
|
1967
|
+
supersededBy}`)}}startDispatch(taskId,label3,model,depth=0,agentName=label3,capability,replacement){let previous=replacement&&this.dispatches.get(replacement.taskId);previous&&(previous.supersededBy=label3),this.flowStageKind==="starting"&&(this.flowStageKind="running");let now=Date.now();this.dispatches.set(taskId,{taskId,label:label3,agentName,capability,model,startedAt:now,turns:0,toolCalls:0,lastActivity:"starting",activityTail:["starting"],costUsd:0,nestedCostUsd:0,status:"running",...previous?
|
|
1968
|
+
{backup:`backup for ${shortName(previous.model)} (${replacement.reasonClass})`}:{},depth,progress:createProgressView(now)}),this.log(`dispatch ${taskId} \u2192 ${label3} on ${model} (depth=${depth})`),this.render()}recordProgress(taskId,observation,check2,now=Date.now()){let dispatch=this.dispatches.get(taskId);if(!dispatch)return;applyObservation(dispatch.progress,observation,now),observation.kind==="progress"&&(this.latestActivity=`${dispatch.label}: ${observation.detail}`),applyWarnings(dispatch.
|
|
1969
|
+
progress,check2.warnings,now,warning=>this.log(` ${taskId} ${warning}`));let detail=observation.detail.replace(/\s+/g," ").trim();observation.kind==="progress"&&detail!=="tool execution completed"&&dispatch.lastLoggedProgressDetail!==detail&&(detail.startsWith("nested worker progress")||dispatch.lastLoggedProgressAt===void 0||now-dispatch.lastLoggedProgressAt>=6e4)&&(dispatch.lastLoggedProgressDetail=detail,dispatch.lastLoggedProgressAt=now,this.log(` ${taskId} progress: ${detail}`)),this.scheduleRender()}onChildEvent(taskId,event2){
|
|
1970
|
+
let d=this.dispatches.get(taskId);if(!d)return;let changed=null;switch(event2?.type){case"tool_execution_start":{d.toolCalls+=1,d.lastTool=event2.toolName;let detail=shortArgs(event2.toolName,event2.args);changed=`${event2.toolName}${detail?` ${detail}`:""}`,this.log(` ${taskId} tool#${d.toolCalls} ${changed}`);break}case"tool_execution_end":event2.isError&&(changed=`${event2.toolName} \u2717`,this.log(` ${taskId} tool ${event2.toolName} returned error`));break;case"message_start":event2.message?.
|
|
1971
|
+
role==="assistant"&&(changed="thinking");break;case"message_end":event2.message?.role==="assistant"&&(d.turns+=1,d.costUsd+=reportedCost2(event2.message?.usage?.cost?.total)??0,this.enforceSentinelCost(),changed=`turn ${d.turns} done (${d.toolCalls} tools)`);break;default:return}changed&&(this.latestActivity=`${d.label}: ${changed}`,d.lastActivity=changed,d.activityTail.push(changed),d.activityTail.length>MAX_ACTIVITY_TAIL&&d.activityTail.splice(0,d.activityTail.length-MAX_ACTIVITY_TAIL)),this.scheduleRender()}endDispatch(taskId,exitCode,costUsd,note,usageReported=!0){
|
|
1972
|
+
let d=this.dispatches.get(taskId);if(!d)return;d.usageUnreported=!usageReported,d.endedAt=Date.now(),d.status=this.cancellation.isCancelled?"cancelled":exitCode===0?"done":"failed",d.costUsd=costUsd||d.costUsd,this.enforceSentinelCost();let diagnostic=note===void 0?void 0:redactPaths2(redactCredentials(note));d.lastActivity=diagnostic??(d.status==="cancelled"?"cancelled by user":exitCode===0?"finished":`exit ${exitCode}`),this.log(`dispatch ${taskId} ${d.status} in ${fmtElapsed(d.endedAt-d.startedAt)}\
|
|
1973
|
+
\u2014 ${d.turns} turns, ${d.toolCalls} tool calls, $${d.costUsd.toFixed(4)}${d.nestedCostUsd>0?` + $${d.nestedCostUsd.toFixed(4)} in subagents`:""}${diagnostic?` \u2014 ${diagnostic}`:""}`),this.render()}setNestedCost(taskId,costUsd){let d=this.dispatches.get(taskId);d&&(d.nestedCostUsd=costUsd,this.enforceSentinelCost(),this.scheduleRender())}totalCost(){let c=0;for(let d of this.dispatches.values())c+=d.costUsd+d.nestedCostUsd;return c+this.externalCostUsd}externalCostUsd=0;externalEstimatedUsd=0;externalHasEstimate=!1;externalHasReported=!1;externalUsageUnknown=!1;addExternalCost(usd,complete,estimatedUsd=0,basis=complete?
|
|
1974
|
+
"reported":"unknown"){let reported=reportedCost2(usd),estimated=reportedCost2(estimatedUsd);(reported===void 0||estimated===void 0)&&(this.externalUsageUnknown=!0,complete=!1,basis=(reported??0)>0||(estimated??0)>0?"partial":"unknown"),usd=reported??0,estimatedUsd=estimated??0,this.externalCostUsd+=usd,this.externalHasReported||=basis==="reported"||usd>0,this.externalEstimatedUsd+=estimatedUsd,this.externalHasEstimate||=basis==="estimated"||estimatedUsd>0,(basis==="partial"||basis==="unknown"||!complete&&
|
|
1975
|
+
basis==="reported")&&(this.externalUsageUnknown=!0),this.enforceSentinelCost()}costComplete(){if(this.externalUsageUnknown||this.externalHasEstimate)return!1;for(let d of this.dispatches.values())if(d.endedAt===void 0||d.usageUnreported)return!1;return!0}estimatedCost(){return this.externalEstimatedUsd}costBasis(){let dispatches=[...this.dispatches.values()],hasUnknown=this.externalUsageUnknown||dispatches.some(d=>d.endedAt===void 0||d.usageUnreported),hasKnown=this.externalHasReported||this.externalHasEstimate||
|
|
1976
|
+
this.totalCost()>0||dispatches.some(d=>d.endedAt!==void 0&&!d.usageUnreported);return hasUnknown?hasKnown?"partial":"unknown":this.externalHasEstimate?"estimated":"reported"}scheduleRender(){this.renderTimer||(this.renderTimer=setTimeout(()=>{this.renderTimer=void 0,this.render()},250))}setPendingChecks(rows){this.pendingChecks=rows.slice(0,MAX_PENDING_CHECKS).map(row=>({...row})),this.render()}summaryInput(now){let dispatches=[...this.dispatches.values()].filter(d=>!d.supersededBy),running=dispatches.
|
|
1977
|
+
filter(d=>d.status==="running"),first=running[0],failed=dispatches.filter(d=>d.status==="failed").at(-1),cancelled=dispatches.filter(d=>d.status==="cancelled").at(-1),warning=running.find(d=>d.progress.warning)?.progress.warning;return{phase:this.phase,elapsedMs:now-this.startedAt,costUsd:this.totalCost()||void 0,running:running.length,ended:dispatches.filter(d=>d.status==="done").length,failed:dispatches.filter(d=>d.status==="failed").length,cancelled:dispatches.filter(d=>d.status==="cancelled").
|
|
1978
|
+
length,ciPending:this.pendingChecks.filter(row=>row.outcome==="pending").length,now:first?{label:first.label,model:shortName(first.model),...first.backup?{backup:first.backup}:{},detail:first.progress.lastProgressDetail?`progress ${fmtElapsed(now-first.progress.lastProgressAt)} ago: ${first.progress.lastProgressDetail}`:first.lastActivity}:void 0,alert:failed?{token:"error",text:`${failed.label} failed: ${failed.lastActivity}`}:cancelled?{token:"warning",text:`${cancelled.label}: ${cancelled.lastActivity}`}:
|
|
1979
|
+
this.cancellation.isCancelled?{token:"warning",text:`cancellation requested (${this.cancelReason??"user"})`}:warning?{token:"warning",text:warning.text}:void 0}}render(){this.closed||!flowStage.owns(this)&&flowStage.holdsWidget()||(safeUi2(()=>{let theme=this.ctx.ui.theme??plainTheme,ciPending=this.pendingChecks.filter(row=>row.outcome==="pending").length,summary=this.summaryInput(Date.now());this.ctx.ui.setStatus("orchestrator",styleSegments([["muted","HUMAIN Code - Flow "],["accent",sanitizeControlChars(
|
|
1980
|
+
this.phase)],["muted",` \xB7 ${fmtElapsed(Date.now()-this.startedAt)} \xB7 $${this.totalCost().toFixed(4)}${this.pendingChecks.length?` \xB7 ${ciPending} CI pending`:""}`],...summary.now?.backup?[["muted",` \xB7 ${summary.now.label} \xB7 ${summary.now.model} \xB7 ${summary.now.backup}`]]:[],...summary.failed?[["error",` \xB7 ${summary.failed} failed`]]:[]],1/0,theme))}),this.ctx.mode==="tui"&&(flowStage.owns(this)?safeUi2(()=>flowStage.refresh()):safeUi2(()=>this.ctx.ui.setWidget("orchestrator",
|
|
1981
|
+
(_tui,theme)=>({invalidate(){},render:width=>formatFlowSummary(this.summaryInput(Date.now()),width,theme,truncateToWidth)})))))}boardLines(theme=plainTheme){let now=this.closedAt??Date.now(),running=[...this.dispatches.values()].filter(d=>d.status==="running"),done=[...this.dispatches.values()].filter(d=>d.status!=="running"),logicalDone=done.filter(d=>!d.supersededBy),failed=logicalDone.filter(d=>d.status==="failed").length,cancelled=logicalDone.filter(d=>d.status==="cancelled").length,elapsed=fmtElapsed(
|
|
1974
1982
|
now-this.startedAt),totalCost=this.totalCost(),worktree=this.worktree,th={fg:(token,text2)=>theme.fg(token,sanitizeControlChars(redactCredentials(text2))),bold:text2=>theme.bold?.(text2)??text2},seg=(parts,max=1/0)=>styleSegments(parts,max,th),bold=text2=>th.bold?.(text2)??text2,lines=[];lines.push(bold(seg([["accent",`HUMAIN Code - Flow \xB7 ${this.phase}`]]))),this.title&&lines.push(th.fg("text",` Title: ${this.title}`));let goal=sanitizeControlChars(redactCredentials(this.goal)).replace(/\s+/g,
|
|
1975
|
-
" ").trim();lines.push(th.fg("text",goal.length<=120?` Goal: ${goal}`:` Goal: ${goal.slice(0,80)} \u2026 ${goal.slice(-40)}`));let first=running[0];if(first){let detail=(first.progress.lastProgressDetail||first.lastActivity||"").replace(/\s+/g," ").trim();lines.push(seg([["text"," Now: "],["accent",first.label],["text",detail?` \u2014 ${detail}`:""]],120))}else lines.push(seg([["text",` Now: ${this.phase}`]]));if(lines.
|
|
1976
|
-
4)}`],...done.length>0?[["muted",` \xB7 ${running.length} running ${
|
|
1977
|
-
".repeat(2+d.depth),progressLine=formatProgressLine(d.progress,now,indent,th);progressLine&&lines.push(progressLine);let warningLine=formatWarningLine(d.progress,now,indent,th);warningLine&&lines.push(warningLine),lines.push(...formatNestedWorkerRows(d.progress,now,d.depth,th))}}if(done.length>0){lines.push(""),lines.push(bold(th.fg("text",` \u25B8 completed (${done.length}) \xB7 exit status only, not verification`)));
|
|
1978
|
-
d.progress,now,d.depth,th))}this.pendingChecks.length>0&&lines.push("",...formatPendingCheckRows(this.pendingChecks,th)),lines.push(""),lines.push(seg([["dim",` \u21AF updated ${new Date(now).toISOString().slice(11,19)} UTC \xB7 log: ${this.file("run.log")}`]])),lines.push("",th.fg("text"," Recent run.log:"));for(let line of this.statusSnapshot().recentLog)lines.push(th.fg("muted",` ${redactPaths2(
|
|
1979
|
-
now),model=shortName(d.model).padEnd(20),elapsed=fmtElapsed(now-d.startedAt).padStart(7),turns=`t${d.turns}`.padStart(4),tools=`\u2699${d.toolCalls}`.padStart(5),cost=`$${(d.costUsd+d.nestedCostUsd).toFixed(4)}`.padStart(9),idleMs=now-d.progress.lastProgressAt,idle=idleMs>6e4?` idle ${fmtElapsed(idleMs)}`:"";return styleSegments([["text",indent],["accent",spin],["text",` ${d.label.padEnd(20)}`],
|
|
1980
|
-
let indent=" ".repeat(2+d.depth),tail=d.activityTail.slice(0,-1);tail.length>0&&lines.push(styleSegments([["muted",`${indent}\u21B3 ${tail.join(" \xB7 ")}`]],120,th));let nestedWorkers=d.progress.nested.size,nestedTurns=[...d.progress.nested.values()].reduce((total,worker)=>total+worker.turns,0);nestedWorkers>0&&lines.push(th.fg("text",`${indent}${nestedWorkers} worker${nestedWorkers===
|
|
1981
|
-
"done"?"\u2713":d.status==="cancelled"?"\u23F9":"\u2717",model=shortName(d.model).padEnd(20),elapsed=fmtElapsed((d.endedAt??now)-d.startedAt).padStart(7),turns=`t${d.turns}`.padStart(4),tools=`\u2699${d.toolCalls}`.padStart(5),cost=`$${(d.costUsd+d.nestedCostUsd).toFixed(4)}`.padStart(9),note=d.
|
|
1982
|
-
padEnd(20)}`],["muted",` ${model} ${elapsed} ${turns} ${tools} ${cost}`],[markToken,note]],1/0,th)}close(){this.closed||(this.rejectPendingLeadMessages(),this.tickTimer&&clearInterval(this.tickTimer),this.sentinelDeadlineTimer?.clear(),this.renderTimer&&clearTimeout(this.
|
|
1983
|
-
this.closedAt=Date.now(),this.closed=!0,this.log(`run ${this.runId} closed after ${fmtElapsed(Date.now()-this.startedAt)}`))}cancelledDispatches(){return[...this.dispatches.values()].filter(d=>d.status==="cancelled").map(d=>d.label)}statusSnapshot(logLines=20){let now=Date.
|
|
1984
|
-
Math.max(1,Math.min(200,Math.trunc(logLines))):20,recentLog=[];try{let path=this.file("run.log"),text2=capChildStderrFile(path,48*1024,0)??readFileSync13(path,"utf8");recentLog=redactCredentials(text2).split(`
|
|
1985
|
-
`).filter(l=>l.length>0).slice(-clampedLines)}catch{recentLog=[]}return{runId:this.runId,phase:this.phase,elapsedMs:now-this.startedAt,totalCostUsd:this.totalCost(),dispatches,recentLog}}},ACTIVE_RUN=null;function getActiveRun(){return ACTIVE_RUN}var SyncedRunRegistry=class extends RunRegistry{claim(session,tags={},aliasTable=null,modelSources=null,routing){let claimed=super.claim(session,tags,aliasTable,modelSources,routing);return claimed&&(ACTIVE_RUN=session,CURRENT_ALIAS_TABLE=aliasTable,CURRENT_MODEL_SOURCES=modelSources??{}),claimed}release(context){super.release(context),ACTIVE_RUN===context.session&&(ACTIVE_RUN=null,CURRENT_ALIAS_TABLE=null,CURRENT_MODEL_SOURCES={})}},runRegistry=new SyncedRunRegistry;function cleanOrchestratorStatus(s){let clean5=text2=>sanitizeControlChars(redactCredentials(text2));return{...s,runId:clean5(s.runId),phase:clean5(s.phase),dispatches:s.dispatches.map(d=>({...d,label:clean5(d.label),model:clean5(d.model),status:clean5(d.status),lastTool:d.lastTool===void 0?void 0:clean5(d.lastTool)})),recentLog:s.recentLog.map(clean5)}}function formatOrchestratorStatus(s){s=cleanOrchestratorStatus(s);let lines=[`
|
|
1986
|
-
s.elapsedMs)} \xB7 total cost $${s.totalCostUsd.toFixed(4)}`];if(s.dispatches.length>0){lines.push("","Dispatches:");for(let d of s.dispatches)lines.push(` - ${d.label} (${d.model}) [${d.status}] ${fmtElapsed(d.elapsedMs)} \xB7 turns ${d.turns}${d.lastTool?` \xB7 last tool ${d.lastTool}`:""} \xB7 $${d.costUsd.toFixed(4)}`)}else lines.push("","Dispatches: none yet");if(s.recentLog.
|
|
1983
|
+
" ").trim();lines.push(th.fg("text",goal.length<=120?` Goal: ${goal}`:` Goal: ${goal.slice(0,80)} \u2026 ${goal.slice(-40)}`));let first=running[0];if(first){let detail=(first.progress.lastProgressDetail||first.lastActivity||"").replace(/\s+/g," ").trim();lines.push(seg([["text"," Now: "],["accent",first.label],["text",detail?` \u2014 ${detail}`:""],["muted",first.backup?` \xB7 ${shortName(first.model)} \xB7 ${first.backup}`:""]],120))}else lines.push(seg([["text",` Now: ${this.phase}`]]));if(lines.
|
|
1984
|
+
push(seg([["muted",` ${this.runId} \xB7 ${elapsed} \xB7 $${totalCost.toFixed(4)}`],...done.length>0?[["muted",` \xB7 ${running.length} running ${logicalDone.length} done `],[failed>0?"error":"muted",`${failed} failed`],["muted"," "],[cancelled>0?"warning":"muted",`${cancelled} cancelled`]]:[],["muted",worktree?` ${worktree.shortBranch} @ ${worktree.root}`:""]])),running.length>0){lines.push(""),lines.push(bold(th.fg("text",` \u25B8 running (${running.length})`)));for(let d of running){lines.push(
|
|
1985
|
+
this.formatRunningRow(d,now,th)),this.appendActivityTail(lines,d,th);let indent=" ".repeat(2+d.depth),progressLine=formatProgressLine(d.progress,now,indent,th);progressLine&&lines.push(progressLine);let warningLine=formatWarningLine(d.progress,now,indent,th);warningLine&&lines.push(warningLine),lines.push(...formatNestedWorkerRows(d.progress,now,d.depth,th))}}if(done.length>0){lines.push(""),lines.push(bold(th.fg("text",` \u25B8 completed (${done.length}) \xB7 exit status only, not verification`)));
|
|
1986
|
+
for(let d of done)lines.push(this.formatDoneRow(d,now,th)),lines.push(...formatNestedWorkerRows(d.progress,now,d.depth,th))}this.pendingChecks.length>0&&lines.push("",...formatPendingCheckRows(this.pendingChecks,th)),lines.push(""),lines.push(seg([["dim",` \u21AF updated ${new Date(now).toISOString().slice(11,19)} UTC \xB7 log: ${this.file("run.log")}`]])),lines.push("",th.fg("text"," Recent run.log:"));for(let line of this.statusSnapshot().recentLog)lines.push(th.fg("muted",` ${redactPaths2(
|
|
1987
|
+
line)}`));return lines}formatRunningRow(d,now,th){let indent=" ".repeat(1+d.depth),spin=spinnerFrame2(now),model=shortName(d.model).padEnd(20),elapsed=fmtElapsed(now-d.startedAt).padStart(7),turns=`t${d.turns}`.padStart(4),tools=`\u2699${d.toolCalls}`.padStart(5),cost=`$${(d.costUsd+d.nestedCostUsd).toFixed(4)}`.padStart(9),idleMs=now-d.progress.lastProgressAt,idle=idleMs>6e4?` idle ${fmtElapsed(idleMs)}`:"";return styleSegments([["text",indent],["accent",spin],["text",` ${d.label.padEnd(20)}`],
|
|
1988
|
+
["muted",` ${model} ${elapsed} ${turns} ${tools} ${cost}`],["warning",idle]],1/0,th)}appendActivityTail(lines,d,th){let indent=" ".repeat(2+d.depth),tail=d.activityTail.slice(0,-1);tail.length>0&&lines.push(styleSegments([["muted",`${indent}\u21B3 ${tail.join(" \xB7 ")}`]],120,th));let nestedWorkers=d.progress.nested.size,nestedTurns=[...d.progress.nested.values()].reduce((total,worker)=>total+worker.turns,0);nestedWorkers>0&&lines.push(th.fg("text",`${indent}${nestedWorkers} worker${nestedWorkers===
|
|
1989
|
+
1?"":"s"} (${nestedTurns} turns)`))}formatDoneRow(d,now,th){let indent=" ".repeat(1+d.depth),mark=d.supersededBy?"\u21BB":d.status==="done"?"\u2713":d.status==="cancelled"?"\u23F9":"\u2717",model=shortName(d.model).padEnd(20),elapsed=fmtElapsed((d.endedAt??now)-d.startedAt).padStart(7),turns=`t${d.turns}`.padStart(4),tools=`\u2699${d.toolCalls}`.padStart(5),cost=`$${(d.costUsd+d.nestedCostUsd).toFixed(4)}`.padStart(9),note=d.supersededBy?` replaced by ${d.supersededBy} \xB7 ${d.lastActivity}`:
|
|
1990
|
+
d.status!=="done"&&d.lastActivity?` ${d.lastActivity}`:"",markToken=d.supersededBy||d.status==="done"?"muted":d.status==="cancelled"?"warning":"error";return styleSegments([["text",indent],[markToken,mark],["text",` ${d.label.padEnd(20)}`],["muted",` ${model} ${elapsed} ${turns} ${tools} ${cost}`],[markToken,note]],1/0,th)}close(){this.closed||(this.rejectPendingLeadMessages(),this.tickTimer&&clearInterval(this.tickTimer),this.sentinelDeadlineTimer?.clear(),this.renderTimer&&clearTimeout(this.
|
|
1991
|
+
renderTimer),this.ctx.mode==="tui"&&(flowStage.holdsWidget()||safeUi2(()=>this.ctx.ui.setWidget("orchestrator",void 0)),(flowStage.owns(this)||!flowStage.holdsWidget())&&safeUi2(()=>this.ctx.ui.setStatus("orchestrator",void 0))),this.closedAt=Date.now(),this.closed=!0,this.log(`run ${this.runId} closed after ${fmtElapsed(Date.now()-this.startedAt)}`))}cancelledDispatches(){return[...this.dispatches.values()].filter(d=>d.status==="cancelled").map(d=>d.label)}statusSnapshot(logLines=20){let now=Date.
|
|
1992
|
+
now(),dispatches=[...this.dispatches.values()].map(d=>({label:d.label,model:d.model,status:d.status,...d.supersededBy?{supersededBy:d.supersededBy}:{},elapsedMs:(d.endedAt??now)-d.startedAt,turns:d.turns,lastTool:d.lastTool,costUsd:d.costUsd})),clampedLines=Number.isFinite(logLines)?Math.max(1,Math.min(200,Math.trunc(logLines))):20,recentLog=[];try{let path=this.file("run.log"),text2=capChildStderrFile(path,48*1024,0)??readFileSync13(path,"utf8");recentLog=redactCredentials(text2).split(`
|
|
1993
|
+
`).filter(l=>l.length>0).slice(-clampedLines)}catch{recentLog=[]}return{runId:this.runId,phase:this.phase,elapsedMs:now-this.startedAt,totalCostUsd:this.totalCost(),dispatches,recentLog}}},ACTIVE_RUN=null;function getActiveRun(){return ACTIVE_RUN}var SyncedRunRegistry=class extends RunRegistry{claim(session,tags={},aliasTable=null,modelSources=null,routing){let claimed=super.claim(session,tags,aliasTable,modelSources,routing);return claimed&&(ACTIVE_RUN=session,CURRENT_ALIAS_TABLE=aliasTable,CURRENT_MODEL_SOURCES=modelSources??{}),claimed}release(context){super.release(context),ACTIVE_RUN===context.session&&(ACTIVE_RUN=null,CURRENT_ALIAS_TABLE=null,CURRENT_MODEL_SOURCES={})}},runRegistry=new SyncedRunRegistry;function cleanOrchestratorStatus(s){let clean5=text2=>sanitizeControlChars(redactCredentials(text2));return{...s,runId:clean5(s.runId),phase:clean5(s.phase),dispatches:s.dispatches.map(d=>({...d,label:clean5(d.label),model:clean5(d.model),status:clean5(d.status),lastTool:d.lastTool===void 0?void 0:clean5(d.lastTool),...d.supersededBy?{supersededBy:clean5(d.supersededBy)}:{}})),recentLog:s.recentLog.map(clean5)}}function formatOrchestratorStatus(s){s=cleanOrchestratorStatus(s);let lines=[`Orchest\
|
|
1994
|
+
ration ${s.runId} \u2014 phase: ${s.phase} \xB7 elapsed ${fmtElapsed(s.elapsedMs)} \xB7 total cost $${s.totalCostUsd.toFixed(4)}`];if(s.dispatches.length>0){lines.push("","Dispatches:");for(let d of s.dispatches)lines.push(` - ${d.label} (${d.model}) [${d.supersededBy?`replaced by ${d.supersededBy}`:d.status}] ${fmtElapsed(d.elapsedMs)} \xB7 turns ${d.turns}${d.lastTool?` \xB7 last tool ${d.lastTool}`:""} \xB7 $${d.costUsd.toFixed(4)}`)}else lines.push("","Dispatches: none yet");if(s.recentLog.
|
|
1995
|
+
length>0){lines.push("","Recent log:");for(let line of s.recentLog)lines.push(` ${line}`)}return lines.join(`
|
|
1987
1996
|
`)}function registerOrchestratorStatusTool(pi){let parameters=typebox_exports.Object({logLines:typebox_exports.Optional(typebox_exports.Number({description:"Number of trailing run.log lines to include (clamped to 1..200; default 20)."}))});pi.registerTool({name:"orchestrator_status",label:"Orchestrator Status",description:"Read-only status of the current /flow run, if any: phase, elapsed time, total cost, per-dispatch progress (model, status, turns, last tool call, cost), and recent run.log line\
|
|
1988
1997
|
s. Does not affect the run.",promptSnippet:"orchestrator_status: check progress of a live /flow run without blocking on it",parameters,async execute(_toolCallId,params){if(!ACTIVE_RUN)return{content:[{type:"text",text:"No orchestrator run is active."}],details:void 0};let snapshot=cleanOrchestratorStatus(ACTIVE_RUN.statusSnapshot(params.logLines??20)),text2=formatOrchestratorStatus(snapshot);return{content:[{type:"text",text:ACTIVE_RUN.hideCost?redactDollarAmounts(text2):text2}],details:snapshot}}})}
|
|
1989
1998
|
function registerFlowStatusCommand(pi){let opening=!1,closeView;pi.on("session_shutdown",()=>{safeUi2(()=>closeView?.())}),pi.registerCommand("flow-status",{description:"Open the full live orchestration board (\u2191\u2193 PgUp/PgDn scroll, Esc closes without cancelling).",handler:async(_args,ctx)=>{if(ctx.mode!=="tui"){safeUi2(()=>ctx.ui.notify("/flow-status requires terminal UI; use orchestrator_status for read-only status.","info"));return}let session=ACTIVE_RUN;if(!session){ctx.ui.notify("No\
|
|
@@ -2006,11 +2015,11 @@ JSON:
|
|
|
2006
2015
|
`,toolPermissions={},session=run?.session;try{let capability=bound2?"triage":adapter.implementation_fast?"implementation_fast":adapter.worker?"worker":"scout",declared=run?.candidates?.[capability],twins=run?.aliasTable?providerFallbacksFor(cheapest.model,run.aliasTable):[],strict=run?.policy?.strict_qualification===!0,resident=run?.residentModels,routeCandidates=(strict||resident?preflightRole(declared??[],run?.policy,run?.aliasTable??void 0).eligible:declared?usableModels(declared,cheapest.model):
|
|
2007
2016
|
[cheapest.model,...twins]).filter(model=>!resident||resident.includes(model));if((strict||resident)&&routeCandidates.length===0)return session?.log(`triage ineligible: ${declared?.flatMap(candidate=>candidate.reasons).join("; ")||"no qualified candidates"}; role tier is configured routing; eligibility comes from runtime registry/facts`),null;let triageResult,health=run?.modelHealth??new ModelHealth,r=(await dispatchWithFailover({taskId:"triage",capability,prompt},routeCandidates,{runAttempt:async(model,task,attempt,spendCapOffsetUsd,delayMs,previous)=>{
|
|
2008
2017
|
let taskId=attempt===1?"triage":`triage-fallback-${attempt-1}`,base={logicalTaskId:`${runId}-triage`,mode:"single"},recovery=session?.recovery,logicalTaskId=`${runId}-triage`;return recovery?.registerDispatchTasks([{taskId,capability,task,stage:"triage",...toolPermissions,trace:{logicalTaskId,mode:"single"}}]),recovery?.beforeLaunch(logicalTaskId,taskId,previous),triageResult=await dispatchSingleAttempt({cwd,agentName:"orch-implementation-fast",task,model,...resident?{residentModels:resident}:{},
|
|
2009
|
-
...bound2?.effort?{effort:bound2.effort}:{},ctx,taskId,...toolPermissions,label:attempt===1?"triage":`triage\u21BB${attempt-1}`,capability,...attempt===1&&model!==cheapest.model?{flowRouteReason:routeReason(health,cheapest.model)}:{},session,spendCapOffsetUsd,activity:run?.activity,retryDelayMs:delayMs,trace:attempt===1?base:recoveryTrace(base,triageResult,
|
|
2010
|
-
triageResult.captureFailure&&session?.log(`triage capture failure: ${triageResult.captureFailure}`),recovery?.settled(logicalTaskId,taskId,{...triageResult,taskId,capability,model:triageResult.model??model,filesChanged:[],claimedFiles:[]}),triageResult},readEvents:result=>result.rawStdout.split(/\r?\n/),snapshot:()=>guardedDirtySnapshot(cwd).snapshot,changedSince:snapshot=>{
|
|
2011
|
-
contentChangedSince(root,before,after):null},sleep:async ms=>{session&&await new Promise(resolve11=>{let timer=setTimeout(()=>{remove(),resolve11()},ms),remove=session.cancellation.onCancel(()=>{clearTimeout(timer),remove(),resolve11()})})},health,isCancelled:()=>(session?.cancellation.isCancelled||session?.flowTelemetry?.stopped)??!1,recordEvent:(event2,payload)=>({...payload},
|
|
2012
|
-
|
|
2013
|
-
|
|
2018
|
+
...bound2?.effort?{effort:bound2.effort}:{},ctx,taskId,...toolPermissions,label:attempt===1?"triage":`triage\u21BB${attempt-1}`,...previous?{replacement:{taskId:attempt===2?"triage":`triage-fallback-${attempt-2}`,reasonClass:routeReasonForHealthClass(previous.cls)}}:{},capability,...attempt===1&&model!==cheapest.model?{flowRouteReason:routeReason(health,cheapest.model)}:{},session,spendCapOffsetUsd,activity:run?.activity,retryDelayMs:delayMs,trace:attempt===1?base:recoveryTrace(base,triageResult,
|
|
2019
|
+
"model_failover","retry"),...recovery?{onSpawned:owner=>recovery.launched(logicalTaskId,taskId,owner)}:{}}),costSink.usd+=triageResult.costUsd,triageResult.captureFailure&&session?.log(`triage capture failure: ${triageResult.captureFailure}`),recovery?.settled(logicalTaskId,taskId,{...triageResult,taskId,capability,model:triageResult.model??model,filesChanged:[],claimedFiles:[]}),triageResult},readEvents:result=>result.rawStdout.split(/\r?\n/),snapshot:()=>guardedDirtySnapshot(cwd).snapshot,changedSince:snapshot=>{
|
|
2020
|
+
let before=snapshot,after=guardedDirtySnapshot(cwd).snapshot;if(!before||!after)return null;let root=topLevelOf(cwd);return root?contentChangedSince(root,before,after):null},sleep:async ms=>{session&&await new Promise(resolve11=>{let timer=setTimeout(()=>{remove(),resolve11()},ms),remove=session.cancellation.onCancel(()=>{clearTimeout(timer),remove(),resolve11()})})},health,isCancelled:()=>(session?.cancellation.isCancelled||session?.flowTelemetry?.stopped)??!1,recordEvent:(event2,payload)=>({...payload},
|
|
2021
|
+
void 0),log:line=>session?.log(line),config:failoverConfig(),redact:redactPaths2,effortDropped:model=>!!(cheapest.effort&&!declared?.find(candidate=>candidate.model===model)?.effortControl)})).result;if(r.exitCode!==0)return console.warn(`[orchestrator] triage exited ${r.exitCode}: ${summarizeStderr(r.stderr||r.rawStdout,400)||"(no output)"}`),null;let text2=r.finalText||r.stdout;return text2.trim()?parseTriageResponse(text2):(console.warn("[orchestrator] triage produced no assistant text"),null)}catch(err){
|
|
2022
|
+
if(session?.recovery?.failed||session?.flowTelemetry?.stopped)throw err;return console.warn(`[orchestrator] triage failed: ${err.message}`),null}}async function planRun2(runId,opts){return planRun({runId,...opts})}function recordEvent(_event,_payload){}function recordOutcome(_outcome){}async function finishRun(runId){return await(ACTIVE_RUN?.runId===runId?ACTIVE_RUN:null)?.drainControlAttempts(),CLEAN_FLUSH_REPORT}async function completeRun(runId,_summary,_timing,_since){return finishRun(runId)}async function failRun(runId,_error,_timing,_since){return finishRun(runId)}function cancelReasonLabel(reason){switch(reason){case"shutdown":return"\
|
|
2014
2023
|
session_shutdown";case"signal":return"signal";case"user":return"orchestrate_cancel";default:return"unknown"}}async function cancelRun(runId,_reason,_timing,_since){return finishRun(runId)}async function dispatchParallel(cwd,runId,tasks,adapter,ctx,depth=0,deps={recordEvent,runProcess:runSubagentProcess2}){if(tasks.length===0)return[];let session=ACTIVE_RUN,recovery=session?.recovery;if(recovery?.registerDispatchTasks(tasks),recovery?.failed)throw new Error("Recovery persistence failed; no further dispatch admitted");let runContext=runRegistry.active(),modelHealth=runContext?.modelHealth??new ModelHealth,modelSources=deps.modelSources??CURRENT_MODEL_SOURCES,canaryConfig=parseModelCanaries(
|
|
2015
2024
|
METHOD.rules.model_canaries).config,efficiencyControls=deps.efficiencyControls??loadEfficiencyControls(),canaryAliasTable=deps.aliasTable===void 0?CURRENT_ALIAS_TABLE:deps.aliasTable,taskInputs=tasks.map(t=>{let binding=adapter[t.capability]??adapter.worker??adapter.scout??Object.values(adapter).find(v=>v&&typeof v=="object")??{model:"unknown"},canaryAssignment=assignCanary({runId,capability:t.capability,baselineModel:binding.model??"unknown",explicitOverride:modelSources[t.capability]==="flag",
|
|
2016
2025
|
config:canaryConfig,aliasTable:canaryAliasTable});return{agent:agentNameFor(t.capability),task:formatTaskPrompt(t,runId),model:binding.model??"unknown",effort:binding.effort,tools:t.tools,timeoutMs:t.timeoutMs,cwd,_capability:t.capability,_taskId:t.taskId,_retryOf:t.retryOf,_retryCount:t.retryCount,_policyEscalation:t.policyEscalation,_policyReview:t.policyReview,_policyReviewRisk:t.policyReviewRisk,_phase:t.phase,_canaryAssignment:canaryAssignment,_trace:t.trace}}),activity=runContext?.activity,
|
|
@@ -2021,19 +2030,20 @@ filter(model=>!resident||resident.includes(model));if((preflight||resident)&&rou
|
|
|
2021
2030
|
/facts.`;return deps.recordEvent("dispatch_ineligible",{run_id:runId,task_id:input._taskId,capability:input._capability,reason}),{taskId:input._taskId??`unknown-${runId}`,capability:input._capability??"unknown",model:input.model,exitCode:-1,stdout:"",stderr:reason,usage:{input:0,output:0,cacheRead:0,cacheWrite:0,cost:0,contextTokens:0,turns:0},durationMs:0,costUsd:0,costReported:!1,outcome:"ineligible",filesChanged:[],claimedFiles:[]}}deps.recordEvent("dispatch_started",{run_id:runId,task_id:input.
|
|
2022
2031
|
_taskId,capability:input._capability,agent:input.agent,model:routeCandidates[0],retry_of:input._retryOf});let latestChangedFiles=[],lastResult,scheduled=input._trace;activity&&scheduled&&!scheduled.retryOfAttemptId&&!scheduled.retryReason&&!scheduled.dependencies?.length&&activity.decision({decision:"schedule",mode:scheduled.mode,provenance:{source:"command",command:"flow"},logicalTaskId:scheduled.logicalTaskId,...scheduled.wave===void 0?{}:{wave:scheduled.wave},...scheduled.order===void 0?{}:{order:scheduled.
|
|
2023
2032
|
order}});let failover=await dispatchWithFailover({taskId:input._taskId??`unknown-${runId}`,capability:input._capability??"unknown",prompt:input.task},routeCandidates,{runAttempt:async(model,prompt,attempt,spentBeforeUsd,delayMs,previous)=>{let taskId=attempt===1||!input._taskId?input._taskId:`${input._taskId}-fallback-${attempt-1}`,base=input._trace,trace=base&&(attempt===1?base:recoveryTrace(base,lastResult,"model_failover","retry")),logicalTaskId=input._trace?.logicalTaskId??input._taskId;recovery?.
|
|
2024
|
-
beforeLaunch(logicalTaskId,taskId,previous);let result=await dispatchSingleAttempt({cwd:input.cwd,agentName:input.agent,task:prompt,model,...resident?{residentModels:resident}:{},effort:input.effort,taskId,label:attempt===1?shortId3:`${shortId3}\u21BB${attempt-1}`,capability:input._capability,depth,tools:input.tools,timeoutMs:input.
|
|
2025
|
-
{flowRouteReason:routeReason(modelHealth,input.model)}:{},...recovery?{onSpawned:owner=>recovery.launched(logicalTaskId,taskId,owner)}:{}},deps.runProcess);return lastResult=result,paidAttempts.push(result),latestChangedFiles=result.personaCanMutate?parseFilesChanged(result.stdout):[],recovery?.settled(logicalTaskId,taskId,{...result,
|
|
2026
|
-
parseFilesChanged(result.stdout):[]}),result},readEvents:result=>result.rawStdout.split(/\r?\n/),snapshot:()=>guardedDirtySnapshot(cwd).snapshot,changedSince:snapshot=>{let before=snapshot,after=guardedDirtySnapshot(cwd).snapshot;if(!before||!after)return null;let root=topLevelOf(cwd);return root?[...new Set([...contentChangedSince(
|
|
2027
|
-
cancellation.onCancel(()=>{clearTimeout(timer),remove(),resolve11()})})},health:modelHealth,isCancelled:()=>(session?.cancellation.isCancelled||session?.flowTelemetry?.stopped)??!1,recordEvent:(event2,payload)=>deps.recordEvent(event2,{run_id:runId,...payload}),log:line=>session?.log(line),config:failoverConfig(),requireCompatibleBedrock:runContext?.
|
|
2028
|
-
find(candidate=>candidate.model===model)?.effortControl)}),attempts=failover.attempts.map(attempt=>attempt.result),finalAttempt=attempts.at(-1);for(let index=0;index<attempts.length-1;index++){let attempt=attempts[index],model=failover.attempts[index].model;recordProviderErrors(deps.recordEvent,{runId,taskId:input._taskId,dispatchAttempt:index},
|
|
2029
|
-
model,provider:model.split("/",1)[0],billing_route:billingRouteFor(model),attempt:index+1,retry_count:index,exit_code:attempt.exitCode,duration_ms:attempt.durationMs,cost_usd:attempt.costUsd,nested_cost_usd:attempt.nestedCostUsd,dispatch_attempt:index,turns:attempt.usage.turns,stop_reason:attempt.stopReason,log_dir:session?.dir,superseded_by_fallback:!0
|
|
2030
|
-
stderr,usage:attempts.reduce((sum,attempt)=>sumUsage(sum,attempt.usage),{input:0,output:0,cacheRead:0,cacheWrite:0,cost:0,contextTokens:0,turns:0}),costUsd:attempts.reduce((sum,attempt)=>sum+attempt.costUsd,0),nestedCostUsd:attempts.reduce((sum,attempt)=>sum+(attempt.nestedCostUsd??0),0),nestedCalls:attempts.some(attempt=>attempt.nestedCalls)?attempts.flatMap(
|
|
2031
|
-
costReported)},dispatchAttempt=attempts.length-1,ownNestedCostUsd=finalAttempt.nestedCostUsd;return recordProviderErrors(deps.recordEvent,{runId,taskId:input._taskId,dispatchAttempt},r),deps.recordEvent("dispatch_finished",{...dispatchHealth({...r,model:r.model??input.model}),run_id:runId,task_id:input._taskId,capability:input._capability,model:r.
|
|
2032
|
-
exit_code:r.exitCode,duration_ms:finalAttempt.durationMs,cost_usd:finalAttempt.costUsd,nested_cost_usd:ownNestedCostUsd,dispatch_attempt:dispatchAttempt,turns:finalAttempt.usage.turns,stop_reason:r.stopReason,log_dir:ACTIVE_RUN?.dir,...r.captureFailure?{capture_failure:r.captureFailure}:{}}),{taskId:input._taskId??`unknown-${runId}`,
|
|
2033
|
-
exitCode,stdout:r.stdout,finalMessageRaw:r.finalMessageRaw,stderr:r.exitCode===0?r.stderr:summarizeStderr(r.stderr||r.rawStdout,2e3)||"(no output)",usage:r.usage,durationMs:r.durationMs,costUsd:r.costUsd,...(r.nestedCostUsd??0)>0?{nestedCostUsd:r.nestedCostUsd}:{},...r.nestedCalls?{nestedCalls:r.nestedCalls}:{},costReported:r.costReported,
|
|
2034
|
-
filesChanged:r.personaCanMutate?parseFilesChanged(r.stdout):[],claimedFiles:isLeadCapability(input._capability)||r.personaCanMutate?parseFilesChanged(r.stdout):[],...input.effort?{effort:input.effort}:{},...r.telemetry?{telemetry:input._phase?{...r.telemetry,dispatch_phase:input._phase}:r.telemetry}:{},...input._canaryAssignment?
|
|
2035
|
-
experimentFlags:efficiencyControls.enabled}}catch(err){let capture=err;return{...capture?.trace?{trace:capture.trace}:{},...capture?.captureFailure?{captureFailure:capture.captureFailure}:{},taskId:input._taskId??`unknown-${runId}`,capability:input._capability??"unknown",model:input.model??"unknown",exitCode:-1,stdout:"",stderr:err.
|
|
2036
|
-
reduce((sum,attempt)=>sum+attempt.durationMs,0),costUsd:paidAttempts.reduce((sum,attempt)=>sum+attempt.costUsd,0),nestedCostUsd:paidAttempts.reduce((sum,attempt)=>sum+(attempt.nestedCostUsd??0),0),costReported:paidAttempts.length>0&&paidAttempts.every(attempt=>attempt.costReported),filesChanged:[],claimedFiles:[]}}});if(recovery?.
|
|
2033
|
+
beforeLaunch(logicalTaskId,taskId,previous);let result=await dispatchSingleAttempt({cwd:input.cwd,agentName:input.agent,task:prompt,model,...resident?{residentModels:resident}:{},effort:input.effort,taskId,label:attempt===1?shortId3:`${shortId3}\u21BB${attempt-1}`,...previous&&input._taskId?{replacement:{taskId:attempt===2?input._taskId:`${input._taskId}-fallback-${attempt-2}`,reasonClass:routeReasonForHealthClass(previous.cls)}}:{},capability:input._capability,depth,tools:input.tools,timeoutMs:input.
|
|
2034
|
+
timeoutMs,ctx,session:session??void 0,spendCapOffsetUsd:spentBeforeUsd,activity,trace,retryDelayMs:delayMs,flowTaskId:logicalTaskId,...attempt===1&&model!==input.model?{flowRouteReason:routeReason(modelHealth,input.model)}:{},...recovery?{onSpawned:owner=>recovery.launched(logicalTaskId,taskId,owner)}:{}},deps.runProcess);return lastResult=result,paidAttempts.push(result),latestChangedFiles=result.personaCanMutate?parseFilesChanged(result.stdout):[],recovery?.settled(logicalTaskId,taskId,{...result,
|
|
2035
|
+
taskId,capability:input._capability,model:result.model??model,filesChanged:latestChangedFiles,claimedFiles:isLeadCapability(input._capability)||result.personaCanMutate?parseFilesChanged(result.stdout):[]}),result},readEvents:result=>result.rawStdout.split(/\r?\n/),snapshot:()=>guardedDirtySnapshot(cwd).snapshot,changedSince:snapshot=>{let before=snapshot,after=guardedDirtySnapshot(cwd).snapshot;if(!before||!after)return null;let root=topLevelOf(cwd);return root?[...new Set([...contentChangedSince(
|
|
2036
|
+
root,before,after),...latestChangedFiles])]:null},sleep:async ms=>{session&&await new Promise(resolve11=>{let timer=setTimeout(()=>{remove(),resolve11()},ms),remove=session.cancellation.onCancel(()=>{clearTimeout(timer),remove(),resolve11()})})},health:modelHealth,isCancelled:()=>(session?.cancellation.isCancelled||session?.flowTelemetry?.stopped)??!1,recordEvent:(event2,payload)=>deps.recordEvent(event2,{run_id:runId,...payload}),log:line=>session?.log(line),config:failoverConfig(),requireCompatibleBedrock:runContext?.
|
|
2037
|
+
tags.profile==="oss-first"&&runContext.policy?.paid_fallback?.require_compatible===!0,redact:redactPaths2,effortDropped:model=>!!(input.effort&&!runCandidates?.find(candidate=>candidate.model===model)?.effortControl)}),attempts=failover.attempts.map(attempt=>attempt.result),finalAttempt=attempts.at(-1);for(let index=0;index<attempts.length-1;index++){let attempt=attempts[index],model=failover.attempts[index].model;recordProviderErrors(deps.recordEvent,{runId,taskId:input._taskId,dispatchAttempt:index},
|
|
2038
|
+
{...attempt,model}),deps.recordEvent("dispatch_finished",{...dispatchHealth({...attempt,model}),run_id:runId,task_id:input._taskId,capability:input._capability,model,provider:model.split("/",1)[0],billing_route:billingRouteFor(model),attempt:index+1,retry_count:index,exit_code:attempt.exitCode,duration_ms:attempt.durationMs,cost_usd:attempt.costUsd,nested_cost_usd:attempt.nestedCostUsd,dispatch_attempt:index,turns:attempt.usage.turns,stop_reason:attempt.stopReason,log_dir:session?.dir,superseded_by_fallback:!0,
|
|
2039
|
+
...attempt.captureFailure?{capture_failure:attempt.captureFailure}:{}})}let r={...finalAttempt,model:failover.finalModel,stderr:failover.result.stderr,usage:attempts.reduce((sum,attempt)=>sumUsage(sum,attempt.usage),{input:0,output:0,cacheRead:0,cacheWrite:0,cost:0,contextTokens:0,turns:0}),costUsd:attempts.reduce((sum,attempt)=>sum+attempt.costUsd,0),nestedCostUsd:attempts.reduce((sum,attempt)=>sum+(attempt.nestedCostUsd??0),0),nestedCalls:attempts.some(attempt=>attempt.nestedCalls)?attempts.flatMap(
|
|
2040
|
+
attempt=>attempt.nestedCalls??[]):void 0,durationMs:attempts.reduce((sum,attempt)=>sum+attempt.durationMs,0),costReported:attempts.every(attempt=>attempt.costReported)},dispatchAttempt=attempts.length-1,ownNestedCostUsd=finalAttempt.nestedCostUsd;return recordProviderErrors(deps.recordEvent,{runId,taskId:input._taskId,dispatchAttempt},r),deps.recordEvent("dispatch_finished",{...dispatchHealth({...r,model:r.model??input.model}),run_id:runId,task_id:input._taskId,capability:input._capability,model:r.
|
|
2041
|
+
model??input.model,provider:failover.finalModel.split("/",1)[0],billing_route:billingRouteFor(failover.finalModel),attempt:attempts.length,retry_count:dispatchAttempt,exit_code:r.exitCode,duration_ms:finalAttempt.durationMs,cost_usd:finalAttempt.costUsd,nested_cost_usd:ownNestedCostUsd,dispatch_attempt:dispatchAttempt,turns:finalAttempt.usage.turns,stop_reason:r.stopReason,log_dir:ACTIVE_RUN?.dir,...r.captureFailure?{capture_failure:r.captureFailure}:{}}),{taskId:input._taskId??`unknown-${runId}`,
|
|
2042
|
+
capability:input._capability??"unknown",...r.trace?{trace:r.trace}:{},...r.captureFailure?{captureFailure:r.captureFailure}:{},model:r.model??input.model,exitCode:r.exitCode,stdout:r.stdout,finalMessageRaw:r.finalMessageRaw,stderr:r.exitCode===0?r.stderr:summarizeStderr(r.stderr||r.rawStdout,2e3)||"(no output)",usage:r.usage,durationMs:r.durationMs,costUsd:r.costUsd,...(r.nestedCostUsd??0)>0?{nestedCostUsd:r.nestedCostUsd}:{},...r.nestedCalls?{nestedCalls:r.nestedCalls}:{},costReported:r.costReported,
|
|
2043
|
+
stopReason:r.stopReason,outcome:r.outcome,processTerminationConfirmed:finalAttempt.processTerminationConfirmed,timeoutReason:r.timeoutReason,interruption:r.interruption,filesChanged:r.personaCanMutate?parseFilesChanged(r.stdout):[],claimedFiles:isLeadCapability(input._capability)||r.personaCanMutate?parseFilesChanged(r.stdout):[],...input.effort?{effort:input.effort}:{},...r.telemetry?{telemetry:input._phase?{...r.telemetry,dispatch_phase:input._phase}:r.telemetry}:{},...input._canaryAssignment?
|
|
2044
|
+
{canary:canaryTelemetryFields(input._canaryAssignment,r.model??input.model,`${input._taskId??"unknown"}${(input._retryCount??0)>0?`#retry${input._retryCount}`:""}`)}:{},experimentFlags:efficiencyControls.enabled}}catch(err){let capture=err;return{...capture?.trace?{trace:capture.trace}:{},...capture?.captureFailure?{captureFailure:capture.captureFailure}:{},taskId:input._taskId??`unknown-${runId}`,capability:input._capability??"unknown",model:input.model??"unknown",exitCode:-1,stdout:"",stderr:err.
|
|
2045
|
+
message,usage:paidAttempts.reduce((sum,attempt)=>sumUsage(sum,attempt.usage),{input:0,output:0,cacheRead:0,cacheWrite:0,cost:0,contextTokens:0,turns:0}),durationMs:paidAttempts.reduce((sum,attempt)=>sum+attempt.durationMs,0),costUsd:paidAttempts.reduce((sum,attempt)=>sum+attempt.costUsd,0),nestedCostUsd:paidAttempts.reduce((sum,attempt)=>sum+(attempt.nestedCostUsd??0),0),costReported:paidAttempts.length>0&&paidAttempts.every(attempt=>attempt.costReported),filesChanged:[],claimedFiles:[]}}});if(recovery?.
|
|
2046
|
+
failed)throw new Error("Recovery persistence failed; no further dispatch admitted");return settled}function formatTaskPrompt(t,runId){let retryNote=t.retryOf?`
|
|
2037
2047
|
|
|
2038
2048
|
[Retry context: this is retry #${(t.retryCount??0)+1} of a previous failed attempt on task_id=${t.retryOf}. The previous attempt's review/QA feedback is captured in the orchestrator ledger; if you need that context, ask the lead before starting. Per method.json rules.review_after_fix: re-review at or above the original reviewer's tier, never the cheap tier.]`:"";return[`[orchestrator:run_id=${runId}]`,`[capability=${t.capability}]`,`[task_id=${t.taskId}]`,"",t.task,retryNote,...t.stage==="review"||
|
|
2039
2049
|
t.stage==="qa"?[]:["","---","Output format (required):","## Completed","What was done.","## Files Changed","- `path/to/file` \u2014 what changed","## Verification","Checks run + result.","## Notes / Escalation","Anything the lead should know \u2014 reply to any user messages here."]].join(`
|