opencastle 1.4.2 → 1.4.3

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.
Files changed (51) hide show
  1. package/dist/cli/convoy/spec-types.d.ts +15 -0
  2. package/dist/cli/convoy/spec-types.d.ts.map +1 -1
  3. package/dist/cli/pipeline.d.ts.map +1 -1
  4. package/dist/cli/pipeline.flow.test.js +134 -27
  5. package/dist/cli/pipeline.flow.test.js.map +1 -1
  6. package/dist/cli/pipeline.js +113 -34
  7. package/dist/cli/pipeline.js.map +1 -1
  8. package/dist/cli/plan.d.ts +22 -0
  9. package/dist/cli/plan.d.ts.map +1 -1
  10. package/dist/cli/plan.js +43 -6
  11. package/dist/cli/plan.js.map +1 -1
  12. package/dist/cli/run/adapters/claude.d.ts +13 -0
  13. package/dist/cli/run/adapters/claude.d.ts.map +1 -1
  14. package/dist/cli/run/adapters/claude.js +30 -1
  15. package/dist/cli/run/adapters/claude.js.map +1 -1
  16. package/dist/cli/run/adapters/claude.test.js +34 -1
  17. package/dist/cli/run/adapters/claude.test.js.map +1 -1
  18. package/dist/cli/run/adapters/codex.d.ts.map +1 -1
  19. package/dist/cli/run/adapters/codex.js +4 -0
  20. package/dist/cli/run/adapters/codex.js.map +1 -1
  21. package/dist/cli/run/adapters/codex.test.js +8 -0
  22. package/dist/cli/run/adapters/codex.test.js.map +1 -1
  23. package/dist/cli/run/adapters/copilot.d.ts.map +1 -1
  24. package/dist/cli/run/adapters/copilot.js +4 -1
  25. package/dist/cli/run/adapters/copilot.js.map +1 -1
  26. package/dist/cli/run/adapters/copilot.test.js +9 -0
  27. package/dist/cli/run/adapters/copilot.test.js.map +1 -1
  28. package/dist/cli/run/adapters/stub-cli.test-helper.d.ts +2 -0
  29. package/dist/cli/run/adapters/stub-cli.test-helper.d.ts.map +1 -1
  30. package/dist/cli/run/adapters/stub-cli.test-helper.js +16 -1
  31. package/dist/cli/run/adapters/stub-cli.test-helper.js.map +1 -1
  32. package/dist/cli/run/platform.d.ts +12 -0
  33. package/dist/cli/run/platform.d.ts.map +1 -1
  34. package/dist/cli/run/platform.js +49 -0
  35. package/dist/cli/run/platform.js.map +1 -1
  36. package/dist/cli/run/platform.test.js +21 -1
  37. package/dist/cli/run/platform.test.js.map +1 -1
  38. package/package.json +1 -1
  39. package/src/cli/convoy/spec-types.ts +15 -0
  40. package/src/cli/pipeline.flow.test.ts +143 -28
  41. package/src/cli/pipeline.ts +141 -34
  42. package/src/cli/plan.ts +51 -6
  43. package/src/cli/run/adapters/claude.test.ts +39 -1
  44. package/src/cli/run/adapters/claude.ts +27 -1
  45. package/src/cli/run/adapters/codex.test.ts +9 -0
  46. package/src/cli/run/adapters/codex.ts +3 -0
  47. package/src/cli/run/adapters/copilot.test.ts +11 -0
  48. package/src/cli/run/adapters/copilot.ts +3 -1
  49. package/src/cli/run/adapters/stub-cli.test-helper.ts +16 -1
  50. package/src/cli/run/platform.test.ts +23 -1
  51. package/src/cli/run/platform.ts +50 -0
@@ -1,9 +1,9 @@
1
- import { readFile, writeFile, mkdir } from 'node:fs/promises'
1
+ import { readFile, writeFile, mkdir, rm, rmdir } from 'node:fs/promises'
2
2
  import { existsSync } from 'node:fs'
3
3
  import { createHash } from 'node:crypto'
4
- import { resolve, relative, basename } from 'node:path'
4
+ import { resolve, relative, basename, dirname } from 'node:path'
5
5
  import { c, confirm, closePrompts } from './prompt.js'
6
- import { runPromptStep, freePath } from './plan.js'
6
+ import { runPromptStep, freePath, StepCancelled } from './plan.js'
7
7
  import type { PromptStepOptions, PromptStepResult } from './plan.js'
8
8
  import { resolveAdapter, cleanupAdapters, type ResolvedAdapter } from './run/adapters/index.js'
9
9
  import { findProjectRoot } from './convoy/read-model.js'
@@ -416,11 +416,19 @@ async function settleAll<T>(work: Array<Promise<T>>): Promise<T[]> {
416
416
  }
417
417
 
418
418
  /** generate-convoy, with the one retry an unreadable answer gets. */
419
- async function generatePlan(step: StepRunner, goal: string, context: string, label: string, convoyDir: string): Promise<TaskPlan> {
419
+ async function generatePlan(
420
+ step: StepRunner,
421
+ goal: string,
422
+ context: string,
423
+ label: string,
424
+ convoyDir: string,
425
+ signal?: AbortSignal,
426
+ onStart?: () => void,
427
+ ): Promise<TaskPlan> {
420
428
  let raw = ''
421
429
  let reason = ''
422
430
  for (let attempt = 1; attempt <= 2; attempt++) {
423
- raw = (await step('generate-convoy', { goalText: goal, contextText: context })).rawOutput
431
+ raw = (await step('generate-convoy', { goalText: goal, contextText: context, signal, onStart })).rawOutput
424
432
  const parsed = parseTaskPlanWithReason(raw)
425
433
  if (parsed.plan) return parsed.plan
426
434
  reason = parsed.reason ?? 'unreadable'
@@ -443,13 +451,55 @@ async function fixPlan(step: StepRunner, plan: TaskPlan, problems: string): Prom
443
451
  return normalizePlanFiles(applyPatches(plan, patches)).plan
444
452
  }
445
453
 
454
+ /**
455
+ * A step started before the planner knows it will use it.
456
+ *
457
+ * Planning was a chain of sessions, each waiting for the one before, and every
458
+ * session costs its start-up and its answer however short the question. Where
459
+ * the next step does not depend on the answer it waits for, it starts at the
460
+ * same time, and is stopped if that answer says it is not needed.
461
+ */
462
+ interface Speculation<T> {
463
+ value: Promise<T>
464
+ /**
465
+ * Settles once its session has started, or once the step has failed without
466
+ * one. The planner waits for it before starting the step that decides, so
467
+ * the same answers always lead to the same sessions.
468
+ */
469
+ started: Promise<void>
470
+ /** Stop the session and wait until it has stopped: its answer, if it finished first. */
471
+ drop(): Promise<T | undefined>
472
+ }
473
+
474
+ function speculate<T>(start: (signal: AbortSignal, onStart: () => void) => Promise<T>): Speculation<T> {
475
+ const control = new AbortController()
476
+ let began!: () => void
477
+ const sessionStarted = new Promise<void>((r) => (began = r))
478
+ const value = start(control.signal, began)
479
+ // Settled whether or not anyone awaits it, so a dropped step is not an
480
+ // unhandled rejection.
481
+ const settled = value.then((v) => v, () => undefined)
482
+ return {
483
+ value,
484
+ started: Promise.race([sessionStarted, settled.then(() => undefined)]),
485
+ drop: async () => {
486
+ control.abort()
487
+ return settled
488
+ },
489
+ }
490
+ }
491
+
446
492
  /**
447
493
  * From a request (or an edited PRD) to a checked spec on disk.
448
494
  *
449
495
  * Sessions, all read-only, on the one adapter the caller resolved:
496
+ * - assess-complexity on the request, beside a plan written straight from it,
497
+ * which is kept when the change is small and stopped when it is not;
450
498
  * - generate-prd, unless a PRD was given;
451
- * - validate-prd beside assess-complexity, which is skipped when this exact
452
- * PRD was assessed before; up to two fix-prd + validate-prd rounds;
499
+ * - validate-prd beside the plan from the PRD when how to plan it is already
500
+ * known, or beside assess-complexity on the PRD when it is not, which is
501
+ * skipped when this exact PRD was assessed before; up to two fix-prd +
502
+ * validate-prd rounds, and the plan is written again from the fixed PRD;
453
503
  * - generate-convoy, once, or once per group at the same time for a large
454
504
  * feature; one retry when an answer cannot be read;
455
505
  * - fix-convoy only when the code's checks fail, at most twice;
@@ -459,6 +509,15 @@ async function fixPlan(step: StepRunner, plan: TaskPlan, problems: string): Prom
459
509
  * checks it was there for are done in code, and a person reads the plan
460
510
  * before it runs.
461
511
  */
512
+ function tasksPlanned(plan: TaskPlan): string {
513
+ return `${plan.tasks.length} task${plan.tasks.length === 1 ? '' : 's'}`
514
+ }
515
+
516
+ /** Whether an assessment asks for the work to be planned as groups, side by side. */
517
+ function inGroups(c: ComplexityAssessment): boolean {
518
+ return c.recommended_strategy === 'chain' && c.convoy_groups.length > 1
519
+ }
520
+
462
521
  /** Where a PRD would go, for a change small enough to plan from the request alone. */
463
522
  const NO_PRD = 'There is no PRD: this is a small change, planned straight from the request. Read the code it touches before you plan.'
464
523
 
@@ -469,7 +528,18 @@ export async function planConvoy(req: PlanRequest): Promise<PlanOutcome> {
469
528
  const started = Date.now()
470
529
  const spend: PlanningSpend = { sessions: 0, ms: 0, tokens: 0, costUsd: 0, costComplete: true }
471
530
  const step: StepRunner = async (template, inputs) => {
472
- const r = await runPromptStep({ template, adapter: req.adapter, pkgRoot: req.pkgRoot, cwd: root, verbose: req.verbose, ...inputs })
531
+ let r: PromptStepResult
532
+ try {
533
+ r = await runPromptStep({ template, adapter: req.adapter, pkgRoot: req.pkgRoot, cwd: root, verbose: req.verbose, ...inputs })
534
+ } catch (err) {
535
+ // A stopped session ran, and spent what it never got to report.
536
+ if (err instanceof StepCancelled) {
537
+ spend.sessions++
538
+ spend.costComplete = false
539
+ spend.ms = Date.now() - started
540
+ }
541
+ throw err
542
+ }
473
543
  spend.sessions++
474
544
  spend.tokens += r.tokens ?? 0
475
545
  if (r.costUsd === undefined) spend.costComplete = false
@@ -479,21 +549,37 @@ export async function planConvoy(req: PlanRequest): Promise<PlanOutcome> {
479
549
  }
480
550
 
481
551
  // ── A small change: no PRD ────────────────────────────────────────────────
482
- // Sizing the request first is one short economy session. When it is small,
483
- // the plan is written straight from it: a PRD, its review and its fixes were
484
- // four or five sessions and most of the planning time — 7m 25s in a real
485
- // run — for a change the request already described.
552
+ // When the request is small, the plan is written straight from it: a PRD,
553
+ // its review and its fixes were four or five sessions and most of the
554
+ // planning time — 7m 25s in a real run — for a change the request already
555
+ // described. Neither the plan from the request nor the PRD depends on the
556
+ // size, so all three start together, and the size decides which of the two
557
+ // is kept: the other is stopped. Waiting for the size first added its whole
558
+ // session, about 20s, to every plan.
486
559
  let prdPath: string | null = null
487
560
  let plan: TaskPlan | null = null
488
561
  let quick: ComplexityAssessment | null = null
562
+ let drafting: Speculation<PromptStepResult> | null = null
489
563
  if (!req.prdPath && req.task) {
490
- quick = await step('assess-complexity', { goalText: req.task, contextText: req.task })
564
+ const task = req.task
565
+ const direct = speculate((signal, onStart) => generatePlan(step, task, NO_PRD, 'task', convoyDir, signal, onStart))
566
+ drafting = speculate((signal, onStart) => step('generate-prd', { goalText: task, signal, onStart }))
567
+ await Promise.all([direct.started, drafting.started])
568
+ quick = await step('assess-complexity', { goalText: task, contextText: task })
491
569
  .then((r) => parseComplexityAssessment(r.rawOutput))
492
570
  .catch(() => null)
493
571
  if (quick?.complexity === 'low' && quick.recommended_strategy !== 'chain') {
494
572
  done('Sized', 'low — planned straight from the request, without a PRD')
495
- plan = await generatePlan(step, req.task, appendTaskComplexity(NO_PRD, quick.task_complexity), 'task', convoyDir)
496
- done(`${plan.tasks.length} tasks planned`)
573
+ // A PRD that finished first is not left behind for a change that has none.
574
+ const unneeded = await drafting.drop()
575
+ if (unneeded?.outputPath) {
576
+ await rm(unneeded.outputPath, { force: true })
577
+ await rmdir(dirname(unneeded.outputPath)).catch(() => {})
578
+ }
579
+ plan = await direct.value
580
+ done(`${tasksPlanned(plan)} planned`)
581
+ } else {
582
+ await direct.drop()
497
583
  }
498
584
  }
499
585
 
@@ -503,7 +589,7 @@ export async function planConvoy(req: PlanRequest): Promise<PlanOutcome> {
503
589
  prdPath = resolve(root, req.prdPath)
504
590
  done('PRD', relPath(prdPath))
505
591
  } else {
506
- const written = await step('generate-prd', { goalText: req.task ?? '' })
592
+ const written = drafting ? await drafting.value : await step('generate-prd', { goalText: req.task ?? '' })
507
593
  prdPath = written.outputPath!
508
594
  done('PRD written', relPath(prdPath))
509
595
  }
@@ -514,25 +600,45 @@ export async function planConvoy(req: PlanRequest): Promise<PlanOutcome> {
514
600
  // it is cached under this draft's text, which is the text it describes.
515
601
  const cached = await readCachedComplexity(prdPath, prd)
516
602
  const assessedFrom = prd
517
- const [verdict, complexity] = await settleAll<PromptStepResult | ComplexityAssessment | null>([
518
- step('validate-prd', { goalText: `<!-- validation-pass: 1 -->\n${prd}` }),
519
- // The request was sized already. Only groups need sizing against the
520
- // PRD, whose phases they name.
521
- cached || (quick && quick.recommended_strategy !== 'chain')
522
- ? Promise.resolve(cached ?? quick)
523
- : step('assess-complexity', { goalText: prd, contextText: req.task ?? '' })
524
- .then((r) => parseComplexityAssessment(r.rawOutput))
525
- .catch((err: unknown) => {
526
- warn(`Could not size the work (${message(err)}) — planning it as one`)
527
- return null
528
- }),
529
- ]) as [PromptStepResult, ComplexityAssessment | null]
603
+ // The request was sized already. Only groups need sizing against the PRD,
604
+ // whose phases they name.
605
+ const known = cached ?? (quick && quick.recommended_strategy !== 'chain' ? quick : null)
606
+ const goalFor = (c: ComplexityAssessment | null): string => req.task ?? c?.original_prompt ?? 'Implement the PRD.'
607
+ // When how to plan it is known already, the plan starts beside the review:
608
+ // most PRDs pass, and a plan from one that does not is written again from
609
+ // the fixed text.
610
+ const draft = prd
611
+ let early = known && !inGroups(known)
612
+ ? speculate((signal, onStart) =>
613
+ generatePlan(step, goalFor(known), appendTaskComplexity(draft, known.task_complexity), 'task', convoyDir, signal, onStart))
614
+ : null
615
+ await early?.started
616
+ let verdict: PromptStepResult
617
+ let complexity: ComplexityAssessment | null
618
+ try {
619
+ ;[verdict, complexity] = await settleAll<PromptStepResult | ComplexityAssessment | null>([
620
+ step('validate-prd', { goalText: `<!-- validation-pass: 1 -->\n${prd}` }),
621
+ known
622
+ ? Promise.resolve(known)
623
+ : step('assess-complexity', { goalText: prd, contextText: req.task ?? '' })
624
+ .then((r) => parseComplexityAssessment(r.rawOutput))
625
+ .catch((err: unknown) => {
626
+ warn(`Could not size the work (${message(err)}) — planning it as one`)
627
+ return null
628
+ }),
629
+ ]) as [PromptStepResult, ComplexityAssessment | null]
630
+ } catch (err) {
631
+ await early?.drop()
632
+ throw err
633
+ }
530
634
 
531
635
  if (complexity && !cached && complexity !== quick) await writeCachedComplexity(prdPath, assessedFrom, complexity)
532
636
 
533
637
  if (verdict.isValid) {
534
638
  done('PRD checked')
535
639
  } else {
640
+ await early?.drop()
641
+ early = null
536
642
  let issues = verdict.errors || verdict.rawOutput
537
643
  let fixed = false
538
644
  for (let round = 1; round <= MAX_FIX_ROUNDS && !fixed; round++) {
@@ -554,7 +660,7 @@ export async function planConvoy(req: PlanRequest): Promise<PlanOutcome> {
554
660
 
555
661
  // ── The tasks ─────────────────────────────────────────────────────────────
556
662
  let groups: ConvoyGroup[] | null = null
557
- if (complexity?.recommended_strategy === 'chain' && complexity.convoy_groups.length > 1) {
663
+ if (complexity && inGroups(complexity)) {
558
664
  const check = validateComplexityGroups(complexity)
559
665
  if (check.valid) groups = topologicalSortGroups(complexity.convoy_groups)
560
666
  else warn(`Ignoring the suggested groups (${check.reason}) — planning it as one`)
@@ -592,11 +698,12 @@ export async function planConvoy(req: PlanRequest): Promise<PlanOutcome> {
592
698
  featureName,
593
699
  all.map((g, i) => ({ name: g.name, depends_on: g.depends_on, plan: plans[i] })),
594
700
  )
595
- done(`${plan.tasks.length} tasks planned`, `${all.length} groups, planned side by side`)
701
+ done(`${tasksPlanned(plan)} planned`, `${all.length} groups, planned side by side`)
596
702
  } else {
597
- const goal = req.task ?? complexity?.original_prompt ?? 'Implement the PRD.'
598
- plan = await generatePlan(step, goal, appendTaskComplexity(prd, complexity?.task_complexity), 'task', convoyDir)
599
- done(`${plan.tasks.length} tasks planned`)
703
+ plan = early
704
+ ? await early.value
705
+ : await generatePlan(step, goalFor(complexity), appendTaskComplexity(prd, complexity?.task_complexity), 'task', convoyDir)
706
+ done(`${tasksPlanned(plan)} planned`)
600
707
  }
601
708
  }
602
709
 
package/src/cli/plan.ts CHANGED
@@ -37,6 +37,22 @@ export interface PromptStepOptions {
37
37
  verbose?: boolean
38
38
  /** How long one session may run before it is stopped. Defaults to 10 minutes. */
39
39
  timeoutMs?: number
40
+ /**
41
+ * Stops the session when aborted, and the step fails with a `StepCancelled`.
42
+ * The planner starts some steps before it knows it needs them, and stops the
43
+ * ones it turns out not to.
44
+ */
45
+ signal?: AbortSignal
46
+ /** Called once the session has started, before its answer. */
47
+ onStart?: () => void
48
+ }
49
+
50
+ /** A step stopped through its `signal`, not one that failed. */
51
+ export class StepCancelled extends Error {
52
+ constructor(template: string) {
53
+ super(`${template} was stopped: its answer is no longer needed`)
54
+ this.name = 'StepCancelled'
55
+ }
40
56
  }
41
57
 
42
58
  export interface PromptStepResult {
@@ -265,6 +281,19 @@ function modelFor(adapter: AgentAdapter, template: string): string | undefined {
265
281
  return adapter.tierModels?.[tier]
266
282
  }
267
283
 
284
+ /**
285
+ * How much each step reasons before it answers.
286
+ *
287
+ * Planning sessions spent most of their time thinking, not reading: on a small
288
+ * project a PRD took 129s at Claude Code's default effort and 36s at `low`, with
289
+ * every section, and a plan 55s against 30s at `medium`. The plan gets
290
+ * `medium` because its task prompts are the only instructions the workers see;
291
+ * sizing, the PRD, the checks and the fixes get `low`.
292
+ */
293
+ export function effortFor(template: string): 'low' | 'medium' {
294
+ return template === 'generate-convoy' ? 'medium' : 'low'
295
+ }
296
+
268
297
  /**
269
298
  * Run one planning template through the caller's adapter.
270
299
  *
@@ -297,28 +326,44 @@ export async function runPromptStep(opts: PromptStepOptions): Promise<PromptStep
297
326
  console.log(c.dim(` ${opts.template} · ${opts.adapter.name} · read-only · ${prompt.length} chars`))
298
327
  }
299
328
 
329
+ if (opts.signal?.aborted) throw new StepCancelled(opts.template)
300
330
  const timeoutMs = opts.timeoutMs ?? DEFAULT_STEP_TIMEOUT_MS
301
331
  const stop = opts.verbose ? null : startProgress(opts.template)
302
332
  let timer: ReturnType<typeof setTimeout> | undefined
333
+ let onAbort: (() => void) | undefined
303
334
  let execResult
304
335
  try {
336
+ const running = opts.adapter.execute(task, {
337
+ verbose: opts.verbose ?? false,
338
+ cwd: opts.cwd ?? process.cwd(),
339
+ permissionMode: 'plan',
340
+ // Everything a planning step needs is in its prompt or in the files it
341
+ // reads: no MCP servers, skills or web searches.
342
+ lean: true,
343
+ effort: effortFor(opts.template),
344
+ ...(modelFor(opts.adapter, opts.template) ? { model: modelFor(opts.adapter, opts.template) } : {}),
345
+ })
346
+ opts.onStart?.()
305
347
  execResult = await Promise.race([
306
- opts.adapter.execute(task, {
307
- verbose: opts.verbose ?? false,
308
- cwd: opts.cwd ?? process.cwd(),
309
- permissionMode: 'plan',
310
- ...(modelFor(opts.adapter, opts.template) ? { model: modelFor(opts.adapter, opts.template) } : {}),
311
- }),
348
+ running,
312
349
  new Promise<never>((_, reject) => {
313
350
  timer = setTimeout(() => {
314
351
  // A hung session would otherwise hold the whole plan open forever.
315
352
  opts.adapter.kill?.(task)
316
353
  reject(new Error(`${opts.template} ran longer than ${Math.round(timeoutMs / 60_000)}m and was stopped`))
317
354
  }, timeoutMs)
355
+ // Stopped by id. The planner only cancels a step while it is the one
356
+ // session of its template, so no other session shares the id.
357
+ onAbort = () => {
358
+ opts.adapter.kill?.(task)
359
+ reject(new StepCancelled(opts.template))
360
+ }
361
+ opts.signal?.addEventListener('abort', onAbort, { once: true })
318
362
  }),
319
363
  ])
320
364
  } finally {
321
365
  if (timer) clearTimeout(timer)
366
+ if (onAbort) opts.signal?.removeEventListener('abort', onAbort)
322
367
  stop?.()
323
368
  }
324
369
 
@@ -3,7 +3,7 @@ import { existsSync, readFileSync, writeFileSync, readdirSync } from 'node:fs'
3
3
  import { join } from 'node:path'
4
4
  import type { Task } from '../../convoy/spec-types.js'
5
5
  import { installStubCli, type StubCli } from './stub-cli.test-helper.js'
6
- import { execute, isAvailable, kill, parseClaudeOutput } from './claude.js'
6
+ import { claudeSessionArgs, execute, isAvailable, kill, parseClaudeOutput } from './claude.js'
7
7
 
8
8
  const posix = process.platform !== 'win32'
9
9
 
@@ -182,6 +182,44 @@ describe.skipIf(!posix)('claude adapter — against a stub `claude`', () => {
182
182
  expect(argv).not.toContain('plan')
183
183
  })
184
184
 
185
+ /** What `claude --help` lists for these flags in a version that has them. */
186
+ const HELP = [
187
+ ' --effort <level> Effort level for the current session',
188
+ ' --strict-mcp-config Only use MCP servers from --mcp-config',
189
+ ' --disable-slash-commands Disable all skills',
190
+ ' --tools <tools...> Specify the list of available tools',
191
+ ].join('\n')
192
+
193
+ it('asks for less effort and a lean session when this version has the flags', async () => {
194
+ stub.help(HELP)
195
+ await execute(makeTask(), { cwd: stub.work, permissionMode: 'plan', effort: 'low', lean: true, model: 'sonnet' })
196
+ const argv = stub.argv()
197
+ expect(argv[argv.indexOf('--effort') + 1]).toBe('low')
198
+ expect(argv).toContain('--strict-mcp-config')
199
+ expect(argv).toContain('--disable-slash-commands')
200
+ expect(argv[argv.indexOf('--tools') + 1]).toBe('Read,Grep,Glob')
201
+ expect(argv[argv.indexOf('--model') + 1]).toBe('sonnet')
202
+ })
203
+
204
+ it('leaves out a flag an older version does not list, rather than fail the session', async () => {
205
+ stub.help(' --model <model> Model for the current session')
206
+ const result = await execute(makeTask(), { cwd: stub.work, effort: 'low', lean: true })
207
+ expect(result.success).toBe(true)
208
+ expect(stub.argv().filter((a) => /^--(effort|strict-mcp-config|disable-slash-commands|tools)$/.test(a))).toEqual([])
209
+ })
210
+
211
+ it('passes none of them to a worker that asks for neither', async () => {
212
+ stub.help(HELP)
213
+ await execute(makeTask(), { cwd: stub.work })
214
+ expect(stub.argv().filter((a) => /^--(effort|strict-mcp-config|disable-slash-commands|tools)$/.test(a))).toEqual([])
215
+ })
216
+
217
+ it('matches a flag by its whole name', () => {
218
+ expect(claudeSessionArgs({ effort: 'medium' }, ' --effort <level> x')).toEqual(['--effort', 'medium'])
219
+ expect(claudeSessionArgs({ effort: 'medium' }, ' --effortless x')).toEqual([])
220
+ expect(claudeSessionArgs({ lean: true }, ' --tools-extra x')).toEqual([])
221
+ })
222
+
185
223
  it('does not cap turns: the timeout bounds a session', async () => {
186
224
  await execute(makeTask(), { cwd: stub.work })
187
225
  expect(stub.argv()).not.toContain('--max-turns')
@@ -1,5 +1,5 @@
1
1
  import type { Task, ExecuteOptions, ExecuteResult, TokenUsage } from '../../convoy/spec-types.js'
2
- import { commandExists } from '../platform.js'
2
+ import { commandExists, helpText } from '../platform.js'
3
3
  import { runAgent, stopTask, promptOf, interruptedMessage, OUTPUT_LIMIT } from './agent-process.js'
4
4
 
5
5
  /**
@@ -134,11 +134,37 @@ export function claudePermissionArgs(mode: ExecuteOptions['permissionMode']): st
134
134
  return ['--permission-mode', mode ?? 'acceptEdits']
135
135
  }
136
136
 
137
+ /** The tools a lean session keeps: reading files, nothing else. */
138
+ export const LEAN_TOOLS = 'Read,Grep,Glob'
139
+
140
+ /**
141
+ * The flags that make a session cheaper and faster, each passed only when the
142
+ * installed Claude Code lists it in `--help`: a version without one fails the
143
+ * whole session on the unknown flag.
144
+ *
145
+ * A lean session starts no MCP server, loads no skill or command, and keeps
146
+ * only the tools that read files. Measured on a planning step it cost less than
147
+ * half as much — the skills, MCP tool schemas and sub-agent definitions no
148
+ * longer went into its context — and it could not wander into a web search.
149
+ */
150
+ export function claudeSessionArgs(options: Pick<ExecuteOptions, 'effort' | 'lean'>, help: string): string[] {
151
+ const has = (flag: string) => new RegExp(`(^|\\s)${flag}(\\s|,|=|$)`, 'm').test(help)
152
+ const args: string[] = []
153
+ if (options.effort && has('--effort')) args.push('--effort', options.effort)
154
+ if (options.lean) {
155
+ if (has('--strict-mcp-config')) args.push('--strict-mcp-config')
156
+ if (has('--disable-slash-commands')) args.push('--disable-slash-commands')
157
+ if (has('--tools')) args.push('--tools', LEAN_TOOLS)
158
+ }
159
+ return args
160
+ }
161
+
137
162
  export async function execute(task: Task, options: ExecuteOptions = {}): Promise<ExecuteResult> {
138
163
  // A worker has no terminal, so a permission prompt is a refusal it cannot
139
164
  // answer: without a mode it tries to write, is denied, and exits 0 having
140
165
  // written nothing. `acceptEdits` is the least that lets it do the work.
141
166
  const args = ['-p', '--output-format', 'json', ...claudePermissionArgs(options.permissionMode)]
167
+ if (options.effort || options.lean) args.push(...claudeSessionArgs(options, await helpText('claude')))
142
168
  if (options.model) args.push('--model', options.model)
143
169
  // No --max-turns: the task's timeout bounds a session, and a turn cap only
144
170
  // cut long tasks short with a result that looked like an ordinary failure.
@@ -125,6 +125,15 @@ describe.skipIf(!posix)('codex adapter — against a stub `codex`', () => {
125
125
  expect(argv[argv.indexOf('-m') + 1]).toBe('gpt-5.1-codex')
126
126
  })
127
127
 
128
+ it('sets the reasoning effort as a config override, quoted as TOML', async () => {
129
+ await execute(makeTask(), { cwd: stub.work })
130
+ expect(stub.argv()).not.toContain('-c')
131
+ await execute(makeTask(), { cwd: stub.work, effort: 'medium' })
132
+ const argv = stub.argv()
133
+ expect(argv[argv.indexOf('-c') + 1]).toBe('model_reasoning_effort="medium"')
134
+ expect(argv.at(-1)).toBe('-')
135
+ })
136
+
128
137
  it('reports the failure messages on a non-zero exit', async () => {
129
138
  process.env.STUB_EXIT = '1'
130
139
  delete process.env.STUB_LAST_MESSAGE
@@ -119,6 +119,9 @@ export async function execute(task: Task, options: ExecuteOptions = {}): Promise
119
119
  '-o', lastMessagePath,
120
120
  ]
121
121
  if (options.model) args.push('-m', options.model)
122
+ // A config override, which every `codex exec` takes; the value is TOML, so
123
+ // the string is quoted. No shell is involved, so the quotes reach codex.
124
+ if (options.effort) args.push('-c', `model_reasoning_effort="${options.effort}"`)
122
125
  args.push('-') // the prompt, from stdin
123
126
 
124
127
  try {
@@ -124,6 +124,17 @@ describe.skipIf(!posix)('copilot adapter — against a stub `copilot`', () => {
124
124
  expect(argv[argv.indexOf('--model') + 1]).toBe('gpt-5.2')
125
125
  })
126
126
 
127
+ it('asks for less effort only when this version has --effort', async () => {
128
+ stub.help(' --effort, --reasoning-effort <level> Set the reasoning effort level')
129
+ await execute(makeTask(), { cwd: stub.work, effort: 'low' })
130
+ const argv = stub.argv()
131
+ expect(argv[argv.indexOf('--effort') + 1]).toBe('low')
132
+
133
+ stub.help(' --model <model> Set the AI model to use')
134
+ await execute(makeTask(), { cwd: stub.work, effort: 'low' })
135
+ expect(stub.argv()).not.toContain('--effort')
136
+ })
137
+
127
138
  it('lets Copilot load the project\'s MCP config from an untrusted worktree', async () => {
128
139
  const script = join(stub.bin, 'copilot')
129
140
  writeFileSync(script, readFileSync(script, 'utf8').replace('pwd > "$log/cwd"', 'pwd > "$log/cwd"; printf %s "$GITHUB_COPILOT_PROMPT_MODE_WORKSPACE_MCP" > "$log/mcp"'))
@@ -1,5 +1,5 @@
1
1
  import type { Task, ExecuteOptions, ExecuteResult } from '../../convoy/spec-types.js'
2
- import { commandExists } from '../platform.js'
2
+ import { commandExists, helpText } from '../platform.js'
3
3
  import { copilotPermissionArgs } from './permission-modes.js'
4
4
  import { runAgent, stopTask, promptOf, interruptedMessage, OUTPUT_LIMIT } from './agent-process.js'
5
5
 
@@ -91,6 +91,8 @@ export function parseCopilotOutput(stdout: string): ParsedCopilot {
91
91
  export async function execute(task: Task, options: ExecuteOptions = {}): Promise<ExecuteResult> {
92
92
  const args = ['--output-format', 'json', '--no-ask-user', '--no-auto-update']
93
93
  if (options.model) args.push('--model', options.model)
94
+ // Only when this version has it: an unknown flag fails the session.
95
+ if (options.effort && /(^|\s)--effort[\s,]/m.test(await helpText('copilot'))) args.push('--effort', options.effort)
94
96
  args.push(...copilotPermissionArgs(options.permissionMode))
95
97
 
96
98
  const exit = await runAgent(task, {
@@ -1,6 +1,7 @@
1
1
  import { mkdtempSync, mkdirSync, writeFileSync, chmodSync, readFileSync, rmSync, realpathSync, existsSync } from 'node:fs'
2
2
  import { tmpdir } from 'node:os'
3
3
  import { join, delimiter } from 'node:path'
4
+ import { forgetHelpText } from '../platform.js'
4
5
 
5
6
  /**
6
7
  * A stand-in agent CLI for adapter tests: a POSIX shell script put on a
@@ -10,6 +11,9 @@ import { join, delimiter } from 'node:path'
10
11
  */
11
12
 
12
13
  const SCRIPT = `#!/bin/sh
14
+ # The adapters read --help to learn which flags this version has. It is
15
+ # answered here and not recorded, so argv is still the session's.
16
+ if [ "$1" = "--help" ]; then printf '%s\\n' "$STUB_HELP"; exit 0; fi
13
17
  log="$STUB_LOG"
14
18
  pwd > "$log/cwd"
15
19
  : > "$log/argv"
@@ -37,6 +41,8 @@ export interface StubCli {
37
41
  work: string
38
42
  /** What the stub prints on stdout (and stderr) next time it runs. */
39
43
  respond(stdout: string, stderr?: string): void
44
+ /** What it prints for `--help`; nothing until set. */
45
+ help(text: string): void
40
46
  argv(): string[]
41
47
  cwd(): string
42
48
  stdin(): string
@@ -59,7 +65,9 @@ export function installStubCli(...names: string[]): StubCli {
59
65
  writeFileSync(join(bin, name), SCRIPT)
60
66
  chmodSync(join(bin, name), 0o755)
61
67
  }
62
- const saved = { PATH: process.env.PATH, STUB_LOG: process.env.STUB_LOG }
68
+ const saved = { PATH: process.env.PATH, STUB_LOG: process.env.STUB_LOG, STUB_HELP: process.env.STUB_HELP }
69
+ delete process.env.STUB_HELP
70
+ forgetHelpText()
63
71
  process.env.PATH = [bin, '/usr/bin', '/bin'].join(delimiter)
64
72
  process.env.STUB_LOG = log
65
73
  const read = (f: string) => (existsSync(join(log, f)) ? readFileSync(join(log, f), 'utf8') : '')
@@ -67,6 +75,10 @@ export function installStubCli(...names: string[]): StubCli {
67
75
  bin,
68
76
  log,
69
77
  work,
78
+ help(text) {
79
+ process.env.STUB_HELP = text
80
+ forgetHelpText()
81
+ },
70
82
  respond(stdout, stderr) {
71
83
  writeFileSync(join(log, 'stdout.txt'), stdout)
72
84
  if (stderr !== undefined) writeFileSync(join(log, 'stderr.txt'), stderr)
@@ -78,6 +90,9 @@ export function installStubCli(...names: string[]): StubCli {
78
90
  process.env.PATH = saved.PATH
79
91
  if (saved.STUB_LOG === undefined) delete process.env.STUB_LOG
80
92
  else process.env.STUB_LOG = saved.STUB_LOG
93
+ if (saved.STUB_HELP === undefined) delete process.env.STUB_HELP
94
+ else process.env.STUB_HELP = saved.STUB_HELP
95
+ forgetHelpText()
81
96
  delete process.env.STUB_EXIT
82
97
  delete process.env.STUB_LAST_MESSAGE
83
98
  delete process.env.STUB_SLEEP
@@ -2,7 +2,7 @@ import { mkdtempSync, writeFileSync, chmodSync, rmSync, existsSync } from 'node:
2
2
  import { tmpdir } from 'node:os'
3
3
  import { join } from 'node:path'
4
4
  import { describe, it, expect, afterEach } from 'vitest'
5
- import { resolveCommand, commandExists, quoteForCmd, runShell, spawnCommand, killTree } from './platform.js'
5
+ import { resolveCommand, commandExists, quoteForCmd, runShell, spawnCommand, killTree, helpText, forgetHelpText } from './platform.js'
6
6
 
7
7
  const posix = process.platform !== 'win32'
8
8
 
@@ -26,6 +26,28 @@ describe('finding a command without `which`', () => {
26
26
  })
27
27
  })
28
28
 
29
+ describe('reading a CLI\'s --help', () => {
30
+ afterEach(() => forgetHelpText())
31
+
32
+ it('is empty for a command that is not there, and asks only once', async () => {
33
+ const missing = 'opencastle-no-such-cli-' + process.pid
34
+ expect(await helpText(missing)).toBe('')
35
+ expect(helpText(missing)).toBe(helpText(missing))
36
+ })
37
+
38
+ it.skipIf(!posix)('reads what the command prints', async () => {
39
+ const dir = mkdtempSync(join(tmpdir(), 'oc-help-'))
40
+ const cli = join(dir, 'fake-cli')
41
+ writeFileSync(cli, '#!/bin/sh\necho " --effort <level> Effort"\n')
42
+ chmodSync(cli, 0o755)
43
+ try {
44
+ expect(await helpText(cli)).toContain('--effort <level>')
45
+ } finally {
46
+ rmSync(dir, { recursive: true, force: true })
47
+ }
48
+ })
49
+ })
50
+
29
51
  describe('quoting for cmd.exe', () => {
30
52
  // The same output cross-spawn produces for these inputs.
31
53
  it('quotes and caret-escapes metacharacters', () => {