@xenosystem/agent-sdk 0.10.41 → 0.10.43
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/artifacts/index.cjs +1 -1
- package/dist/artifacts/index.js +1 -1
- package/dist/automation/index.cjs +1 -1
- package/dist/automation/index.d.cts +2 -0
- package/dist/automation/index.d.ts +2 -0
- package/dist/automation/index.js +1 -1
- package/dist/control-plane/index.cjs +1 -1
- package/dist/control-plane/index.js +1 -1
- package/dist/electron/index.cjs +203 -293
- package/dist/electron/index.d.cts +13 -1
- package/dist/electron/index.d.ts +13 -1
- package/dist/electron/index.js +204 -294
- package/dist/electron/metafile-cjs.json +1 -1
- package/dist/electron/metafile-esm.json +1 -1
- package/dist/governance/index.cjs +22 -28
- package/dist/governance/index.d.cts +43 -17
- package/dist/governance/index.d.ts +43 -17
- package/dist/governance/index.js +21 -27
- package/dist/governance/metafile-cjs.json +1 -1
- package/dist/governance/metafile-esm.json +1 -1
- package/dist/index.cjs +408 -543
- package/dist/index.d.cts +72 -22
- package/dist/index.d.ts +72 -22
- package/dist/index.js +410 -545
- package/dist/mcp/index.d.cts +2 -0
- package/dist/mcp/index.d.ts +2 -0
- package/dist/metafile-cjs.json +1 -1
- package/dist/metafile-esm.json +1 -1
- package/dist/session/index.cjs +1 -1
- package/dist/session/index.js +1 -1
- package/dist/utils/index.cjs +22 -23
- package/dist/utils/index.d.cts +3 -3
- package/dist/utils/index.d.ts +3 -3
- package/dist/utils/index.js +18 -19
- package/dist/utils/metafile-cjs.json +1 -1
- package/dist/utils/metafile-esm.json +1 -1
- package/package.json +1 -1
|
@@ -203,11 +203,18 @@ interface CompletionGuardEvaluationContext {
|
|
|
203
203
|
}
|
|
204
204
|
type CompletionGuardDecision = {
|
|
205
205
|
allow: true;
|
|
206
|
+
final?: boolean;
|
|
206
207
|
} | {
|
|
207
208
|
allow: false;
|
|
208
209
|
guidance: string;
|
|
209
210
|
stop?: boolean;
|
|
211
|
+
blocking?: boolean;
|
|
212
|
+
toolPolicy?: CompletionGuardToolPolicy;
|
|
210
213
|
};
|
|
214
|
+
interface CompletionGuardToolPolicy {
|
|
215
|
+
mode: string;
|
|
216
|
+
[key: string]: unknown;
|
|
217
|
+
}
|
|
211
218
|
interface CompletionGuard {
|
|
212
219
|
name: string;
|
|
213
220
|
order?: number;
|
|
@@ -239,9 +246,9 @@ interface ValidationSignal {
|
|
|
239
246
|
clusters: FailureCluster[];
|
|
240
247
|
}
|
|
241
248
|
interface ContractLedgerSummary {
|
|
249
|
+
requiredOutputPaths: string[];
|
|
242
250
|
projectLike: boolean;
|
|
243
251
|
benchmarkMode: boolean;
|
|
244
|
-
requiredOutputPaths: string[];
|
|
245
252
|
requiredValidation: boolean;
|
|
246
253
|
}
|
|
247
254
|
interface ValidationLedgerSummary {
|
|
@@ -277,23 +284,33 @@ interface ExecutionGovernanceOptions {
|
|
|
277
284
|
taskPrompt?: string;
|
|
278
285
|
benchmarkMode?: boolean;
|
|
279
286
|
requiredOutputPaths?: string[];
|
|
287
|
+
cwd?: string;
|
|
288
|
+
}
|
|
289
|
+
interface MissingRequiredOutput {
|
|
290
|
+
path: string;
|
|
291
|
+
problem: "missing" | "empty" | "not_a_file";
|
|
280
292
|
}
|
|
293
|
+
declare function findMissingRequiredOutputs(paths: readonly string[], cwd?: string): MissingRequiredOutput[];
|
|
281
294
|
interface RecordToolResultInput {
|
|
282
295
|
toolName: string;
|
|
283
296
|
input: Record<string, unknown>;
|
|
284
297
|
result: ToolResult;
|
|
285
298
|
iteration: number;
|
|
286
299
|
}
|
|
287
|
-
declare function shouldEnableExecutionGovernance(options: ExecutionGovernanceOptions): boolean;
|
|
288
300
|
declare class ExecutionGovernance {
|
|
289
301
|
private readonly contract;
|
|
290
302
|
private readonly signals;
|
|
291
303
|
private readonly clusters;
|
|
292
304
|
private toolCalls;
|
|
293
305
|
private workspaceRevision;
|
|
306
|
+
private readonly ownTasks;
|
|
307
|
+
private nextOwnTaskId;
|
|
308
|
+
private uncheckedChangesAdvised;
|
|
294
309
|
private lastCompletionDecision;
|
|
295
310
|
private lastValidationIteration;
|
|
296
311
|
private lastEvaluatedIteration;
|
|
312
|
+
private readonly cwd;
|
|
313
|
+
private readonly taskPrompt;
|
|
297
314
|
constructor(options?: ExecutionGovernanceOptions);
|
|
298
315
|
recordToolResult(input: RecordToolResultInput): ValidationSignal[];
|
|
299
316
|
evaluateCompletion(args: {
|
|
@@ -337,6 +354,14 @@ interface InteractiveGovernanceDecision {
|
|
|
337
354
|
message: string;
|
|
338
355
|
blocking: boolean;
|
|
339
356
|
}
|
|
357
|
+
declare const MAX_HOST_WEB_SEARCHES_PER_TURN = 200;
|
|
358
|
+
declare const MAX_HOST_WEB_FETCHES_PER_TURN = 500;
|
|
359
|
+
interface WebResearchBudgetInput {
|
|
360
|
+
searches?: string | number;
|
|
361
|
+
fetches?: string | number;
|
|
362
|
+
calls?: string | number;
|
|
363
|
+
}
|
|
364
|
+
declare function parseWebResearchBudget(input: WebResearchBudgetInput): InteractiveTurnGovernanceOptions;
|
|
340
365
|
declare function isExplicitResearchPrompt(taskPrompt: string): boolean;
|
|
341
366
|
declare function isSimpleInformationalPrompt(taskPrompt: string): boolean;
|
|
342
367
|
declare function resolveInteractiveTurnMaxIterations(taskPrompt: string, configuredMaxIterations: number): number;
|
|
@@ -348,6 +373,7 @@ declare class InteractiveTurnGovernance {
|
|
|
348
373
|
private readonly maxLocalInspectionCalls;
|
|
349
374
|
private readonly simpleInformationalPrompt;
|
|
350
375
|
private readonly explicitResearchPrompt;
|
|
376
|
+
private readonly hostWebBudget;
|
|
351
377
|
private readonly searchQueries;
|
|
352
378
|
private readonly fetchedUrls;
|
|
353
379
|
private readonly localInspectionRecords;
|
|
@@ -380,52 +406,52 @@ declare class InteractiveTurnGovernance {
|
|
|
380
406
|
private findOverlappingTranscriptRead;
|
|
381
407
|
}
|
|
382
408
|
declare class InteractiveChatTurnGovernance {
|
|
409
|
+
private readonly options;
|
|
383
410
|
private active;
|
|
384
411
|
private activePrompt;
|
|
385
412
|
readonly promptSection: PromptSectionProvider;
|
|
386
413
|
readonly toolMiddleware: ToolMiddleware;
|
|
387
414
|
readonly completionGuard: CompletionGuard;
|
|
415
|
+
constructor(options?: InteractiveTurnGovernanceOptions);
|
|
388
416
|
beginTurn(taskPrompt: string): void;
|
|
389
417
|
endTurn(): void;
|
|
390
418
|
}
|
|
391
|
-
declare function
|
|
392
|
-
|
|
419
|
+
declare function isRemoteEvalCommand(command: string): boolean;
|
|
420
|
+
declare function createRemoteEvalGuard(): ToolMiddleware;
|
|
393
421
|
interface ProjectDomainProfile {
|
|
394
|
-
|
|
422
|
+
id: string;
|
|
395
423
|
label: string;
|
|
396
|
-
trigger: RegExp;
|
|
397
424
|
verifierRequirements: string[];
|
|
398
425
|
finalAuditItems: string[];
|
|
399
426
|
}
|
|
400
427
|
interface ProjectExecutionPhase {
|
|
401
|
-
|
|
402
|
-
|
|
428
|
+
id: string;
|
|
429
|
+
title: string;
|
|
403
430
|
objective: string;
|
|
404
431
|
}
|
|
405
432
|
interface ProjectExecutionProfile {
|
|
406
433
|
projectLike: boolean;
|
|
407
|
-
hiddenVerifierLikely: boolean;
|
|
408
|
-
requiredOutputs: string[];
|
|
409
|
-
referencedPaths: string[];
|
|
410
434
|
domains: ProjectDomainProfile[];
|
|
411
435
|
phases: ProjectExecutionPhase[];
|
|
412
436
|
verifierRequirements: string[];
|
|
413
437
|
finalAuditItems: string[];
|
|
414
438
|
}
|
|
415
|
-
declare function buildProjectExecutionProfile(prompt?: string): ProjectExecutionProfile;
|
|
416
|
-
declare function buildProjectExecutionGuidance(prompt?: string): string;
|
|
417
|
-
declare function buildProjectBudgetFinalizationGuidance(prompt?: string): string;
|
|
418
439
|
interface BenchBashMiddlewareOptions {
|
|
419
440
|
benchmarkMode?: boolean;
|
|
420
441
|
}
|
|
421
|
-
declare function
|
|
442
|
+
declare function buildContractLedgerGuidance(_userPrompt?: string): string;
|
|
443
|
+
declare function buildProjectExecutionGuidance(_prompt?: string): string;
|
|
444
|
+
declare function buildProjectBudgetFinalizationGuidance(_prompt?: string): string;
|
|
445
|
+
declare function buildProjectExecutionProfile(_prompt?: string): ProjectExecutionProfile;
|
|
446
|
+
declare function shouldEnableExecutionGovernance(_options?: unknown): boolean;
|
|
447
|
+
declare function createBenchBashMiddleware(_options?: BenchBashMiddlewareOptions): ToolMiddleware;
|
|
422
448
|
interface GovernanceExtensionsOptions {
|
|
423
449
|
taskPrompt: string;
|
|
424
450
|
benchmarkMode?: boolean;
|
|
425
451
|
requiredOutputPaths?: string[];
|
|
452
|
+
cwd?: string;
|
|
426
453
|
interactiveTurnGovernance?: InteractiveTurnGovernanceOptions | false;
|
|
427
454
|
executionGovernance?: boolean;
|
|
428
|
-
promptGuidance?: boolean;
|
|
429
455
|
onExecutionGovernanceUpdate?: (summary: ExecutionGovernanceSummary) => void | Promise<void>;
|
|
430
456
|
}
|
|
431
457
|
interface GovernanceExtensions {
|
|
@@ -435,4 +461,4 @@ interface GovernanceExtensions {
|
|
|
435
461
|
getExecutionGovernanceSummary(): ExecutionGovernanceSummary | null;
|
|
436
462
|
}
|
|
437
463
|
declare function createGovernanceExtensions(options: GovernanceExtensionsOptions): GovernanceExtensions;
|
|
438
|
-
export { type BenchBashMiddlewareOptions, type CompletionDecision, ExecutionGovernance, type ExecutionGovernanceOptions, type ExecutionGovernanceSummary, type FailureCluster, type GovernanceExtensions, type GovernanceExtensionsOptions, InteractiveChatTurnGovernance, InteractiveTurnGovernance, type InteractiveTurnGovernanceOptions, type ProjectDomainProfile, type ProjectExecutionPhase, type ProjectExecutionProfile, type ValidationSignal, buildContractLedgerGuidance, buildProjectBudgetFinalizationGuidance, buildProjectExecutionGuidance, buildProjectExecutionProfile, createBenchBashMiddleware, createGovernanceExtensions, isExplicitResearchPrompt, isSimpleInformationalPrompt, resolveInteractiveTurnMaxIterations, shouldEnableExecutionGovernance };
|
|
464
|
+
export { type BenchBashMiddlewareOptions, type CompletionDecision, ExecutionGovernance, type ExecutionGovernanceOptions, type ExecutionGovernanceSummary, type FailureCluster, type GovernanceExtensions, type GovernanceExtensionsOptions, InteractiveChatTurnGovernance, InteractiveTurnGovernance, type InteractiveTurnGovernanceOptions, MAX_HOST_WEB_FETCHES_PER_TURN, MAX_HOST_WEB_SEARCHES_PER_TURN, type ProjectDomainProfile, type ProjectExecutionPhase, type ProjectExecutionProfile, type ValidationSignal, type WebResearchBudgetInput, buildContractLedgerGuidance, buildProjectBudgetFinalizationGuidance, buildProjectExecutionGuidance, buildProjectExecutionProfile, createBenchBashMiddleware, createGovernanceExtensions, createRemoteEvalGuard, findMissingRequiredOutputs, isExplicitResearchPrompt, isRemoteEvalCommand, isSimpleInformationalPrompt, parseWebResearchBudget, resolveInteractiveTurnMaxIterations, shouldEnableExecutionGovernance };
|
package/dist/governance/index.js
CHANGED
|
@@ -1,33 +1,27 @@
|
|
|
1
|
-
|
|
2
|
-
`)}var fe=/(?:[A-Za-z]:\\[^\s"'`<>|]+|\/[^\s"'`<>|]+)/g,ge=[/\b(?:save|write|place|store)\s+(?:the\s+)?(?:output|result|answer|solution|model|artifact|file|contents?)\s+(?:as|to|in)\s+(?:"|'|`)?([^\s"'`]+)(?:"|'|`)?/gi,/\b(?:save|write|place|store)\s+(?:the\s+)?final\s+(?:output|result|answer|solution|model|artifact|file)\s+(?:as|to|in)\s+(?:"|'|`)?([^\s"'`]+)(?:"|'|`)?/gi,/\b(?:create|place)\s+(?:a\s+file\s+(?:called|named)|the\s+file)\s+(?:"|'|`)?([^\s"'`]+)(?:"|'|`)?/gi,/\b(?:write|create|implement)\s+(?:a\s+)?(?:C|C\+\+|Python|Rust|Go|JavaScript|TypeScript|shell|bash)?\s*(?:source\s+)?(?:program|script|implementation|module|file|code)\s+(?:at|as|in|to)?\s*(?:"|'|`)?((?:\/|\.{1,2}[\\/]|[A-Za-z0-9_.-]+[\\/])[^\s"'`]+|[A-Za-z0-9_.-]+\.(?:c|cc|cpp|h|hpp|py|js|ts|tsx|sh|rs|go|java|rb|pl|php|json|xml|tex|sql|vim))(?:"|'|`)?/gi,/\b(?:must|should|needs?\s+to)\s+be\s+(?:saved|written|placed|stored)\s+(?:as|to|in)\s+(?:"|'|`)?([^\s"'`]+)(?:"|'|`)?/gi,/\bfinal\s+(?:model|output|artifact|answer|solution)\s+(?:needs?\s+to|should|must)\s+be\s+saved\s+as\s+(?:"|'|`)?([^\s"'`]+)(?:"|'|`)?/gi,/\b(?:file|path)\s+(?:"|'|`)?((?:\/app|\/workspace|\/tmp|\.{1,2}\/)[^\s"'`]+)(?:"|'|`)?\s+(?:must|should|needs?\s+to|containing|with)\b/gi],be=[{key:"ml_artifact",label:"ML/model artifact",trigger:/\b(?:model|weights?|checkpoint|ckpt|onnx|torch|pytorch|tensorflow|keras|fasttext|embedding|inference|prediction|logits?|classif(?:y|ication)|train(?:ing)?|accuracy|loss|gpt-?2|tokeni[sz]er|vocab|bpe)\b/i,verifierRequirements:["inspect model, weight, tokenizer, preprocessing, label-order, and entrypoint schema before wrapping it","validate multiple representative samples or known labels; one smoke input is not enough","when provided artifacts exist, prove dependency by loading/schema-checking or mutation/removal changing outputs","for distributed/tensor-parallel code, run the actual multiprocess/world-size verifier shape instead of only syntax or static checks"],finalAuditItems:["final model or wrapper loads from the submitted path","final invocation uses provided weights/tokenizers instead of constants","metric or known-output evidence is recorded against the final artifact"]},{key:"visual_artifact",label:"visual/video/geometry artifact",trigger:/\b(?:image|video|frame|opencv|cv2|ffmpeg|ocr|render|raster|pixel|sprite|gcode|g-code|path\s*tracing|ray\s*tracing|camera|toml|move\s+extraction|mask|segmentation|pdf|invoice|document)\b/i,verifierRequirements:["derive answers from rendered pixels, frame samples, geometry, OCR, or simulation rather than filenames/comments","use two independent views for exact text, coordinates, masks, or temporal outputs","read generated images, CSVs, PDFs, or media outputs back through the same shape the verifier will inspect"],finalAuditItems:["submitted visual/document/media artifact exists at the required path","second-pass content check agrees with the final output","temporary previews did not replace or remove the final deliverable"]},{key:"structured_data",label:"structured data or script output",trigger:/\b(?:csv|tsv|parquet|arrow|jsonl?|dataframe|table|schema|columns?|rows?|coords_[xy]|metadata|reshard|compress|decompress|output_path)\b/i,verifierRequirements:["run the submitted script or converter end-to-end, then read the generated artifact back","assert row count, column order, scalar/list field types, nulls, dtypes, and exact value preservation","for conversions, compare source and produced artifact with dataframe or byte-level equality where relevant"],finalAuditItems:["final generated artifact has the required schema and parseable fields","clean/reference inputs were not overwritten unless explicitly required","single-file deliverables contain only expected final content"]},{key:"performance",label:"performance or optimization",trigger:/\b(?:optimi[sz]e|faster|speed\s*up|runtime|latency|throughput|benchmark|profile|median|p95|under\s+\d+(?:\.\d+)?\s*(?:ms|s|sec|seconds?|min|minutes?)|accuracy|score)\b/i,verifierRequirements:["measure a baseline before optimizing and compare against the final candidate","use bounded warmed runs with medians or thresholds instead of one noisy timing","inspect relevant plans/profiles and reject changes that only preserve correctness while losing the target metric"],finalAuditItems:["best measured candidate is written to the required path","metric evidence has clear margin beyond the threshold","no long benchmark loop is still running in the final state"]},{key:"compiler_emulator",label:"compiler, emulator, or cross-architecture",trigger:/\b(?:compile|compiler|cross-?compile|gcc|clang|cargo|rustc|make|cmake|ninja|mips|riscv|x86|arm|kernel|qemu|emulator|interpreter|polyglot|doom|windows\s+3\.11|assembly|linker)\b/i,verifierRequirements:["identify the exact target toolchain and verifier command first","run a small compile/run smoke before expensive full builds","leave the final runnable artifact, VM, or emulator state after the last positive check"],finalAuditItems:["final binary/script/service starts with the verifier-shaped command","logs show the latest build/run result, not an old intermediate","background VM/emulator/service remains alive when the task requires post-run access"]},{key:"service_vm",label:"service, VM, network, or SSH",trigger:/\b(?:server|service|daemon|webserver|http|https|localhost|port\s+\d+|ssh|sshd|git\s+(?:server|clone|push)|grpc|protobuf|proto\b|rpc|request|response|client|qemu|vm|virtual\s+machine|container|socket|telnet|serial|monitor\s+socket|qmp|sendkey)\b/i,verifierRequirements:["separate setup, readiness polling, final client command, and cleanup into bounded phases","verify the exact user/verifier client command including auth, content, and protocol behavior","for gRPC/protobuf/RPC work, instantiate generated request messages with required fields and call every required RPC through a real client","for VM/QEMU work, verify monitor/QMP/serial control surfaces and expected framebuffer or service behavior, not screenshots alone","keep only required long-lived processes in the background and preserve logs"],finalAuditItems:["final service or VM is running if the verifier connects after completion","last positive client check happened after cleanup/negative tests","open port is backed by protocol-level success, not only socket readiness","protocol schemas, request fields, response fields, and VM control sockets match the verifier contract when applicable"]},{key:"search_symbolic",label:"search, symbolic, regex, or code-size",trigger:/\b(?:regex|regular expression|solver|constraint|backtracking|search|codegolf|shortest|smallest|fibonacci|circuit|sat|smt|brute\s*force|decompress|codec|round\s*trip)\b/i,verifierRequirements:["build a correctness oracle or counterexample generator before optimizing size or speed","checkpoint the best valid candidate to the required output before long searches","for regex/chess/legal-move tasks, compare against an independent oracle such as python-chess across provided PGN/FEN fixtures","cap search loops and pivot after repeated failures in the same direction"],finalAuditItems:["current best valid candidate is preserved at the submission path","randomized or adversarial fixtures ran against the final candidate","no known counterexample from the latest check remains unresolved"]},{key:"security_sanitization",label:"security, sanitization, archive, or certificate",trigger:/\b(?:xss|sanitize|html|javascript|script|payload|exploit|decrypt|archive|7z|zip|rar|hash|password|secret|credential|token|leak|git\s+repo|repository\s+cleanup|diff\s+scope|certificate|openssl|pem|tls)\b/i,verifierRequirements:["test harmful and clean/idempotent cases through the submitted entrypoint","use format-specific tooling before broad guessing for archives, hashes, and certificates","avoid regex-only sanitizers when parser or allowlist behavior is required","for repository secret cleanup, scan for remaining secrets and audit changed paths against the contaminated/allowed file set"],finalAuditItems:["clean inputs remain semantically unchanged when required","harmful/adversarial inputs are blocked by the final artifact","placeholder outputs such as UNKNOWN or TODO are absent","repository diff scope contains no unrelated clean-file modifications when the task asks for surgical cleanup"]},{key:"science_bio_numeric",label:"science, biosequence, or numeric fitting",trigger:/\b(?:dna|primer|protein|genome|melting|tm\b|oligotm|raman|spectrum|fit|curve|simulation|molecule|assembly|mjcf|robot)\b/i,verifierRequirements:["measure every stated numeric constraint using the specified calculator or an equivalent exact implementation","keep safety margin beyond hard thresholds and rerun validation on the final submitted artifact","for biological assembly, verify orientation, overhangs, circularity, translation, and sequence order end-to-end"],finalAuditItems:["final sequence/numeric file passes exact threshold calculations","no intermediate candidate is mistaken for the final artifact","round-trip or reconstruction checks cover the complete intended product"]},{key:"binary_recovery",label:"binary/ELF/recovery",trigger:/\b(?:elf|binary|disassembl|objdump|readelf|segment|memory|address|endianness|reverse\s*engineer)\b/i,verifierRequirements:["parse file-backed bytes and metadata, not only loader-expanded memory","validate address formats, endian handling, p_filesz/p_memsz boundaries, and exact JSON/value types","test on a second generated or varied sample when possible"],finalAuditItems:["final parser reads the required input file directly","output values match declared numeric/string formats","metadata and data-region boundary cases are covered"]},{key:"async_process",label:"async, signal, or process cleanup",trigger:/\b(?:async|asyncio|signal|sigterm|sigint|interrupt|cancel(?:lation)?|cleanup|terminate|shutdown|background\s+process|worker|taskgroup|semaphore)\b/i,verifierRequirements:["exercise the real interruption, signal, cancellation, or shutdown path through the submitted entrypoint","assert cleanup markers, drained finalizers, process termination, and exit behavior","include boundary cases around queued work or concurrency limits when mentioned"],finalAuditItems:["final entrypoint handles the same signal path the verifier will call","cleanup evidence comes from the submitted artifact, not only the validation harness","no orphaned process remains unless it is the required final service"]}];function q(t){return t.trim().replace(/^[`'"]+|[`'"]+$/g,"").replace(/[.,;:)\]]+$/g,"").trim()}function $(t){return!!(!t||/^[a-z][a-z0-9+.-]*:\/\//i.test(t)||t.startsWith("//"))}function y(t,e){let n=[],i=new Set;for(let r of t){let s=r.trim();if(!(!s||i.has(s))&&(i.add(s),n.push(s),n.length>=e))break}return n}function ve(t){let e=[];for(let n of ge){let i;for(;(i=n.exec(t))!==null;){let r=q(i[1]??"");$(r)||e.push(r)}}return y(e,10)}function ye(t,e){let n=new Set(e),i=t.match(fe)??[];return y(i.map(q).filter(r=>!$(r)&&!n.has(r)),10)}function we(t){return be.filter(e=>e.trigger.test(t)).slice(0,6)}function U(t){return/\b(?:terminal-bench|benchmark|hidden tests?|verifier|\/tests|test\.sh|run-tests\.sh|\/app)\b/i.test(t)}function ke(t,e,n){return e.length>0||n.length>0||U(t)?!0:/\b(?:implement|fix|build|create|write|debug|optimi[sz]e|train|configure|recover|extract|convert|process|validate)\b/i.test(t)}function Re(t,e){let n=t.some(r=>r.key==="ml_artifact"||r.key==="compiler_emulator"||r.key==="service_vm"||r.key==="search_symbolic"||r.key==="science_bio_numeric"),i=e||t.some(r=>r.key==="structured_data"||r.key==="visual_artifact"||r.key==="security_sanitization"||r.key==="binary_recovery"||r.key==="async_process");return n?[{name:"inspect",budgetPercent:15,objective:"extract the acceptance contract, toolchain, inputs, and verifier path before touching expensive work"},{name:"baseline",budgetPercent:15,objective:"create the smallest runnable baseline or measurement harness and write a checkpoint if an output path exists"},{name:"implement",budgetPercent:40,objective:"iterate on the candidate while keeping work bounded and evidence-driven"},{name:"validate",budgetPercent:20,objective:"run verifier-shaped checks against the final candidate and fix concrete failures only"},{name:"finalize",budgetPercent:10,objective:"restore final state, remove accidental temp artifacts, and preserve required outputs/services"}]:i?[{name:"inspect",budgetPercent:20,objective:"extract required outputs, fixtures, schema, and hidden-verifier assumptions"},{name:"baseline",budgetPercent:15,objective:"produce a narrow runnable baseline and a failing/passing local oracle"},{name:"implement",budgetPercent:35,objective:"implement the simplest general solution that satisfies the oracle"},{name:"validate",budgetPercent:20,objective:"read back artifacts and run adversarial, round-trip, or protocol checks"},{name:"finalize",budgetPercent:10,objective:"ensure the final filesystem/process state is exactly what the user or verifier will inspect"}]:[{name:"inspect",budgetPercent:20,objective:"understand the requested final state and available tests"},{name:"baseline",budgetPercent:10,objective:"make a small working baseline or reproduce the issue"},{name:"implement",budgetPercent:40,objective:"make the targeted change"},{name:"validate",budgetPercent:20,objective:"run the most relevant tests against the final state"},{name:"finalize",budgetPercent:10,objective:"clean temporary state and report only after validation"}]}function E(t){let e=t?.trim()??"",n=ve(e),i=ye(e,n),r=we(e),s=U(e),a=ke(e,n,r),o=Re(r,s),c=y([s?"check /tests, /test.sh, /run-tests.sh, README/instruction files, and prompt-provided commands early; if hidden, synthesize a contract-matched self-check":"look for existing tests or task-provided commands before writing custom checks",n.length>0?"write or preserve the best current candidate at each required output path before long-running work":"if a final artifact emerges, keep it in a stable path and validate that path","after any failed verifier/self-check, fix the first concrete failure and rerun the same check until a later passing signal supersedes it",...r.flatMap(m=>m.verifierRequirements)],12),d=y([...n.map(m=>`required output exists, is non-empty when applicable, and was read back: ${m}`),"latest validation ran after the last write to the submitted artifact","no known failed verifier, self-check, diff, build, or runtime signal remains unresolved","final filesystem/process state matches what the user or verifier will inspect after the agent exits",...r.flatMap(m=>m.finalAuditItems)],14);return{projectLike:a,hiddenVerifierLikely:s,requiredOutputs:n,referencedPaths:i,domains:r,phases:o,verifierRequirements:c,finalAuditItems:d}}function T(t){let e=E(t);if(!e.projectLike)return"";let n=["","","# Project Execution Board","- Treat non-trivial coding/terminal work as a project with phases, a live contract, a current best candidate, and explicit final-state proof.","- Do not optimize for appearing done. Optimize for the final filesystem, process, service, or artifact state a verifier/user will inspect.",`- Phase budget: ${e.phases.map(i=>`${i.name} ${i.budgetPercent}%`).join(" -> ")}.`];for(let i of e.phases)n.push(`- ${i.name}: ${i.objective}.`);return e.requiredOutputs.length>0&&n.push(`- Required outputs to preserve early: ${e.requiredOutputs.join(", ")}.`),e.referencedPaths.length>0&&n.push(`- Reference/input paths to avoid overwriting unless required: ${e.referencedPaths.join(", ")}.`),e.domains.length>0&&n.push(`- Domain kits active: ${e.domains.map(i=>i.label).join(", ")}.`),n.push("","# Verifier Synthesis",...e.verifierRequirements.map(i=>`- ${i}.`),"","# Final-State Auditor",...e.finalAuditItems.map(i=>`- ${i}.`)),n.join(`
|
|
3
|
-
|
|
4
|
-
`)}var w={official:6,project:5,user:4,self:3,smoke:2,syntax:1},V=/\b(?:pytest|py\.test|unittest|npm\s+(?:test|run\s+test)|pnpm\s+(?:test|run\s+test)|yarn\s+test|cargo\s+test|go\s+test|make\s+(?:test|check)|ctest|run-tests?\.sh|test\.sh|verifier|verify|check)\b/i,Ee=/(?:^|\s)(?:\/tests\b|\/run-tests\.sh\b|\.\/run-tests?\.sh\b|\.\/test\.sh\b|test_outputs\.py\b|official\s+verifier|hidden\s+tests?|verifier\b)/i,_=/\b(?:SELF_CHECK|CONTRACT|READBACK|ROUNDTRIP|SCHEMA|VALIDATION|VERIFIER)[_-]?(?:PASS|FAIL|FAILED|ERROR)\b/i,Te=/(?:^|\s)(?:cat\s+>|tee\b|cp\b|mv\b|rm\b|touch\b|mkdir\b|sed\b.*\s-i\b|patch\b|apply_patch\b|npm\s+install|pip\s+install)\b|[>]{1,2}|\b(?:writeFileSync|open\s*\([^)]*,\s*["']w|Path\([^)]*\)\.write_text)\b/i,W=[/\bFAILED\b/i,/\bFAILURES?\b/i,/\bAssertionError\b/i,/\bTraceback \(most recent call last\)/i,/\b(?:RuntimeError|ValueError|TypeError|SyntaxError|ModuleNotFoundError|ImportError)\b/i,/\b(?:mismatch|differs?|wrong output|does not match|not equal|not equivalent)\b/i,/\b(?:exit|status|return code|returncode)\s*[:=]?\s*[1-9]\d*\b/i,/\btimed?\s*out\b|\btimeout\b/i],Ae=[/\b(?:all\s+tests?\s+passed|all\s+checks?\s+passed|verifier\s+passed|validation\s+passed)\b/i,/\b(?:SELF_CHECK|CONTRACT|READBACK|ROUNDTRIP|SCHEMA|VALIDATION|VERIFIER)[_-]?PASS\b/i,/\b(?:0\s+failed|no\s+failures?|passed)\b/i,/\b(?:SUCCESS|successful|verified)\b/i];function _e(t,e=500){return t.replace(/\r\n/g,`
|
|
5
|
-
`).replace(/[ \t]+$/gm,"").trim().slice(0,e)}function Se(t){return t.toLowerCase().replace(/\b0x[0-9a-f]+\b/g,"0x").replace(/\b\d+(?:\.\d+)?\b/g,"#").replace(/\s+/g," ").trim().slice(0,160)}function b(t){let e=t.command;return typeof e=="string"&&e.trim().length>0?e.trim():void 0}function Ce(t,e,n){let i=b(e)??"";return/^Bash$/i.test(t)&&V.test(i)||/^TaskOutput$/i.test(t)&&(V.test(n)||_.test(n))?!0:_.test(n)}function Ie(t,e,n){let i=b(e)??"",r=`${i}
|
|
6
|
-
${n}`;return Ee.test(r)?"official":/\b(?:pytest|npm\s+(?:test|run\s+test)|pnpm\s+(?:test|run\s+test)|yarn\s+test|cargo\s+test|go\s+test|make\s+(?:test|check)|ctest)\b/i.test(i)?"project":_.test(r)||/\bself[-_ ]?check\b/i.test(r)?"self":/\b(?:syntax|compile|lint|import)\b/i.test(r)?"syntax":/^Bash$/i.test(t)?"user":"smoke"}function Pe(t){let e,n,i=t.match(/(?:^|\s)(\d+)\s+failed\b/i),r=t.match(/(?:^|\s)(\d+)\s+passed\b/i);return i&&(e=Number.parseInt(i[1],10)),r&&(n=Number.parseInt(r[1],10)),{failed:e,passed:n}}function Ne(t,e){let n=t.replace(/\r\n/g,`
|
|
1
|
+
import{readdirSync as z,statSync as Q}from"node:fs";import{isAbsolute as K,resolve as Y}from"node:path";function L(t,e=process.cwd()){let n=[];for(let s of t){let i=K(s)?s:Y(e,s);try{let r=Q(i);r.isDirectory()?z(i).length===0&&n.push({path:s,problem:"empty"}):r.isFile()?r.size===0&&n.push({path:s,problem:"empty"}):n.push({path:s,problem:"not_a_file"})}catch{n.push({path:s,problem:"missing"})}}return n}var v={official:6,project:5,user:4,self:3,smoke:2,syntax:1},P=/\b(?:pytest|py\.test|unittest|npm\s+(?:test|run\s+test)|pnpm\s+(?:test|run\s+test)|yarn\s+test|cargo\s+test|go\s+test|make\s+(?:test|check)|ctest|run-tests?\.sh|test\.sh|verifier|verify|check)\b/i,w=/\b(?:SELF_CHECK|CONTRACT|READBACK|ROUNDTRIP|SCHEMA|VALIDATION|VERIFIER)[_-]?(?:PASS|FAIL|FAILED|ERROR)\b/i,F=/(?:^|\s)(?:cat\s+>|tee\b|cp\b|mv\b|rm\b|touch\b|mkdir\b|sed\b.*\s-i\b|patch\b|apply_patch\b|npm\s+install|pip\s+install)\b|[>]{1,2}|\b(?:writeFileSync|open\s*\([^)]*,\s*["']w|Path\([^)]*\)\.write_text)\b/i,O=[/\bFAILED\b/i,/\bFAILURES?\b/i,/\bAssertionError\b/i,/\bTraceback \(most recent call last\)/i,/\b(?:RuntimeError|ValueError|TypeError|SyntaxError|ModuleNotFoundError|ImportError)\b/i,/\b(?:mismatch|differs?|wrong output|does not match|not equal|not equivalent)\b/i,/\b(?:exit|status|return code|returncode)\s*[:=]?\s*[1-9]\d*\b/i,/\btimed?\s*out\b|\btimeout\b/i],Z=[/\b(?:all\s+tests?\s+passed|all\s+checks?\s+passed|verifier\s+passed|validation\s+passed)\b/i,/\b(?:SELF_CHECK|CONTRACT|READBACK|ROUNDTRIP|SCHEMA|VALIDATION|VERIFIER)[_-]?PASS\b/i,/\b(?:0\s+failed|no\s+failures?|passed)\b/i,/\b(?:SUCCESS|successful|verified)\b/i];function J(t,e=500){return t.replace(/\r\n/g,`
|
|
2
|
+
`).replace(/[ \t]+$/gm,"").trim().slice(0,e)}function ee(t){return t.toLowerCase().replace(/\b0x[0-9a-f]+\b/g,"0x").replace(/\b\d+(?:\.\d+)?\b/g,"#").replace(/\s+/g," ").trim().slice(0,160)}function m(t){let e=t.command;return typeof e=="string"&&e.trim().length>0?e.trim():void 0}function y(t){return t.replace(/\d*>&\d+|&>\s*\/dev\/null|\d*>>?\s*\/dev\/null/g," ").replace(/-(?:o|-output)\s+\/dev\/null/g," ")}var te=new Set(["ls","ll","dir","pwd","cd","echo","printf","cat","head","tail","less","more","wc","stat","file","find","grep","egrep","fgrep","rg","which","whereis","type","command","test","[","true","env","printenv","id","whoami","date","tree","du","df","ps","sort","uniq","cut","awk","sed","tr","set"]);function ne(t){let e=y(t).split(/&&|\|\||;|\||\n/).map(n=>n.trim()).filter(n=>n.length>0);return e.length===0?!1:e.some(n=>{let i=(n.replace(/^(?:[A-Za-z_][A-Za-z0-9_]*=\S*\s+)+/,"").split(/\s+/)[0]??"").replace(/^.*\//,"");return i.length>0&&!te.has(i)})}function N(t){return t.replace(/\s+/g," ").trim()}function se(t,e){let n=N(t);return n.length>=12&&N(e).includes(n)}function ie(t,e,n){let s=m(e)??"";return/^Bash$/i.test(t)&&P.test(s)||/^TaskOutput$/i.test(t)&&(P.test(n)||w.test(n))?!0:w.test(n)}var re=/(?:^|[;&|(]\s*|(?<![\w./-])(?:bash|sh|zsh|source|exec|env|timeout\s+\S+)\s+(?:-\S+\s+)*)(?:\.\/|\/)?(?:[\w.-]+\/)*(?:run-tests?\.sh|test\.sh)\b|\b(?:pytest|py\.test|python3?\s+-m\s+pytest)\b[^;&|\n]*(?:\/tests?\b|\btest_outputs\.py\b)/i;function oe(t,e,n){let s=m(e)??"",i=`${s}
|
|
3
|
+
${n}`;return re.test(s)?"official":/\b(?:pytest|py\.test|python3?\s+-m\s+unittest|unittest\s+discover|npm\s+(?:test|run\s+test)|pnpm\s+(?:test|run\s+test)|yarn\s+test|bun\s+test|vitest|jest|cargo\s+test|go\s+test|make\s+(?:test|check)|ctest|mvn\s+test|gradle\s+test|dotnet\s+test)\b/i.test(s)?"project":w.test(i)||/\bself[-_ ]?check\b/i.test(i)?"self":/\b(?:syntax|compile|lint|import)\b/i.test(i)?"syntax":/^Bash$/i.test(t)?"user":"smoke"}function ae(t){let e,n,s=t.match(/(?:^|\s)(\d+)\s+failed\b/i),i=t.match(/(?:^|\s)(\d+)\s+passed\b/i);return s&&(e=Number.parseInt(s[1],10)),i&&(n=Number.parseInt(i[1],10)),{failed:e,passed:n}}function le(t,e){let n=t.replace(/\r\n/g,`
|
|
7
4
|
`).split(`
|
|
8
|
-
`),
|
|
9
|
-
`);
|
|
10
|
-
`).find(c=>c.trim().length>0)?.trim().slice(0,140)??"Validation failure",count:1,firstIteration:e,lastIteration:e,latestExcerpt:
|
|
11
|
-
${e.result.error??""}
|
|
12
|
-
`),blocking:!0,unresolvedFailures:[],latestAuthoritativeSignal:
|
|
13
|
-
`)
|
|
14
|
-
`);return this.setDecision({action:e.stopReason==="max_iterations"?"incomplete":"continue",finalStateVerified:!1,reason:
|
|
15
|
-
`)
|
|
16
|
-
`)}
|
|
17
|
-
`)}}
|
|
18
|
-
`)}
|
|
19
|
-
`)
|
|
20
|
-
`)}}
|
|
21
|
-
`)}}
|
|
5
|
+
`),s=[];for(let r=0;r<n.length;r+=1){let o=n[r]??"";if(/^(?:FAILED|ERROR)\s+[\w./:-]+/i.test(o.trim())||O.some(a=>a.test(o))){let a=n.slice(Math.max(0,r-1),Math.min(n.length,r+3)).join(`
|
|
6
|
+
`);s.push(J(a,260))}}let i=new Map;for(let r of s.slice(0,12)){let o=ee(r);if(!o)continue;let a=i.get(o);if(a){a.count+=1,a.latestExcerpt=r,a.lastIteration=e;continue}i.set(o,{signature:o,title:r.split(`
|
|
7
|
+
`).find(c=>c.trim().length>0)?.trim().slice(0,140)??"Validation failure",count:1,firstIteration:e,lastIteration:e,latestExcerpt:r})}return[...i.values()]}function ce(t,e){let n=ae(e);if(n.failed!==void 0&&n.failed>0)return{outcome:"fail",failureCount:n.failed,...n.passed!==void 0?{passCount:n.passed}:{},summary:`${n.failed} pytest failure(s)${n.passed!==void 0?`, ${n.passed} passed`:""}`};if(t.success===!1||O.some(i=>i.test(e)))return{outcome:"fail",summary:t.error?`Command failed: ${t.error}`:"Validation output contains failure evidence"};if(n.passed!==void 0&&n.passed>0)return{outcome:"pass",passCount:n.passed,summary:`${n.passed} pytest test(s) passed`};if(Z.some(i=>i.test(e)))return{outcome:"pass",summary:"Validation output contains pass evidence"};let s=e.match(/\bRan\s+(\d+)\s+tests?\b[\s\S]{0,200}?\n\s*OK\b/);if(s&&Number.parseInt(s[1],10)>0){let i=Number.parseInt(s[1],10);return{outcome:"pass",passCount:i,summary:`${i} unittest test(s) passed`}}return t.success===!0&&t.error===void 0&&e.trim().length>0?{outcome:"pass",summary:"Check command exited 0 with no failure output"}:{outcome:"unknown",summary:t.success?"Validation-like command produced no clear pass/fail signal":"Command failed without parseable validation signal"}}function ue(t,e,n){if(!n.success)return!1;if(/^(?:Write|Edit|NotebookEdit|MemoryWrite)$/i.test(t))return!0;let s=m(e);return/^Bash$/i.test(t)&&!!s&&F.test(y(s))}function T(t){return v[t.authority]>=v.project}var g=class{contract;signals=[];clusters=new Map;toolCalls=0;workspaceRevision=0;ownTasks=new Map;nextOwnTaskId=1;uncheckedChangesAdvised=!1;lastCompletionDecision=null;lastValidationIteration=null;lastEvaluatedIteration=null;cwd;taskPrompt;constructor(e={}){this.cwd=e.cwd??process.cwd(),this.taskPrompt=e.taskPrompt??"",this.contract={requiredOutputPaths:[...e.requiredOutputPaths??[]],projectLike:!0,benchmarkMode:!1,requiredValidation:!1}}recordToolResult(e){if(this.toolCalls+=1,e.result.success===!0&&/^TaskCreate$/i.test(e.toolName)){let l=typeof e.input.subject=="string"?e.input.subject:"task";this.ownTasks.set(String(this.nextOwnTaskId++),{subject:l,status:"pending"})}else if(e.result.success===!0&&/^TaskUpdate$/i.test(e.toolName)){let l=String(e.input.taskId??""),u=typeof e.input.status=="string"?e.input.status:void 0;u==="deleted"?this.ownTasks.delete(l):u&&this.ownTasks.has(l)&&(this.ownTasks.get(l).status=u)}if(ue(e.toolName,e.input,e.result)){this.workspaceRevision+=1;for(let l of this.signals)l.stale=!0}let n=`${e.result.output??""}
|
|
8
|
+
${e.result.error??""}`,s=m(e.input)??"",i=/^Bash$/i.test(e.toolName)&&se(s,this.taskPrompt),r=ie(e.toolName,e.input,n),o=!r&&/^Bash$/i.test(e.toolName)&&e.result.success===!0&&!F.test(y(s))&&(i||this.workspaceRevision>0&&ne(s));if(!r&&!o)return[];let a=i?"official":o?"self":oe(e.toolName,e.input,n),c=o?{outcome:"pass",summary:i?"The check named in the task exited 0":"Command exited 0"}:ce(e.result,n),d={id:`validation-${this.signals.length+1}`,iteration:e.iteration,toolName:e.toolName,...m(e.input)?{command:m(e.input)}:{},authority:a,outcome:c.outcome,stale:!1,workspaceRevision:this.workspaceRevision,summary:c.summary,...c.failureCount!==void 0?{failureCount:c.failureCount}:{},...c.passCount!==void 0?{passCount:c.passCount}:{},clusters:c.outcome==="fail"?le(n,e.iteration):[]};this.signals.push(d),this.lastValidationIteration=e.iteration;for(let l of d.clusters){let u=this.clusters.get(l.signature);if(u){u.count+=l.count,u.lastIteration=l.lastIteration,u.latestExcerpt=l.latestExcerpt;continue}this.clusters.set(l.signature,{...l})}return[d]}evaluateCompletion(e){this.lastEvaluatedIteration=e.iteration;let n=this.getLatestUnresolvedFailure(),s=this.getLatestAuthoritativeSignal();if(e.stopReason!=="progress_checkpoint"){let i=[...this.ownTasks.values()].filter(r=>r.status!=="completed");if(i.length>0)return this.setDecision({action:e.stopReason==="max_iterations"?"incomplete":"continue",finalStateVerified:!1,reason:"own_tasks_unfinished",message:["Do not finish yet. Your own task list still has unfinished work:",...i.slice(0,8).map(r=>`- ${r.subject} (${r.status})`),"Carry it out now. If an item is truly done, mark it completed; if it cannot be done, say exactly why in your answer and delete it."].join(`
|
|
9
|
+
`),blocking:!0,unresolvedFailures:[],latestAuthoritativeSignal:s})}if(this.contract.requiredOutputPaths.length>0&&e.stopReason!=="progress_checkpoint"){let i=L(this.contract.requiredOutputPaths,this.cwd);if(i.length>0)return this.setDecision({action:e.stopReason==="max_iterations"?"incomplete":"continue",finalStateVerified:!1,reason:"required_outputs_missing",message:["Do not finish yet. Required output files are not in place.",...i.map(r=>`- ${r.path} (${r.problem==="missing"?"does not exist":r.problem==="empty"?"is empty":"is not a file"})`),"Create or complete them, then check their contents before answering."].join(`
|
|
10
|
+
`),blocking:!0,unresolvedFailures:[],latestAuthoritativeSignal:s})}if(n){let i=this.getRepeatedFailure(),r=["Do not finish yet. The latest authoritative validation signal is still failing.",`Latest failure: ${n.summary}.`,i?`Repeated failure signature detected (${i.count}x): ${i.title}`:"Use the concrete failure output, make the smallest targeted repair, then rerun the same verifier-shaped check.","A self-check pass or candidate note cannot supersede a later project/official failure."].join(`
|
|
11
|
+
`);return this.setDecision({action:e.stopReason==="max_iterations"?"incomplete":"continue",finalStateVerified:!1,reason:"authoritative_validation_failed",message:r,blocking:!0,unresolvedFailures:n.clusters,latestAuthoritativeSignal:s})}if(s?.outcome==="pass"&&!s.stale)return this.setDecision({action:"complete",finalStateVerified:!0,reason:"authoritative_validation_passed",message:"Latest authoritative validation passed after the current workspace revision.",blocking:!1,unresolvedFailures:[],latestAuthoritativeSignal:s});if(this.workspaceRevision>0&&e.stopReason!=="progress_checkpoint"){let i=this.getLatestSignal(),r=i?.outcome==="pass"&&!i.stale;return this.signals.some(a=>T(a)&&a.outcome!=="unknown")?this.setDecision({action:e.stopReason==="max_iterations"?"incomplete":"continue",finalStateVerified:!1,reason:"tests_not_rerun_after_changes",message:["Do not finish yet. You changed files after the last run of the project's tests.","Run them again on the current files and fix what fails before answering."].join(`
|
|
12
|
+
`),blocking:!0,unresolvedFailures:[],latestAuthoritativeSignal:s}):r?this.setDecision({action:"complete",finalStateVerified:!1,reason:"self_validation_passed",message:"No project test suite was run. The agent's own check passed against the current workspace; this is not an independent verification.",blocking:!1,unresolvedFailures:[],latestAuthoritativeSignal:s}):this.uncheckedChangesAdvised?this.setDecision({action:"complete",finalStateVerified:!1,reason:"changes_unverified",message:"The workspace was changed and no check was run against the final state.",blocking:!1,unresolvedFailures:[],latestAuthoritativeSignal:s}):(this.uncheckedChangesAdvised=!0,this.setDecision({action:e.stopReason==="max_iterations"?"incomplete":"continue",finalStateVerified:!1,reason:"changes_not_checked",message:["Before you finish: you changed the workspace and have not checked the result since your last change.","Run the check that would fail if the work were wrong (the project's tests, the command the task names, or your own comparison against an independent answer).","If nothing can be run against this change, say so plainly in your answer."].join(`
|
|
13
|
+
`),blocking:!1,unresolvedFailures:[],latestAuthoritativeSignal:s}))}return this.setDecision({action:"complete",finalStateVerified:!1,reason:"no_changes_made",message:"Nothing in the workspace was changed, so there is no result to verify.",blocking:!1,unresolvedFailures:[],latestAuthoritativeSignal:s})}getSummary(){return{contract:{...this.contract,requiredOutputPaths:[...this.contract.requiredOutputPaths]},validation:{latestSignal:this.cloneSignal(this.getLatestSignal()),latestAuthoritativeSignal:this.cloneSignal(this.getLatestAuthoritativeSignal()),latestUnresolvedFailure:this.cloneSignal(this.getLatestUnresolvedFailure()),signals:this.signals.slice(-20).map(e=>this.cloneSignal(e))},progress:{toolCalls:this.toolCalls,validationRuns:this.signals.length,workspaceRevision:this.workspaceRevision,repeatedFailureSignature:this.getRepeatedFailure()?.signature??null,repeatedFailureCount:this.getRepeatedFailure()?.count??0,iterationsSinceLastValidation:this.lastValidationIteration===null?null:Math.max(0,(this.lastEvaluatedIteration??this.lastValidationIteration)-this.lastValidationIteration)},completionDecision:this.lastCompletionDecision?{...this.lastCompletionDecision}:null}}getLatestSignal(){return this.signals.at(-1)??null}getLatestAuthoritativeSignal(){return[...this.signals].reverse().find(e=>T(e))??null}getLatestUnresolvedFailure(){let e=[...this.signals].reverse().find(s=>T(s)&&s.outcome==="fail"&&!s.stale);return e?this.signals.some(s=>s.iteration>e.iteration&&!s.stale&&s.outcome==="pass"&&v[s.authority]>=v[e.authority])?null:e:null}getRepeatedFailure(){let e=null;for(let n of this.clusters.values())n.count<2||(!e||n.count>e.count)&&(e=n);return e}setDecision(e){return this.lastCompletionDecision=e,e}cloneSignal(e){return e?{...e,clusters:e.clusters.map(n=>({...n}))}:null}};var de=200,he=500;function S(t,e,n){if(e===void 0||e==="")return;let s=typeof e=="number"?e:/^[0-9]+$/.test(e.trim())?Number(e.trim()):NaN;if(!Number.isSafeInteger(s)||s<1||s>n)throw Object.assign(new Error(`${t} must be a whole number from 1 to ${n}.`),{code:"WEB_RESEARCH_BUDGET_INVALID"});return s}function me(t){let e=S("The web search limit",t.searches,200),n=S("The web fetch limit",t.fetches,500),s=S("The total web call limit",t.calls,700);return{...e===void 0?{}:{maxWebSearches:e},...n===void 0?{}:{maxWebFetches:n},...s===void 0?{}:{maxTotalWebResearchCalls:s}}}var pe=15,fe=new Set(["bash","elfanalyze","gitbranch","gitdiff","gitlog","gitstatus","glob","grep","ls","read","readimage"]),ge=new Set(["applypatch","edit","notebookedit","write"]),be=/\?|\b(?:can|could|did|do|does|has|have|is|should|was|were|will|would)\b|\b(?:correct|right)\s*[.!?]*$/i,ve=/\b(?:audit|build|change|check|clone|configure|copy|create|delete|deploy|edit|find|fix|implement|inspect|install|locate|make|migrate|move|publish|refactor|release|remove|rename|research|run|save|scaffold|search|set|start|stop|test|update|verify|write)\b/i,Re=/^(?:ok(?:ay)?[\s,!.:-]*)?(?:then\s+)?(?:(?:let(?:'|’)s|lets)\s+)?(?:continue|do\s+it|fix\s+it|get\s+started|go\s+ahead|implement\s+it|make\s+it|proceed|procede|ship\s+it|start)(?:\s+(?:now|please))?[\s.!?]*$/i,M=new Set(["add","address","adjust","adopt","append","apply","build","bump","carry","change","clean","commit","complete","continue","convert","correct","create","delete","deploy","disable","do","drop","edit","enable","execute","extend","extract","finalize","finish","fix","follow","generate","go","handle","implement","improve","include","insert","install","integrate","introduce","keep","land","make","merge","migrate","modify","move","patch","port","prepend","proceed","publish","push","put","rebase","rebuild","redo","reduce","refactor","release","remove","rename","replace","rerun","resolve","restore","retry","revert","rewrite","run","set","ship","split","start","switch","test","tidy","try","tweak","undo","update","upgrade","use","wire","write"]),Ee=/^(?:(?:ok(?:ay)?|alright|all\s+right|right|great|good|cool|yes|yep|yeah|sure|thanks|thank\s+you|perfect|nice|fine|now|then|so|and|please|pls|kindly|just|also|let(?:'|’)?s|let\s+us)\b[\s,!.:;-]*)+/i,Te=/^(?:can|could|would|will)\s+you\s+(?:please\s+)?([a-z]+)/i,we=/^do\s+(?:you|we|i|they|he|she)\b/i;function ye(t){let e=t.trim();if(!e)return!1;let n=Te.exec(e);if(n)return M.has(n[1].toLowerCase());if(/\?\s*$/.test(e)&&!/[,\s](?:ok(?:ay)?|right|please|yes)\s*\?\s*$/i.test(e))return!1;let s=e.replace(Ee,"");if(we.test(s))return!1;let i=/^([a-z]+)/i.exec(s)?.[1]?.toLowerCase();return i!==void 0&&M.has(i)}function Se(t){return t.split(/(?<=[.!?;:])\s+|\s+[—–]\s+|\n+/).some(ye)}var _e=["audit","build","change","check","clone","configure","create","delete","deploy","implement","inspect","install","locate","migrate","publish","refactor","release","remove","rename","research","scaffold","search","start","update","verify","write"],xe=/\b(?:browse|investigate|research|search)\b|\b(?:check|find|look)\s+(?:it\s+)?(?:up|online|on\s+the\s+web)\b/i,Ce=["browse","investigate","research","search"],Ae=/\b(?:Add-Content|Clear-Content|Copy-Item|git\s+(?:add|commit|merge|mv|push|rebase|reset|restore|rm|switch)|Move-Item|New-Item|npm\s+(?:install|publish|uninstall)|pnpm\s+(?:add|install|publish|remove)|Remove-Item|Rename-Item|Set-Content|Start-Process|yarn\s+(?:add|install|publish|remove))\b|(?:^|[^<])>{1,2}\s*[^&]/i,Ie=/\b(?:installed|install(?:ed)?|on\s+(?:my|this)\s+(?:machine|pc|computer|system)|cli|command(?:\s+line)?|executable|on\s+(?:the\s+)?path|version|where(?:\.exe)?|which|available)\b/i,ke=/\b(?:Get-Command|where(?:\.exe)?|command\s+-v|which|type\s+-a?|--version|-v\b|--help|-h\b)\b/i,Pe=/\b(?:yes|installed|you\s+(?:have|do\s+have)|found|available|on\s+(?:your|the)\s+path|callable|working|responds?|verified|confirmed)\b/i,Ne=/\b(?:cannot\s+confirm|can't\s+confirm|not\s+confirm(?:ed)?|not\s+proven|not\s+verified|uncertain|failed|fails|could\s+not\s+verify|not\s+installed|does\s+not\s+appear|isn't\s+available|not\s+available)\b/i,Le=/\b(?:exit\s+code|exit\s+status|status|return\s+code|returncode)\s*[:= -]?\s*(?:-[1-9]\d*|[1-9]\d*)\b|\b(?:not\s+recognized|not\s+found|could\s+not\s+find|cannot\s+find|no\s+such\s+file|failed)\b/i,Fe=/\b(?:created|generated|produced|saved|wrote|written|exported|converted|built|rendered|flattened|creat|generat|produs|salvat|scris|exportat|convertit|aplatizat)\b/i,Oe=/\b(?:not|didn['’]?t|couldn['’]?t|cannot|failed\s+to|incomplete|missing|nu|n-am|nereu[sÈ™]it)\b/i,Me=/\b(?:pages?|page\s+count|dpi|ocr|text\s+layer|extractible\s+text|renders?|opens?|dimensions?|metadata|pagini|strat\s+(?:ocr|de\s+text)|text\s+extractibil|se\s+deschide|rezolu[tÈ›]ie)\b/i,We=/(?:^|[\\/])\.xeno[\\/](?:sessions|audit)[\\/]/i,De=/\b(?:official|docs?|documentation|source|reference|install(?:ation)?|supported|features?|commands?)\b/i,Ue=/\b(?:search\s+online|look\s+online|web\s+search|web\s+fetch|fetch\s+(?:the\s+)?(?:official\s+)?page|official|docs?|documentation|source|reference|summarize|url)\b/i,$e=/\b(?:HTTP\s+404|404\s+Not\s+Found|not\s+found|does\s+not\s+exist|gone|HTTP\s+410|410\s+Gone)\b/i,Ve=/\b(?:curl|wget|Invoke-WebRequest|Invoke-RestMethod|iwr|irm)\b[\s\S]*https?:\/\/|\bpython(?:3|\.exe)?\b[\s\S]*\b(?:urllib\.request|requests\.get|http\.client)\b[\s\S]*https?:\/\/|\bnode(?:\.exe)?\b[\s\S]*\b(?:fetch|https\.get|axios)\b[\s\S]*https?:\/\//i,Ge=/https?:\/\/[^\s)>\]]+/i,je=/^(?:localhost|127(?:\.\d{1,3}){3}|0\.0\.0\.0|\[?::1\]?|10(?:\.\d{1,3}){3}|192\.168(?:\.\d{1,3}){2}|172\.(?:1[6-9]|2\d|3[01])(?:\.\d{1,3}){2}|[a-z0-9-]+\.(?:local|localhost|test|internal))$/i;function Be(t){return Ve.test(t)?[...t.matchAll(/https?:\/\/(\[[0-9a-f:]+\]|[^\s/:"'`)>\]]+)/gi)].map(n=>n[1]).some(n=>!je.test(n)):!1}function f(t){return t.trim().replace(/\s+/g," ")}function He(t,e){if(t===e)return!0;if(Math.abs(t.length-e.length)>1)return!1;if(t.length===e.length){let a=[];for(let c=0;c<t.length;c+=1)if(t[c]!==e[c]&&a.push(c),a.length>2)return!1;return a.length===1?!0:a.length===2&&a[1]===a[0]+1&&t[a[0]]===e[a[1]]&&t[a[1]]===e[a[0]]}let[n,s]=t.length<e.length?[t,e]:[e,t],i=0,r=0,o=!1;for(;i<n.length&&r<s.length;){if(n[i]===s[r]){i+=1,r+=1;continue}if(o)return!1;o=!0,r+=1}return!0}function q(t,e){return(t.toLowerCase().match(/[a-z]+/g)??[]).some(s=>s.length>=5&&e.some(i=>He(s,i)))}function qe(t){return Re.test(f(t))||ve.test(t)||q(t,_e)}function I(t){return xe.test(t)||q(t,Ce)}function k(t){return t.replace(/[\s_-]+/g,"").toLowerCase()}function _(t){return Array.isArray(t)?t.map(_):t&&typeof t=="object"?Object.fromEntries(Object.entries(t).sort(([e],[n])=>e.localeCompare(n)).map(([e,n])=>[e,_(n)])):typeof t=="string"?f(t.replace(/\\/g,"/")):t}function W(t,e){return`${k(t)}:${JSON.stringify(_(e))}`}function D(t){return fe.has(k(t))}function Xe(t,e){let n=k(t);return ge.has(n)?!0:n==="bash"&&Ae.test(x(e)??"")}function R(t){let e=f(t);return!e||e.length>320?!1:be.test(e)&&!qe(e)&&!Se(e)}function ze(t,e){let n=Math.max(1,Math.floor(e));return R(t)?Math.min(n,pe):n}function Qe(t){if(typeof t!="string")return null;let e=f(t).toLowerCase();return e.length>0?e:null}function U(t){if(typeof t!="string")return null;try{let e=new URL(t);return e.hash="",e.pathname=e.pathname.replace(/\/+$/,"")||"/",e.toString().toLowerCase()}catch{let e=f(t).toLowerCase().replace(/#.*$/,"").replace(/\/+$/,"");return e.length>0?e:null}}function x(t){let e=t.command;return typeof e=="string"&&e.trim().length>0?e.trim():null}function C(t){return typeof t=="string"?[t]:Array.isArray(t)?t.flatMap(C):t&&typeof t=="object"?Object.values(t).flatMap(C):[]}function $(t){return t.replace(/\\/g,"/").toLowerCase()}function V(t){return f([t.output,t.error].filter(Boolean).join(" ")).slice(0,240)}function G(t){return t.success===!1||Le.test([t.output,t.error].filter(Boolean).join(`
|
|
14
|
+
`))}function j(t){return/^Bash$/i.test(t)}function B(t){return/^WebSearch$/i.test(t)}function H(t){return/^WebFetch$/i.test(t)}var p=class{taskPrompt;maxWebSearches;maxWebFetches;maxTotalWebResearchCalls;maxLocalInspectionCalls;simpleInformationalPrompt;explicitResearchPrompt;hostWebBudget;searchQueries=new Map;fetchedUrls=new Map;localInspectionRecords=new Map;localEvidence=[];webFetchEvidence=[];artifactEvidence=[];verificationRecords=[];pendingAwaitOperations=new Map;transcriptReadRanges=new Map;webSearches=0;webFetches=0;localInspectionCalls=0;mutationEpoch=0;constructor(e,n={}){this.taskPrompt=e,this.explicitResearchPrompt=I(e),this.maxWebSearches=Math.max(1,n.maxWebSearches??(this.explicitResearchPrompt?5:3)),this.maxWebFetches=Math.max(1,n.maxWebFetches??(this.explicitResearchPrompt?12:4)),this.hostWebBudget=n.maxWebSearches!==void 0||n.maxWebFetches!==void 0||n.maxTotalWebResearchCalls!==void 0;let s=this.explicitResearchPrompt?16:6;this.maxTotalWebResearchCalls=Math.max(1,n.maxTotalWebResearchCalls??(this.hostWebBudget?Math.max(s,this.maxWebSearches+this.maxWebFetches):s)),this.simpleInformationalPrompt=R(e),this.maxLocalInspectionCalls=Math.max(1,n.maxLocalInspectionCalls??(this.simpleInformationalPrompt?12:Number.MAX_SAFE_INTEGER))}maybeBlockToolCall(e){let n=this.findOverlappingTranscriptRead(e.toolName,e.input);if(n)return this.blockedResult(["[Xeno continuation-state guard]",`This transcript range overlaps an earlier read in the current turn: ${n}`,"Use the structured operation/continuation checkpoint and the existing excerpt. Do not scan the growing session Markdown to rediscover current state."]);if(Xe(e.toolName,e.input)){if(this.simpleInformationalPrompt)return this.blockedResult(["[Xeno interactive turn guard]","This is a short informational question, not a request to change files, configuration, packages, processes, or repository state.",`Blocked unrequested mutation through ${e.toolName}.`,"Answer the question from the evidence already available. Ask before making changes if a change would materially help."]);this.mutationEpoch+=1}if(D(e.toolName)){let s=`${this.mutationEpoch}:${W(e.toolName,e.input)}`,i=this.localInspectionRecords.get(s);if(i?.successful||(i?.attempts??0)>=2)return this.blockedResult(["[Xeno interactive turn guard]",i?.successful===!0?`This exact ${e.toolName} inspection already succeeded during the current turn.`:`This exact ${e.toolName} inspection has already failed twice during the current turn.`,"Do not repeat or cosmetically repackage the same inspection. Use the existing result, choose one materially different check, or answer now with the uncertainty that remains."]);if(this.localInspectionCalls>=this.maxLocalInspectionCalls)return this.blockedResult(["[Xeno interactive turn guard]",`The local inspection budget for this turn is exhausted (${this.localInspectionCalls}/${this.maxLocalInspectionCalls}).`,"Stop exploring. Give the shortest accurate answer supported by the evidence already gathered, and state one limitation if needed."]);this.localInspectionCalls+=1,this.localInspectionRecords.set(s,{attempts:(i?.attempts??0)+1,successful:i?.successful??!1})}if(j(e.toolName)&&this.isWebResearchQuestion()){let s=x(e.input);if(s&&Be(s))return this.blockedResult(["[Xeno interactive research guard]","Do not use Bash, Python, PowerShell, curl, wget, or ad hoc scripts to fetch public web pages during a web-research turn.","Use WebSearch to discover sources and WebFetch to read exact URLs. WebFetch handles timeouts, redirects, readable extraction, source metadata, and discovered documentation links.",this.fetchedSourceSummary()])}if(B(e.toolName)){let s=Qe(e.input.query),i=s?this.searchQueries.get(s)??0:0;if(this.shouldStopOfficialResearch())return this.blockedResult(["[Xeno interactive research guard]","Official web evidence has already been fetched this turn.",this.fetchedSourceSummary(),"Stop searching. Answer now from the fetched official source(s), naming the URL(s) used and clearly stating any remaining uncertainty."]);if(s&&i>0)return this.blockedResult(["[Xeno interactive research guard]",`The WebSearch query has already been run this turn: ${s}`,"Do not repeat equivalent searches. Use the existing search result, fetch one clearly relevant source, run a local verification command if the question is about this machine, or answer with the uncertainty that remains."]);if(this.webSearches>=this.maxWebSearches||this.totalWebResearchCalls()>=this.maxTotalWebResearchCalls)return this.blockedResult(["[Xeno interactive research guard]",`The per-turn web-search budget is exhausted (${this.webSearches}/${this.maxWebSearches} searches, ${this.totalWebResearchCalls()}/${this.maxTotalWebResearchCalls} total web calls).`,"Stop broad web exploration. Prefer official documentation already found, run a local check if relevant, or give a bounded answer that states what is and is not verified."]);this.webSearches+=1,s&&this.searchQueries.set(s,i+1)}if(H(e.toolName)){let s=U(e.input.url),i=s?this.fetchedUrls.get(s)??0:0;if(this.shouldStopOfficialResearch())return this.blockedResult(["[Xeno interactive research guard]","Enough official web evidence has already been fetched this turn.",this.fetchedSourceSummary(),"Do not guess more nearby documentation URLs. Answer from the fetched source(s), cite the URL(s), and mention if a specific detail was not present."]);if(s&&i>0)return this.blockedResult(["[Xeno interactive research guard]",`This URL has already been fetched this turn: ${s}`,"Do not fetch the same page again. Use the existing content, fetch a more precise official source, run a local verification command if relevant, or answer with the uncertainty that remains."]);if(this.webFetches>=this.maxWebFetches||this.totalWebResearchCalls()>=this.maxTotalWebResearchCalls)return this.blockedResult(["[Xeno interactive research guard]",`The per-turn web-fetch budget is exhausted (${this.webFetches}/${this.maxWebFetches} fetches, ${this.totalWebResearchCalls()}/${this.maxTotalWebResearchCalls} total web calls).`,"Stop broad web exploration. Use the best source already gathered, run a local check if relevant, or answer with a clear limitation."]);this.webFetches+=1,s&&this.fetchedUrls.set(s,i+1)}return null}recordToolResult(e){let n=e.result.operation;n?.completionPolicy==="await"&&(n.terminal?this.pendingAwaitOperations.delete(n.operationId):this.pendingAwaitOperations.set(n.operationId,n.taskId??n.operationId));for(let r of e.result.evidence??n?.evidence??[]){let o=this.artifactEvidence.findIndex(c=>c.operationId===r.operationId&&c.path===r.path),a={iteration:e.iteration,path:r.path,status:r.status,operationId:r.operationId};o>=0?this.artifactEvidence[o]=a:this.artifactEvidence.push(a)}if(Ke(e.toolName)&&this.verificationRecords.push({iteration:e.iteration,toolName:e.toolName,inputValues:C(e.input),success:e.result.success===!0&&!G(e.result)}),D(e.toolName)){let r=`${this.mutationEpoch}:${W(e.toolName,e.input)}`,o=this.localInspectionRecords.get(r);o&&(o.successful=o.successful||e.result.success===!0)}if(B(e.toolName))return;if(H(e.toolName)){let r=U(e.input.url);r&&this.webFetchEvidence.push({iteration:e.iteration,url:r,success:e.result.success===!0,summary:V(e.result)});return}if(!j(e.toolName)||!this.isLocalSetupQuestion())return;let s=x(e.input);if(!s||!ke.test(s))return;let i=G(e.result);this.localEvidence.push({iteration:e.iteration,command:s,success:e.result.success===!0&&!i,summary:V(e.result)})}evaluateCompletion(e){if(this.pendingAwaitOperations.size>0)return{blocking:!0,message:["[Xeno pending-operation guard]",`Awaited operation(s) are still nonterminal: ${Array.from(this.pendingAwaitOperations.values()).join(", ")}.`,"Suspend this turn without a final answer. The runtime will resume the objective exactly once when the operation becomes terminal."].join(`
|
|
15
|
+
`)};let n=this.evaluateArtifactClaims(e.finalText);if(n)return n;if(this.isWebResearchQuestion()){let o=this.evaluateWebResearchCompletion(e.finalText);if(o)return o}if(!this.isLocalSetupQuestion())return null;let s=[...this.localEvidence].reverse().find(o=>!o.success);if(!s||this.localEvidence.some(o=>o.iteration>=s.iteration&&o.success))return null;let r=e.finalText.trim();return!r||!Pe.test(r)||Ne.test(r)?null:{blocking:!0,message:["[Xeno evidence correction]","Do not claim the local tool/app/CLI is installed or working yet.",`The latest local verification command failed: ${s.command}`,s.summary?`Failure evidence: ${s.summary}`:null,"Next step: either run one robust local verification command that directly proves the claim, or answer that the launcher/path may exist but the CLI status is not confirmed.","Do not use web documentation as proof of what is installed on this machine."].filter(Boolean).join(`
|
|
16
|
+
`)}}evaluateWebResearchCompletion(e){let n=e.trim();if(!n)return null;let s=this.successfulWebFetches(),i=s.map(a=>a.url),r=Ge.test(n),o=i.some(a=>n.toLowerCase().includes(a.toLowerCase()));return s.length>0&&(!r||!o)?{blocking:!0,message:["[Xeno source-citation correction]","The answer uses web/documentation evidence but does not clearly cite the fetched source URL(s).",this.fetchedSourceSummary(),"Rewrite the final answer with a short Sources section using Markdown links like `Sources: [Title](url)`, then the requested sections. Do not run more tools unless a required detail is still missing."].join(`
|
|
17
|
+
`)}:null}isLocalSetupQuestion(){return Ie.test(this.taskPrompt)}totalWebResearchCalls(){return this.webSearches+this.webFetches}isOfficialResearchQuestion(){return De.test(this.taskPrompt)}isWebResearchQuestion(){return this.explicitResearchPrompt||Ue.test(this.taskPrompt)}successfulWebFetches(){return this.webFetchEvidence.filter(e=>e.success)}failedSpeculativeWebFetches(){return this.webFetchEvidence.filter(e=>!e.success&&$e.test(e.summary))}shouldStopOfficialResearch(){if(this.explicitResearchPrompt||this.hostWebBudget||!this.isOfficialResearchQuestion())return!1;let e=this.successfulWebFetches();return e.length>=this.minimumOfficialEvidenceFetches()?!0:e.length>=1&&this.failedSpeculativeWebFetches().length>=1}minimumOfficialEvidenceFetches(){let e=this.taskPrompt.toLowerCase(),n=/\binstall(?:ation)?|update|upgrade|version|verify\b/.test(e),s=/\binteractive|usage|using|agent\s+commands?|session|resume|flags?|shortcuts?\b/.test(e),i=/\bslash|reference|commands?\s+list|all\s+commands?\b/.test(e);return n&&s||i?Math.min(4,this.maxWebFetches):2}fetchedSourceSummary(){let e=this.successfulWebFetches().map(n=>n.url);return e.length===0?"No successful web fetch is recorded yet.":`Fetched source(s): ${e.join(", ")}`}blockedResult(e){return{success:!1,output:e.join(`
|
|
18
|
+
`),error:"Interactive turn guard blocked redundant, excessive, or unrequested tool use"}}evaluateArtifactClaims(e){let n=e.trim();if(!Fe.test(n)||Oe.test(n))return null;let s=this.artifactEvidence.filter(o=>o.status==="verified");if(s.length===0){let o=this.artifactEvidence.filter(a=>a.status==="failed");return{blocking:!0,message:["[Xeno artifact-evidence guard]","Do not claim that an artifact was created, saved, converted, or written without current verified artifact evidence.",o.length>0?`The latest postcondition evidence failed for: ${o.map(a=>a.path??a.operationId).join(", ")}.`:"No successful artifact postcondition is recorded in this turn.","Inspect the target, verify it is the expected file, and only then give the completion answer."].join(`
|
|
19
|
+
`)}}if(!Me.test(n))return null;let i=Math.max(...s.map(o=>o.iteration));return this.verificationRecords.some(o=>o.success&&o.iteration>=i&&s.some(a=>!a.path||o.inputValues.some(c=>$(c).includes($(a.path)))))?null:{blocking:!0,message:["[Xeno semantic-evidence guard]","File existence does not prove semantic claims such as page count, OCR absence, dimensions, metadata, or successful rendering.","Run one bounded verifier against the generated artifact and then report only the properties that verifier established."].join(`
|
|
20
|
+
`)}}findOverlappingTranscriptRead(e,n){if(!/^Read$/i.test(e))return null;let s=typeof n.file_path=="string"?n.file_path:"";if(!We.test(s))return null;let i=Math.max(0,Number.isFinite(n.offset)?Math.floor(Number(n.offset)):0),r=Math.max(1,Number.isFinite(n.limit)?Math.floor(Number(n.limit)):2e3),o=i+r,a=s.toLowerCase(),c=this.transcriptReadRanges.get(a)??[],d=c.find(l=>i<l.end&&o>l.start);return d?`${s}:${i}-${o} overlaps ${d.start}-${d.end}`:(c.push({start:i,end:o}),this.transcriptReadRanges.set(a,c),null)}};function Ke(t){return/^(?:Bash|Read|ReadImage|ElfAnalyze|NotebookRead)$/i.test(t)}var A=class{constructor(e={}){this.options=e}options;active=null;activePrompt=null;promptSection={name:"interactive-chat-answer-budget",order:20,provide:()=>this.activePrompt?I(this.activePrompt)?[`
|
|
22
21
|
|
|
23
22
|
<interactive_research_budget>`,"The user explicitly requested research. Gather enough primary evidence to answer the requested scope; do not treat this as a four-fetch quick lookup.","Start broad once, then fetch distinct targeted sources. For a public repository, prefer repository metadata, one recursive tree, and only the files needed for the answer.","Do not fetch duplicate representations of the same content or guess files already disproved by the repository tree.","Synthesize the answer once the evidence is sufficient. Tool limits preserve a separate tool-free final-answer turn.","</interactive_research_budget>"].join(`
|
|
24
23
|
`):R(this.activePrompt)?[`
|
|
25
24
|
|
|
26
25
|
<interactive_answer_budget>`,"This turn is a short informational question, not an implementation request.","Answer directly when the current context already contains the answer.","If local verification is genuinely needed, use one broad lookup and at most one targeted read, then answer.","Do not modify files, configuration, packages, processes, or repository state. Do not convert the question into an installation or workflow task.","</interactive_answer_budget>"].join(`
|
|
27
|
-
`):null:null};toolMiddleware=async(e,n)=>{let
|
|
28
|
-
`);let
|
|
29
|
-
`):null}function _t(t){return!yt.test(t)||!wt.test(t)||!kt.test(t)?null:["[xeno guidance]","This command appears to synthesize or overwrite a named/provided training dataset.","Do not replace CIFAR, MNIST, Yelp, C4, LMDB, or other task datasets with random, synthetic, dummy, or placeholder data to recover from a crash.","Fix the real data path instead: repair the download/extraction/conversion/dependency issue, remove corrupted partial outputs, and rerun only the failed stage with bounded resources."].join(`
|
|
30
|
-
`)}function St(t){return ft.test(t)}function Ct(){return{success:!1,output:["[Xeno benchmark Bash guard]",'Blocked a shell-eval-download command (eval "$(curl \xE2\u20AC\xA6)" / eval "$(wget \xE2\u20AC\xA6)").',"Piping remote content straight into a shell evaluator is unsafe and non-reproducible.","Download the artifact to a file with WebFetch or curl/wget, inspect it, then run the verified script explicitly."].join(`
|
|
31
|
-
`),error:"Benchmark Bash guard blocked a shell-eval-download command"}}function M(t={}){let e=t.benchmarkMode===!0;return async(n,i)=>{if(!Et(n.toolName))return i();let r=xt(n.input);if(!r)return i();if(St(r))return Ct();if(e){let s=At(r);s&&n.addGuidance(s);let a=_t(r);a&&n.addGuidance(a)}return i()}}var ne=`
|
|
32
|
-
|
|
33
|
-
`;function $t(t){let e=t.taskPrompt??"",n=t.benchmarkMode===!0,i=t.requiredOutputPaths??[],r=t.interactiveTurnGovernance===!1?null:new h(e,t.interactiveTurnGovernance??{}),a=(t.executionGovernance===!1?!1:t.executionGovernance===!0||k({taskPrompt:e,benchmarkMode:n,requiredOutputPaths:i}))?new v({taskPrompt:e,benchmarkMode:n,requiredOutputPaths:i}):null,o=a?.getSummary()??null,c=[];(r||a)&&c.push(async(l,u)=>{if(r){let F=r.maybeBlockToolCall({toolName:l.toolName,input:l.input,iteration:l.iteration});if(F)return F}let f=await u();return r&&r.recordToolResult({toolName:l.toolName,input:l.input,result:f,iteration:l.iteration}),a&&(a.recordToolResult({toolName:l.toolName,input:l.input,result:f,iteration:l.iteration}),o=a.getSummary(),t.onExecutionGovernanceUpdate?.(o)),f}),c.push(M({benchmarkMode:n}));let d=[];r&&d.push({name:"interactive-turn-governance",order:10,evaluate(l){let u=r.evaluateCompletion({finalText:l.finalText,iteration:l.iteration,stopReason:l.stopReason});return u?{allow:!1,guidance:u.message}:{allow:!0}}}),a&&d.push({name:"execution-governance",order:20,evaluate(l){let u=a.evaluateCompletion({finalText:l.finalText,iteration:l.iteration,stopReason:l.stopReason,messages:l.messages,maxIterations:l.maxIterations});if(o=a.getSummary(),t.onExecutionGovernanceUpdate?.(o),u.action==="complete"||!u.blocking)return{allow:!0};let f=u.action==="incomplete";return{allow:!1,guidance:u.message,stop:f}}});let m=[];return t.promptGuidance!==!1&&(m.push({name:"contract-ledger",order:100,provide(l){let u=x(l.taskPrompt??e);return u?`${ne}${u.replace(/^\n+/,"")}`:null}}),m.push({name:"project-execution",order:110,provide(l){let u=T(l.taskPrompt??e);return u?`${ne}${u.replace(/^\n+/,"")}`:null}})),{toolMiddleware:c,promptSections:m,completionGuards:d,getExecutionGovernanceSummary:()=>o}}export{v as ExecutionGovernance,P as InteractiveChatTurnGovernance,h as InteractiveTurnGovernance,x as buildContractLedgerGuidance,xe as buildProjectBudgetFinalizationGuidance,T as buildProjectExecutionGuidance,E as buildProjectExecutionProfile,M as createBenchBashMiddleware,$t as createGovernanceExtensions,N as isExplicitResearchPrompt,R as isSimpleInformationalPrompt,mt as resolveInteractiveTurnMaxIterations,k as shouldEnableExecutionGovernance};
|
|
26
|
+
`):null:null};toolMiddleware=async(e,n)=>{let s=this.active;if(!s)return n();let i=s.maybeBlockToolCall({toolName:e.toolName,input:e.input,iteration:e.iteration});if(i)return i;let r=await n();return s.recordToolResult({toolName:e.toolName,input:e.input,result:r,iteration:e.iteration}),r};completionGuard={name:"interactive-chat-turn-governance",order:10,evaluate:e=>{let n=this.active?.evaluateCompletion({finalText:e.finalText,iteration:e.iteration,stopReason:e.stopReason});return n?{allow:!1,guidance:n.message}:{allow:!0}}};beginTurn(e){this.activePrompt=e,this.active=new p(e,this.options)}endTurn(){this.active=null,this.activePrompt=null}};var Ye=String.raw`(?:^|[\n;&|]\s*|\(\s*)`,Ze=new RegExp(String.raw`${Ye}(?:timeout\s+\S+\s+)?(?:sudo\s+)?eval\s+(?:"|'|)?\$\(\s*(?:curl|wget)\b`,"i");function X(t){return Ze.test(t)}function Je(){return{success:!1,output:['Blocked: this command evaluates downloaded content directly in the shell (eval "$(curl ...)" or eval "$(wget ...)").',"Running remote content unseen is unsafe and cannot be reproduced.","Download it to a file, read it, then run the script explicitly."].join(`
|
|
27
|
+
`),error:"Blocked a command that evaluates downloaded content in the shell"}}function b(){return async(t,e)=>{if(!/^Bash$/i.test(t.toolName))return e();let n=typeof t.input.command=="string"?t.input.command.trim():"";return n&&X(n)?Je():e()}}function et(t){return""}function tt(t){return""}function nt(t){return""}function st(t){return{projectLike:!1,domains:[],phases:[],verifierRequirements:[],finalAuditItems:[]}}function it(t){return!0}function rt(t={}){return b()}function gt(t){let e=t.taskPrompt??"",n=t.requiredOutputPaths??[],s=t.interactiveTurnGovernance===!1?null:new p(e,t.interactiveTurnGovernance??{}),r=t.executionGovernance!==!1?new g({taskPrompt:e,requiredOutputPaths:n,...t.cwd?{cwd:t.cwd}:{}}):null,o=r?.getSummary()??null,a=[];(s||r)&&a.push(async(l,u)=>{if(s){let E=s.maybeBlockToolCall({toolName:l.toolName,input:l.input,iteration:l.iteration});if(E)return E}let h=await u();return s&&s.recordToolResult({toolName:l.toolName,input:l.input,result:h,iteration:l.iteration}),r&&(r.recordToolResult({toolName:l.toolName,input:l.input,result:h,iteration:l.iteration}),o=r.getSummary(),t.onExecutionGovernanceUpdate?.(o)),h}),a.push(b());let c=[];return s&&c.push({name:"interactive-turn-governance",order:10,evaluate(l){let u=s.evaluateCompletion({finalText:l.finalText,iteration:l.iteration,stopReason:l.stopReason});return u?{allow:!1,guidance:u.message}:{allow:!0}}}),r&&c.push({name:"execution-governance",order:20,evaluate(l){let u=r.evaluateCompletion({finalText:l.finalText,iteration:l.iteration,stopReason:l.stopReason,messages:l.messages,maxIterations:l.maxIterations});if(o=r.getSummary(),t.onExecutionGovernanceUpdate?.(o),u.action==="complete")return{allow:!0,...u.reason==="authoritative_validation_passed"||u.reason==="self_validation_passed"?{final:!0}:{}};if(!u.blocking)return{allow:!0};let h=u.action==="incomplete";return{allow:!1,guidance:u.message,stop:h,blocking:!h}}}),{toolMiddleware:a,promptSections:[],completionGuards:c,getExecutionGovernanceSummary:()=>o}}export{g as ExecutionGovernance,A as InteractiveChatTurnGovernance,p as InteractiveTurnGovernance,he as MAX_HOST_WEB_FETCHES_PER_TURN,de as MAX_HOST_WEB_SEARCHES_PER_TURN,et as buildContractLedgerGuidance,nt as buildProjectBudgetFinalizationGuidance,tt as buildProjectExecutionGuidance,st as buildProjectExecutionProfile,rt as createBenchBashMiddleware,gt as createGovernanceExtensions,b as createRemoteEvalGuard,L as findMissingRequiredOutputs,I as isExplicitResearchPrompt,X as isRemoteEvalCommand,R as isSimpleInformationalPrompt,me as parseWebResearchBudget,ze as resolveInteractiveTurnMaxIterations,it as shouldEnableExecutionGovernance};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"inputs":{"src/governance/
|
|
1
|
+
{"inputs":{"src/governance/execution-governance.ts":{"bytes":28939,"imports":[{"path":"node:fs","kind":"import-statement","external":true},{"path":"node:path","kind":"import-statement","external":true}],"format":"esm"},"src/governance/interactive-turn-governance.ts":{"bytes":41923,"imports":[],"format":"esm"},"src/governance/remote-eval-guard.ts":{"bytes":1669,"imports":[],"format":"esm"},"src/governance/deprecated.ts":{"bytes":2689,"imports":[{"path":"src/governance/remote-eval-guard.ts","kind":"import-statement","original":"./remote-eval-guard.js"}],"format":"esm"},"src/governance/index.ts":{"bytes":9749,"imports":[{"path":"src/governance/execution-governance.ts","kind":"import-statement","original":"./execution-governance.js"},{"path":"src/governance/interactive-turn-governance.ts","kind":"import-statement","original":"./interactive-turn-governance.js"},{"path":"src/governance/remote-eval-guard.ts","kind":"import-statement","original":"./remote-eval-guard.js"},{"path":"src/governance/execution-governance.ts","kind":"import-statement","original":"./execution-governance.js"},{"path":"src/governance/interactive-turn-governance.ts","kind":"import-statement","original":"./interactive-turn-governance.js"},{"path":"src/governance/remote-eval-guard.ts","kind":"import-statement","original":"./remote-eval-guard.js"},{"path":"src/governance/deprecated.ts","kind":"import-statement","original":"./deprecated.js"}],"format":"esm"}},"outputs":{"dist/governance/index.cjs":{"imports":[{"path":"node:fs","kind":"require-call","external":true},{"path":"node:path","kind":"require-call","external":true}],"exports":[],"entryPoint":"src/governance/index.ts","inputs":{"src/governance/index.ts":{"bytesInOutput":2224},"src/governance/execution-governance.ts":{"bytesInOutput":13606},"src/governance/interactive-turn-governance.ts":{"bytesInOutput":22452},"src/governance/remote-eval-guard.ts":{"bytesInOutput":725},"src/governance/deprecated.ts":{"bytesInOutput":227}},"bytes":40221}}}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"inputs":{"src/governance/
|
|
1
|
+
{"inputs":{"src/governance/execution-governance.ts":{"bytes":28939,"imports":[{"path":"node:fs","kind":"import-statement","external":true},{"path":"node:path","kind":"import-statement","external":true}],"format":"esm"},"src/governance/interactive-turn-governance.ts":{"bytes":41923,"imports":[],"format":"esm"},"src/governance/remote-eval-guard.ts":{"bytes":1669,"imports":[],"format":"esm"},"src/governance/deprecated.ts":{"bytes":2689,"imports":[{"path":"src/governance/remote-eval-guard.ts","kind":"import-statement","original":"./remote-eval-guard.js"}],"format":"esm"},"src/governance/index.ts":{"bytes":9749,"imports":[{"path":"src/governance/execution-governance.ts","kind":"import-statement","original":"./execution-governance.js"},{"path":"src/governance/interactive-turn-governance.ts","kind":"import-statement","original":"./interactive-turn-governance.js"},{"path":"src/governance/remote-eval-guard.ts","kind":"import-statement","original":"./remote-eval-guard.js"},{"path":"src/governance/execution-governance.ts","kind":"import-statement","original":"./execution-governance.js"},{"path":"src/governance/interactive-turn-governance.ts","kind":"import-statement","original":"./interactive-turn-governance.js"},{"path":"src/governance/remote-eval-guard.ts","kind":"import-statement","original":"./remote-eval-guard.js"},{"path":"src/governance/deprecated.ts","kind":"import-statement","original":"./deprecated.js"}],"format":"esm"}},"outputs":{"dist/governance/index.js":{"imports":[{"path":"node:fs","kind":"import-statement","external":true},{"path":"node:path","kind":"import-statement","external":true}],"exports":["ExecutionGovernance","InteractiveChatTurnGovernance","InteractiveTurnGovernance","MAX_HOST_WEB_FETCHES_PER_TURN","MAX_HOST_WEB_SEARCHES_PER_TURN","buildContractLedgerGuidance","buildProjectBudgetFinalizationGuidance","buildProjectExecutionGuidance","buildProjectExecutionProfile","createBenchBashMiddleware","createGovernanceExtensions","createRemoteEvalGuard","findMissingRequiredOutputs","isExplicitResearchPrompt","isRemoteEvalCommand","isSimpleInformationalPrompt","parseWebResearchBudget","resolveInteractiveTurnMaxIterations","shouldEnableExecutionGovernance"],"entryPoint":"src/governance/index.ts","inputs":{"src/governance/execution-governance.ts":{"bytesInOutput":13602},"src/governance/interactive-turn-governance.ts":{"bytesInOutput":22455},"src/governance/remote-eval-guard.ts":{"bytesInOutput":725},"src/governance/index.ts":{"bytesInOutput":1532},"src/governance/deprecated.ts":{"bytesInOutput":227}},"bytes":39185}}}
|