@humain/humain-code 0.4.13 → 0.4.14
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 +6 -0
- package/dist/bundle/chunks/{chunk-JQCWRL5K.js → chunk-HDA2IGKA.js} +1 -1
- package/dist/bundle/chunks/{chunk-JNHXXVLA.js → chunk-IUKCPYKD.js} +380 -381
- package/dist/bundle/chunks/{chunk-TC7EANW4.js → chunk-KA7K6ECX.js} +6 -6
- package/dist/bundle/chunks/{compat-PCHMBE76.js → compat-OQMUE3QD.js} +1 -1
- package/dist/bundle/chunks/{dist-UWE5M6HK.js → dist-65YQEF26.js} +68 -66
- package/dist/bundle/chunks/{virtual-modules-JSGQ72M6.js → virtual-modules-5KW36RPG.js} +1 -1
- package/dist/bundle/cli-runtime.js +1 -1
- package/dist/bundle/flow/package.json +1 -1
- package/dist/bundle/index.js +3 -3
- package/dist/bundle/rpc-entry.js +1 -1
- package/npm-shrinkwrap.json +6 -6
- package/package.json +2 -2
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { createRequire as __piCreateRequire } from "node:module"; const require = __piCreateRequire(import.meta.url);
|
|
2
|
-
import"./chunk-
|
|
3
|
-
import"./chunk-OX2IBCCA.js";import"./chunk-COF5P635.js";import"./chunk-NNKA2PAP.js";import"./chunk-TJG52LZB.js";import"./chunk-BVHXWQLD.js";import"./chunk-
|
|
2
|
+
import"./chunk-HDA2IGKA.js";import{FLOW_ACCOUNT_PERSISTENCE_NOTICE,FLOW_MESSAGE_MAX_LENGTH,FLOW_SETUP_TERMINAL_ONLY,assertDhRetryAdmission,assessNodeFallback,checkDhControlFence,dhCanonicalText,discoverAgents,flowBuildUnavailable,getFlowAccountsHost,getFlowChildLaunchHost,getFlowControlHost,getFlowTraceProducer,parseDhControlDelivery,parseFlowCommand,parseFlowControlCommandV1,parseFlowControlReceiptV1,parseFlowMessageReceiptV1,parseFlowStatusV1,renderFlowHelp,renderTaskWithContext,resolveDhEffectiveTerminals}from"./chunk-KA7K6ECX.js";
|
|
3
|
+
import"./chunk-OX2IBCCA.js";import"./chunk-COF5P635.js";import"./chunk-NNKA2PAP.js";import"./chunk-TJG52LZB.js";import"./chunk-BVHXWQLD.js";import"./chunk-IUKCPYKD.js";import"./chunk-Z74ZYQPX.js";import{ScrollView,matchesKey,mixColors,styleText,truncateToWidth,visibleWidth,wrapTextWithAnsi}from"./chunk-UHLW4KJ7.js";import"./chunk-XQRYOCHA.js";import"./chunk-DNGJMRJW.js";import"./chunk-36Q5UVQL.js";import"./chunk-UGXYG7HN.js";
|
|
4
4
|
import"./chunk-QYCOHSI7.js";import"./chunk-H2FY3PEV.js";import"./chunk-KQM7ZGL6.js";import"./chunk-CIA6V3BP.js";import"./chunk-XQZG5HPT.js";import"./chunk-FACBDLFU.js";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,
|
|
5
5
|
FlowTimestampSchema,StrictObject,canonicalFlowJson,canonicalWithout,compileFlow,hasDuplicateModels,lit,parseFlowData,partialByRole,typebox_exports,verifyFlowDigest}from"./chunk-4DXXZHY2.js";import{getAgentDir}from"./chunk-YRCLNWFV.js";import"./chunk-MF2NEHP4.js";import"./chunk-FRUFMISJ.js";import"./chunk-YJ3NQWES.js";import"./chunk-DBL35X7L.js";import"./chunk-MG5PX4KU.js";import"./chunk-LUL775V7.js";import"./chunk-RYC5BYVE.js";import"./chunk-VEYTRNQC.js";
|
|
6
6
|
import{__export}from"./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 FlowEffortSchema=typebox_exports.Union([typebox_exports.Literal("low"),typebox_exports.Literal("medium"),typebox_exports.Literal("high")]),FlowRoleBindingSchema=StrictObject({primary:FlowModelRefSchema,backups:typebox_exports.Array(FlowModelRefSchema,{maxItems:8}),effort:FlowEffortSchema}),FLOW_MODEL_SELECTION_TIERS=["cheap","mid","premium","frontier"],FLOW_MODEL_SELECTION_CAPABILITIES=["scout","scope_scout","worker","implementation_fast","analysis_mid","technical_lead","lead_small","lead","\
|
|
@@ -319,8 +319,8 @@ ${scanned.slice(tailStart)}`),canonicalMarker=`
|
|
|
319
319
|
`:"":line));let match=rawTriggerMatch(scanned),index=scanned===original?decodedIndex:decodedTriggerIndex(scanned),escapeCutoff=-1;if(index==="capped"){let encoding=scanned.search(ENCODING_RE);if(!match||encoding<match.index+match[0].length){escapeCutoff=protectedBoundary===1/0?scanned.lastIndexOf(`
|
|
320
320
|
`,encoding-1)+1:0;for(let userinfo of scanned.matchAll(URL_USERINFO_BOUNDARY_RE))if(userinfo.index+3<=encoding&&encoding<userinfo.index+userinfo[0].length){escapeCutoff=userinfo.index+3;break}}}else index!==-1&&(!match||index<match.index)&&(escapeCutoff=index);let out,credentialCutoff=escapeCutoff;if(match&&escapeCutoff===-1){let groups=match.groups,replacementPrefix=groups.flagName!==void 0?`${groups.flagPrefix}${groups.flagName} `:groups.asgName!==void 0?`${groups.asgName}=`:groups.bearerKw!==
|
|
321
321
|
void 0?"Bearer ":match[0];credentialCutoff=match.index,out=`${scanned.slice(0,match.index)}${replacementPrefix}[REDACTED]`}else escapeCutoff!==-1?out=`${scanned.slice(0,escapeCutoff)}[REDACTED]`:out=scanned;if(credentialCutoff!==-1){for(let userinfo of scanned.matchAll(URL_USERINFO_BOUNDARY_RE))if(userinfo.index+3<=credentialCutoff&&credentialCutoff<userinfo.index+userinfo[0].length){out=`${scanned.slice(0,userinfo.index)}://[REDACTED]`;break}}for(let pattern of TOKEN_SHAPE_PATTERNS)out=out.replace(
|
|
322
|
-
pattern,"[REDACTED]");out=out.replace(URL_USERINFO_RE,"://***@");let secrets=[...new Set(Object.entries(env??{}).filter(([name,value])=>value&&ENV_CRED_NAME_RE.test(name)).flatMap(([,value])=>[value,...value.split(/\r?\n/)]).filter(
|
|
323
|
-
truncated?`${out.replace(/\n$/,"")}\u2026[REDACTED: input exceeded ${scanLimit}-char redaction scan limit; remainder dropped]`:out}import{execFileSync,spawn}from"node:child_process";import{readdirSync as readdirSync2,readFileSync as readFileSync2,statSync}from"node:fs";import{hostname}from"node:os";var LINEAGE_ENV="HC_FLOW_LINEAGE",segment=/^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/;function lineageMarker(ids){let parts=[ids.rootRunId,ids.runId,ids.logicalTaskId,ids.attemptId];if(parts.some(part=>typeof part!="string"||!segment.test(part)))throw new Error("Invalid lineage identity segment");return parts.join("/")}var psOptions={encoding:"\
|
|
322
|
+
pattern,"[REDACTED]");out=out.replace(URL_USERINFO_RE,"://***@");let secrets=[...new Set(Object.entries(env??{}).filter(([name,value])=>value&&ENV_CRED_NAME_RE.test(name)).flatMap(([,value])=>[value,...value.split(/\r?\n/)]).filter(value=>value.trim().length>=8&&/[^\d\s]/.test(value)&&new Set(value.replace(/\s/g,"")).size>=4))].sort((a,b)=>b.length-a.length);if(secrets.length){let pattern=new RegExp(`\\[REDACTED\\]|${secrets.map(secret=>secret.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")).join("|")}`,"\
|
|
323
|
+
g");out=out.replace(pattern,()=>"[REDACTED]")}return credentialCutoff!==-1&&(out+=canonicalMarker),truncated?`${out.replace(/\n$/,"")}\u2026[REDACTED: input exceeded ${scanLimit}-char redaction scan limit; remainder dropped]`:out}import{execFileSync,spawn}from"node:child_process";import{readdirSync as readdirSync2,readFileSync as readFileSync2,statSync}from"node:fs";import{hostname}from"node:os";var LINEAGE_ENV="HC_FLOW_LINEAGE",segment=/^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/;function lineageMarker(ids){let parts=[ids.rootRunId,ids.runId,ids.logicalTaskId,ids.attemptId];if(parts.some(part=>typeof part!="string"||!segment.test(part)))throw new Error("Invalid lineage identity segment");return parts.join("/")}var psOptions={encoding:"\
|
|
324
324
|
utf8",timeout:2e3,maxBuffer:64*1024*1024,env:{...process.env,LC_ALL:"C",TZ:"UTC",[LINEAGE_ENV]:""}},LINUX_CLK_TCK=100;function isErrno2(error,code){return typeof error=="object"&&error!==null&&error.code===code}function listLinuxProcesses(procRoot="/proc",readEnvironment=!0,deadline=performance.now()+2e3){let checkDeadline=()=>{if(performance.now()>=deadline)throw new Error("Linux process inspection timed out")};checkDeadline();let btime=/^btime\s+(\d+)/m.exec(readFileSync2(`${procRoot}/stat`,"u\
|
|
325
325
|
tf8"));if(!btime)throw new Error("Missing btime in /proc/stat");let bootMs=Number(btime[1])*1e3,rows=[];checkDeadline();for(let name of readdirSync2(procRoot)){if(checkDeadline(),!/^\d+$/.test(name))continue;let base=`${procRoot}/${name}/`;try{let stat=readFileSync2(`${base}stat`,"utf8");checkDeadline();let fields=stat.slice(stat.lastIndexOf(")")+2).split(" "),row={pid:Number(name),ppid:Number(fields[1]),pgid:Number(fields[2]),sid:Number(fields[3]),uid:statSync(base).uid,zombie:fields[0]==="Z",startedAtMs:bootMs+
|
|
326
326
|
Number(fields[19])/LINUX_CLK_TCK*1e3,environ:readEnvironment?"unreadable":"hidden"};checkDeadline();try{let uid=/^Uid:\s+(\d+)/m.exec(readFileSync2(`${base}status`,"utf8"));uid&&(row.uid=Number(uid[1])),checkDeadline(),readEnvironment&&(row.environ=readFileSync2(`${base}environ`,"utf8").split("\0"))}catch(error){if(isErrno2(error,"ENOENT")||isErrno2(error,"ESRCH"))continue;row.environ="unreadable"}checkDeadline(),rows.push(row)}catch(error){if(isErrno2(error,"ENOENT")||isErrno2(error,"ESRCH"))continue;
|
|
@@ -586,20 +586,22 @@ rows),hasEstimate=costBasis==="estimated"||(report.liveQa?.hasEstimatedCost??liv
|
|
|
586
586
|
tial":"unknown":hasEstimate?"estimated":costBasis??"reported";return enforceRunResultBounds(clipForBounds({schema:RUN_RESULT_SCHEMA,version:1,runId:report.runId,outcome:outcomeFromCauses(causes,external),causes,codeVerification:codeVerificationFor(report),liveQa:{verdict:stage?.verdict??"not_requested",...typeof row?.session_id=="string"?{sessionId:row.session_id}:{},...typeof row?.tested_revision=="string"?{testedCommit:row.tested_revision}:{},reasons:stage?.reasons??(report.liveQa?.notRunReason?
|
|
587
587
|
[report.liveQa.notRunReason]:[])},...report.acceptance?{acceptance:report.acceptance}:{},externalChecks:external.map(c=>({provider:c.provider,id:c.id,outcome:c.outcome,...c.reason?{reason:c.reason}:{}})),openItems:report.openItems??report.reportLines.filter(l=>/^\s*[-*]\s+/.test(l)).map(l=>l.replace(/^\s*[-*]\s+/,"")),diagnostics:report.independentReviewBlocker?[report.independentReviewBlocker]:report.dispatchOk?[]:[report.firstFailureLine],cost:{usd:report.totalCostUsd,reportedUsd:report.totalCostUsd,
|
|
588
588
|
estimatedUsd,basis,complete:basis==="reported"},runLog:report.runLogPath}))}function buildTerminalRunResult(input){return enforceRunResultBounds({schema:RUN_RESULT_SCHEMA,version:1,runId:input.runId,outcome:outcomeFromCauses(input.causes),causes:input.causes,codeVerification:"not_run",liveQa:{verdict:"not_requested",reasons:[]},externalChecks:[],openItems:[],diagnostics:[truncateMarked(input.diagnostic,RUN_RESULT_LIMITS.stringChars)],cost:{usd:input.costUsd,reportedUsd:input.costUsd,estimatedUsd:input.
|
|
589
|
-
estimatedUsd??0,basis:input.costBasis??(input.costComplete?"reported":input.costUsd>0?"partial":"unknown"),complete:input.costComplete&&(input.costBasis===void 0||input.costBasis==="reported")},runLog:input.runLog})}import{spawn as spawn3}from"node:child_process";import{createHash as createHash5,randomUUID as randomUUID2}from"node:crypto";import{closeSync as closeSync4,constants as constants2,existsSync as existsSync3,fstatSync as fstatSync4,lstatSync as lstatSync4,openSync as openSync4,readdirSync as readdirSync3,readSync as readSync4,realpathSync}from"node:fs";import{basename as basename2,delimiter,dirname as dirname5,resolve as resolve3}from"node:path";import{fileURLToPath as fileURLToPath4}from"node:url";
|
|
589
|
+
estimatedUsd??0,basis:input.costBasis??(input.costComplete?"reported":input.costUsd>0?"partial":"unknown"),complete:input.costComplete&&(input.costBasis===void 0||input.costBasis==="reported")},runLog:input.runLog})}import{spawn as spawn3}from"node:child_process";import{createHash as createHash5,createHmac,randomBytes as randomBytes2,randomUUID as randomUUID2}from"node:crypto";import{closeSync as closeSync4,constants as constants2,existsSync as existsSync3,fstatSync as fstatSync4,lstatSync as lstatSync4,openSync as openSync4,readdirSync as readdirSync3,readSync as readSync4,realpathSync}from"node:fs";import{basename as basename2,delimiter,dirname as dirname5,resolve as resolve3}from"node:path";import{fileURLToPath as fileURLToPath4}from"node:url";
|
|
590
590
|
import{stripVTControlCharacters as stripVTControlCharacters4}from"node:util";import{createHash as createHash4}from"node:crypto";import{stripVTControlCharacters as stripVTControlCharacters3}from"node:util";function buildRepairEvidence(input){let hash2=text2=>createHash4("sha256").update(text2).digest("hex"),scope=[...new Set(input.scope)].sort();return{suiteKey:hash2(JSON.stringify({level:input.suiteSalt,scope,checks:input.checks})),candidateRoot:input.repoRoot,candidateTree:input.before?.tree??"",integrityVerified:input.before!==null&&input.after!==null&&input.before.tree===input.after.tree,configurationCurrent:()=>input.results.every(result=>result.configurationCurrent?.()!==!1),checks:input.checks.
|
|
591
591
|
map((check2,index)=>{let result=input.results[index],matched=result?.name===check2.name&&JSON.stringify(result.argv)===JSON.stringify(check2.argv),diagnosticIds=matched&&result?[...new Set(result.diagnosticIds??normalizeDiagnostics((result.diagnosticLines??[]).join(`
|
|
592
592
|
`),input.repoRoot).map(hash2))].sort():[],status=matched&&result&&result.exitCode!==null&&![126,127].includes(result.exitCode)&&(result.status==="pass"||result.status==="fail")?result.status:"unverified";return{key:hash2(JSON.stringify({command:result?.comparisonKey??check2,scope})),status,diagnosticIds:status==="fail"?diagnosticIds:[],comparable:!!result?.comparisonKey,complete:matched&&input.results.length===input.checks.length&&Array.isArray(result?.diagnosticLines)&&result.diagnosticsTruncated===
|
|
593
|
-
!1&&status!=="unverified"&&(status==="pass"||diagnosticIds.length>0),diagnosticTail:result?.outputTruncated?"Output truncated; diagnostic tail withheld.":sanitizeControlChars(redactCredentials(stripVTControlCharacters3(result?.tail??""),process.env)).slice(-4e3)}})}}function
|
|
594
|
-
|
|
595
|
-
|
|
596
|
-
|
|
597
|
-
|
|
598
|
-
|
|
599
|
-
|
|
600
|
-
|
|
601
|
-
|
|
602
|
-
|
|
593
|
+
!1&&result.diagnosticEvidenceWithheld!==!0&&status!=="unverified"&&(status==="pass"||diagnosticIds.length>0),diagnosticTail:result?.outputTruncated?"Output truncated; diagnostic tail withheld.":sanitizeControlChars(redactCredentials(stripVTControlCharacters3(result?.tail??""),process.env)).slice(-4e3)}})}}function compareBaselineChecks(baseline,current2,repoRoot){let diagnostics={reasonCounts:{},baselineDiagnosticCount:0,currentDiagnosticCount:0,newDiagnosticCount:0},preexistingIndexes=[],ids=result=>result.diagnosticIds??normalizeDiagnostics((result.diagnosticLines??[]).join(`
|
|
594
|
+
`),repoRoot),incomplete=result=>{if(result.diagnosticEvidenceWithheld||!result.diagnosticIds&&result.diagnosticLines?.some(line=>line.includes("[REDACTED")))return"redaction_loss";if(result.diagnosticsTruncated===!0)return"truncated_evidence";if(!result.comparisonKey||result.diagnosticsTruncated!==!1||!Array.isArray(result.diagnosticLines)||!ids(result).length||ids(result).some(id2=>!id2))return"missing_evidence"};for(let[index,result]of current2.entries()){let code=(()=>{if(result.status!=="fai\
|
|
595
|
+
l")return"not_failed";let candidates=baseline?.filter(before2=>before2.name===result.name);if(!candidates?.length)return"missing_baseline";let matching=candidates.filter(before2=>JSON.stringify(before2.argv)===JSON.stringify(result.argv));if(!matching.length)return"argv_mismatch";let before=matching.find(before2=>before2.comparisonKey===result.comparisonKey&&before2.exitCode===result.exitCode)??matching[0];if(before.status!=="fail")return"baseline_not_failed";if(result.exitCode===null||[126,127].
|
|
596
|
+
includes(result.exitCode)||before.exitCode!==result.exitCode)return"exit_mismatch";let missing2=incomplete(result)??incomplete(before);if(missing2)return missing2;if(result.comparisonKey!==before.comparisonKey||result.configurationCurrent?.()===!1)return"configuration_mismatch";let now=new Set(ids(result)),known=new Set(ids(before)),added=[...now].filter(id2=>!known.has(id2)).length;return diagnostics.baselineDiagnosticCount=Math.min(1e4,diagnostics.baselineDiagnosticCount+known.size),diagnostics.
|
|
597
|
+
currentDiagnosticCount=Math.min(1e4,diagnostics.currentDiagnosticCount+now.size),diagnostics.newDiagnosticCount=Math.min(1e4,diagnostics.newDiagnosticCount+added),added?"new_diagnostics":"preexisting"})();diagnostics.reasonCounts[code]=Math.min(1e4,(diagnostics.reasonCounts[code]??0)+1),code==="preexisting"&&preexistingIndexes.push(index)}return{preexistingIndexes,diagnostics}}function persistedRepairEvidence(evidence){return{suiteKey:evidence.suiteKey,candidateRoot:createHash4("sha256").update(
|
|
598
|
+
evidence.candidateRoot).digest("hex"),candidateTree:createHash4("sha256").update(evidence.candidateTree).digest("hex"),integrityVerified:evidence.integrityVerified,checks:evidence.checks.map(check2=>({key:check2.key,status:check2.status,diagnosticIds:[...check2.diagnosticIds],complete:check2.complete,comparable:check2.comparable,diagnosticTail:""}))}}function decideRepair(state,evidence,options){let next={...state,seenFailureSets:[...state.seenFailureSets]},decision=(action,reason)=>(action==="r\
|
|
599
|
+
epair"||action==="escalate")&&options.explicitMaxRetries!==void 0&&options.repairRounds>=options.explicitMaxRetries?{action:"stop",reason:"explicit retry ceiling",state:next}:{action,reason,state:next};if(evidence&&!evidence.integrityVerified)return decision("stop","candidate integrity not verified");let valid=value=>value.suiteKey!==""&&value.candidateRoot!==""&&value.candidateTree!==""&&value.checks.length>0&&new Set(value.checks.map(c=>c.key)).size===value.checks.length&&value.checks.every(c=>c.
|
|
600
|
+
key!==""&&c.complete&&(c.status==="pass"||c.status==="fail")&&(c.status!=="fail"||c.diagnosticIds.length>0&&c.diagnosticIds.every(Boolean))),previous=state.previous;if(!(evidence&&valid(evidence)&&evidence.configurationCurrent?.()!==!1&&evidence.checks.every(c=>c.comparable)&&(!previous||valid(previous)&&previous.checks.every(c=>c.comparable)&&previous.integrityVerified&&evidence.suiteKey===previous.suiteKey&&evidence.candidateRoot===previous.candidateRoot&&evidence.checks.length===previous.checks.
|
|
601
|
+
length&&previous.checks.every(c=>evidence.checks.some(current2=>current2.key===c.key))))||!evidence)return state.recoveryPending?decision("stop","unverified"):(next.recoveryPending=!0,decision("recover_verification","incomparable verification evidence"));if(next.recoveryPending=!1,evidence.checks.every(c=>c.status==="pass"))return decision("complete","all checks passed");let failures=value=>new Set(value.checks.filter(c=>c.status==="fail").flatMap(c=>c.diagnosticIds.map(id2=>JSON.stringify([c.key,
|
|
602
|
+
id2])))),currentSet=failures(evidence),signature=JSON.stringify([...currentSet].sort()),seen=state.seenFailureSets.includes(signature);if(seen||next.seenFailureSets.push(signature),next.previous=evidence,!previous)return decision("repair","baseline failed verification");let previousSet=failures(previous),regression=previous.checks.some(c=>c.status==="pass"&&evidence.checks.some(current2=>current2.key===c.key&¤t2.status==="fail"));if(!seen&&!regression&¤tSet.size<previousSet.size&&[...currentSet].
|
|
603
|
+
every(id2=>previousSet.has(id2)))return next.nonProgressRounds=0,decision("repair","verified progress");next.nonProgressRounds++;let limit=state.escalated?options.postEscalationLimit:options.nonProgressLimit;return next.nonProgressRounds<limit?decision("repair","no proven progress"):state.escalated?decision("stop","stalled"):(next.escalated=!0,next.nonProgressRounds=0,decision("escalate","consecutive non-progress rounds"))}function cleanDiagnosticLine(line){return stripVTControlCharacters3(line).
|
|
604
|
+
replace(/\[?\b\d{4}-\d{2}-\d{2}[T ]\d{2}:\d{2}:\d{2}(?:\.\d+)?(?:Z|[+-]\d{2}:?\d{2})?\]?/g,"").replace(/^\s*\[?\d{2}:\d{2}:\d{2}(?:\.\d+)?\]?\s*/,"").replace(/\[\s*\d+(?:\.\d+)?\s*(?:ns|us|µs|ms|s|seconds?|minutes?)\s*\]|\bin\s+\d+(?:\.\d+)?\s*(?:ns|us|µs|ms|s|seconds?|minutes?)\b/g,"").trim()}function isDiagnosticLine(line){let clean8=cleanDiagnosticLine(line);return/^(?:\(pass\)|\(skip\))|^[\w./\\-]+::\S+\s+PASSED\b/.test(clean8)||/^(?:[=\s]*\d+\s+(?:fail(?:ed|ures)?|pass(?:ed)?|errors?|skipped)\b|Found\s+\d+\s+errors?\b|Ran\s+\d+\s+tests?\b|[=\s]*(?:short test summary|test session starts)\b)/i.
|
|
603
605
|
test(clean8)?!1:/\(fail\)|\b(?:FAILED|FAIL)\b|\berror\b|\b[A-Za-z]*Error\b|[✗×]|\S+:\d+:\d+(?::|\s)|\S+\(\d+,\d+\):/i.test(clean8)}function normalizeDiagnostics(text2,repoRoot){let root=`${repoRoot.replace(/[\\/]+$/,"")}/`;return[...new Set(text2.split(/\r?\n/).filter(isDiagnosticLine).map(line=>cleanDiagnosticLine(line).split(root).join("")))].sort()}var TAIL=4e3,NEG="(?:do not|don['\u2019]t|never|must not|cannot|can['\u2019]t)",LOCK="(?:lock ?files?|package-lock\\.json|npm-shrinkwrap\\.json|yarn\\.lock|pnpm-lock\\.yaml|bun\\.lockb?|node_modules|dependencies)(?![\\w-])",INSTALL_BANS=[new RegExp(`\\b${NEG}\\s+(?:run\\s+)?(?:(?:(?:npm|pnpm|yarn|bun)\\s+(?:install|add)|install)\\b|add\\s+(?:(?:a|any|new)\\s+)*(?:dependenc(?:y|ies)|packages?)\\b)`,"i"),new RegExp(`\\b${NEG}\\s+(?:create|add|modify|change|update|touch|commit|generate)\\s+(?:(?:a|th\
|
|
604
606
|
e|any)\\s+)?(?:new\\s+)?${LOCK}`,"i"),/\bno (?:new )?(?:lock ?files?|dependency) changes\b/i,/\bno installs?\b/i,/\bwithout installing\b/i];function goalForbidsInstalls(goal){return INSTALL_BANS.some(ban=>ban.test(goal))}function safeCheckNames(names){return names.slice(0,5).map(n=>redactCredentials(n,process.env).replace(/[^A-Za-z0-9 ._:/@+-]/g,"_").slice(0,100))}function unavailableChecksWarning(names,reviewOnly){return`deterministic check(s) unavailable in this environment: ${safeCheckNames(names).
|
|
605
607
|
join(", ")}; independent review${reviewOnly?"":" and QA"} passed (evidence_status: unverified_checks_unavailable)`}var ZSH_NOT_FOUND_NAME=/command not found: (\S+)/,SHELL_NOT_FOUND_NAME=/(\S+): (?:command )?not found\b/,SHELL_BUILTINS=new Set("eval exec source . command builtin type cd export set test [ printf echo read trap exit return shift unset alias hash wait true false :".split(" ")),notFoundNames=output=>output.split(`
|
|
@@ -609,7 +611,7 @@ function nodeModulesAbsent(cwd,repoRoot){try{let root=realpathSync(repoRoot),dir
|
|
|
609
611
|
let entry=json[field];if(entry&&typeof entry=="object")for(let name of Object.keys(entry))names.add(name)}return names}catch{return}finally{fd!==void 0&&closeSync4(fd)}}function commandResolvable(argv0,cwd,env=checkEnv()){if(process.platform==="win32")return!0;let exists=path=>{try{return lstatSync4(path),!0}catch{return!1}};return argv0.includes("/")?exists(resolve3(cwd,argv0)):(env.PATH??"").split(delimiter).some(dir=>exists(resolve3(cwd,dir||".",argv0)))}var packageName=specifier=>specifier.split(
|
|
610
612
|
"/",specifier.startsWith("@")?2:1).join("/");function classifyUnavailable(exitCode,output,outputTruncated,cwd,repoRoot){if(outputTruncated||TEST_RUN_MARKERS.test(output)||CODE_FAILURE_MARKERS.test(output)||!nodeModulesAbsent(cwd,repoRoot))return;let missing2=[...output.matchAll(MISSING_SPECIFIER)].map(m=>m[1]);if(missing2.length){if(missing2.some(s=>!BARE_SPECIFIER.test(s)))return;let declared=declaredPackages(cwd,repoRoot);if(!declared||missing2.some(s=>!declared.has(packageName(s))))return}if(exitCode===
|
|
611
613
|
127){let names=notFoundNames(output);if(names.length>0&&names.every(n=>PLAIN_COMMAND_TOKEN.test(n)&&!SHELL_BUILTINS.has(n)&&!commandResolvable(n,cwd)))return"command_not_found"}return missing2.length?"missing_dependencies":void 0}var ENV_ALLOW=/^(PATH|HOME|TMPDIR|LANG|LC_ALL|LC_CTYPE|LC_COLLATE|LC_MESSAGES|LC_NUMERIC|LC_TIME|LC_MONETARY|TERM|SHELL|USER|LOGNAME|TZ|SSL_CERT_FILE|NODE_EXTRA_CA_CERTS|VIRTUAL_ENV|JAVA_HOME|GOPATH)$/,PROXY=/^(HTTPS?_PROXY|https?_proxy|NO_PROXY|no_proxy)$/,hasUserinfo=v=>v.
|
|
612
|
-
includes("@");function checkEnv(parent=process.env){let env={CI:"1"};for(let[k,v]of Object.entries(parent))v!==void 0&&(ENV_ALLOW.test(k)||PROXY.test(k)&&(k.toLowerCase()==="no_proxy"||!hasUserinfo(v)))&&(env[k]=v);return env}var ESCALATION_MS=5e3,DIAGNOSTIC_LINES=2e3,DIAGNOSTIC_BYTES=256*1024;function checkComparisonKey(check2,repoRoot,cwd,env){try{let root=realpathSync(repoRoot),inside=path=>isPathWithin(root,path),known=/^(?:package\.json|tsconfig.*\.json|jsconfig\.json|eslint\.config\..+|\.eslintrc.*|biome\.jsonc?|bunfig\.toml|(?:vitest|jest)\.config\..+|pyproject\.toml|setup\.cfg|tox\.ini|pytest\.ini|\.?ruff\.toml|mypy\.ini|Makefile|bun\.lockb?|package-lock\.json|npm-shrinkwrap\.json|yarn\.lock|pnpm-lock\.yaml|uv\.lock|poetry\.lock)$/,
|
|
614
|
+
includes("@");function checkEnv(parent=process.env){let env={CI:"1"};for(let[k,v]of Object.entries(parent))v!==void 0&&(ENV_ALLOW.test(k)||PROXY.test(k)&&(k.toLowerCase()==="no_proxy"||!hasUserinfo(v)))&&(env[k]=v);return env}var ESCALATION_MS=5e3,DIAGNOSTIC_LINES=2e3,DIAGNOSTIC_BYTES=256*1024,diagnosticIdentityKey=randomBytes2(32);function checkComparisonKey(check2,repoRoot,cwd,env){try{let root=realpathSync(repoRoot),inside=path=>isPathWithin(root,path),known=/^(?:package\.json|tsconfig.*\.json|jsconfig\.json|eslint\.config\..+|\.eslintrc.*|biome\.jsonc?|bunfig\.toml|(?:vite|vitest|jest)\.config\..+|pyproject\.toml|setup\.cfg|tox\.ini|pytest\.ini|\.?ruff\.toml|mypy\.ini|Makefile|bun\.lockb?|package-lock\.json|npm-shrinkwrap\.json|yarn\.lock|pnpm-lock\.yaml|uv\.lock|poetry\.lock)$/,
|
|
613
615
|
files=new Set([resolve3(root,check2.source)]);for(let dir of new Set([root,realpathSync(cwd)])){if(!inside(dir))return;for(let name of readdirSync3(dir))known.test(name)&&files.add(resolve3(dir,name))}let explicitConfigs=(tokens,directory)=>{let targets=[];for(let i=0;i<tokens.length;i++){let token=tokens[i],target=token.match(/^(?:--(?:project|config|tsconfig)=|-[pc])(.+)$/)?.[1]??(/^(?:--(?:project|config|tsconfig)|-[pc])$/.test(token)?tokens[++i]:void 0);if(!(target===void 0&&!/^(?:--(?:project|config|tsconfig)|-[pc])$/.
|
|
614
616
|
test(token))){if(!target||/[$`]/.test(target)||tokens.includes("cd"))throw new Error("Unresolved explicit config");targets.push(resolve3(realpathSync(directory),target))}}return targets};for(let path of explicitConfigs(check2.argv,cwd))files.add(path);let configs=[],visited=new Set,fingerprint3=(path,depth=0,inherited=!1)=>{if(!inside(path))throw new Error("Config outside repo");try{lstatSync4(path)}catch(err){if(!inherited&&err.code==="ENOENT"){configs.push([path,null]);return}throw err}let real=realpathSync(
|
|
615
617
|
path),validated=lstatSync4(real);if(!inside(real)||!validated.isFile())throw new Error("Unsafe config");if(visited.has(real))return;if(depth>16)throw new Error("Config inheritance too deep");visited.add(real);let fd;try{fd=openSync4(real,constants2.O_RDONLY|constants2.O_NONBLOCK|constants2.O_NOFOLLOW);let stat=fstatSync4(fd),limit=1024*1024;if(!stat.isFile()||stat.size>limit||stat.dev!==validated.dev||stat.ino!==validated.ino)throw new Error("Unsafe config descriptor");let revalidate=()=>{let currentRoot=realpathSync(
|
|
@@ -622,20 +624,19 @@ base))throw new Error("Config import outside repo");let extensions=[".js",".mjs"
|
|
|
622
624
|
/\.jsonc?$/.test(real)||/^(?:tsconfig.*\.json|jsconfig\.json|biome\.jsonc?|\.eslintrc(?:\.json)?)$/.test(basename2(path))){let json=content.toString("utf8").replace(/^\uFEFF/,"").replace(/"(?:\\.|[^"\\])*"|\/\/[^\r\n]*|\/\*[\s\S]*?\*\//g,token=>token.startsWith('"')?token:" ").replace(/"(?:\\.|[^"\\])*"|,\s*(?=[}\]])/g,token=>token.startsWith('"')?token:""),config=JSON.parse(json),targets=config.extends===void 0?[]:Array.isArray(config.extends)?config.extends:[config.extends];for(let target of targets){
|
|
623
625
|
if(typeof target!="string"||!target)throw new Error("Invalid config inheritance");if(!target.startsWith(".")&&!target.startsWith("/"))continue;let inheritedPath=resolve3(dirname5(real),target);try{lstatSync4(inheritedPath)}catch(err){if(err.code!=="ENOENT"||inheritedPath.endsWith(".json"))throw err;inheritedPath+=".json"}fingerprint3(inheritedPath,depth+1,!0)}}}finally{fd!==void 0&&closeSync4(fd)}};for(let path of[...files].sort())fingerprint3(path);return createHash5("sha256").update(JSON.stringify(
|
|
624
626
|
{argv:check2.argv,cwd,source:check2.source,configs,env:Object.entries(env).sort(([a],[b])=>a.localeCompare(b))})).digest("hex")}catch{return}}function runOne(check2,repoRoot,timeoutMs,recovery,cancellation,wrapCommand){let cwd=resolve3(repoRoot,check2.cwd),id2=`check-${createHash5("sha256").update(JSON.stringify([check2.name,check2.argv,cwd])).digest("hex")}`,nativeId=`check-${randomUUID2()}`;recovery&&(recovery.registerDispatchTasks([{taskId:id2,capability:"deterministic_check",task:JSON.stringify(
|
|
625
|
-
check2),stage:"other"}]),recovery.beforeLaunch(id2,nativeId));let started=Date.now(),env=checkEnv(),redactEnv={...process.env,...env},comparisonKey=checkComparisonKey(check2,repoRoot,cwd,env),marker=recovery?.marker?.(id2,nativeId);return new Promise((resolveResult,reject)=>{let out="",outputLength=0,outputTruncated=!1,diagnosticLines=[],
|
|
626
|
-
diagnosticBytes+bytes>DIAGNOSTIC_BYTES){diagnosticsTruncated=!0;return}diagnosticBytes+=bytes;let clean8=normalizeDiagnostics(line,repoRoot)[0],redacted=
|
|
627
|
-
replace(/[^a-z]/gi,"");(/PRIVATE[\s\S]{0,8}KEY/i.test(normalized)||/-----BEGIN [^\r\n-]*PRIVATE KEY-----/i.
|
|
628
|
-
exited=!1,launchFailed=!1,launchError,registered=!1,noProcessLaunchFailed=!1,spawnMissingCommand=!1,rejectLaunch=()=>finish(
|
|
629
|
-
|
|
627
|
+
check2),stage:"other"}]),recovery.beforeLaunch(id2,nativeId));let started=Date.now(),env=checkEnv(),redactEnv={...process.env,...env},comparisonKey=checkComparisonKey(check2,repoRoot,cwd,env),marker=recovery?.marker?.(id2,nativeId);return new Promise((resolveResult,reject)=>{let out="",outputLength=0,outputTruncated=!1,diagnosticLines=[],capturedDiagnosticIds=new Set,sanitizeFinal=text2=>redactCredentials(stripVTControlCharacters4(text2).replace(/[\x00-\x08\x0b-\x1f\x7f-\x9f]/g,""),redactEnv).replace(
|
|
628
|
+
/[A-Za-z0-9+/=]{40,}/g,run=>/[A-Z]/.test(run)&&/[a-z]/.test(run)&&/\d/.test(run)?"[REDACTED-BASE64]":run),diagnosticsTruncated=!1,diagnosticBytes=0,collect=line=>{if(!isDiagnosticLine(line))return;let bytes=Buffer.byteLength(line)+1;if(diagnosticLines.length>=DIAGNOSTIC_LINES||diagnosticBytes+bytes>DIAGNOSTIC_BYTES){diagnosticsTruncated=!0;return}diagnosticBytes+=bytes;let clean8=normalizeDiagnostics(line,repoRoot)[0],redacted=sanitizeFinal(clean8);clean8.length>64*1024&&(diagnosticsTruncated=!0),
|
|
629
|
+
capturedDiagnosticIds.add((redacted===clean8?createHash5("sha256"):createHmac("sha256",diagnosticIdentityKey)).update(clean8).digest("hex")),diagnosticLines.push(redacted)},withholdOutputEvidence=!1,streams=[0,1].map(()=>({pending:"",dropping:!1,pendingRaw:"",scanStopped:!1,textCarry:"",letters:""})),scanText=(text2,stream)=>{let normalized=stream.textCarry+stripVTControlCharacters4(text2),letters=normalized.replace(/[^a-z]/gi,"");(/PRIVATE[\s\S]{0,8}KEY/i.test(normalized)||/-----BEGIN [^\r\n-]*PRIVATE KEY-----/i.
|
|
630
|
+
test(normalized)||/PRIVATEKEY/i.test(letters)||/PRIVATEKEY/i.test(stream.letters+letters))&&(withholdOutputEvidence=!0),stream.textCarry=normalized.slice(-256),stream.letters=(stream.letters+letters).slice(-64)},collectStream=stream=>collect(stripVTControlCharacters4(stream.pending)),timedOut=!1,cancelled=!1,removeCancellationListener,settled=!1,child,timer,escalationTimer,launchSettleTimer,exited=!1,launchFailed=!1,launchError,registered=!1,noProcessLaunchFailed=!1,spawnMissingCommand=!1,rejectLaunch=()=>finish(
|
|
631
|
+
"error",null),finish=(status,exitCode)=>{if(settled)return;settled=!0,removeCancellationListener?.(),clearTimeout(timer),clearTimeout(escalationTimer),clearTimeout(launchSettleTimer);for(let stream of streams)stream.pendingRaw.endsWith("\x1B")&&(withholdOutputEvidence=!0),stream.scanStopped||scanText(stream.pendingRaw,stream),!stream.dropping&&stream.pending&&collectStream(stream);let notice="[REDACTED: private key output withheld]",tail=sanitizeFinal(outputTruncated?out.includes(`
|
|
630
632
|
`)?out.slice(out.indexOf(`
|
|
631
|
-
`)+1):"":out),finalDiagnostics=diagnosticLines
|
|
632
|
-
"
|
|
633
|
-
|
|
634
|
-
|
|
635
|
-
|
|
636
|
-
|
|
637
|
-
|
|
638
|
-
outputLength>TAIL&&(outputTruncated=!0);let clean8=stripVTControlCharacters4(text2).split(`
|
|
633
|
+
`)+1):"":out),finalDiagnostics=diagnosticLines;[tail,...finalDiagnostics].some(text2=>text2.replace(/[^a-z]/gi,"").toUpperCase().includes("PRIVATEKEY"))&&(withholdOutputEvidence=!0);let diagnosticIds=withholdOutputEvidence?[]:[...capturedDiagnosticIds].sort(),unavailableReason=status==="error"&&spawnMissingCommand?"command_not_found":status==="fail"?classifyUnavailable(exitCode,out,outputTruncated,cwd,repoRoot):void 0,result={name:check2.name,argv:check2.argv,status:unavailableReason?"unavailabl\
|
|
634
|
+
e":status,...unavailableReason?{unavailableReason}:{},exitCode,durationMs:Date.now()-started,tail:withholdOutputEvidence?notice:tail,outputTruncated,comparisonKey:comparisonKey&&comparisonKey===checkComparisonKey(check2,repoRoot,cwd,env)?comparisonKey:void 0,configurationCurrent:()=>comparisonKey!==void 0&&comparisonKey===checkComparisonKey(check2,repoRoot,cwd,checkEnv()),diagnosticLines:withholdOutputEvidence?[notice]:finalDiagnostics,diagnosticIds,diagnosticsTruncated,diagnosticEvidenceWithheld:withholdOutputEvidence};
|
|
635
|
+
(async()=>{let cleaned=child?.pid===void 0;child?.pid!==void 0&&(cleaned=await killProcessTree(child),!cleaned&&liveDispatchPids.has(child.pid)&&console.warn(`[orchestrator] check owned cleanup liveness ${dispatchCustody(child).ownedTreeState} after bounded TERM/KILL`));let custody=child?.pid===void 0?{ownedTreeState:"absent",replayBlocked:!1}:dispatchCustody(child);cleaned||=custody.ownedTreeState==="absent";try{recovery&&(registered||noProcessLaunchFailed||launchFailed)&&recovery.settled(id2,nativeId,
|
|
636
|
+
{processTerminationConfirmed:cleaned,processExitObserved:exited||noProcessLaunchFailed,...custody,...noProcessLaunchFailed?{noProcessLaunchFailed:!0}:{},...launchFailed?{launchRegistrationFailed:!0}:{},taskId:nativeId,capability:"deterministic_check",model:"local",exitCode:exitCode??-1,stdout:result.tail,stderr:"",usage:{input:0,output:0,cacheRead:0,cacheWrite:0,cost:0,contextTokens:0,turns:0},costUsd:0,costReported:!0,durationMs:result.durationMs,outcome:cancelled?"cancelled":status==="timeout"?
|
|
637
|
+
"timed_out":status==="pass"?"completed":"failed",filesChanged:[],claimedFiles:[]}),launchFailed?reject(launchError):resolveResult({...result,...custody})}catch(error){reject(launchFailed?launchError:error)}})().catch(reject)},spawnedAtMs=Date.now();try{let argv=wrapCommand?.(check2)??check2.argv;child=spawn3(argv[0],argv.slice(1),{cwd,shell:!1,detached:!0,stdio:["ignore","pipe","pipe"],env:marker?{...env,[LINEAGE_ENV]:marker}:env})}catch(err){noProcessLaunchFailed=!0,out=String(err),finish("erro\
|
|
638
|
+
r",null);return}let identity3=child.pid===void 0?void 0:spawnedProcessIdentity(child.pid,spawnedAtMs);registerDispatchPid(child.pid,child,identity3);let spawnedPid=child.pid,append=(text2,stream=streams[0])=>{if(!stream.scanStopped){let raw=stream.pendingRaw+text2;/[\u0080-\u009f]|\x1b(?!\[)[\s\S]/.test(raw)&&(withholdOutputEvidence=!0);let p=raw.length-1;for(;p>=0&&!/[\x1b\u0080-\u009f]/.test(raw[p]);)p--;let suffix=p>=0?raw.slice(p):"",incomplete=/^\x1b$/.test(suffix)||/^(?:\x1b\[|\u009b)[\x30-\x3f]*[\x20-\x2f]*$/.
|
|
639
|
+
test(suffix)||/^(?:\x1b[\]P^_X]|[\u009d\u0090\u009e\u009f\u0098])[^\x07\u009c]*?(?:\x1b)?$/.test(suffix);stream.pendingRaw=incomplete?suffix:"",stream.pendingRaw.length>4096?(withholdOutputEvidence=!0,stream.scanStopped=!0,stream.pendingRaw=""):scanText(incomplete?raw.slice(0,p):raw,stream)}outputLength+=text2.length,outputLength>TAIL&&(outputTruncated=!0);let clean8=stripVTControlCharacters4(text2).split(`
|
|
639
640
|
`).map(line=>redactCredentials(line,redactEnv)).join(`
|
|
640
641
|
`);out=(out+clean8).slice(-TAIL);let parts=text2.split(`
|
|
641
642
|
`);for(let i=0;i<parts.length;i++)stream.dropping||(stream.pending+=parts[i],Buffer.byteLength(stream.pending)>DIAGNOSTIC_BYTES&&(diagnosticsTruncated=!0,stream.pending="",stream.dropping=!0)),i<parts.length-1&&(stream.dropping||collectStream(stream),stream.pending="",stream.dropping=!1)};child.stdout?.setEncoding("utf8").on("data",text2=>append(text2,streams[0])),child.stderr?.setEncoding("utf8").on("data",text2=>append(text2,streams[1]));let clearTimers=()=>{clearTimeout(timer),clearTimeout(escalationTimer)},
|
|
@@ -911,14 +912,14 @@ for(let id2 of head?.childRunIds??[])checkClaimedChild(stateRoot,id2,deps,rootRu
|
|
|
911
912
|
stateRoot,childRunId);if(child.rootRunId!==rootRunId||child.parentRunId!==selectedRunId)throw recoveryError("claim child lineage mismatch");lock.verify(),parentDirectory.verify(),atomicJson(stateRoot,parent,{rootRunId,headRunId:childRunId,childRunIds:[...previous?.childRunIds??[],childRunId]},`${rootRunId}.head.json`),lock.verify()}finally{lock.release()}})},release(){let lock;try{try{lstatSync7(dir)}catch(error){if(codeOf(error)==="ENOENT"){parentDirectory.verify();return}throw error}if(lock=lockClaim(
|
|
912
913
|
stateRoot,dir,deps),readClaim(stateRoot,dir).token!==token)return;let tombstone=join10(parent,`.released-${rootRunId}-${randomUUID3()}`);lock.verify(),parentDirectory.verify(),renameSync2(dir,tombstone),parentDirectory.verify(),syncDirectory(parent),rmSync3(tombstone,{recursive:!0})}catch(error){throw sanitizedError("claim release refused",error)}finally{lock?.release()}}};try{checkHead(),publicationLock.verify()}catch(error){throw publicationLock.release(),claim.release(),error}finally{publicationLock.
|
|
913
914
|
release()}return claim}function addClaimWorker(stateRoot,rootRunId,token,worker){recoveryBoundary("claim worker registration refused",()=>{registerClaimWorker(stateRoot,rootRunId,token,worker)})}function registerClaimWorker(stateRoot,rootRunId,token,worker){if(!validIdentity(worker))throw recoveryError("claim worker identity unknown");let dir=claimPath(stateRoot,rootRunId),lock=lockClaim(stateRoot,dir);try{let claim=readClaim(stateRoot,dir);if(claim.token!==token)throw recoveryError("claim token\
|
|
914
|
-
mismatch");lock.verify(),atomicJson(stateRoot,dir,{...claim,workers:[...claim.workers,worker]}),lock.verify()}finally{lock.release()}}import{randomBytes as
|
|
915
|
+
mismatch");lock.verify(),atomicJson(stateRoot,dir,{...claim,workers:[...claim.workers,worker]}),lock.verify()}finally{lock.release()}}import{randomBytes as randomBytes5}from"node:crypto";import{closeSync as closeSync10,constants as constants6,lstatSync as lstatSync9,mkdirSync as mkdirSync5,openSync as openSync10}from"node:fs";import{join as join13}from"node:path";var FLOW_WARNING_REASONS=["preexisting_check_failures"],Mode=lit("auto","direct"),Effort=lit("low","medium","high"),EventModelRefSchema=StrictObject({provider:FlowIdSchema,model:typebox_exports.String({pattern:FLOW_ID_PATTERN})}),event=(kind,payload)=>StrictObject({schema:typebox_exports.Literal("humain-flow-event"),schemaVersion:typebox_exports.Literal(1),eventId:FlowIdSchema,runId:FlowIdSchema,seq:FlowPositiveIntSchema,ts:FlowTimestampSchema,profile:FlowProfileRefSchema,causes:typebox_exports.
|
|
915
916
|
Array(FlowIdSchema,{maxItems:16}),kind:typebox_exports.Literal(kind),payload}),RoleTotals=StrictObject({tokens:FlowCountSchema,costMicrousd:FlowMicrousdSchema,durationMs:FlowCountSchema,requests:FlowCountSchema}),FlowEventV1Schema=typebox_exports.Union([event("run_started",StrictObject({mode:Mode,surface:lit("cli","web"),admissionDigest:FlowDigestSchema,inputsCount:FlowCountSchema,goalSha256:FlowDigestSchema})),event("size_decided",StrictObject({size:FlowSizeSchema,source:lit("rules","triage","o\
|
|
916
917
|
verride"),ruleScore:typebox_exports.Number({minimum:0,maximum:1e6}),thresholds:StrictObject({mediumAt:typebox_exports.Number({minimum:0,maximum:1e6}),largeAt:typebox_exports.Number({minimum:0,maximum:1e6})})})),event("escalated",StrictObject({from:FlowSizeSchema,to:FlowSizeSchema,reasonClass:FlowReasonClassSchema})),event("route_bound",StrictObject({taskId:FlowIdSchema,role:FlowRoleSchema,model:EventModelRefSchema,effort:Effort,binding:lit("primary","backup","lead_selected"),backupIndex:typebox_exports.
|
|
917
918
|
Integer({minimum:0,maximum:7})})),event("fallback",StrictObject({taskId:FlowIdSchema,role:FlowRoleSchema,from:EventModelRefSchema,to:EventModelRefSchema,reasonClass:FlowReasonClassSchema})),event("attempt",StrictObject({taskId:FlowIdSchema,role:FlowRoleSchema,attempt:FlowPositiveIntSchema,state:lit("started","succeeded","failed","retried","cancelled"),failureClass:typebox_exports.Optional(FlowFailureClassSchema)})),event("request_usage",StrictObject({requestId:FlowIdSchema,taskId:FlowIdSchema,role:FlowRoleSchema,
|
|
918
919
|
model:EventModelRefSchema,inputTokens:FlowCountSchema,outputTokens:FlowCountSchema,cacheReadTokens:FlowCountSchema,cacheWriteTokens:FlowCountSchema,costMicrousd:typebox_exports.Union([FlowMicrousdSchema,typebox_exports.Null()]),costBasis:lit("reported","estimated","unknown"),durationMs:FlowCountSchema})),event("verdict",StrictObject({stage:lit("check","review","qa"),taskId:FlowIdSchema,verdict:lit("pass","fail","blocked"),findingsCount:FlowCountSchema,checkId:typebox_exports.Optional(FlowIdSchema)})),
|
|
919
920
|
event("budget",StrictObject({spentMicrousd:FlowMicrousdSchema,capMicrousd:FlowMicrousdSchema,pct:typebox_exports.Number({minimum:0,maximum:100}),state:lit("ok","warn","stop")})),event("control",StrictObject({action:lit("pause","resume","cancel","message","status"),commandId:FlowIdSchema,state:lit("accepted","applied","rejected"),latencyMs:FlowCountSchema})),event("message",StrictObject({messageId:FlowIdSchema,disposition:lit("live","queued","rejected"),targetRole:FlowRoleSchema,textSha256:FlowDigestSchema,
|
|
920
921
|
textLength:typebox_exports.Integer({minimum:1,maximum:16e3})})),event("run_settled",StrictObject({outcome:lit("succeeded","failed","cancelled","budget_stopped","interrupted"),failureClass:typebox_exports.Optional(FlowFailureClassSchema),settledCleanly:typebox_exports.Boolean(),retryOffer:typebox_exports.Array(lit("flow","direct"),{maxItems:2,uniqueItems:!0}),totals:partialByRole(RoleTotals)})),event("warning",StrictObject({reason:lit(...FLOW_WARNING_REASONS),checkIds:typebox_exports.Array(FlowIdSchema,
|
|
921
|
-
{minItems:1,maxItems:16,uniqueItems:!0})}))]),Validator2=compileFlow(FlowEventV1Schema);function crossFieldsValid2(doc){return doc.kind==="request_usage"?doc.payload.costMicrousd===null==(doc.payload.costBasis==="unknown"):!0}function isEvent(value){return Validator2.Check(value)&&crossFieldsValid2(value)}function parseFlowEventV1(input){return parseFlowData("event_invalid",input,isEvent)}import{createHash as createHash8,randomBytes as
|
|
922
|
+
{minItems:1,maxItems:16,uniqueItems:!0})}))]),Validator2=compileFlow(FlowEventV1Schema);function crossFieldsValid2(doc){return doc.kind==="request_usage"?doc.payload.costMicrousd===null==(doc.payload.costBasis==="unknown"):!0}function isEvent(value){return Validator2.Check(value)&&crossFieldsValid2(value)}function parseFlowEventV1(input){return parseFlowData("event_invalid",input,isEvent)}import{createHash as createHash8,randomBytes as randomBytes3}from"node:crypto";import{closeSync as closeSync8,constants as constants4,existsSync as existsSync4,fstatSync as fstatSync8,fsyncSync as fsyncSync3,linkSync as linkSync2,mkdirSync as mkdirSync3,openSync as openSync8,readSync as readSync8,realpathSync as realpathSync5,rmSync as rmSync4,statSync as statSync3,unlinkSync as unlinkSync3,writeFileSync as writeFileSync3}from"node:fs";import{dirname as dirname8,isAbsolute as isAbsolute7,join as join11,
|
|
922
923
|
relative as relative5,resolve as resolve5,sep as sep3}from"node:path";var FlowRunAdmissionV1Schema=StrictObject({schema:typebox_exports.Literal("humain-flow-admission"),schemaVersion:typebox_exports.Literal(1),runId:FlowIdSchema,surface:typebox_exports.Union([typebox_exports.Literal("cli"),typebox_exports.Literal("web")]),tenantId:typebox_exports.Optional(FlowIdSchema),projectId:typebox_exports.Optional(FlowIdSchema),mode:typebox_exports.Union([typebox_exports.Literal("auto"),typebox_exports.Literal("direct")]),profile:FlowProfileV1Schema,sizeOverride:typebox_exports.
|
|
923
924
|
Optional(FlowSizeSchema),directModel:typebox_exports.Optional(FlowModelRefSchema),spendCapMicrousd:FlowMicrousdSchema,inputs:typebox_exports.Array(StrictObject({kind:typebox_exports.Union([typebox_exports.Literal("plan"),typebox_exports.Literal("sketch")]),ref:FlowIdSchema,sha256:FlowDigestSchema,path:typebox_exports.String({minLength:1,maxLength:1024})}),{maxItems:64}),issuedAt:FlowTimestampSchema,admissionDigest:FlowDigestSchema}),Validator3=compileFlow(FlowRunAdmissionV1Schema);function flowAdmissionDigestInput(doc){
|
|
924
925
|
return canonicalWithout(doc,"admissionDigest")}function isAdmissionShape(value){if(!Validator3.Check(value))return!1;try{return parseFlowProfileV1Shape(value.profile),!0}catch{return!1}}function parseFlowRunAdmissionV1Shape(input){return parseFlowData("admission_invalid",input,isAdmissionShape)}function parseFlowRunAdmissionV1(input,hasher){let admission=parseFlowRunAdmissionV1Shape(input);if(!verifyFlowDigest(hasher,flowProfileDigestInput(admission.profile),admission.profile.digest))throw new FlowContractError(
|
|
@@ -940,7 +941,7 @@ inputs.length>0){let path=join11(runDir2,FLOW_APPROVED_INPUTS_FILE),block=readRe
|
|
|
940
941
|
`,"utf8")))return fail4(`Frozen approved inputs ${path} do not match the approved inputs.`)}return{ok:!0,source:picked.source,inputs:loaded.inputs}}function admissionFor(source,runId,config){return source.kind==="file"?source.admission:buildCliAdmission({runId,resolved:source.resolved,issuedAt:(config.now??(()=>new Date))()})}function fdIsConfinedFile(fd,path,realRoot){try{let real=realpathSync5(path),rel=relative5(realRoot,real);if(rel===""||rel===".."||rel.startsWith(`..${sep3}`)||isAbsolute7(
|
|
941
942
|
rel))return!1;let named=statSync3(real),opened=fstatSync8(fd);return named.dev===opened.dev&&named.ino===opened.ino}catch{return!1}}function readRegularBounded(path,max,realRoot,privateFile=!1){let fd;try{fd=openSync8(path,constants4.O_RDONLY|constants4.O_NOFOLLOW|constants4.O_NONBLOCK);let stat=fstatSync8(fd);if(!stat.isFile())return{ok:!1,reason:"not-regular"};if(privateFile&&(typeof process.getuid!="function"||stat.uid!==process.getuid()))return{ok:!1,reason:"wrong-owner"};if(privateFile&&(stat.
|
|
942
943
|
mode&4095)!==384)return{ok:!1,reason:"mode must be 0600"};if(realRoot!==void 0&&!fdIsConfinedFile(fd,path,realRoot))return{ok:!1,reason:"not-confined"};let buffer=Buffer.alloc(max+1),size=0;for(;size<=max;){let n=readSync8(fd,buffer,size,max+1-size,null);if(n===0)break;size+=n}return size>max?{ok:!1,reason:"too-large"}:{ok:!0,bytes:buffer.subarray(0,size)}}catch(error){return{ok:!1,reason:error.code??"error"}}finally{fd!==void 0&&closeSync8(fd)}}function syncDirectory2(dir){let fd=openSync8(dir,
|
|
943
|
-
constants4.O_RDONLY|constants4.O_NOFOLLOW);try{fsyncSync3(fd)}finally{closeSync8(fd)}}function writeAdmissionAtomic(path,admission){if(existsSync4(path))return fail4(`${path} already exists; an admission is frozen once per run.`);let tmp=`${path}.${
|
|
944
|
+
constants4.O_RDONLY|constants4.O_NOFOLLOW);try{fsyncSync3(fd)}finally{closeSync8(fd)}}function writeAdmissionAtomic(path,admission){if(existsSync4(path))return fail4(`${path} already exists; an admission is frozen once per run.`);let tmp=`${path}.${randomBytes3(6).toString("hex")}.tmp`;try{mkdirSync3(dirname8(path),{recursive:!0,mode:448});let fd=openSync8(tmp,constants4.O_WRONLY|constants4.O_CREAT|constants4.O_EXCL|constants4.O_NOFOLLOW,384);try{writeFileSync3(fd,`${JSON.stringify(admission,null,
|
|
944
945
|
" ")}
|
|
945
946
|
`),fsyncSync3(fd)}finally{closeSync8(fd)}return linkSync2(tmp,path),unlinkSync3(tmp),syncDirectory2(dirname8(path)),{ok:!0}}catch(error){try{rmSync4(tmp,{force:!0})}catch{}let code=error.code;return code==="EEXIST"&&existsSync4(path)?fail4(`${path} already exists; an admission is frozen once per run.`):fail4(`Cannot write ${path}: ${code??"error"}.`)}}function writeApprovedInputsFile(path,inputs){try{return writeFileSync3(path,`${approvedInputsBlock(inputs)}
|
|
946
947
|
`,{flag:"wx",mode:384}),{ok:!0}}catch(error){return fail4(`Cannot write ${path}: ${error.code??"error"}.`)}}function insideRoot(path,root){let rel=relative5(root,path);if(rel===""||rel===".."||rel.startsWith(`..${sep3}`)||isAbsolute7(rel))return!1;try{return realpathSync5(dirname8(path))===dirname8(join11(realpathSync5(root),rel))}catch{return!1}}function loadApprovedInputs(inputs,roots){let loaded=[],allowed=[roots.cwd,...roots.admissionDir!==void 0?[roots.admissionDir]:[]];for(let input of inputs){
|
|
@@ -950,7 +951,7 @@ put ${input.ref} cannot be read (${read.reason}): ${path}`);if(createHash8("sha2
|
|
|
950
951
|
`
|
|
951
952
|
`)}function attachApprovedInputs(prompt,inputs){return inputs.length===0?prompt:`${prompt}
|
|
952
953
|
|
|
953
|
-
${approvedInputsBlock(inputs)}`}function createEscalationGate(onEscalated,limit=1){let used=0;return{available:()=>used<limit,escalate:payload=>used>=limit?!1:(used++,onEscalated?.(payload),!0)}}function fail4(message){return{ok:!1,message}}import{createHash as createHash10,randomBytes as
|
|
954
|
+
${approvedInputsBlock(inputs)}`}function createEscalationGate(onEscalated,limit=1){let used=0;return{available:()=>used<limit,escalate:payload=>used>=limit?!1:(used++,onEscalated?.(payload),!0)}}function fail4(message){return{ok:!1,message}}import{createHash as createHash10,randomBytes as randomBytes4}from"node:crypto";import{chmodSync as chmodSync2,closeSync as closeSync9,constants as constants5,fchmodSync,fstatSync as fstatSync9,fsyncSync as fsyncSync4,ftruncateSync,linkSync as linkSync3,lstatSync as lstatSync8,mkdirSync as mkdirSync4,openSync as openSync9,readdirSync as readdirSync4,readFileSync as readFileSync5,readSync as readSync9,renameSync as renameSync3,rmSync as rmSync5,unlinkSync as unlinkSync4,writeSync as writeSync2}from"node:fs";
|
|
954
955
|
import{basename as basename4,dirname as dirname9,join as join12}from"node:path";import{createHash as createHash9}from"node:crypto";var SINK_FAILURE="flow telemetry sink failure",INVALID_OPTIONS="flow emitter options invalid",INVALID_EVENT="flow event invalid",REENTRANT="flow emit reentrant",MAX_IN_FLIGHT=1e4,MAX_FAILURES=32,SAFE_CODES=new Set(["ENOSPC","EIO","EBADF","EPIPE","EACCES","EPERM","EROFS","EDQUOT","EMFILE","ENFILE","ECONNRESET","ETIMEDOUT","ERR_STREAM_DESTROYED"]);function deepFreeze(value){if(value!==null&&typeof value=="object"&&!Object.isFrozen(value)){Object.freeze(value);for(let item of Object.values(value))deepFreeze(
|
|
955
956
|
item)}return value}function errorCode(error){try{let code=error?.code;return typeof code=="string"&&SAFE_CODES.has(code)?code:void 0}catch{return}}function createFlowEmitter(opts){let now=opts.now??Date.now,seq=opts.startSeq??1,profile;try{profile=deepFreeze(parseFlowEventV1({schema:"humain-flow-event",schemaVersion:1,eventId:"probe",runId:opts.runId,seq,ts:new Date(now()).toISOString(),profile:opts.profile,causes:[],kind:"budget",payload:{spentMicrousd:0,capMicrousd:0,pct:0,state:"ok"}}).profile)}catch{
|
|
956
957
|
throw new Error(INVALID_OPTIONS)}let runId=opts.runId,idPrefix=createHash9("sha256").update(runId).digest("hex").slice(0,32),states=opts.sinks.map(sink=>({sink,pending:void 0,inFlight:0,dropped:!1})),failures=[],failureCount=0,emitting=!1,listeners=new Set,settling,record2=(sink,phase,error)=>{if(failureCount++,failures.length>=MAX_FAILURES)return;let code=errorCode(error);failures.push(code===void 0?{sink,phase}:{sink,phase,code})};function deliver(state,index,event2){if(state.dropped)return;if(state.
|
|
@@ -959,7 +960,7 @@ state.pending=first,done(first))}async function runSettle(){if(await Promise.all
|
|
|
959
960
|
!0;try{let event2;try{event2=deepFreeze(parseFlowEventV1({schema:"humain-flow-event",schemaVersion:1,eventId:`${idPrefix}.${seq}`,runId,seq,ts:new Date(now()).toISOString(),profile,causes:input.causes??[],kind:input.kind,payload:input.payload}))}catch{throw new Error(INVALID_EVENT)}seq++;let snapshot=[...listeners];for(let[index,state]of states.entries())deliver(state,index,event2);for(let listener of snapshot)try{let result=listener(event2);result&&result.catch(()=>{})}catch{}return event2}finally{
|
|
960
961
|
emitting=!1}},subscribe(listener){let entry=event2=>listener(event2);return listeners.add(entry),()=>{listeners.delete(entry)}},settle(){if(settling)return settling;let current2=runSettle().finally(()=>{settling=void 0});return settling=current2,current2}}}var ID_RE2=/^[a-z0-9][a-z0-9_.:-]{0,127}$/,NEWLINE=10,CR=13,NOFOLLOW=constants5.O_NOFOLLOW??0,POSIX=process.platform!=="win32",sha2563=data=>createHash10("sha256").update(data).digest("hex");function parseJson(line){try{return{json:JSON.parse(line.toString("utf8"))}}catch{return}}function validateLine(json,runId){try{let event2=parseFlowEventV1(json);return event2.runId===runId?event2:void 0}catch{return}}var LOCK_RE=/^(\d+) ([a-f0-9]{32})$/,BUSY="flow ledger busy";function isAlive(pid){try{return process.
|
|
961
962
|
kill(pid,0),!0}catch(error){return error.code!=="ESRCH"}}function readLock(path){let fd;try{fd=openSync9(path,constants5.O_RDONLY|NOFOLLOW|constants5.O_NONBLOCK)}catch(error){if(error.code==="ENOENT")return;throw new Error(BUSY)}try{let stat=fstatSync9(fd),uid=process.getuid?.();if(!stat.isFile()||uid!==void 0&&stat.uid!==uid)throw new Error(BUSY);let buf=Buffer.alloc(128),text2=buf.toString("utf8",0,readSync9(fd,buf,0,128,0));if(!LOCK_RE.test(text2))throw new Error(BUSY);return text2}catch{throw new Error(
|
|
962
|
-
BUSY)}finally{closeSync9(fd)}}function acquireLock(lockPath){let nonce=
|
|
963
|
+
BUSY)}finally{closeSync9(fd)}}function acquireLock(lockPath){let nonce=randomBytes4(16).toString("hex"),mine=`${process.pid} ${nonce}`,tmp=`${lockPath}.${nonce}.tmp`,publish2=()=>{let fd=openSync9(tmp,constants5.O_CREAT|constants5.O_EXCL|constants5.O_WRONLY|NOFOLLOW,384);try{try{writeSync2(fd,mine)}finally{closeSync9(fd)}return linkSync3(tmp,lockPath),!0}catch(error){if(error.code==="EEXIST")return!1;throw error}finally{try{rmSync5(tmp,{force:!0})}catch{}}},scanStale=()=>{let prefix=`${basename4(
|
|
963
964
|
lockPath)}.stale.`;for(let name of readdirSync4(dirname9(lockPath))){if(!name.startsWith(prefix))continue;let stalePath=join12(dirname9(lockPath),name),content2=readLock(stalePath);if(content2===void 0)continue;let pid=Number(content2.split(" ")[0]);if(pid===process.pid||isAlive(pid))throw new Error(BUSY);rmSync5(stalePath,{force:!0})}};if(scanStale(),publish2())return mine;scanStale();let held=readLock(lockPath);if(held===void 0){if(publish2())return mine;throw new Error(BUSY)}if(isAlive(Number(
|
|
964
965
|
held.split(" ")[0]))||held.startsWith(`${process.pid} `))throw new Error(BUSY);let moved=`${lockPath}.stale.${nonce}`;try{renameSync3(lockPath,moved)}catch(error){if(error.code==="ENOENT"&&publish2())return mine;throw new Error(BUSY)}let content;try{content=readLock(moved)}catch{content=void 0}if(content===held){if(unlinkSync4(moved),publish2())return mine;throw new Error(BUSY)}try{linkSync3(moved,lockPath)}catch{}throw rmSync5(moved,{force:!0}),new Error(BUSY)}function releaseLock(lockPath,mine){
|
|
965
966
|
try{readLock(lockPath)===mine&&unlinkSync4(lockPath)}catch{}}function openJsonlLedgerSink(opts){let{runsRoot,runId}=opts;if(!ID_RE2.test(runId))throw new Error("flow ledger runId invalid");let dir=join12(runsRoot,runId),path=join12(dir,"events.jsonl"),lockPath=`${path}.lock`,uid=process.getuid?.();mkdirSync4(dir,{recursive:!0,mode:448});let dirStat=lstatSync8(dir);if(!dirStat.isDirectory()||uid!==void 0&&dirStat.uid!==uid)throw new Error("flow ledger dir invalid");POSIX&&dirStat.mode&63&&chmodSync2(
|
|
@@ -970,7 +971,7 @@ handleOnOpen,offset);break}if(!event2||seen.has(event2.eventId)||event2.seq<=las
|
|
|
970
971
|
ow ledger runId mismatch");let text2=JSON.stringify(snapshot),digest=sha2563(text2),known=seen.get(snapshot.eventId);if(known!==void 0){if(known===digest)return;throw new Error("flow ledger conflict")}if(snapshot.seq<=lastSeq)throw new Error("flow ledger seq not increasing");let line=Buffer.from(`${text2}
|
|
971
972
|
`,"utf8");try{let written=0;for(;written<line.length;)written+=writeSync2(target,line,written)}catch{throw failed=!0,new Error("flow ledger failed")}seen.set(snapshot.eventId,digest),lastSeq=snapshot.seq},async flush(){fsyncSync4(openFd())},flushSync(){fsyncSync4(openFd())},close(){if(handle===void 0)return;let target=handle;handle=void 0;try{fsyncSync4(target)}finally{try{closeSync9(target)}finally{releaseLock(lockPath,lockContent)}}}}}var ID=new RegExp(FLOW_ID_PATTERN),LINE_BREAK=/[\r\n]/,DIGEST=new RegExp(FLOW_DIGEST_PATTERN);function isRecord4(value){return typeof value=="object"&&value!==null}function validId(value){return typeof value=="string"&&!LINE_BREAK.test(value)&&ID.test(value)}function identityFromRawFile(file){if(file===void 0)return{};try{let read=readRegularBounded(file,MAX_ADMISSION_FILE_BYTES);if(!read.ok)return{};let raw=JSON.parse(read.bytes.toString("utf8"));if(!isRecord4(raw))return{};let profile=isRecord4(
|
|
972
973
|
raw.profile)?raw.profile:{};return{...validId(raw.runId)?{runId:raw.runId}:{},profile:{...validId(profile.id)?{id:profile.id}:{},...typeof profile.version=="number"&&Number.isSafeInteger(profile.version)&&profile.version>=1?{version:profile.version}:{},...typeof profile.digest=="string"&&!LINE_BREAK.test(profile.digest)&&DIGEST.test(profile.digest)?{digest:profile.digest}:{}}}}catch{return{}}}function refusalIdentity(source){if(source.admission)return source.admission;let raw=identityFromRawFile(
|
|
973
|
-
source.admissionFile);return{runId:raw.runId??`flow-refused-${
|
|
974
|
+
source.admissionFile);return{runId:raw.runId??`flow-refused-${randomBytes5(8).toString("hex")}`,profile:{id:raw.profile?.id??"unknown",version:raw.profile?.version??1,digest:raw.profile?.digest??flowSha256Hasher.sha256Hex("unknown")}}}function markHeadlessFailure(mode){(mode==="print"||mode==="json")&&(process.exitCode=1)}async function emitRefusalSettled(runsRoot,writeFrame,identity3,failureClass){let event2;try{let id2=identity3();event2=parseFlowEventV1({schema:"humain-flow-event",schemaVersion:1,
|
|
974
975
|
eventId:`${id2.runId.slice(0,120)}.refused`,runId:id2.runId,seq:1,ts:new Date().toISOString(),profile:id2.profile,causes:[],kind:"run_settled",payload:{outcome:"failed",failureClass,settledCleanly:!0,retryOffer:["direct"],totals:{}}})}catch{return}try{let dir=join13(runsRoot,event2.runId);mkdirSync5(dir,{recursive:!0,mode:448});let st=lstatSync9(dir);if(st.isSymbolicLink()||!st.isDirectory())throw new Error("run dir is not a real directory");closeSync10(openSync10(join13(dir,"events.jsonl"),constants6.
|
|
975
976
|
O_WRONLY|constants6.O_CREAT|constants6.O_EXCL|(constants6.O_NOFOLLOW??0),384));let sink=openJsonlLedgerSink({runsRoot,runId:event2.runId});try{sink.lastSeq===0&&sink.write(event2)}finally{sink.close()}}catch{}if(writeFrame)try{await writeFrame({type:"flow_event",event:event2})}catch{}}function safeUi(fn){try{fn()}catch{}}var text=(value,max=512)=>redactCredentials(value).replace(/[\x00-\x1f\x7f-\x9f]/g," ").slice(0,max),errorText=error=>text(error instanceof Error?error.message:"Recovery evidence unavailable"),missing=error=>error?.code==="ENOENT";function inspectLineage(plan,scanner=scanLineage){try{return scanner(recoveryLineageQuery(plan.snapshot))}catch{return{state:"unknown",pids:[],reasons:["Lineage inspection failed"]}}}function lineageBlockers(scan){return scan.state==="absent"?[]:[DESCENDANT_EVIDENCE_REASON,
|
|
976
977
|
...scan.reasons]}async function defaultRecoveryPreview(stateRoot,cwd,runId,deps={}){if(runId!==void 0&&!isValidRunId(runId))throw new Error("Invalid run id");let runs=join14(stateRoot,"runs");try{for(let path of[stateRoot,runs])if(!lstatSync10(path).isDirectory())throw new Error("Recovery storage must be a directory, not a symlink")}catch(error){if(missing(error))return[];throw error}let ids=runId!==void 0?[runId]:readdirSync5(runs,{withFileTypes:!0}).filter(entry=>entry.isDirectory()&&isValidRunId(
|
|
@@ -1653,36 +1654,37 @@ null:startObservation?startObservation.snapshot:runTreeSnapshot(),manifestBefore
|
|
|
1653
1654
|
!carry&&(savedLevel==="direct"||savedLevel==="checked")?savedLevel:(workflowMode.mode==="enforce"||sizeLevel!==void 0)&&!carry&&workflow2&&workflowPolicy&&!workflowPolicy.excluded_task_classes.includes(effectiveTaskClass)&&(workflow2.level==="direct"||workflow2.level==="checked")?workflow2.level:null,smallRun=admissionSmall&&flatLevel!==null,ceiling=Math.min(deps.recovery?.snapshot.retryCeiling??1/0,parsed.maxRetriesExplicit?parsed.maxRetries:1/0),explicitCeiling=Number.isFinite(ceiling)?ceiling:
|
|
1654
1655
|
void 0,exactRepairRoundsKnown=!deps.recovery||deps.recovery.snapshot.repairRounds!==void 0,repairRounds=carry?.priorFixRounds??deps.recovery?.snapshot.repairRounds??0,repairStates=new Map(Object.entries(carry?.repairStates??{})),repairTarget=logicalTaskIdFor(flatLevel?`${runId}-impl`:`${runId}-lead-0`);carry?.repairStates?.[`${runId}-impl`]&&repairStates.set(repairTarget,carry.repairStates[`${runId}-impl`]);let repairStopReason,repairVerificationOnlyReason,escalationSteps=0,repairSuiteSalt=carry?.
|
|
1655
1656
|
repairSuiteSalt??flatLevel??"run",repairCheckCommands=evidence=>evidence?.checks.flatMap((check2,index)=>{let command=deterministicChecks[index];return check2.status==="fail"&&command?[redactPaths(redactCredentials(`${JSON.stringify(redactCheckArgv(command.argv,deps.env))} (cwd ${JSON.stringify(resolve7(evidenceRoot,command.cwd))})`,deps.env))]:[]})??[],checkLabels=(evidence,pick2)=>evidence.checks.flatMap((check2,index)=>pick2(check2)?[deterministicChecks[index]?.name??"deterministic check"]:[]),
|
|
1656
|
-
checkScope=[...new Set(deterministicChecks.map(check2=>check2.cwd))],flatCheckResults=[],ledCheckResults=[],preexistingChecks=[],lastRawCheckResults=[],withBaseline=results=>{lastRawCheckResults=results;let
|
|
1657
|
-
|
|
1658
|
-
|
|
1659
|
-
|
|
1660
|
-
|
|
1661
|
-
state.
|
|
1662
|
-
|
|
1663
|
-
|
|
1664
|
-
|
|
1665
|
-
|
|
1666
|
-
|
|
1667
|
-
|
|
1668
|
-
|
|
1669
|
-
|
|
1670
|
-
|
|
1671
|
-
|
|
1672
|
-
|
|
1673
|
-
cwd
|
|
1674
|
-
|
|
1675
|
-
|
|
1676
|
-
|
|
1677
|
-
|
|
1678
|
-
|
|
1679
|
-
|
|
1680
|
-
|
|
1681
|
-
|
|
1682
|
-
|
|
1683
|
-
|
|
1684
|
-
|
|
1685
|
-
{...
|
|
1657
|
+
checkScope=[...new Set(deterministicChecks.map(check2=>check2.cwd))],flatCheckResults=[],ledCheckResults=[],preexistingChecks=[],lastRawCheckResults=[],withBaseline=results=>{lastRawCheckResults=results;let{preexistingIndexes,diagnostics}=compareBaselineChecks(baselineCheckResults,results,evidenceRoot),indexes=new Set(preexistingIndexes),verdict=results.every((result,index)=>result.status==="pass"||indexes.has(index))?"pass":results.some((result,index)=>result.status==="fail"&&!indexes.has(index))?
|
|
1658
|
+
"fail":"blocked";if(results.some(result=>result.status==="fail"))for(let[reason,count3]of Object.entries({...diagnostics.reasonCounts,baseline_diagnostic_count:diagnostics.baselineDiagnosticCount,current_diagnostic_count:diagnostics.currentDiagnosticCount,new_diagnostic_count:diagnostics.newDiagnosticCount}))session.flowTelemetry?.emit({kind:"verdict",payload:{stage:"check",taskId:telemetryTaskId(`${deps.admission?.runId??runId}-baseline-comparison`),checkId:`baseline_comparison:${reason}`,verdict,
|
|
1659
|
+
findingsCount:count3}});return preexistingChecks=results.filter((_,i)=>indexes.has(i)).map(r=>r.name),results.map((r,i)=>indexes.has(i)?{...r,status:"pass",preexistingFailure:!0}:r)},baselineFailing=()=>(baselineCheckResults??[]).filter(r=>r.status==="fail").map(r=>r.name),captureFlatChecks=async(...args2)=>(flatCheckResults=withBaseline(await(deps.runChecks??runChecks)(...args2)),flatCheckResults),deterministicEvidence=async()=>{if(!deterministicChecks.length)return;session.cancellation.throwIfCancelled();
|
|
1660
|
+
let pre=candidateTreeIdentityResult(evidenceRoot);if(!pre.ok)return startedInGit?buildRepairEvidence({checks:deterministicChecks,results:[],repoRoot:evidenceRoot,scope:checkScope,suiteSalt:repairSuiteSalt,before:null,after:null}):void 0;let results=withBaseline(await(deps.runChecks??runChecks)(deterministicChecks,evidenceRoot,checkTimeoutMs,session.cancellation));ledCheckResults=results,session.cancellation.throwIfCancelled();let post=candidateTreeIdentityResult(evidenceRoot);return buildRepairEvidence(
|
|
1661
|
+
{checks:deterministicChecks,results,repoRoot:evidenceRoot,scope:checkScope,suiteSalt:repairSuiteSalt,before:pre.ok?pre.identity:null,after:post.ok?post.identity:null})},takeSizeEscalation=(from,to)=>{let flowSize={small:"small",standard:"medium",large:"large"},fromSize=from===void 0?void 0:leadSizeOf(from),toSize=to===void 0?void 0:leadSizeOf(to);fromSize&&toSize&&fromSize!==toSize&&deps.escalation.escalate({from:flowSize[fromSize],to:flowSize[toSize],reasonClass:"size_underestimated"})},repairDecision=(taskId,evidence,rounds=repairRounds)=>{
|
|
1662
|
+
let id2=logicalTaskIdFor(taskId),state=repairStates.get(id2)??{nonProgressRounds:0,escalated:!1,recoveryPending:!1,seenFailureSets:[]},decision=decideRepair(state,evidence,{repairRounds:rounds,explicitMaxRetries:explicitCeiling,nonProgressLimit:METHOD.rules.progress_repair.non_progress_rounds,postEscalationLimit:METHOD.rules.progress_repair.post_escalation_rounds});repairStates.set(id2,decision.state);let ids=value=>new Set(value?.checks.filter(c=>c.status==="fail").flatMap(c=>c.diagnosticIds.map(
|
|
1663
|
+
d=>`${c.key}:${d}`))??[]),comparable=evidence&&state.previous&&evidence.integrityVerified&&state.previous.integrityVerified&&evidence.suiteKey===state.previous.suiteKey&&evidence.candidateRoot===state.previous.candidateRoot&&evidence.checks.length===state.previous.checks.length&&evidence.checks.every(c=>c.complete&&c.comparable&&state.previous.checks.some(previous2=>previous2.key===c.key))&&state.previous.checks.every(c=>c.complete&&c.comparable),previous=comparable?ids(state.previous):new Set,current2=comparable?
|
|
1664
|
+
ids(evidence):new Set;return deps.recordEvent("repair_decision",{run_id:runId,logical_task_id:id2,round:repairRounds,action:decision.action,reason:decision.reason,resolved_diagnostics:[...previous].filter(d=>!current2.has(d)).length,new_diagnostics:[...current2].filter(d=>!previous.has(d)).length,escalated:decision.state.escalated,approach_change:decision.action==="escalate",cumulative_cost_usd:session.totalCost(),elapsed_ms:session.terminalTiming().elapsed_ms,stop_reason:decision.action==="stop"?
|
|
1665
|
+
decision.reason:null}),decision.action==="stop"&&(repairStopReason=decision.reason==="unverified"?"unverified evidence":decision.reason==="candidate integrity not verified"?"unsafe scope: candidate integrity not verified":decision.reason),decision},completesStaleReviewRow=(history,verification)=>flatLevel!==null&&verification.evidenceStatus==="unverified_checks_unavailable"&&verification.repairEvidence?.integrityVerified===!0&&verification.repairEvidence.checks.length===0&&verification.repairEvidence.
|
|
1666
|
+
configurationCurrent?.()!==!1&&(history.previous?.checks??[]).every(c=>c.key==="review"),toolEvidenceCache=new Map,resolveClaimScope=(changed,results,reportOnly=!1)=>{let listing=(deps.worktreeListing??gitWorktreeListing)(cwd);if(!listing)return{kind:"blocked",reason:"git worktree listing unavailable at verification time",reasonKind:"observation_unavailable"};let resolveClaim=claim=>physicalPath(claim.startsWith("/")?claim:`${runStartRoot??repoRoot}/${claim}`,{realpath:REAL_LIVE_TREE_SEAMS.realpath,
|
|
1667
|
+
exists:lstatExists}),evidence=results.map(r=>leadToolEvidence(session,r.taskId,toolEvidenceCache,cwd));if(evidence.some(e=>e.unavailable))return{kind:"blocked",reason:"child tool-event log unreadable or has an unparsable/oversize tool event; cannot rule out writes outside the candidate",reasonKind:"observation_unavailable"};if(changed.length===0&&evidence.some((e,i)=>e.missing&&(results[i].usage?.tool_calls??0)>0))return{kind:"blocked",reason:"child tool-event log missing for a dispatch that ran\
|
|
1668
|
+
tools; cannot rule out writes outside the candidate",reasonKind:"observation_unavailable"};if(evidence.some(e=>e.mutatingCdTargets.includes(UNRESOLVABLE_CD_TARGET)))return{kind:"blocked",reason:"cannot establish the directory of a mutating shell command (unresolvable cd/pushd/popd/env -C/git -C); cannot rule out writes outside the candidate",reasonKind:"observation_unavailable"};let root=runStartRoot??repoRoot,nested=listing.allRoots.filter(n=>n!==root&&isPathWithin(root,n)),toolPaths=new Set;for(let e of evidence){
|
|
1669
|
+
for(let p of e.writePaths){let resolved3=resolveToolWritePath(p,cwd);resolved3!==null&&toolPaths.add(resolved3)}for(let t of e.mutatingCdTargets)toolPaths.add(resolve7(cwd,t));for(let p of e.workerReportedPaths)toolPaths.add(resolveToolWritePath(p,cwd)??p)}let outsideTool=[...toolPaths].filter(p=>{let abs=resolveClaim(p);return abs===null||!isPathWithin(root,abs)||nested.some(n=>isPathWithin(n,abs))}),claims=[...candidateOwnedFilesForLiveQa(results),...outsideTool];if(listing.overflow&&claims.length>
|
|
1670
|
+
0)return{kind:"blocked",reason:"worktree listing truncated; cannot attribute claimed paths to the candidate",reasonKind:"observation_unavailable"};let operationalRoot=resolveClaim(dirname12(session.file("run.log")));return resolveCandidateScope({root:runStartRoot??repoRoot,changed,claims,reportOnly,resolveClaim,exists:lstatExists,operationalRoots:operationalRoot===null?[]:[operationalRoot],nestedRoots:listing.allRoots,scratchRoots:(()=>{try{return[realpathSync8(tmpdir4())]}catch{return[]}})(),insideGitTree:hasGitEntryAbove})},
|
|
1671
|
+
checkRows=new Map,latestExternalChecks=[],hierarchyDeps={recoveryPlan:deps.recovery,dispatch:tasks=>{let traced=tasks.map(task=>carry&&isLeadCapability(task.capability)&&task.trace&&!task.trace.classification?{...task,trace:recoveryTrace(task.trace,carry.priorClaimResults?.at(-1),"workflow_level_escalated","escalate")}:task);for(let task of traced)task.trace?.logicalTaskId&&repairBudget.inherit(task.trace.logicalTaskId,task.taskId);return deps.dispatchParallel(cwd,runId,traced,adapter,ctx,claimed)},
|
|
1672
|
+
captureDispatchCost:deps.captureDispatchCost,maxLeads:deps.maxLeads,evidenceMaxChars:deps.reconEvidenceMaxChars,repoRoot,providedContext:deps.providedContext,approvedPlan:deps.approvedInputs?.some(input=>input.kind==="plan"||input.kind==="sketch")??!1,currentCandidateSha:()=>runTreeSnapshot()?.size===0?gitHead(cwd):null,inWaveRecovery:explicitCeiling!==0&&!readOnly,fileOwnershipMode:efficiency.controls.file_ownership.mode,recordEvent:deps.recordEvent,externalScopeVerification:(taskId,stage)=>{let historyId=`${logicalTaskIdFor(
|
|
1673
|
+
taskId)}:external`;if(stage==="recovered"){let state=repairStates.get(historyId);state&&latestExternalChecks.every(check2=>check2.outcome==="success")&&repairStates.set(historyId,{...state,recoveryPending:!1})}else repairDecision(historyId,void 0)},writeCheckDiagnostic:(_name,text2)=>writeCheckFailureDiagnostic(session,text2,deps.env),waitForChecks:async checks=>(latestExternalChecks=await waitForPendingChecks(checks,{cwd,cancellation:session.cancellation,...deps.ciWait,expectedSha:gitHead(cwd),
|
|
1674
|
+
expectedRepo:canonicalOrigin(cwd),setPendingChecks:rows=>{for(let row of rows)checkRows.set(`${row.provider}:${row.id}`,row);session.setPendingChecks?.([...checkRows.values()])},onOutcome:({check:check2,outcome,reason,jobId})=>{deps.recordEvent("external_check",{run_id:runId,provider:check2.provider,id:check2.id,outcome,reason,job_id:jobId}),deps.recordOutcome({run_id:runId,stage:"external_check",provider:check2.provider,check_id:check2.id,outcome,reason,job_id:jobId})}}),latestExternalChecks),observedChangedFiles:()=>{
|
|
1675
|
+
if(!dirtyBefore)return null;let after=runTreeSnapshot();if(!after)return null;let observed=changedFilesSinceRunStart(cwd,headBefore,dirtyBefore,[],after);return observed.historyUnavailable?null:observed.changed},markFiles:()=>({head:gitHead(cwd),dirty:runTreeSnapshot()}),filesChangedSince:(mark,claimedFiles)=>{let{head,dirty}=mark;return changedFilesSinceRunStart(cwd,head,dirty,claimedFiles,runTreeSnapshot()).changed}},ossPolicy=claimed.policy?.escalationTarget?claimed.policy:void 0,repairLimit=ossPolicy?.
|
|
1676
|
+
repair_attempts??1,recoveryBudget=Object.fromEntries(Object.values(deps.recovery?.snapshot.tasks??{}).filter(task=>task.stage==="implementation"||task.stage==="lead").map(task=>[task.logicalTaskId,task.repairCount])),repairBudget=new RepairBudget(carry?.repairBudget??recoveryBudget,repairLimit);ossPolicy&&carry&&repairBudget.inherit(`${runId}-impl`,`${runId}-lead-0`);let environmentBlocked=r=>["blocked","partial"].includes(parseLeadStatus(r.stdout))&&/(?:environment|runtime|dependencies?)\s*[:|].*(?:unavailable|blocked|fail)/i.
|
|
1677
|
+
test(r.stdout),substantiveResult=r=>r.stopReason!=="unknown_cost"&&r.stopReason!=="spend_cap"&&r.outcome!=="ineligible"&&r.outcome!=="timed_out"&&r.outcome!=="cancelled"&&!isTransientLeadFailure(r)&&!(r.exitCode!==0&&(isQuotaError(r.stderr)||isTransientProviderError(r.stderr))),recordRepair=(taskId,capability,model,reason,failedChecks2,codex)=>{codex||repairBudget.consume(taskId),deps.recordEvent(codex?"escalated_to_codex":"oss_repair_attempted",{run_id:runId,task_id:taskId,from_model:pickModel(
|
|
1678
|
+
capability,adapter,0),to_model:model,reason,repair_count:repairBudget.count(taskId),failed_checks:failedChecks2})},codexHandoff=(taskId,capability,files,reason,failedChecks2,attempt,heading,checkFeedback)=>buildHandoff({taskId,attempt,previousModel:pickModel(capability,adapter,0),failureClass:"failed_checks",reason,filesChanged:files,scan:{toolCalls:0,toolInFlight:!1,lastAssistantText:"",finishedWorkers:[],unfinishedWorkers:[],subagentCalls:[]},objective:parsed.goal,heading,constraints:deps.providedContext,
|
|
1679
|
+
diffSummary:files.join(", ")||"(no tracked diff observed)",checks:failedChecks2,attemptedRepair:`OSS repair attempts: ${repairBudget.count(taskId)}`,unresolvedIssue:reason,externalCheckFeedback:checkFeedback,redact:text2=>redactPaths(redactSecrets(text2,deps.env))}),inWaveCodex=new Set,exhaustedTasks=new Set,repairWaves=new Map;hierarchyDeps.dispatchRepair=async(original,attempted,reason,previous,_codexOnly,checkFeedback,waveKey)=>{if(environmentBlocked(previous))return repairStopReason="blocked\
|
|
1680
|
+
: precondition or stop condition",[];if(readOnly||explicitCeiling===0||!substantiveResult(previous)||repairStopReason)return[];if(startProbeFailure||observationUnsafe)return repairStopReason="unsafe scope",[];if(startedInGit){let observed=manifestBefore?.ok?observeRunTree(manifestBefore.manifest.entries.keys()):null,since=changedFilesSinceRunStart(cwd,headBefore,dirtyBefore,new Set,observed?.snapshot??null),changed=manifestBefore?.ok&&observed?.manifest.ok?[...new Set([...since.changed,...manifestChanges(
|
|
1681
|
+
manifestBefore.manifest,observed.manifest.manifest).changed])]:since.changed;if(!observed?.snapshot||!observed.manifest.ok||since.historyUnavailable||resolveClaimScope(changed,[...carry?.priorClaimResults??[],previous]).kind==="blocked")return repairStopReason="unsafe scope",[]}let repairEvidence=async()=>{let local=await deterministicEvidence();if(checkFeedback===void 0)return local;let externalKeys=latestExternalChecks.map(c=>`external:${c.workflowKey??""}`),uniqueExternalKeys=new Set(externalKeys),
|
|
1682
|
+
identity3=local?null:candidateTreeIdentityResult(evidenceRoot),base=local??buildRepairEvidence({checks:[],results:[],repoRoot:evidenceRoot,scope:checkScope,suiteSalt:repairSuiteSalt,before:identity3?.ok?identity3.identity:null,after:identity3?.ok?identity3.identity:null}),external=latestExternalChecks.map(({outcome,workflowKey,jobName,logTail,logComplete},index)=>{let key=externalKeys[index],complete=!!workflowKey&&uniqueExternalKeys.size===externalKeys.length&&(outcome==="success"||outcome==="f\
|
|
1683
|
+
ailure"&&logComplete===!0&&!!logTail?.trim()&&!!jobName),ids=outcome==="failure"?normalizeDiagnostics(logTail??"",evidenceRoot):[];return{key,status:outcome==="success"?"pass":outcome==="failure"?"fail":"unverified",complete,comparable:complete,diagnosticTail:"",diagnosticIds:outcome==="failure"?(ids.length?ids:[outcome]).map(line=>createHash15("sha256").update(`${workflowKey}:${jobName}:${line}`).digest("hex")).sort():[]}});return{...base,suiteKey:JSON.stringify([base.suiteKey,externalKeys.sort()]),
|
|
1684
|
+
checks:[...base.checks,...external]}},historyId=`${logicalTaskIdFor(original.taskId)}${checkFeedback===void 0?"":":external"}`,evidence=await repairEvidence(),decision=repairDecision(historyId,evidence,waveKey?repairWaves.get(waveKey)??repairRounds:repairRounds);if(decision.action==="recover_verification"){if(checkFeedback!==void 0&&latestExternalChecks.length){let previousBatch=latestExternalChecks,refreshed=await hierarchyDeps.waitForChecks(previousBatch.map(result2=>result2.check));for(let previous2 of previousBatch){
|
|
1685
|
+
let current2=refreshed.find(result2=>result2.check.provider===previous2.check.provider&&result2.check.id===previous2.check.id);current2&&Object.assign(previous2,current2)}}evidence=await repairEvidence(),decision=repairDecision(historyId,evidence)}if(decision.action!=="repair"&&decision.action!=="escalate")return[];(!waveKey||!repairWaves.has(waveKey))&&(waveKey&&repairWaves.set(waveKey,repairRounds),repairRounds++,exactRepairRoundsKnown&&(deps.recovery&&(deps.recovery.snapshot.repairRounds=repairRounds),
|
|
1686
|
+
session.recovery?.update(s=>{s.repairRounds=repairRounds})));let planned=planEscalation([reason],[{task:{...original,capability:previous.capability},result:previous}],plan.complexity,plan.risk,0,void 0,{...ossPolicy?{policy:"oss-first"}:{},escalationSteps:decision.action==="escalate"&&deps.escalation.available()?1:0,decisionReason:decision.reason,diagnostics:evidence?.checks.map(c=>c.diagnosticTail),checkCommands:repairCheckCommands(evidence)});takeSizeEscalation(previous.capability,planned[0]?.
|
|
1687
|
+
capability);let repairFeedback=planned[0]?.task.slice(original.task.length)??"";attempted={...attempted,capability:planned[0]?.capability??attempted.capability,task:`${attempted.task}
|
|
1686
1688
|
|
|
1687
1689
|
${repairFeedback}`};let codex=!!(ossPolicy&&(inWaveCodex.has(original.taskId)||repairBudget.count(original.taskId)>=repairLimit)),model=codex?ossPolicy.escalationTarget:pickModel(attempted.capability,adapter,0),task={...codex?{...original,policyEscalation:!0,task:`${original.task}
|
|
1688
1690
|
|
|
@@ -1945,7 +1947,7 @@ O_NOFOLLOW|constants10.O_NONBLOCK);try{let st=fstatSync14(rfd);st.isFile()&&st.n
|
|
|
1945
1947
|
!1}}seal(terminal){return terminal.then(ok2=>{ok2||(this.failed=!0)},()=>{this.failed=!0}),this.sealing?this.sealing:(this.accepting=!1,this.sealing=(async()=>{let timer,acknowledged;try{let writers=new Promise(done=>{this.drained=done,this.leases.size||done()});acknowledged=await Promise.race([Promise.all([terminal,writers]).then(([ok2])=>ok2),new Promise(done=>{timer=setTimeout(()=>done(!1),SEAL_DRAIN_TIMEOUT_MS)})])}finally{timer!==void 0&&clearTimeout(timer),this.drained=void 0}if(!acknowledged||
|
|
1946
1948
|
this.failed)return!1;let files={},buffer=Buffer.alloc(1024*1024);for(let[name,identity3]of this.files){let fd=openSync15(join21(this.dir,name),constants10.O_RDONLY|constants10.O_NOFOLLOW|constants10.O_NONBLOCK);try{let st=fstatSync14(fd);if(!st.isFile()||st.nlink!==1||st.dev!==identity3.dev||st.ino!==identity3.ino)throw new Error("diagnostic inode changed before seal");let finalSnapshot=this.childStderrFinal.get(name);if(finalSnapshot&&(st.size!==finalSnapshot.size||st.mtimeMs!==finalSnapshot.mtimeMs))
|
|
1947
1949
|
throw new Error(`child stderr file changed after the orchestrator's final write; seal vetoed: ${name}`);fsyncSync5(fd);let hash2=createHash16("sha256"),raw_bytes=0,n;for(;(n=readSync13(fd,buffer,0,buffer.length,null))>0;)hash2.update(buffer.subarray(0,n)),raw_bytes+=n;files[name]={sha256:hash2.digest("hex"),raw_bytes}}finally{closeSync15(fd)}}return publish(this.dir,SEAL_FILE,{...this.owner,sealed_at:new Date().toISOString(),files}),!0})().catch(error=>(console.warn(`[orchestrator] diagnostics n\
|
|
1948
|
-
ot sealed: ${String(error)}`),!1)).finally(()=>{owners2.delete(resolve9(this.dir))}),this.sealing)}};import{randomBytes as
|
|
1950
|
+
ot sealed: ${String(error)}`),!1)).finally(()=>{owners2.delete(resolve9(this.dir))}),this.sealing)}};import{randomBytes as randomBytes6}from"node:crypto";import{existsSync as existsSync9,mkdirSync as mkdirSync7,readFileSync as readFileSync10,renameSync as renameSync5,unlinkSync as unlinkSync6,writeFileSync as writeFileSync5}from"node:fs";import{dirname as dirname15}from"node:path";function writeProfilesFile(profilesPath,file){mkdirSync7(dirname15(profilesPath),{recursive:!0});let tmp=`${profilesPath}.${randomBytes6(8).toString("hex")}.tmp`;try{writeFileSync5(tmp,`${JSON.stringify(file,null,2)}
|
|
1949
1951
|
`,{mode:384,flag:"wx"}),renameSync5(tmp,profilesPath)}catch(err){try{unlinkSync6(tmp)}catch{}throw err}}function loadProfiles(opts){let{profilesPath,legacyAdapterPath,shippedProfilesPath:shippedProfilesPath2}=opts,notes=[];if(existsSync9(profilesPath))try{let{file,problems}=parseProfilesFile(JSON.parse(readFileSync10(profilesPath,"utf-8")));return existsSync9(legacyAdapterPath)&¬es.push(`${legacyAdapterPath} is ignored now that ${profilesPath} exists; delete it to silence this note.`),{file,present:!0,
|
|
1950
1952
|
problems,notes}}catch(err){return{file:emptyProfilesFile(),present:!0,problems:[`${profilesPath} could not be parsed: ${err.message}`],notes}}return notes.push(`${profilesPath} not found; using fallback bindings. Copy the shipped profiles from ${shippedProfilesPath2()} to create it.`),existsSync9(legacyAdapterPath)&¬es.push(`${legacyAdapterPath} is ignored; the shipped profiles replace it.`),{file:emptyProfilesFile(),present:!1,problems:[],notes}}import{spawnSync as spawnSync4}from"node:child_process";import{createHash as createHash19,randomUUID as randomUUID6}from"node:crypto";import{existsSync as existsSync11,mkdirSync as mkdirSync8,readdirSync as readdirSync8,readFileSync as readFileSync13,realpathSync as realpathSync10,rmSync as rmSync8,statSync as statSync8}from"node:fs";import{homedir as homedir3,tmpdir as tmpdir7}from"node:os";import{basename as basename9,dirname as dirname16,join as join24,relative as relative10,resolve as resolve10}from"node:path";var memory_exports={};__export(memory_exports,{Assign:()=>Assign,Clone:()=>Clone,Create:()=>Create,Discard:()=>Discard,Metrics:()=>Metrics,Update:()=>Update});var Metrics={assign:0,create:0,clone:0,discard:0,update:0};var settings_exports={};__export(settings_exports,{Get:()=>Get,Reset:()=>Reset,Set:()=>Set2});var guard_exports={};__export(guard_exports,{CodePointCount:()=>CodePointCount2,Counted:()=>Counted,Entries:()=>Entries,EntriesRegExp:()=>EntriesRegExp,Every:()=>Every,EveryAll:()=>EveryAll,GraphemeCount:()=>GraphemeCount2,HasPropertyKey:()=>HasPropertyKey,IsArray:()=>IsArray,IsBigInt:()=>IsBigInt,IsBoolean:()=>IsBoolean,IsClassInstance:()=>IsClassInstance,IsConstructor:()=>IsConstructor,IsDeepEqual:()=>IsDeepEqual,IsEqual:()=>IsEqual,IsFunction:()=>IsFunction,IsGreaterEqualThan:()=>IsGreaterEqualThan,
|
|
1951
1953
|
IsGreaterThan:()=>IsGreaterThan,IsInteger:()=>IsInteger,IsLessEqualThan:()=>IsLessEqualThan,IsLessThan:()=>IsLessThan,IsMaxLength:()=>IsMaxLength2,IsMinLength:()=>IsMinLength2,IsMultipleOf:()=>IsMultipleOf,IsNull:()=>IsNull,IsNumber:()=>IsNumber,IsObject:()=>IsObject,IsObjectNotArray:()=>IsObjectNotArray,IsString:()=>IsString,IsSymbol:()=>IsSymbol,IsUndefined:()=>IsUndefined,IsUnsafePropertyKey:()=>IsUnsafePropertyKey,IsValueLike:()=>IsValueLike,Keys:()=>Keys,ShiftLeft:()=>ShiftLeft,Some:()=>Some,
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { createRequire as __piCreateRequire } from "node:module"; const require = __piCreateRequire(import.meta.url);
|
|
2
|
-
import{dist_exports as dist_exports3}from"./chunk-
|
|
2
|
+
import{dist_exports as dist_exports3}from"./chunk-HDA2IGKA.js";import{compile_exports,dist_exports as dist_exports2,value_exports}from"./chunk-KA7K6ECX.js";import"./chunk-OX2IBCCA.js";import"./chunk-COF5P635.js";import"./chunk-NNKA2PAP.js";import"./chunk-TJG52LZB.js";import"./chunk-BVHXWQLD.js";import{all_exports,compat_exports}from"./chunk-IUKCPYKD.js";import{build_exports}from"./chunk-Z74ZYQPX.js";import{dist_exports}from"./chunk-UHLW4KJ7.js";
|
|
3
3
|
import"./chunk-XQRYOCHA.js";import"./chunk-DNGJMRJW.js";import"./chunk-36Q5UVQL.js";import"./chunk-UGXYG7HN.js";import"./chunk-QYCOHSI7.js";import"./chunk-H2FY3PEV.js";import"./chunk-KQM7ZGL6.js";import"./chunk-CIA6V3BP.js";import"./chunk-XQZG5HPT.js";import"./chunk-FACBDLFU.js";import"./chunk-4DXXZHY2.js";import"./chunk-YRCLNWFV.js";import"./chunk-MF2NEHP4.js";import"./chunk-FRUFMISJ.js";import"./chunk-YJ3NQWES.js";
|
|
4
4
|
import"./chunk-DBL35X7L.js";import"./chunk-MG5PX4KU.js";import"./chunk-LUL775V7.js";import"./chunk-RYC5BYVE.js";import"./chunk-VEYTRNQC.js";import"./chunk-JXWJOIH4.js";var oauth_exports={};var VIRTUAL_MODULES={typebox:build_exports,"typebox/compile":compile_exports,"typebox/value":value_exports,"@sinclair/typebox":build_exports,"@sinclair/typebox/compile":compile_exports,"@sinclair/typebox/value":value_exports,"@earendil-works/pi-agent-core":dist_exports2,"@earendil-works/pi-tui":dist_exports,"@earendil-works/pi-ai":compat_exports,"@earendil-works/pi-ai/compat":compat_exports,"@earendil-works/pi-ai/oauth":oauth_exports,"@earendil-works/pi-ai/providers/all":all_exports,"@earendil-w\
|
|
5
5
|
orks/pi-coding-agent":dist_exports3,"@mariozechner/pi-agent-core":dist_exports2,"@mariozechner/pi-tui":dist_exports,"@mariozechner/pi-ai":compat_exports,"@mariozechner/pi-ai/compat":compat_exports,"@mariozechner/pi-ai/oauth":oauth_exports,"@mariozechner/pi-ai/providers/all":all_exports,"@mariozechner/pi-coding-agent":dist_exports3};export{VIRTUAL_MODULES};
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
2
|
import { createRequire as __piCreateRequire } from "node:module"; const require = __piCreateRequire(import.meta.url);
|
|
3
|
-
import{configureHttpDispatcher,main,warnIfDeprecatedCommand}from"./chunks/chunk-
|
|
3
|
+
import{configureHttpDispatcher,main,warnIfDeprecatedCommand}from"./chunks/chunk-KA7K6ECX.js";import"./chunks/chunk-OX2IBCCA.js";import"./chunks/chunk-COF5P635.js";import"./chunks/chunk-NNKA2PAP.js";import"./chunks/chunk-TJG52LZB.js";import"./chunks/chunk-BVHXWQLD.js";import"./chunks/chunk-IUKCPYKD.js";import"./chunks/chunk-Z74ZYQPX.js";import"./chunks/chunk-UHLW4KJ7.js";import"./chunks/chunk-XQRYOCHA.js";import"./chunks/chunk-DNGJMRJW.js";import"./chunks/chunk-36Q5UVQL.js";import"./chunks/chunk-UGXYG7HN.js";
|
|
4
4
|
import"./chunks/chunk-QYCOHSI7.js";import"./chunks/chunk-H2FY3PEV.js";import"./chunks/chunk-KQM7ZGL6.js";import"./chunks/chunk-CIA6V3BP.js";import"./chunks/chunk-XQZG5HPT.js";import"./chunks/chunk-FACBDLFU.js";import"./chunks/chunk-4DXXZHY2.js";import{APP_COMMAND,ENV_PREFIX}from"./chunks/chunk-YRCLNWFV.js";import"./chunks/chunk-MF2NEHP4.js";import"./chunks/chunk-FRUFMISJ.js";import"./chunks/chunk-YJ3NQWES.js";import"./chunks/chunk-DBL35X7L.js";import"./chunks/chunk-MG5PX4KU.js";import"./chunks/chunk-LUL775V7.js";
|
|
5
5
|
import"./chunks/chunk-RYC5BYVE.js";import"./chunks/chunk-VEYTRNQC.js";import"./chunks/chunk-JXWJOIH4.js";function setupCli(){process.title=APP_COMMAND,process.env.PI_CODING_AGENT="true",process.env[`${ENV_PREFIX}_CODING_AGENT`]="true",process.env.AI_AGENT="pi",process.emitWarning=(()=>{}),configureHttpDispatcher()}setupCli();warnIfDeprecatedCommand(process.argv.slice(2));main(process.argv.slice(2));
|
package/dist/bundle/index.js
CHANGED
|
@@ -1,11 +1,11 @@
|
|
|
1
1
|
import { createRequire as __piCreateRequire } from "node:module"; const require = __piCreateRequire(import.meta.url);
|
|
2
|
-
import{ShowImagesSelectorComponent,ThemeSelectorComponent}from"./chunks/chunk-
|
|
2
|
+
import{ShowImagesSelectorComponent,ThemeSelectorComponent}from"./chunks/chunk-HDA2IGKA.js";import{ACCOUNT_RETURN_COOLDOWN_MS,ACCOUNT_RETURN_MAX_COOLDOWN_MS,AgentExecInputError,AgentSession,AgentSessionRuntime,AssistantMessageComponent,BashExecutionComponent,BorderedLoader,BranchSummaryMessageComponent,CompactionSummaryMessageComponent,CredentialSynchronizationError,CustomEditor,CustomMessageComponent,DEFAULT_COMPACTION_SETTINGS,DefaultPackageManager,DefaultResourceLoader,DynamicBorder,ExtensionEditorComponent,
|
|
3
3
|
ExtensionInputComponent,ExtensionRunner,ExtensionSelectorComponent,FLOW_ACCOUNT_PERSISTENCE_NOTICE,FLOW_SETUP_TERMINAL_ONLY,FLOW_SUBCOMMANDS,FooterComponent,InteractiveMode,LoginDialogComponent,ModelRegistry,ModelRuntime,ModelSelectorComponent,OAuthAccountPool,OAuthSelectorComponent,RpcClient,SessionSelectorComponent,SettingsManager,SettingsSelectorComponent,SkillInvocationMessageComponent,ThinkingSelectorComponent,ToolExecutionComponent,TreeSelectorComponent,UserMessageComponent,UserMessageSelectorComponent,
|
|
4
4
|
VIRTUAL_MODEL_STATE_ENTRY,assessNodeFallback,calculateContextTokens,collectEntriesForBranchSummary,compact,completeFlowArguments,convertToPng,copyToClipboard,createAgentSession,createAgentSessionFromServices,createAgentSessionRuntime,createAgentSessionServices,createBashTool,createBashToolDefinition,createCodemodeExtension,createCodingTools,createEditTool,createEditToolDefinition,createEventBus,createExtensionRuntime,createFindTool,createFindToolDefinition,createGrepTool,createGrepToolDefinition,
|
|
5
5
|
createLocalBashOperations,createLocalPowerShellOperations,createLsTool,createLsToolDefinition,createMcpExtension,createPiAgentExecutionHost,createPowerShellTool,createPowerShellToolDefinition,createReadOnlyTools,createReadTool,createReadToolDefinition,createSubagentTool,createSyntheticSourceInfo,createToolSearchExtension,createWriteTool,createWriteToolDefinition,defineTool,detectSupportedImageMimeTypeFromFile,discoverAgents,discoverAndLoadExtensions,estimateTokens,executeHumainAgentRequest,findCutPoint,
|
|
6
6
|
findTurnStartIndex,flowBuildUnavailable,formatSkillsForPrompt,generateBranchSummary,generateDiffString,generateSummary,generateSummaryWithUsage,generateUnifiedPatch,getFlowAccountsHost,getFlowChildLaunchHost,getFlowControlHost,getFlowTraceProducer,getLastAssistantUsage,isBashToolResult,isEditToolResult,isFindToolResult,isGrepToolResult,isLsToolResult,isPowerShellToolResult,isReadToolResult,isToolCallEventType,isWriteToolResult,loadProjectContextFiles,loadSkills,loadSkillsFromDir,main,parseArgs,parseFlowCommand,
|
|
7
|
-
parseFrontmatter,parseSkillBlock,prepareBranchEntries,prepareChildLaunch,renderDiff,renderFlowHelp,renderTaskWithContext,resolveCliModel,resolveModelScopeWithDiagnostics,runAgentExecMode,runPrintMode,runRpcMode,serializeConversation,shouldCompact,stripFrontmatter,withFileMutationQueue,wrapRegisteredTool,wrapRegisteredTools}from"./chunks/chunk-
|
|
8
|
-
hasTrustRequiringProjectResources}from"./chunks/chunk-TJG52LZB.js";import{CURRENT_SESSION_VERSION,SessionManager,buildContextEntries,buildSessionContext,buildSessionProjection,convertToLlm,formatDimensionNote,getLatestCompactionEntry,migrateSessionEntries,parseSessionEntries,resizeImage,sessionEntryToContextMessages}from"./chunks/chunk-BVHXWQLD.js";import"./chunks/chunk-
|
|
7
|
+
parseFrontmatter,parseSkillBlock,prepareBranchEntries,prepareChildLaunch,renderDiff,renderFlowHelp,renderTaskWithContext,resolveCliModel,resolveModelScopeWithDiagnostics,runAgentExecMode,runPrintMode,runRpcMode,serializeConversation,shouldCompact,stripFrontmatter,withFileMutationQueue,wrapRegisteredTool,wrapRegisteredTools}from"./chunks/chunk-KA7K6ECX.js";import"./chunks/chunk-OX2IBCCA.js";import"./chunks/chunk-COF5P635.js";import{ArminComponent}from"./chunks/chunk-NNKA2PAP.js";import{ProjectTrustStore,
|
|
8
|
+
hasTrustRequiringProjectResources}from"./chunks/chunk-TJG52LZB.js";import{CURRENT_SESSION_VERSION,SessionManager,buildContextEntries,buildSessionContext,buildSessionProjection,convertToLlm,formatDimensionNote,getLatestCompactionEntry,migrateSessionEntries,parseSessionEntries,resizeImage,sessionEntryToContextMessages}from"./chunks/chunk-BVHXWQLD.js";import"./chunks/chunk-IUKCPYKD.js";import{DEFAULT_MAX_BYTES,DEFAULT_MAX_LINES,formatSize,truncateHead,truncateLine,truncateTail,truncateToVisualLines}from"./chunks/chunk-Z74ZYQPX.js";
|
|
9
9
|
import{Theme,getLanguageFromPath,getMarkdownTheme,getSelectListTheme,getSettingsListTheme,highlightCode,initTheme,keyHint,keyText,rawKeyHint}from"./chunks/chunk-UHLW4KJ7.js";import"./chunks/chunk-XQRYOCHA.js";import"./chunks/chunk-DNGJMRJW.js";import{readStoredCredential}from"./chunks/chunk-36Q5UVQL.js";import{getPowerShellConfig,getShellConfig}from"./chunks/chunk-UGXYG7HN.js";import"./chunks/chunk-QYCOHSI7.js";import"./chunks/chunk-H2FY3PEV.js";import"./chunks/chunk-KQM7ZGL6.js";import"./chunks/chunk-CIA6V3BP.js";
|
|
10
10
|
import"./chunks/chunk-XQZG5HPT.js";import"./chunks/chunk-FACBDLFU.js";import{HUMAIN_AGENT_EXECUTION_FAILURE_CODES,HUMAIN_AGENT_EXECUTION_SCHEMA_VERSION,HumainAgentArtifactSchema,HumainAgentExecutionClaimSchema,HumainAgentExecutionControlsSchema,HumainAgentExecutionOutcomeSchema,HumainAgentExecutionRequestSchema,HumainAgentExecutionResponseSchema,HumainAgentRouteRefSchema,HumainAgentUsageSchema,parseHumainAgentExecutionRequest,parseHumainAgentExecutionResponse}from"./chunks/chunk-4DXXZHY2.js";import{
|
|
11
11
|
CONFIG_DIR_NAME,UPSTREAM_PI_VERSION,VERSION,getAgentDir,getDocsPath,getExamplesPath,getPackageDir,getReadmePath}from"./chunks/chunk-YRCLNWFV.js";import"./chunks/chunk-MF2NEHP4.js";import"./chunks/chunk-FRUFMISJ.js";import"./chunks/chunk-YJ3NQWES.js";import"./chunks/chunk-DBL35X7L.js";import"./chunks/chunk-MG5PX4KU.js";import"./chunks/chunk-LUL775V7.js";import"./chunks/chunk-RYC5BYVE.js";import"./chunks/chunk-VEYTRNQC.js";import"./chunks/chunk-JXWJOIH4.js";export{ACCOUNT_RETURN_COOLDOWN_MS,ACCOUNT_RETURN_MAX_COOLDOWN_MS,AgentExecInputError,AgentSession,AgentSessionRuntime,ArminComponent,AssistantMessageComponent,BashExecutionComponent,BorderedLoader,BranchSummaryMessageComponent,CONFIG_DIR_NAME,CURRENT_SESSION_VERSION,CompactionSummaryMessageComponent,CredentialSynchronizationError,CustomEditor,CustomMessageComponent,DEFAULT_COMPACTION_SETTINGS,DEFAULT_MAX_BYTES,DEFAULT_MAX_LINES,DefaultPackageManager,DefaultResourceLoader,DynamicBorder,ExtensionEditorComponent,
|
package/dist/bundle/rpc-entry.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
2
|
import { createRequire as __piCreateRequire } from "node:module"; const require = __piCreateRequire(import.meta.url);
|
|
3
|
-
import{configureHttpDispatcher,main}from"./chunks/chunk-
|
|
3
|
+
import{configureHttpDispatcher,main}from"./chunks/chunk-KA7K6ECX.js";import"./chunks/chunk-OX2IBCCA.js";import"./chunks/chunk-COF5P635.js";import"./chunks/chunk-NNKA2PAP.js";import"./chunks/chunk-TJG52LZB.js";import"./chunks/chunk-BVHXWQLD.js";import"./chunks/chunk-IUKCPYKD.js";import"./chunks/chunk-Z74ZYQPX.js";import"./chunks/chunk-UHLW4KJ7.js";import"./chunks/chunk-XQRYOCHA.js";import"./chunks/chunk-DNGJMRJW.js";import"./chunks/chunk-36Q5UVQL.js";import"./chunks/chunk-UGXYG7HN.js";import"./chunks/chunk-QYCOHSI7.js";
|
|
4
4
|
import"./chunks/chunk-H2FY3PEV.js";import"./chunks/chunk-KQM7ZGL6.js";import"./chunks/chunk-CIA6V3BP.js";import"./chunks/chunk-XQZG5HPT.js";import"./chunks/chunk-FACBDLFU.js";import"./chunks/chunk-4DXXZHY2.js";import{APP_COMMAND}from"./chunks/chunk-YRCLNWFV.js";import"./chunks/chunk-MF2NEHP4.js";import"./chunks/chunk-FRUFMISJ.js";import"./chunks/chunk-YJ3NQWES.js";import"./chunks/chunk-DBL35X7L.js";import"./chunks/chunk-MG5PX4KU.js";import"./chunks/chunk-LUL775V7.js";import"./chunks/chunk-RYC5BYVE.js";import"./chunks/chunk-VEYTRNQC.js";
|
|
5
5
|
import"./chunks/chunk-JXWJOIH4.js";process.title=`${APP_COMMAND}-rpc`;process.env.PI_CODING_AGENT="true";process.env.AI_AGENT="pi";process.emitWarning=(()=>{});configureHttpDispatcher();main(["--mode","rpc",...process.argv.slice(2)]);
|