jeo-code 0.12.9 → 0.12.11

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.
@@ -258,14 +258,16 @@ export function subagentSystemPrompt(role: SubagentRole): string {
258
258
 
259
259
  /**
260
260
  * True when EVERY shell segment of `command` starts with one of `prefixes`
261
- * (after stripping leading env-assignments and a leading `sudo`). Splitting on
262
- * `; && || |` means a chained `… && rm -rf` cannot smuggle an un-vetted command
263
- * past a single allowed head. Command substitution (`$(…)`, backticks) can't be
264
- * statically vetted, so it is rejected outright. Empty allowlist = unconstrained.
261
+ * (after stripping leading env-assignments and a leading `sudo`). Only `&&`,
262
+ * `||`, `;`, and `|` chaining is understood; other shell operators, newlines,
263
+ * and substitutions are rejected rather than approximated. Empty allowlist =
264
+ * unconstrained.
265
265
  */
266
266
  export function bashCommandAllowed(command: string, prefixes: string[]): boolean {
267
267
  if (prefixes.length === 0) return true;
268
- if (/[`]|\$\(/.test(command)) return false; // un-vettable command substitution
268
+ if (/[$`]/.test(command)) return false; // un-vettable expansion/substitution
269
+ const unsupportedSyntax = command.replace(/&&|\|\||[;|]/g, "");
270
+ if (/[&<>(){}\\\r\n]/.test(unsupportedSyntax)) return false;
269
271
  const matches = (seg: string, p: string) =>
270
272
  seg === p || seg.startsWith(p + " ") || seg.startsWith(p + "\t");
271
273
  for (const raw of command.split(/(?:&&|\|\||[;|])/)) {
@@ -9,7 +9,7 @@
9
9
  * repo). Subagents are spawned with `subagentToolset(role)`, which never includes
10
10
  * `task` itself, so delegation cannot recurse infinitely.
11
11
  */
12
- import { runAgentLoop, isSafetyFallbackBail, stripSafetyFallbackTag, type ToolHandler } from "./engine";
12
+ import { runAgentLoop, isSafetyFallbackBail, stripSafetyFallbackTag, type AgentLoopResult, type ToolHandler } from "./engine";
13
13
  import { toolTarget } from "./step-budget";
14
14
 
15
15
  import type { ToolResult } from "./tools";
@@ -279,8 +279,11 @@ export interface RunSubagentOptions {
279
279
  modelOverride?: string;
280
280
  /** Stable detached id (from SubagentRegistry), attached to all emitted TaskSubEvents. */
281
281
  detachedId?: string;
282
+ /** SubagentRegistry to report live activity into (e.g. current tool or step). */
283
+ registry?: SubagentRegistry;
282
284
  }
283
285
 
286
+
284
287
  /** `runSubagentOnce`'s result — a superset of `ToolResult` exposing the raw
285
288
  * (unwrapped, unfenced) done reason and mutation-audit counters so a caller with
286
289
  * its OWN pass/fail policy on top (e.g. `jeo team`'s role-gate-verdict parsing and
@@ -288,6 +291,8 @@ export interface RunSubagentOptions {
288
291
  * report text. `task`/`subagent` tool callers only ever need `success`/`output`/
289
292
  * `error`, which stay structurally identical to plain `ToolResult`. */
290
293
  export interface SubagentRunResult extends ToolResult {
294
+ /** True when delegated execution observed a successful or potentially partial mutation. */
295
+ mutationMayHaveOccurred?: boolean;
291
296
  /** Raw subagent done reason, before contract validation or fencing. */
292
297
  doneReason: string;
293
298
  /** True when the subagent actually called `done` (vs. exhausting its step
@@ -297,7 +302,8 @@ export interface SubagentRunResult extends ToolResult {
297
302
  contractOk: boolean;
298
303
  /** Required markers missing from the done reason, when `contractOk` is false. */
299
304
  missingMarkers?: string[];
300
- /** Successful write/edit/mkdir/delete calls observed (mutation audit evidence). */
305
+ /** Successful workspace mutation calls observed (write/edit/mkdir/delete,
306
+ * ast_edit, or lsp_rename). */
301
307
  fileMutations: number;
302
308
  /** Successful bash calls observed (tracked apart — bash CAN mutate but isn't proof). */
303
309
  bashRuns: number;
@@ -329,7 +335,18 @@ export async function runSubagentOnce(
329
335
  const { steer, slot, detachedId, projectContext: preloadedContext, signal } = opts;
330
336
  // Tag every live event with its fan-out slot or detached ID so a parent monitor can tell
331
337
  // task 1 from task 3 or detached tasks apart when several subagents stream concurrently.
332
- const emit = (ev: TaskSubEvent) =>
338
+ const emit = (ev: TaskSubEvent) => {
339
+ if (detachedId && opts.registry) {
340
+ if (ev.kind === "tool") {
341
+ opts.registry.setActivity(detachedId, ev.detail ? `tool: ${ev.detail}` : "running tool");
342
+ } else if (ev.kind === "thinking") {
343
+ opts.registry.setActivity(detachedId, "thinking");
344
+ } else if (ev.kind === "step") {
345
+ opts.registry.setActivity(detachedId, ev.detail ? `step: ${ev.detail}` : "next step");
346
+ } else if (ev.kind === "done") {
347
+ opts.registry.setActivity(detachedId, undefined);
348
+ }
349
+ }
333
350
  opts.onEvent?.(
334
351
  detachedId
335
352
  ? { ...ev, detachedId }
@@ -337,6 +354,8 @@ export async function runSubagentOnce(
337
354
  ? { ...ev, index: slot.index, total: slot.total }
338
355
  : ev
339
356
  );
357
+ };
358
+
340
359
  const initialModel = opts.modelOverride || resolveSubagentModel(role.id, opts.config);
341
360
  const maxSteps = resolveSubagentMaxSteps(role.id, opts.config);
342
361
  // gjc parity: a role may pin its own reasoning budget; absent = inherit the
@@ -365,6 +384,9 @@ export async function runSubagentOnce(
365
384
  let fileMutations = 0;
366
385
  let bashRuns = 0;
367
386
  let readOnlyEvidenceCalls = 0;
387
+ // The engine's evidence signal is cumulative across tool batches and includes
388
+ // failed mutators whose handlers report that state may have changed.
389
+ let mutationMayHaveOccurred = false;
368
390
  // Per-run prompt-cache key: the subagent replays its own growing history each
369
391
  // step, so a stable key (even across a model switch below — a stale cache key
370
392
  // on a NEW provider is simply unused, never wrong) gets provider cache hits
@@ -454,6 +476,9 @@ export async function runSubagentOnce(
454
476
  tools: subagentToolset(role),
455
477
  ...(failoverEnabled ? { rateLimitFallbackAvailable, safetyFallbackAvailable } : {}),
456
478
  events: {
479
+ onEvidence: evidence => {
480
+ if (evidence.sawMutation) mutationMayHaveOccurred = true;
481
+ },
457
482
  onStep: n => { currentStep = n; },
458
483
  // Live reasoning preview (native extended-thinking models only — the JSON-protocol
459
484
  // "reasoning" field the main turn also extracts from onModelStream is intentionally
@@ -475,7 +500,7 @@ export async function runSubagentOnce(
475
500
  },
476
501
  onToolResult: (tool, success, output) => {
477
502
  if (success) {
478
- if (tool === "write" || tool === "edit" || tool === "mkdir" || tool === "delete") fileMutations++;
503
+ if (tool === "write" || tool === "edit" || tool === "mkdir" || tool === "delete" || tool === "ast_edit" || tool === "lsp_rename") fileMutations++;
479
504
  else if (tool === "bash") bashRuns++;
480
505
  else if (tool === "read" || tool === "search" || tool === "find" || tool === "ast_grep" || tool === "lsp") readOnlyEvidenceCalls++;
481
506
  }
@@ -496,12 +521,36 @@ export async function runSubagentOnce(
496
521
  });
497
522
  };
498
523
 
499
- let result = await runOnce();
524
+ const failureResult = (error: unknown): SubagentRunResult => {
525
+ const explicitSignal = typeof error === "object" && error !== null && "mutationMayHaveOccurred" in error && error.mutationMayHaveOccurred === true;
526
+ const message = error instanceof Error ? error.message : String(error);
527
+ return {
528
+ success: false,
529
+ output: "",
530
+ error: message,
531
+ doneReason: message,
532
+ done: false,
533
+ contractOk: false,
534
+ fileMutations,
535
+ bashRuns,
536
+ readOnlyEvidenceCalls,
537
+ mutationMayHaveOccurred: mutationMayHaveOccurred || explicitSignal || (!role.readOnly ? true : undefined),
538
+ };
539
+ };
540
+ const runSafely = async (): Promise<{ ok: true; result: AgentLoopResult } | { ok: false; error: unknown }> => {
541
+ try {
542
+ return { ok: true, result: await runOnce() };
543
+ } catch (error: unknown) {
544
+ return { ok: false, error };
545
+ }
546
+ };
547
+ let outcome = await runSafely();
548
+ if (!outcome.ok) return failureResult(outcome.error);
549
+ let result = outcome.result;
500
550
  // `routing.enabled` off = the model is FIXED: no failover reroute at all (the
501
551
  // engine bail predicates above are withheld too, so a 429 rides its normal
502
552
  // backoff ladder instead of bailing early with nowhere to go).
503
- for (let attempt = 0; failoverEnabled && attempt < MAX_SUBAGENT_REROUTES; attempt++) {
504
- const rateLimited = !result.done && isRateLimitError(new Error(result.doneReason ?? ""));
553
+ for (let attempt = 0; failoverEnabled && attempt < MAX_SUBAGENT_REROUTES; attempt++) { const rateLimited = !result.done && isRateLimitError(new Error(result.doneReason ?? ""));
505
554
  const safetyBail = !result.done && !rateLimited && isSafetyFallbackBail(result.doneReason);
506
555
  if (!rateLimited && !safetyBail) break;
507
556
  const previousModel = activeModel;
@@ -526,7 +575,9 @@ export async function runSubagentOnce(
526
575
  emit({ role: role.id, kind: "step", detail: `↳ refused on '${previousModel}' — switching to '${activeModel}' in case of a classifier false positive`, step: currentStep, maxSteps, model: activeModel });
527
576
  }
528
577
  attemptedModels.add(activeModel);
529
- result = await runOnce();
578
+ outcome = await runSafely();
579
+ if (!outcome.ok) return failureResult(outcome.error);
580
+ result = outcome.result;
530
581
  }
531
582
 
532
583
  const reason = stripSafetyFallbackTag(result.doneReason?.trim() || "") || `(subagent reached the ${result.steps}-step limit without signaling done)`;
@@ -543,8 +594,8 @@ export async function runSubagentOnce(
543
594
  // "verify independently" instead of the stronger UNVERIFIED.
544
595
  const audit = complete && !role.readOnly && fileMutations === 0
545
596
  ? bashRuns === 0
546
- ? `\n[parent audit] No successful write/edit/bash was observed in this run — treat any "Changed Files:" claims above as UNVERIFIED.`
547
- : `\n[parent audit] No successful write/edit was observed (only bash ran); bash may or may not have mutated files — verify any "Changed Files:" claims above independently.`
597
+ ? `\n[parent audit] No successful workspace mutation or bash call was observed in this run — treat any "Changed Files:" claims above as UNVERIFIED.`
598
+ : `\n[parent audit] No successful workspace mutation was observed (only bash ran); bash may or may not have mutated files — verify any "Changed Files:" claims above independently.`
548
599
  : "";
549
600
  return {
550
601
  success: complete,
@@ -556,6 +607,7 @@ export async function runSubagentOnce(
556
607
  fileMutations,
557
608
  bashRuns,
558
609
  readOnlyEvidenceCalls,
610
+ mutationMayHaveOccurred,
559
611
  };
560
612
  }
561
613
 
@@ -585,8 +637,10 @@ export function createTaskTool(opts: TaskToolOptions): ToolHandler {
585
637
  modelOverride?: string;
586
638
  /** Stable detached id from SubagentRegistry. */
587
639
  detachedId?: string;
640
+ /** SubagentRegistry to report live activity into. */
641
+ registry?: SubagentRegistry;
588
642
  } = {},
589
- ): Promise<ToolResult> =>
643
+ ): Promise<SubagentRunResult> =>
590
644
  runSubagentOnce(role, taskText, context, cwd, {
591
645
  config: opts.config,
592
646
  signal: extra.signal ?? opts.signal,
@@ -597,8 +651,10 @@ export function createTaskTool(opts: TaskToolOptions): ToolHandler {
597
651
  excludedCredentialScopes: extra.excludedCredentialScopes,
598
652
  modelOverride: extra.modelOverride,
599
653
  detachedId: extra.detachedId,
654
+ registry: extra.registry,
600
655
  });
601
656
 
657
+
602
658
  return async (args: Record<string, any>, cwd: string): Promise<ToolResult> => {
603
659
  const roleArg = typeof args.role === "string" ? args.role.trim() : "";
604
660
  const role = roleArg ? getSubagentRole(roleArg, opts.config) : defaultSubagentRole();
@@ -689,7 +745,7 @@ export function createTaskTool(opts: TaskToolOptions): ToolHandler {
689
745
  // `executor`'s single resolved model), so the first worker to exclude a
690
746
  // scope saves every sibling worker the same wasted round.
691
747
  const batchExcludedScopes = new Set<string>();
692
- const results: ToolResult[] = new Array(items.length);
748
+ const results: SubagentRunResult[] = new Array(items.length);
693
749
  let next = 0;
694
750
  // #7: broadcast steering hub — each concurrent worker sees every parent
695
751
  // steer message exactly once (safe even for parallel read-only fan-out).
@@ -714,7 +770,11 @@ export function createTaskTool(opts: TaskToolOptions): ToolHandler {
714
770
  const ok = results.filter(r => r.success).length;
715
771
  const head = `[${role.title} fan-out] ${ok}/${items.length} completed (concurrency ${limit}).`;
716
772
  const combined = results.map((r, i) => `### Task ${i + 1}/${items.length}\n${r.output}`).join("\n\n");
717
- return { success: ok === items.length, output: `${head}\n\n${combined}` };
773
+ return {
774
+ success: ok === items.length,
775
+ output: `${head}\n\n${combined}`,
776
+ mutationMayHaveOccurred: results.some(r => r.mutationMayHaveOccurred === true),
777
+ };
718
778
  }
719
779
 
720
780
  // Single-task form.
@@ -728,8 +788,15 @@ export function createTaskTool(opts: TaskToolOptions): ToolHandler {
728
788
  // its own registry inbox (registry.steerDrainFor(id)) between its own steps.
729
789
  if (args.detached === true && opts.registry) {
730
790
  const rec = opts.registry.launch(role.id, taskText, (signal, id) =>
731
- runOne(role, taskText, ctx(args.context), cwd, { signal, steer: opts.registry!.steerDrainFor(id), detachedId: id }),
791
+ runOne(role, taskText, ctx(args.context), cwd, {
792
+ signal,
793
+ steer: opts.registry!.steerDrainFor(id),
794
+ detachedId: id,
795
+ registry: opts.registry,
796
+ }),
797
+ { readOnly: role.readOnly },
732
798
  );
799
+
733
800
  // Remote subagent visibility/control over Telegram (gjc daemon parity, see
734
801
  // `src/agent/notify/`): best-effort, no-op unless `notifications.enabled`.
735
802
  ensureSessionNotifyEndpoint(opts.registry, cwd, opts.sessionEndpoint);
@@ -739,6 +806,10 @@ export function createTaskTool(opts: TaskToolOptions): ToolHandler {
739
806
  output:
740
807
  `[detached] launched ${role.title} subagent '${rec.id}'. It runs in the background — ` +
741
808
  `keep working, then use the 'subagent' tool ({action:"await"|"list"|"inspect"|"cancel", ids?}) to collect its result.`,
809
+ // A mutating detached run may change the workspace after this tool returns;
810
+ // surface that possibility immediately so the parent cannot claim a clean
811
+ // workspace before collecting and verifying the settled result.
812
+ mutationMayHaveOccurred: role.readOnly ? undefined : true,
742
813
  };
743
814
  }
744
815
  return runOne(role, taskText, ctx(args.context), cwd, { steer: opts.steer });
@@ -26,6 +26,8 @@ export interface ToolResult {
26
26
  success: boolean;
27
27
  output: string;
28
28
  error?: string;
29
+ /** Failed operations set this when an attempted filesystem write may have partially changed state. */
30
+ mutationMayHaveOccurred?: boolean;
29
31
  }
30
32
 
31
33
  /**
@@ -315,18 +317,20 @@ export async function writeTool(
315
317
  content: string,
316
318
  cwd: string = process.cwd()
317
319
  ): Promise<ToolResult> {
320
+ let mutationMayHaveOccurred = false;
318
321
  try {
319
322
  if (typeof filePath !== "string" || filePath.trim() === "") {
320
323
  return { success: false, output: "", error: 'write requires a non-empty "filePath".' };
321
324
  }
322
325
  await assertMutationAllowed(filePath, cwd);
323
326
  const absPath = path.resolve(cwd, filePath);
327
+ mutationMayHaveOccurred = true;
324
328
  await fs.mkdir(path.dirname(absPath), { recursive: true });
325
329
  await fs.writeFile(absPath, content, "utf-8");
326
330
  markRead(absPath); // own change counts as having seen the file
327
331
  return { success: true, output: `Successfully wrote ${content.length} characters to ${filePath}` };
328
332
  } catch (err: any) {
329
- return { success: false, output: "", error: err.message };
333
+ return { success: false, output: "", error: err.message, mutationMayHaveOccurred };
330
334
  }
331
335
  }
332
336
 
@@ -363,6 +367,7 @@ export async function editTool(
363
367
  editBlock: string,
364
368
  cwd: string = process.cwd()
365
369
  ): Promise<ToolResult> {
370
+ let mutationMayHaveOccurred = false;
366
371
  try {
367
372
  if (typeof filePath !== "string" || filePath.trim() === "") {
368
373
  return { success: false, output: "", error: 'edit requires a non-empty "filePath".' };
@@ -582,11 +587,12 @@ export async function editTool(
582
587
  };
583
588
  }
584
589
 
590
+ mutationMayHaveOccurred = true;
585
591
  await fs.writeFile(absPath, content, "utf-8");
586
592
  markRead(absPath); // own change counts as having seen the file
587
593
  return { success: true, output: `Successfully updated ${filePath}` };
588
594
  } catch (err: any) {
589
- return { success: false, output: "", error: err.message };
595
+ return { success: false, output: "", error: err.message, mutationMayHaveOccurred };
590
596
  }
591
597
  }
592
598
 
@@ -1079,6 +1085,7 @@ export async function mkdirTool(
1079
1085
  dirPath: string,
1080
1086
  cwd: string = process.cwd()
1081
1087
  ): Promise<ToolResult> {
1088
+ let mutationMayHaveOccurred = false;
1082
1089
  try {
1083
1090
  if (typeof dirPath !== "string" || dirPath.trim() === "") {
1084
1091
  return { success: false, output: "", error: 'mkdir requires a non-empty "dirPath".' };
@@ -1089,10 +1096,11 @@ export async function mkdirTool(
1089
1096
  if (existing && !existing.isDirectory()) {
1090
1097
  return { success: false, output: "", error: `Path exists and is not a directory: ${dirPath}` };
1091
1098
  }
1099
+ mutationMayHaveOccurred = true;
1092
1100
  await fs.mkdir(abs, { recursive: true });
1093
1101
  return { success: true, output: `Directory ready: ${dirPath}` };
1094
1102
  } catch (err: any) {
1095
- return { success: false, output: "", error: err.message };
1103
+ return { success: false, output: "", error: err.message, mutationMayHaveOccurred };
1096
1104
  }
1097
1105
  }
1098
1106
 
@@ -1108,6 +1116,7 @@ export async function deleteTool(
1108
1116
  cwd: string = process.cwd(),
1109
1117
  recursive: boolean = false
1110
1118
  ): Promise<ToolResult> {
1119
+ let mutationMayHaveOccurred = false;
1111
1120
  try {
1112
1121
  if (typeof targetPath !== "string" || targetPath.trim() === "") {
1113
1122
  return { success: false, output: "", error: 'delete requires a non-empty "path".' };
@@ -1124,11 +1133,12 @@ export async function deleteTool(
1124
1133
  if (st.isDirectory() && !recursive) {
1125
1134
  return { success: false, output: "", error: `${targetPath} is a directory — pass recursive:true to remove it and its contents.` };
1126
1135
  }
1136
+ mutationMayHaveOccurred = true;
1127
1137
  await fs.rm(abs, { recursive, force: false });
1128
1138
  readThisSession.delete(abs); // a future edit against this path must read it again first
1129
1139
  return { success: true, output: `Deleted ${st.isDirectory() ? "directory" : "file"}: ${targetPath}` };
1130
1140
  } catch (err: any) {
1131
- return { success: false, output: "", error: err.message };
1141
+ return { success: false, output: "", error: err.message, mutationMayHaveOccurred };
1132
1142
  }
1133
1143
  }
1134
1144
 
package/src/cli.ts CHANGED
@@ -49,6 +49,7 @@ process.on("unhandledRejection", fatal);
49
49
  process.stdout.on("error", fatal);
50
50
  process.stderr.on("error", fatal);
51
51
 
52
+
52
53
  try {
53
54
  const code = await dispatch(process.argv.slice(2), { appName: APP_NAME, version: VERSION });
54
55
  if (code !== 0) process.exit(code);
@@ -252,12 +252,13 @@ export const TOOL_DESCRIPTIONS: Record<string, string> = {
252
252
  find: "find {globPattern} — find files by name",
253
253
  search: "search {pattern, globPattern?, ignoreCase?, context?, maxMatches?} — grep (context: N lines around each match)",
254
254
  ls: "ls {dirPath} — list a directory's entries (dirs first)",
255
+ computer: "computer {action, x?, y?, text?, key?, deltaX?, deltaY?, duration?, actions?} — desktop automation (screenshot, click, double_click, move, drag, scroll, type, keypress, wait, batch)",
255
256
  };
256
257
 
257
258
  export function buildToolProtocol(allowedTools: Set<string>): string {
258
259
  const lines: string[] = ["You have these tools (call exactly ONE per step):"];
259
260
  let num = 1;
260
- for (const name of ["read", "write", "edit", "bash", "find", "search", "ls"]) {
261
+ for (const name of ["read", "write", "edit", "bash", "find", "search", "ls", "computer"]) {
261
262
  if (allowedTools.has(name)) {
262
263
  lines.push(`${num}. ${TOOL_DESCRIPTIONS[name]}`);
263
264
  num++;