@yaag/runtime 0.10.0 → 0.12.0

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 (59) hide show
  1. package/package.json +1 -1
  2. package/src/agent/agent-compaction.ts +80 -0
  3. package/src/agent/agent-usage.ts +11 -0
  4. package/src/agent/agent.ts +95 -3
  5. package/src/agent/define-agent.ts +7 -5
  6. package/src/agent/fork.ts +74 -0
  7. package/src/agent/index.ts +1 -0
  8. package/src/agent/spawn-open.ts +249 -0
  9. package/src/agent/spawn-request.ts +12 -1
  10. package/src/agent/spawn.ts +25 -197
  11. package/src/ask/ask-exchange.ts +2 -8
  12. package/src/cassette/cassette-replay.ts +33 -1
  13. package/src/cassette/cassette-schema.ts +20 -0
  14. package/src/cassette/cassette.ts +69 -6
  15. package/src/cassette/index.ts +1 -0
  16. package/src/cassette/recording-transport.ts +13 -0
  17. package/src/cassette/replay-divergence.ts +51 -2
  18. package/src/cassette/replay-transport.ts +22 -1
  19. package/src/cassette/resume-transport.ts +27 -2
  20. package/src/catalog/agent-describe-fixture.ts +121 -0
  21. package/src/catalog/agent-describe.ts +210 -0
  22. package/src/catalog/catalog-entry.ts +39 -0
  23. package/src/catalog/catalog-fixture.ts +87 -0
  24. package/src/catalog/catalog-match.ts +77 -0
  25. package/src/catalog/catalog-result.ts +69 -0
  26. package/src/catalog/index.ts +57 -0
  27. package/src/catalog/load-catalog.ts +74 -0
  28. package/src/catalog/program-scan.ts +64 -0
  29. package/src/catalog/registry-paths.ts +26 -0
  30. package/src/catalog/registry-reader.ts +115 -0
  31. package/src/catalog/registry-schema.ts +119 -0
  32. package/src/config/config-paths.ts +14 -7
  33. package/src/config/index.ts +1 -0
  34. package/src/contract/agent-report.ts +42 -0
  35. package/src/contract/error-codes.ts +65 -0
  36. package/src/contract/handle.ts +132 -0
  37. package/src/contract/index.ts +34 -0
  38. package/src/contract/model-spec.ts +81 -0
  39. package/src/contract/spawn-options.ts +127 -0
  40. package/src/error-factories.ts +70 -0
  41. package/src/errors.ts +22 -114
  42. package/src/events.ts +26 -1
  43. package/src/index.ts +49 -0
  44. package/src/model/model-resolution.ts +19 -71
  45. package/src/model/model-swap.ts +1 -1
  46. package/src/model/resolution-loop.ts +1 -1
  47. package/src/model/thinking-level.ts +5 -5
  48. package/src/public-api.ts +28 -0
  49. package/src/run/run-context.ts +4 -2
  50. package/src/summary/index.ts +1 -0
  51. package/src/summary/summary-agent.ts +38 -0
  52. package/src/summary/summary.ts +20 -0
  53. package/src/transport/fake-transport.ts +35 -1
  54. package/src/transport/index.ts +9 -1
  55. package/src/transport/live-transport.ts +9 -0
  56. package/src/transport/pi-state.ts +53 -10
  57. package/src/transport/transport.ts +54 -9
  58. package/src/transport/worktree-transport.ts +39 -6
  59. package/src/types.ts +16 -201
@@ -28,9 +28,17 @@ export function worktreeTransport(inner: TransportFactory): TransportFactory {
28
28
  observeStartup?: TransportStartupObserver,
29
29
  ): Promise<AgentTransport> {
30
30
  if (options.worktree !== true) return inner.open(options, observeStartup);
31
- const root = await repositoryRoot(options.cwd, options.name);
32
- await requireClean(root, options.name);
33
- const resolution = await addWorktree({ root, name: options.name });
31
+ const from = options.worktreeFrom;
32
+ const root = await repositoryRoot(from?.cwd ?? options.cwd, options.name);
33
+ // A fork branches from what its source already committed, so the source's
34
+ // dirty files stay behind and no clean check applies (ADR-0044).
35
+ if (from === undefined) await requireClean(root, options.name);
36
+ const resolution = await addWorktree({
37
+ root,
38
+ name: options.name,
39
+ namingRoot: await namingRoot(root),
40
+ startPoint: from?.branch ?? "HEAD",
41
+ });
34
42
  const { worktree: _worktree, ...innerOptions } = options;
35
43
  let reported = false;
36
44
  const transport = await inner.open(
@@ -69,18 +77,43 @@ async function requireClean(cwd: string, name: string): Promise<void> {
69
77
  }
70
78
  }
71
79
 
72
- async function addWorktree(options: { readonly root: string; readonly name: string }): Promise<{
80
+ /**
81
+ * The repository the worktree directory is named after.
82
+ *
83
+ * For a worktree it is the main repository, not the worktree itself, so a fork
84
+ * of a Worktree Agent does not nest `repo-worktrees/a1-worktrees/a2`.
85
+ */
86
+ async function namingRoot(root: string): Promise<string> {
87
+ const result = await git(root, ["rev-parse", "--path-format=absolute", "--git-common-dir"]);
88
+ const common = result.stdout.trim();
89
+ if (result.code !== 0 || common === "" || !common.endsWith("/.git")) return root;
90
+ return common.slice(0, -"/.git".length);
91
+ }
92
+
93
+ async function addWorktree(options: {
94
+ readonly root: string;
95
+ readonly name: string;
96
+ readonly namingRoot: string;
97
+ readonly startPoint: string;
98
+ }): Promise<{
73
99
  readonly cwd: string;
74
100
  readonly branch: string;
75
101
  }> {
76
- const parent = join(dirname(options.root), `${basename(options.root)}-worktrees`);
102
+ const parent = join(dirname(options.namingRoot), `${basename(options.namingRoot)}-worktrees`);
77
103
  await mkdir(parent, { recursive: true });
78
104
  for (let suffix = 1; ; suffix += 1) {
79
105
  const leaf = suffix === 1 ? options.name : `${options.name}-${suffix}`;
80
106
  const branch = `yaag/${leaf}`;
81
107
  const cwd = join(parent, leaf);
82
108
  if (await candidateTaken(options.root, branch, cwd)) continue;
83
- const result = await git(options.root, ["worktree", "add", "-b", branch, cwd, "HEAD"]);
109
+ const result = await git(options.root, [
110
+ "worktree",
111
+ "add",
112
+ "-b",
113
+ branch,
114
+ cwd,
115
+ options.startPoint,
116
+ ]);
84
117
  if (result.code === 0) return { cwd, branch };
85
118
  if (isCollision(result)) continue;
86
119
  throw new Error(`git worktree add failed: ${result.stderr.trim() || result.stdout.trim()}`);
package/src/types.ts CHANGED
@@ -1,204 +1,19 @@
1
- import type { Static, TSchema } from "typebox";
2
- import type { ModelSpec, ThinkingLevel, ThinkingSpec } from "./model/index.ts";
3
-
4
- export type { ThinkingLevel } from "./model/index.ts";
5
-
6
- /** Options for spawning one Agent (ADR-0001, ADR-0009, ADR-0026). */
7
- export interface SpawnOptions {
8
- /** Working directory. Defaults to the Orchestrator's cwd. */
9
- readonly cwd?: string;
10
- /**
11
- * Model pattern, e.g. "anthropic/claude-haiku-4". Unset inherits the user's default.
12
- *
13
- * An array is an ordered fallback list and a function picks the next candidate
14
- * from the failures so far. Any resolved pattern may carry an inline thinking
15
- * suffix (`"opus-5:medium"`), which wins over `thinking`. Each attempt settles
16
- * the model first, then the thinking level for that model. yaag starts a new
17
- * attempt only when pi reports `not_found`, `auth`, or `rate_limited`. See
18
- * `ModelSpec` and `ModelResolver` for the termination rules (ADR-0037).
19
- */
20
- readonly model?: ModelSpec;
21
- /** Replaces the default system prompt (`pi --system-prompt`). */
22
- readonly systemPrompt?: string;
23
- /**
24
- * Sets pi's thinking level; omission preserves pi's default. A function picks
25
- * the level from the settled model, and is not consulted for a model pattern
26
- * that carries an inline thinking suffix. The resolver runs again for each
27
- * attempt, with the model that settled for that attempt (ADR-0037).
28
- */
29
- readonly thinking?: ThinkingSpec;
30
- /** Appends text to pi's system prompt (`pi --append-system-prompt`). */
31
- readonly appendSystemPrompt?: string;
32
- /**
33
- * Restores pi discovery. Omission or false selects ADR-0026's hermetic baseline.
34
- */
35
- readonly inherit?: boolean;
36
- /**
37
- * Explicit pi extensions layer over either ADR-0026 baseline. Relative entries
38
- * resolve from the Orchestration Program file; each becomes `pi -e <path>`.
39
- */
40
- readonly extensions?: readonly string[];
41
- /**
42
- * Load the Effective Config's `agents.extensions` for this Agent. Default
43
- * true; false spawns with only the extensions this call declares (ADR-0040).
44
- */
45
- readonly configExtensions?: boolean;
46
- /**
47
- * Tool allowlist layered over the ADR-0026 baseline; omission is tool-free when hermetic.
48
- * `disallowedTools` applies last. A non-empty surviving allowlist is verified after startup;
49
- * a missing promised name rejects spawn.
50
- */
51
- readonly tools?: readonly string[];
52
- /**
53
- * Tool denylist applied last under ADR-0026; `['yaag_run']` prevents nested yaag Runs.
54
- * Denying an absent tool is inert and is not presence-validated.
55
- */
56
- readonly disallowedTools?: readonly string[];
57
- /**
58
- * Skill-name allowlist, not filesystem paths, layered over the ADR-0026 baseline.
59
- * Omission is skill-free when hermetic; `disallowedSkills` applies last. Unknown requested
60
- * names reject spawn.
61
- */
62
- readonly skills?: readonly string[];
63
- /** Skill-name denylist discovered from pi and applied last (ADR-0026). */
64
- readonly disallowedSkills?: readonly string[];
65
- /** Log and event label. Defaults to a1, a2, …; duplicate names are suffixed. */
66
- readonly name?: string;
67
- /** Request a fresh Git worktree. The requested cwd remains the base until spawn resolves. */
68
- readonly worktree?: boolean;
69
- /**
70
- * Names this Agent's parent in the Run tree (Parent Link). Data only: it is
71
- * no conversation channel and no lifetime rule.
72
- */
73
- readonly parent?: Handle;
74
- }
75
-
76
1
  /**
77
- * Spawn options after Model Resolution has settled one model and thinking level.
2
+ * The author-facing shapes of the runtime.
78
3
  *
79
- * This is the settled shape, and it is what the Cassette identity hashes
80
- * (ADR-0039).
81
- *
82
- * `parent` is omitted on purpose: a Handle must never reach this shape, because
83
- * an Ask records these options into the Cassette. Spawn resolves the Parent
84
- * Link to a name, which travels in `OpenOptions` and stays out of Ask identity.
85
- */
86
- export interface ResolvedSpawnOptions extends Omit<SpawnOptions, "model" | "thinking" | "parent"> {
87
- readonly model?: string;
88
- readonly thinking?: ThinkingLevel;
89
- }
90
-
91
- /** Topology-only fields that may change when spawning an Agent Definition. */
92
- export interface SpawnOverrides {
93
- /** Log and event label. Defaults to the definition's name; duplicates are suffixed. */
94
- readonly name?: string;
95
- /** Working directory. Defaults to the Orchestrator's cwd. */
96
- readonly cwd?: string;
97
- /** Request a fresh Git worktree. */
98
- readonly worktree?: boolean;
99
- /** Names this Agent's parent in the Run tree (Parent Link). Data only. */
100
- readonly parent?: Handle;
101
- }
102
-
103
- /**
104
- * Options for one Ask (ADR-0003).
105
- *
106
- * Soft limits trip at their configured count: turns are `turn_start` frames and
107
- * tool calls are `tool_execution_start` frames between `agent_start` and
108
- * `agent_settled`; duration is wall time from prompt send. A trip steers the
109
- * Agent, permits one further turn (or a fixed duration grace), then aborts and
110
- * rejects with `ASK_LIMIT` if it has not settled. This leaves the Handle alive.
111
- * `timeoutMs` is independent: it kills the Agent and rejects with `ASK_TIMEOUT`.
112
- *
113
- * A model failure inside an Ask starts Model Fallback and retries the Ask
114
- * (ADR-0038). Each attempt gets fresh soft limits, a fresh Stall Watchdog and a
115
- * fresh output collector. `timeoutMs` is the exception: it is the hard ceiling
116
- * of the whole Ask, and every attempt shares one deadline.
117
- */
118
- export interface AskOptions {
119
- /** Reject and kill the Agent if it has not settled in time. Unset = no bound. */
120
- readonly timeoutMs?: number;
121
- /** Soft budget of `turn_start` frames between `agent_start` and `agent_settled`. */
122
- readonly maxTurns?: number;
123
- /** Soft budget of `tool_execution_start` frames between `agent_start` and `agent_settled`. */
124
- readonly maxToolCalls?: number;
125
- /** Soft wall-clock budget in milliseconds, measured from prompt send. */
126
- readonly maxDurationMs?: number;
127
- /**
128
- * Maximum silence in milliseconds: rejects with `ASK_STALLED` when no frame
129
- * arrives for this span. Complementary to `maxDurationMs` (silence vs.
130
- * trickle) and separate from `timeoutMs`, which always kills. Unset disables
131
- * idle detection (ADR-0020).
132
- */
133
- readonly idleMs?: number;
134
- /**
135
- * Silence budget in milliseconds for the Stall Watchdog, which guards every
136
- * live Ask by default (ADR-0029). On expiry yaag probes the Agent and either
137
- * recovers a missed settlement or rejects with `ASK_STALLED`. Omission uses
138
- * the 10-minute default. `false`, and any value that is not above zero,
139
- * disable the watchdog for this Ask. `ASK_STALLED` is a generic failure: it
140
- * never starts Model Fallback. If the silence budget ends the Ask before pi
141
- * reports a model failure, the Ask fails `ASK_STALLED` and no swap happens
142
- * (ADR-0029).
143
- */
144
- readonly stallMs?: number | false;
145
- /** Per-Ask replacement for the runtime's wrap-up steering message. */
146
- readonly wrapUpPrompt?: string;
147
- }
148
-
149
- /** Ask options that require a schema and preserve its inferred successful result. */
150
- export interface StructuredAskOptions<Schema extends TSchema> extends AskOptions {
151
- /**
152
- * TypeBox object schema the Agent reports its result against, instead of text.
153
- *
154
- * It becomes the input schema of one internal tool, so it must describe an
155
- * object (ADR-0032).
156
- */
157
- readonly outputSchema: Schema;
158
- /**
159
- * Maximum settlements without a reported result that this Ask corrects;
160
- * defaults to 3 when omitted. Argument repair inside a turn is the Agent's
161
- * own loop and costs nothing here.
162
- */
163
- readonly maxSteers?: number;
164
- }
165
-
166
- /**
167
- * A handle to one long-lived Agent.
168
- * ADR-0003: `ask()` is the only conversational verb; everything else is data.
4
+ * The declarations live in `contract/`, which imports nothing outside itself
5
+ * except `typebox` (ADR-0045). This file keeps the historic import path.
169
6
  */
170
- export interface Handle {
171
- /** Stable identity, used in every Lifecycle Event and log line. */
172
- readonly name: string;
173
- /** Resolved absolute working directory; a worktree's actual cwd after spawn resolves. */
174
- readonly cwd: string;
175
- /** Fresh branch for a worktree Agent; undefined for ordinary Agents. */
176
- readonly branch: string | undefined;
177
- /**
178
- * Model id as reported by the Agent's own `get_state` — not the requested
179
- * pattern. A mid-Ask model swap updates it (ADR-0038).
180
- */
181
- readonly model: string;
182
-
183
- /**
184
- * Sends a prompt and resolves after the Agent's turn settles.
185
- *
186
- * Schema-free calls resolve with the exact final assistant text. Calls with
187
- * `outputSchema` resolve with the TypeBox-validated value the Agent reports
188
- * through one internal tool call (ADR-0032). Rejects with a YaagError for a
189
- * failed or empty turn, timeout, `ASK_LIMIT`, or dead Agent. An Ask that
190
- * settles without a reported result is corrected at most `maxSteers` times
191
- * (default 3) and then rejects recoverably with `ASK_INVALID_OUTPUT` after an
192
- * abort settlement; a reported value the schema rejects fails the same way
193
- * without a correction. These recoverable outcomes leave the Handle reusable.
194
- * A retry after a Model Fallback discards the result the failed attempt
195
- * reported, and arms the collector again, so a stale result cannot settle the
196
- * retried Ask (ADR-0032, ADR-0038).
197
- * A concurrent call rejects with `AGENT_BUSY`.
198
- */
199
- ask<Schema extends TSchema>(
200
- prompt: string,
201
- options: StructuredAskOptions<Schema>,
202
- ): Promise<Static<Schema>>;
203
- ask(prompt: string, options?: AskOptions): Promise<string>;
204
- }
7
+ export type {
8
+ AgentProgress,
9
+ AskOptions,
10
+ CompactionResult,
11
+ ForkOptions,
12
+ Handle,
13
+ ModelError,
14
+ ResolvedSpawnOptions,
15
+ SpawnOptions,
16
+ SpawnOverrides,
17
+ StructuredAskOptions,
18
+ ThinkingLevel,
19
+ } from "./contract/index.ts";