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.
@@ -168,8 +168,14 @@ export interface TeamEngineOptions {
168
168
  * write/edit/bash fails the task instead of merely warning (round-11). */
169
169
  strictMutations?: boolean;
170
170
  }
171
+ export interface TeamEngineResult {
172
+ ok: boolean;
173
+ reason?: string;
174
+ /** True when a delegated child may have changed workspace state before settling. */
175
+ mutationMayHaveOccurred?: boolean;
176
+ }
171
177
 
172
- export async function runTeamEngine(opts: TeamEngineOptions = {}): Promise<{ ok: boolean; reason?: string }> {
178
+ export async function runTeamEngine(opts: TeamEngineOptions = {}): Promise<TeamEngineResult> {
173
179
  const cwd = opts.cwd ?? process.cwd();
174
180
 
175
181
  const log = (msg?: any) => {
@@ -339,6 +345,7 @@ export async function runTeamEngine(opts: TeamEngineOptions = {}): Promise<{ ok:
339
345
 
340
346
  await writeWorkflowState("team", teamState, cwd);
341
347
  const renderOpts: RalphRenderOptions = { color: !!process.stdout.isTTY, indexed: true };
348
+ let mutationMayHaveOccurred = false;
342
349
  for (const line of formatRalphTodoGuide(tasks, activeStepIndex(tasks.length, teamState.pending_tasks), teamState.completed_tasks ?? [], renderOpts)) log(line);
343
350
 
344
351
  while (teamState.pending_tasks && teamState.pending_tasks.length > 0) {
@@ -384,20 +391,22 @@ export async function runTeamEngine(opts: TeamEngineOptions = {}): Promise<{ ok:
384
391
  });
385
392
 
386
393
  if (opts.signal?.aborted) {
387
- return { ok: false, reason: "aborted" };
394
+ return { ok: false, reason: "aborted", ...(mutationMayHaveOccurred ? { mutationMayHaveOccurred: true } : {}) };
388
395
  }
389
396
 
390
397
  if (groupResult.ok) {
398
+ mutationMayHaveOccurred ||= groupResult.mutationMayHaveOccurred === true;
391
399
  teamState.completed_tasks = [...(teamState.completed_tasks ?? []), ...groupSteps.map(s => s.name)];
392
400
  teamState.pending_tasks = teamState.pending_tasks.slice(groupSteps.length);
393
401
  await writeWorkflowState("team", teamState, cwd);
394
402
  log(`${categoryBadge("done")} Completed parallel group: ${groupSteps.map(s => `"${s.name}"`).join(", ")}`);
395
403
  } else {
404
+ mutationMayHaveOccurred ||= groupResult.mutationMayHaveOccurred === true;
396
405
  teamState.current_phase = "failed";
397
406
  teamState.failed_task = groupResult.failedTaskName;
398
407
  await writeWorkflowState("team", teamState, cwd);
399
408
  log(`${categoryBadge("error")} Failed on parallel group step: "${groupResult.failedTaskName}". Halting execution.`);
400
- return { ok: false, reason: `Failed on task: "${groupResult.failedTaskName}"` };
409
+ return { ok: false, reason: `Failed on task: "${groupResult.failedTaskName}"`, ...(mutationMayHaveOccurred ? { mutationMayHaveOccurred: true } : {}) };
401
410
  }
402
411
  continue;
403
412
  }
@@ -409,7 +418,7 @@ export async function runTeamEngine(opts: TeamEngineOptions = {}): Promise<{ ok:
409
418
  opts.onProgress({ skill: "team", phase: "executing", detail: `Current task: ${currentTask}` });
410
419
  }
411
420
 
412
- const success = await executeTaskWithAgent({
421
+ const taskResult = await executeTaskWithAgent({
413
422
  task: currentTask,
414
423
  tasks,
415
424
  activeIndex,
@@ -419,12 +428,13 @@ export async function runTeamEngine(opts: TeamEngineOptions = {}): Promise<{ ok:
419
428
  strictMutations: opts.strictMutations ?? false,
420
429
  log,
421
430
  });
431
+ mutationMayHaveOccurred ||= taskResult.mutationMayHaveOccurred === true;
422
432
 
423
433
  if (opts.signal?.aborted) {
424
- return { ok: false, reason: "aborted" };
434
+ return { ok: false, reason: "aborted", ...(mutationMayHaveOccurred ? { mutationMayHaveOccurred: true } : {}) };
425
435
  }
426
436
 
427
- if (success) {
437
+ if (taskResult.ok) {
428
438
  teamState.completed_tasks = [...(teamState.completed_tasks ?? []), currentTask];
429
439
  teamState.pending_tasks = teamState.pending_tasks.slice(1);
430
440
  await writeWorkflowState("team", teamState, cwd);
@@ -436,7 +446,7 @@ export async function runTeamEngine(opts: TeamEngineOptions = {}): Promise<{ ok:
436
446
  teamState.failed_task = currentTask;
437
447
  await writeWorkflowState("team", teamState, cwd);
438
448
  log(`${categoryBadge("error")} Failed on task: "${currentTask}". Halting execution.`);
439
- return { ok: false, reason: `Failed on task: "${currentTask}"` };
449
+ return { ok: false, reason: `Failed on task: "${currentTask}"`, ...(mutationMayHaveOccurred ? { mutationMayHaveOccurred: true } : {}) };
440
450
  }
441
451
  }
442
452
 
@@ -450,7 +460,7 @@ export async function runTeamEngine(opts: TeamEngineOptions = {}): Promise<{ ok:
450
460
  opts.onProgress({ skill: "team", phase: "complete" });
451
461
  }
452
462
  }
453
- return { ok: true };
463
+ return { ok: true, ...(mutationMayHaveOccurred ? { mutationMayHaveOccurred: true } : {}) };
454
464
  } finally {
455
465
  await releaseLock();
456
466
  }
@@ -464,7 +474,11 @@ export async function runTeamCommand(args: string[] = []): Promise<void> {
464
474
  }
465
475
  }
466
476
 
467
- async function executeTaskWithAgent(ctx: RalphSubagentPromptContext & { cwd: string; roleId?: string; strictMutations?: boolean; log: (line: string) => void }): Promise<boolean> {
477
+ interface TeamTaskResult {
478
+ ok: boolean;
479
+ mutationMayHaveOccurred?: boolean;
480
+ }
481
+ async function executeTaskWithAgent(ctx: RalphSubagentPromptContext & { cwd: string; roleId?: string; strictMutations?: boolean; log: (line: string) => void }): Promise<TeamTaskResult> {
468
482
  const log = ctx.log;
469
483
  const config = await readGlobalConfig();
470
484
  const role = getSubagentRole(ctx.roleId, config) ?? defaultSubagentRole();
@@ -476,25 +490,33 @@ async function executeTaskWithAgent(ctx: RalphSubagentPromptContext & { cwd: str
476
490
  const projectContext = await loadProjectContext(ctx.cwd);
477
491
 
478
492
  // `jeo team` now runs every step through the SAME execution core as the `task`/
479
- // `subagent` tools (`runSubagentOnce`) — one way a jeo-code subagent runs,
480
- // whether launched interactively, in a fan-out batch, detached, or as a team
481
- // plan step. This gets team plan steps the same fenced-report protection
482
- // (prompt-injection-safe) and done-reason contract validation the interactive
483
- // tools already had, instead of a second hand-rolled copy of that logic.
484
- const result = await runSubagentOnce(role, buildRalphSubagentPrompt(ctx), "", ctx.cwd, {
485
- config,
486
- projectContext,
487
- onEvent: ev => {
488
- if (ev.kind === "step") {
489
- log(formatRalphStreamEvent("step", ev.detail ?? `${role.title} thinking ${ev.step ?? "?"}/${ev.maxSteps ?? maxSteps}`, renderOpts));
490
- } else if (ev.kind === "tool") {
491
- const suffix = ev.summary ? ` — ${ev.summary}` : "";
492
- log(formatRalphStreamEvent(ev.success ? "complete" : "error", `tool ${ev.detail}${suffix}`, renderOpts));
493
- }
494
- },
495
- });
493
+ // `subagent` tools — one way a jeo-code subagent runs, whether launched
494
+ // interactively, in a fan-out batch, detached, or as a team plan step.
495
+ let result: SubagentRunResult;
496
+ try {
497
+ result = await runSubagentOnce(role, buildRalphSubagentPrompt(ctx), "", ctx.cwd, {
498
+ config,
499
+ projectContext,
500
+ onEvent: ev => {
501
+ if (ev.kind === "step") {
502
+ log(formatRalphStreamEvent("step", ev.detail ?? `${role.title} thinking ${ev.step ?? "?"}/${ev.maxSteps ?? maxSteps}`, renderOpts));
503
+ } else if (ev.kind === "tool") {
504
+ const suffix = ev.summary ? ` — ${ev.summary}` : "";
505
+ log(formatRalphStreamEvent(ev.success ? "complete" : "error", `tool ${ev.detail}${suffix}`, renderOpts));
506
+ }
507
+ },
508
+ });
509
+ } catch (error: unknown) {
510
+ const explicitSignal = typeof error === "object" && error !== null && "mutationMayHaveOccurred" in error && error.mutationMayHaveOccurred === true;
511
+ const message = error instanceof Error ? error.message : String(error);
512
+ log(formatRalphStreamEvent("error", message, renderOpts));
513
+ return { ok: false, ...(explicitSignal || !role.readOnly ? { mutationMayHaveOccurred: true } : {}) };
514
+ }
496
515
 
497
- return evaluateSubagentResult(result, role, ctx.strictMutations ?? false, log, renderOpts);
516
+ return {
517
+ ok: evaluateSubagentResult(result, role, ctx.strictMutations ?? false, log, renderOpts),
518
+ ...(result.mutationMayHaveOccurred ? { mutationMayHaveOccurred: true } : {}),
519
+ };
498
520
  }
499
521
 
500
522
  /**
@@ -543,23 +565,14 @@ function evaluateSubagentResult(
543
565
  return false;
544
566
  }
545
567
 
546
- // Round-8: a mutating role finished without a successful file mutation — the
547
- // task may be legitimately read-only, but its "Changed Files:" claim is
548
- // unverified. bash is tracked apart: an only-bash run MIGHT have mutated.
568
+ // A mutating role's changed-files claim needs an observed workspace mutation.
569
+ // Bash is separate because it may or may not have changed files.
549
570
  if (!role.readOnly && result.fileMutations === 0) {
550
571
  const msg = result.bashRuns === 0
551
- ? `${role.title} completed WITHOUT any successful write/edit/bash — treat its changed-files claim as unverified.`
552
- : `${role.title} completed with only bash (no write/edit) — verify its changed-files claim independently.`;
553
- // Round-11: under --strict-mutations, a mutating role that took NO action at
554
- // all (no write/edit/bash) is a hard failure — an empty run must not pass as
555
- // a completed task. bash-only stays advisory to avoid penalizing shell edits.
556
- const hardFail = strictMutations && result.bashRuns === 0;
557
- // Round-12: separate the tones so a passing advisory run doesn't masquerade
558
- // as a stream:error — only a real hard-fail is red; an advisory note is warn.
559
- log(formatRalphStreamEvent(hardFail ? "error" : "warn", msg, renderOpts));
560
- if (hardFail) {
561
- return false;
562
- }
572
+ ? `${role.title} completed WITHOUT any successful workspace mutation or bash call — treat its changed-files claim as unverified.`
573
+ : `${role.title} completed without a successful workspace mutation (only bash ran) — verify its changed-files claim independently.`;
574
+ log(formatRalphStreamEvent(strictMutations ? "error" : "warn", msg, renderOpts));
575
+ if (strictMutations && result.bashRuns === 0) return false;
563
576
  }
564
577
 
565
578
  // Surface the subagent's full report (header + step trace + fenced reason +
@@ -610,7 +623,7 @@ async function runParallelGroup(
610
623
  log: (line: string) => void;
611
624
  slug: string;
612
625
  },
613
- ): Promise<{ ok: true } | { ok: false; failedTaskName: string }> {
626
+ ): Promise<{ ok: true; mutationMayHaveOccurred?: boolean } | { ok: false; failedTaskName: string; mutationMayHaveOccurred?: boolean }> {
614
627
  const { cwd, teamCfg, tasks, completed, strictMutations, log, slug } = ctx;
615
628
  const renderOpts: RalphRenderOptions = { color: !!process.stdout.isTTY, indexed: true };
616
629
 
@@ -654,16 +667,22 @@ async function runParallelGroup(
654
667
  }
655
668
  },
656
669
  });
657
- // Capture the FULL SubagentRunResult (doneReason/fileMutations/etc.) before
658
- // collapsing it to the plain ToolResult shape SubagentRegistry stores.
670
+ // Capture the FULL SubagentRunResult before collapsing it to the plain
671
+ // ToolResult shape SubagentRegistry stores, including mutation evidence.
659
672
  resultsByIndex.set(step.index, result);
660
- return { success: result.success, output: result.output, error: result.error };
661
- });
673
+ return {
674
+ success: result.success,
675
+ output: result.output,
676
+ error: result.error,
677
+ mutationMayHaveOccurred: result.mutationMayHaveOccurred,
678
+ };
679
+ }, { readOnly: role.readOnly });
662
680
  idByIndex.set(step.index, record.id);
663
681
  }
664
682
 
665
683
  // No timeout — team runs can take as long as needed.
666
684
  await registry.awaitIds([...idByIndex.values()]);
685
+ const registryMutation = registry.list().some(record => record.mutationMayHaveOccurred === true);
667
686
 
668
687
  // Evaluate + commit each successful worktree, IN ARRAY ORDER (not completion
669
688
  // order). Any failure stops the whole group immediately: no merges happen,
@@ -674,12 +693,12 @@ async function runParallelGroup(
674
693
  const wt = worktreeByIndex.get(step.index)!;
675
694
  if (!result) {
676
695
  log(formatRalphStreamEvent("error", `[${step.name}] subagent produced no result`, renderOpts));
677
- return { ok: false, failedTaskName: step.name };
696
+ return { ok: false, failedTaskName: step.name, ...(registryMutation ? { mutationMayHaveOccurred: true } : {}) };
678
697
  }
679
698
  const success = evaluateSubagentResult(result, role, strictMutations, log, renderOpts);
680
699
  if (!success) {
681
700
  log(`${categoryBadge("error")} Parallel group step "${step.name}" failed — its worktree (${wt.path}) and the OTHER group worktrees are left in place for inspection; nothing was merged.`);
682
- return { ok: false, failedTaskName: step.name };
701
+ return { ok: false, failedTaskName: step.name, ...(registryMutation || result.mutationMayHaveOccurred ? { mutationMayHaveOccurred: true } : {}) };
683
702
  }
684
703
  // An empty diff (read-only role, or a no-op) needs no commit — skip it for
685
704
  // the merge step below without treating it as an error.
@@ -687,12 +706,12 @@ async function runParallelGroup(
687
706
  const add = runGitSync(wt.path, ["add", "-A"]);
688
707
  if (!add.ok) {
689
708
  log(`${categoryBadge("error")} Failed to stage changes in worktree ${wt.path} for step "${step.name}": ${add.stderr.trim()}`);
690
- return { ok: false, failedTaskName: step.name };
709
+ return { ok: false, failedTaskName: step.name, ...(registryMutation ? { mutationMayHaveOccurred: true } : {}) };
691
710
  }
692
711
  const commit = runGitSync(wt.path, ["commit", "-m", step.name]);
693
712
  if (!commit.ok) {
694
713
  log(`${categoryBadge("error")} Failed to commit changes in worktree ${wt.path} for step "${step.name}": ${commit.stderr.trim()}`);
695
- return { ok: false, failedTaskName: step.name };
714
+ return { ok: false, failedTaskName: step.name, ...(registryMutation ? { mutationMayHaveOccurred: true } : {}) };
696
715
  }
697
716
  }
698
717
  }
@@ -710,7 +729,7 @@ async function runParallelGroup(
710
729
  `the merge was aborted automatically (no changes were auto-resolved). Resolve manually: ` +
711
730
  `cd ${wt.path} to inspect the change, then run 'git merge ${wt.branch}' yourself from ${cwd}.\n${(merge.stderr + merge.stdout).trim()}`,
712
731
  );
713
- return { ok: false, failedTaskName: step.name };
732
+ return { ok: false, failedTaskName: step.name, ...(registryMutation ? { mutationMayHaveOccurred: true } : {}) };
714
733
  }
715
734
  log(`${categoryBadge("done")} Merged step "${step.name}" (branch ${wt.branch}) into the current branch.`);
716
735
  }
@@ -725,5 +744,5 @@ async function runParallelGroup(
725
744
  }
726
745
  }
727
746
 
728
- return { ok: true };
747
+ return { ok: true, ...(registryMutation ? { mutationMayHaveOccurred: true } : {}) };
729
748
  }
@@ -12,6 +12,7 @@ const TOOLS: Record<string, true> = {
12
12
  bash: true,
13
13
  edit: true,
14
14
  write: true,
15
+ computer: true,
15
16
  };
16
17
 
17
18
  function object(value: unknown, label: string): Record<string, unknown> {
@@ -60,9 +61,11 @@ export function resolveMessengerToken(
60
61
  return undefined;
61
62
  }
62
63
 
64
+ export const DEFAULT_MESSENGER_TOOLS = ["read", "find", "search", "write", "edit", "bash", "computer"];
65
+
63
66
  export function parseMessengerConfig(value: unknown, baseDir: string): MessengerConfig {
64
67
  const input = object(value, "Messenger config");
65
- keys(input, ["cwd", "sessionDir", "toolNames", "platforms"], "Messenger config");
68
+ keys(input, ["cwd", "sessionDir", "toolNames", "platforms", "independentSessions"], "Messenger config");
66
69
  const platformsInput = object(input.platforms, "platforms");
67
70
  keys(platformsInput, PLATFORMS, "platforms");
68
71
  if (Object.keys(platformsInput).length === 0) throw new Error("At least one messenger platform is required");
@@ -97,14 +100,15 @@ export function parseMessengerConfig(value: unknown, baseDir: string): Messenger
97
100
  }
98
101
  platforms[platform] = config;
99
102
  }
100
- const toolNames = input.toolNames === undefined ? [] : input.toolNames;
103
+ const toolNames = input.toolNames === undefined ? DEFAULT_MESSENGER_TOOLS : input.toolNames;
101
104
  if (
102
105
  !Array.isArray(toolNames) ||
103
106
  toolNames.some(name => typeof name !== "string" || !Object.hasOwn(TOOLS, name)) ||
104
107
  new Set(toolNames).size !== toolNames.length
105
108
  ) {
106
- throw new Error("toolNames must be a unique list drawn from read, grep, glob, bash, edit, write");
109
+ throw new Error("toolNames must be a unique list drawn from read, grep, glob, find, search, bash, edit, write, computer");
107
110
  }
111
+ const independentSessions = input.independentSessions !== undefined ? Boolean(input.independentSessions) : true;
108
112
  return {
109
113
  cwd: path.resolve(baseDir, input.cwd === undefined ? "." : string(input.cwd, "cwd")),
110
114
  sessionDir: path.resolve(
@@ -113,6 +117,7 @@ export function parseMessengerConfig(value: unknown, baseDir: string): Messenger
113
117
  ),
114
118
  toolNames: [...toolNames] as string[],
115
119
  platforms,
120
+ independentSessions,
116
121
  };
117
122
  }
118
123
 
@@ -510,11 +510,13 @@ export async function setupDiscordMessenger(
510
510
 
511
511
  const discord: Record<string, unknown> = { ...previous, tokenEnv, allowedUserIds: userIds, allowedChannelIds };
512
512
  if (options.artifacts) discord.artifactDir = "./artifacts";
513
+ const defaultTools = ["read", "find", "search", "write", "edit", "bash", "computer"];
513
514
  const config = {
514
515
  ...existing,
515
516
  cwd: str(existing?.cwd) ?? "./workspace",
516
517
  sessionDir: str(existing?.sessionDir) ?? "./sessions",
517
- toolNames: options.toolNames ?? (Array.isArray(existing?.toolNames) ? existing.toolNames : []),
518
+ toolNames: options.toolNames ?? (Array.isArray(existing?.toolNames) ? existing.toolNames : defaultTools),
519
+ independentSessions: existing?.independentSessions !== undefined ? Boolean(existing.independentSessions) : true,
518
520
  platforms: { ...platforms, discord },
519
521
  };
520
522
  for (const relative of [config.cwd, config.sessionDir, discord.artifactDir]) {
@@ -541,7 +541,11 @@ export function createDiscordAdapter(
541
541
  try {
542
542
  await messengerFetchJson(
543
543
  `${messages}/${encodeURIComponent(statusId)}`,
544
- { method: "DELETE", headers: headers() },
544
+ {
545
+ method: "PATCH",
546
+ headers: headers(),
547
+ body: JSON.stringify({ content: "✅ Complete", allowed_mentions: { parse: [] } }),
548
+ },
545
549
  signal,
546
550
  deps.fetch,
547
551
  );
@@ -5,13 +5,15 @@ interface WorkerProcess {
5
5
  stdout: ReadableStream<Uint8Array>;
6
6
  stderr: ReadableStream<Uint8Array>;
7
7
  exited: Promise<number>;
8
- kill(): void;
8
+ kill(signal?: number | NodeJS.Signals): void;
9
9
  }
10
10
 
11
11
  interface Pending {
12
12
  resolve(text: string): void;
13
13
  reject(error: Error): void;
14
14
  report?: MessengerActivityReporter;
15
+ result?: string;
16
+ written?: boolean;
15
17
  }
16
18
 
17
19
  interface Worker {
@@ -19,20 +21,55 @@ interface Worker {
19
21
  pending?: Pending;
20
22
  lastUsed: number;
21
23
  dead: boolean;
24
+ exited?: boolean;
25
+ idleTimer?: ReturnType<typeof setTimeout>;
26
+ exitTimer?: ReturnType<typeof setTimeout>;
22
27
  }
23
28
 
24
- export function createMessengerSessionPool(spawn: typeof Bun.spawn = Bun.spawn, limit = 16) {
29
+ export function createMessengerSessionPool(spawn: typeof Bun.spawn = Bun.spawn, limit = 16, idleTimeoutMs = 5 * 60_000, shutdownTimeoutMs = 5_000) {
25
30
  const workers = new Map<string, Worker>();
31
+ const allWorkers = new Map<Worker, string>();
32
+ const exits = new Map<Promise<number>, WorkerProcess>();
33
+ const retiring = new Map<string, Promise<number>>();
34
+
26
35
  let closed = false;
36
+ const closedSignal = new AbortController();
37
+
27
38
  let tick = 0;
28
39
 
29
40
  function retire(key: string, worker: Worker) {
30
41
  if (worker.dead) return;
31
42
  worker.dead = true;
32
43
  if (workers.get(key) === worker) workers.delete(key);
44
+ allWorkers.delete(worker);
45
+ if (!worker.exited) {
46
+ retiring.set(key, worker.child.exited);
47
+ void worker.child.exited.then(
48
+ () => { if (retiring.get(key) === worker.child.exited) retiring.delete(key); },
49
+ () => { if (retiring.get(key) === worker.child.exited) retiring.delete(key); },
50
+ );
51
+ }
52
+ if (worker.idleTimer) clearTimeout(worker.idleTimer);
53
+ if (worker.exitTimer) clearTimeout(worker.exitTimer);
54
+ worker.idleTimer = undefined;
33
55
  worker.pending?.reject(new Error("Messenger worker stopped"));
34
56
  worker.pending = undefined;
35
- worker.child.kill();
57
+ if (!worker.exited) {
58
+ try { worker.child.kill(); } catch { /* Shutdown will attempt forced termination. */ }
59
+ }
60
+ }
61
+
62
+ function finishTurn(key: string, worker: Worker, pending: Pending) {
63
+ if (worker.pending !== pending || !pending.written || pending.result === undefined) return;
64
+ worker.pending = undefined;
65
+ if (worker.exited) {
66
+ retire(key, worker);
67
+ } else {
68
+ worker.lastUsed = ++tick;
69
+ worker.idleTimer = setTimeout(() => retire(key, worker), idleTimeoutMs);
70
+ worker.idleTimer.unref();
71
+ }
72
+ pending.resolve(pending.result);
36
73
  }
37
74
 
38
75
  async function readLines(stream: ReadableStream<Uint8Array>, handle: (line: string) => void) {
@@ -60,8 +97,11 @@ export function createMessengerSessionPool(spawn: typeof Bun.spawn = Bun.spawn,
60
97
  }
61
98
  const child = spawn(command, { cwd, env, stdin: "pipe", stdout: "pipe", stderr: "pipe" }) as unknown as WorkerProcess;
62
99
  const worker: Worker = { child, lastUsed: ++tick, dead: false };
100
+ exits.set(child.exited, child);
101
+ void child.exited.then(() => exits.delete(child.exited), () => exits.delete(child.exited));
63
102
  workers.set(key, worker);
64
- void readLines(child.stdout, line => {
103
+ allWorkers.set(worker, key);
104
+ const stdoutDone = readLines(child.stdout, line => {
65
105
  const pending = worker.pending;
66
106
  if (!pending) return;
67
107
  if (line === "JEO_MESSENGER_ERROR") { retire(key, worker); return; }
@@ -69,40 +109,86 @@ export function createMessengerSessionPool(spawn: typeof Bun.spawn = Bun.spawn,
69
109
  try {
70
110
  const text: unknown = JSON.parse(line.slice("JEO_MESSENGER_RESULT ".length));
71
111
  if (typeof text !== "string" || !text.trim()) throw new Error("Invalid response");
72
- worker.pending = undefined;
73
- worker.lastUsed = ++tick;
74
- pending.resolve(text);
112
+ pending.result = text;
113
+ finishTurn(key, worker, pending);
75
114
  } catch { retire(key, worker); }
76
115
  }).catch(() => retire(key, worker));
77
116
  void readLines(child.stderr, line => {
78
- if (line === "JEO_MESSENGER_STEP") worker.pending?.report?.("Working on your request");
117
+ if (line.startsWith("JEO_MESSENGER_ACTIVITY ")) {
118
+ const activityText = line.slice("JEO_MESSENGER_ACTIVITY ".length).trim();
119
+ if (activityText) worker.pending?.report?.(activityText);
120
+ } else if (line === "JEO_MESSENGER_STEP") {
121
+ worker.pending?.report?.("Working on your request");
122
+ }
79
123
  }).catch(() => retire(key, worker));
80
- void child.exited.then(() => retire(key, worker), () => retire(key, worker));
124
+ void child.exited.then(() => {
125
+ if (worker.dead) return;
126
+ worker.exited = true;
127
+ if (workers.get(key) === worker) workers.delete(key);
128
+ worker.exitTimer = setTimeout(() => retire(key, worker), shutdownTimeoutMs);
129
+ worker.exitTimer.unref();
130
+ void stdoutDone.then(() => {
131
+ if (!worker.pending?.result || worker.pending.written) retire(key, worker);
132
+ });
133
+ }, () => retire(key, worker));
81
134
  return worker;
82
135
  }
83
136
 
84
137
  async function turn(key: string, command: string[], cwd: string, env: Record<string, string>, text: string, signal: AbortSignal, report?: MessengerActivityReporter): Promise<string> {
85
138
  if (closed || signal.aborted) throw new Error("Messenger request aborted");
139
+ const previousExit = retiring.get(key);
140
+ if (previousExit) {
141
+ await new Promise<void>((resolve, reject) => {
142
+ const abort = () => { cleanup(); reject(new Error("Messenger request aborted")); };
143
+ const cleanup = () => { signal.removeEventListener("abort", abort); closedSignal.signal.removeEventListener("abort", abort); };
144
+ signal.addEventListener("abort", abort, { once: true });
145
+ closedSignal.signal.addEventListener("abort", abort, { once: true });
146
+ if (signal.aborted || closed) { abort(); return; }
147
+ void previousExit.then(() => { cleanup(); resolve(); }, () => { cleanup(); resolve(); });
148
+ });
149
+ }
150
+ if (closed || signal.aborted) throw new Error("Messenger request aborted");
151
+ if ([...allWorkers].some(([worker, workerKey]) => workerKey === key && worker.pending)) {
152
+ throw new Error("Messenger conversation is already active");
153
+ }
86
154
  const worker = workers.get(key) ?? start(key, command, cwd, env);
87
155
  if (worker.pending) throw new Error("Messenger conversation is already active");
156
+ if (worker.idleTimer) clearTimeout(worker.idleTimer);
157
+ worker.idleTimer = undefined;
88
158
  return await new Promise<string>((resolve, reject) => {
89
159
  const abort = () => retire(key, worker);
90
160
  const cleanup = () => signal.removeEventListener("abort", abort);
91
- worker.pending = { resolve: value => { cleanup(); resolve(value); }, reject: error => { cleanup(); reject(error); }, report };
161
+ const pending: Pending = { resolve: value => { cleanup(); resolve(value); }, reject: error => { cleanup(); reject(error); }, report };
162
+ worker.pending = pending;
92
163
  signal.addEventListener("abort", abort, { once: true });
93
164
  if (signal.aborted) { abort(); return; }
94
165
  void (async () => {
95
166
  await worker.child.stdin.write(`${JSON.stringify(text)}\n`);
96
167
  if (!worker.dead) await worker.child.stdin.flush();
168
+ pending.written = true;
169
+ finishTurn(key, worker, pending);
97
170
  })().catch(() => retire(key, worker));
98
171
  });
99
172
  }
100
173
 
101
174
  async function close() {
102
175
  closed = true;
103
- const all = [...workers.entries()];
104
- for (const [key, worker] of all) retire(key, worker);
105
- await Promise.allSettled(all.map(([, worker]) => worker.child.exited));
176
+ closedSignal.abort();
177
+ for (const [worker, key] of allWorkers) retire(key, worker);
178
+ const waitForExits = async () => {
179
+ let timer: ReturnType<typeof setTimeout> | undefined;
180
+ try {
181
+ return await Promise.race([
182
+ Promise.allSettled([...exits.keys()]).then(() => true),
183
+ new Promise<false>(resolve => { timer = setTimeout(() => resolve(false), shutdownTimeoutMs); }),
184
+ ]);
185
+ } finally { if (timer) clearTimeout(timer); }
186
+ };
187
+ if (await waitForExits()) return;
188
+ for (const child of exits.values()) {
189
+ try { child.kill("SIGKILL"); } catch { /* The process may have exited concurrently. */ }
190
+ }
191
+ if (!(await waitForExits())) throw new Error("Messenger workers did not exit after forced termination");
106
192
  }
107
193
 
108
194
  return { turn, close };
@@ -55,6 +55,8 @@ export interface MessengerConfig {
55
55
  sessionDir: string;
56
56
  toolNames: string[];
57
57
  platforms: Partial<Record<MessengerPlatform, MessengerPlatformConfig>>;
58
+ /** Whether each message invocation runs in an isolated independent session. Defaults to true. */
59
+ independentSessions?: boolean;
58
60
  }
59
61
 
60
62
  export interface MessengerTransportDeps {
@@ -117,9 +117,9 @@ export function buildSkillTask(skill: SkillDoc, intent: string, invokedAs?: stri
117
117
  : "Carry out this skill's workflow now. If it needs a concrete target you weren't given, make a reasonable assumption or ask the user via done."),
118
118
  ].join("\n");
119
119
  }
120
- export function skillsPromptSection(skills: SkillDoc[] = SKILLS): string {
120
+ export function skillsPromptSection(skills: SkillDoc[] = SKILLS, currentTask?: string): string {
121
121
  const bundleSkills: SkillDoc[] = [];
122
- const configuredSkills: SkillDoc[] = [];
122
+ let configuredSkills: SkillDoc[] = [];
123
123
 
124
124
  const bundleNames = new Set(BUILTIN_SKILL_NAMES);
125
125
  for (const s of skills) {
@@ -130,6 +130,20 @@ export function skillsPromptSection(skills: SkillDoc[] = SKILLS): string {
130
130
  }
131
131
  }
132
132
 
133
+ // When a task is provided and skills exceed budget, sort configured skills by relevance
134
+ if (currentTask && currentTask.trim().length > 0 && configuredSkills.length > 5) {
135
+ const qTokens = new Set(
136
+ currentTask.toLowerCase().match(/[a-z0-9._-]{3,}/g) ?? []
137
+ );
138
+ configuredSkills = [...configuredSkills].sort((a, b) => {
139
+ const aScore = (a.name.toLowerCase().split(/[._-]/).some(t => qTokens.has(t)) ? 10 : 0) +
140
+ (qTokens.has(a.name.toLowerCase()) ? 20 : 0);
141
+ const bScore = (b.name.toLowerCase().split(/[._-]/).some(t => qTokens.has(t)) ? 10 : 0) +
142
+ (qTokens.has(b.name.toLowerCase()) ? 20 : 0);
143
+ return bScore - aScore;
144
+ });
145
+ }
146
+
133
147
  const lines: string[] = [];
134
148
  let used = 0;
135
149
 
@@ -295,15 +309,18 @@ export function skillDirs(cwd: string = process.cwd()): string[] {
295
309
  path.join(userHome, ".claude", "skills"),
296
310
  path.join(home, "agent", "skills"),
297
311
  path.join(userHome, ".agents", "skills"),
312
+ path.join(userHome, ".agent-skills"),
298
313
  userSkillsDir(),
299
314
  path.join(cwd, ".claude", "skills"),
300
315
  path.join(cwd, ".agents", "skills"),
316
+ path.join(cwd, ".agent-skills"),
301
317
  path.join(cwd, ".jeo", "skills"),
302
318
  path.join(cwd, ".jeo", "agent", "skills"),
303
319
  ...configured,
304
320
  ];
305
321
  }
306
322
 
323
+
307
324
  /** A frontmatter `name:` usable as a skill identity: one bare token, no spaces. */
308
325
  function sanitizeSkillName(raw: string | undefined): string | undefined {
309
326
  const m = (raw ?? "").trim();