@sourcegraph/amp 0.0.1748851339-g31df22 → 0.0.1748877319-g69d2be

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 (52) hide show
  1. package/dist/amp.js +3 -2
  2. package/dist/amp.js.map +1 -1
  3. package/dist/client-CEMYqypS.js +35 -0
  4. package/dist/client-CEMYqypS.js.map +1 -0
  5. package/dist/{console-k3nh7b4U.js → console-Dz8kjLXq.js} +38668 -17361
  6. package/dist/console-Dz8kjLXq.js.map +1 -0
  7. package/dist/{create_file.node-Dxp9NAiW.js → create_file.node-Dkg9a9qS.js} +2 -2
  8. package/dist/{create_file.node-Dxp9NAiW.js.map → create_file.node-Dkg9a9qS.js.map} +1 -1
  9. package/dist/{edit_file.node-BlCpGVR-.js → edit_file.node-BzmJeIBM.js} +10 -10
  10. package/dist/{edit_file.node-BlCpGVR-.js.map → edit_file.node-BzmJeIBM.js.map} +1 -1
  11. package/dist/{executable-DTI1_xm7.js → executable-BfvtWYTF.js} +2 -2
  12. package/dist/{executable-DTI1_xm7.js.map → executable-BfvtWYTF.js.map} +1 -1
  13. package/dist/{files-DdjDm_B8.js → files-DLJqtzT7.js} +3 -3
  14. package/dist/{files-DdjDm_B8.js.map → files-DLJqtzT7.js.map} +1 -1
  15. package/dist/glob.node-D18uhtO0.js +137 -0
  16. package/dist/glob.node-D18uhtO0.js.map +1 -0
  17. package/dist/index-DDEnF9L5.js +922 -0
  18. package/dist/index-DDEnF9L5.js.map +1 -0
  19. package/dist/{list_directory.node-DDhJZGvT.js → list_directory.node-ldHqnCmb.js} +2 -2
  20. package/dist/{list_directory.node-DDhJZGvT.js.map → list_directory.node-ldHqnCmb.js.map} +1 -1
  21. package/dist/{load-profile-CWDhvBXX.js → load-profile-2hKEWJfV.js} +2 -2
  22. package/dist/{load-profile-CWDhvBXX.js.map → load-profile-2hKEWJfV.js.map} +1 -1
  23. package/dist/main-BnHTihL6.js +19700 -0
  24. package/dist/main-BnHTihL6.js.map +1 -0
  25. package/dist/{node-B1RLuGfG.js → node-BHe5RJPs.js} +41 -41
  26. package/dist/{node-B1RLuGfG.js.map → node-BHe5RJPs.js.map} +1 -1
  27. package/dist/{node-w5kFgl6-.js → node-BMzC1GPN.js} +47 -47
  28. package/dist/{node-w5kFgl6-.js.map → node-BMzC1GPN.js.map} +1 -1
  29. package/dist/node-BRxAOe2b.js +85 -0
  30. package/dist/node-BRxAOe2b.js.map +1 -0
  31. package/dist/{node-DGc3Eu0F.js → node-CUTKGt9Y.js} +3 -3
  32. package/dist/{node-DGc3Eu0F.js.map → node-CUTKGt9Y.js.map} +1 -1
  33. package/dist/{node-BZlRkYQw.js → node-CzSXw-Xz.js} +2 -2
  34. package/dist/{node-BZlRkYQw.js.map → node-CzSXw-Xz.js.map} +1 -1
  35. package/dist/{node-DuhaU87r.js → node-DcXu8fEU.js} +1090 -833
  36. package/dist/node-DcXu8fEU.js.map +1 -0
  37. package/dist/{read_file.node-CsATnmUF.js → read_file.node-6DnwIJAn.js} +2 -2
  38. package/dist/{read_file.node-CsATnmUF.js.map → read_file.node-6DnwIJAn.js.map} +1 -1
  39. package/dist/{stdio-Egb8ZIIg.js → stdio-B_076PGB.js} +29 -29
  40. package/dist/{stdio-Egb8ZIIg.js.map → stdio-B_076PGB.js.map} +1 -1
  41. package/dist/storybook.js +1 -1
  42. package/dist/{undo_edit.node-CHrrMPkn.js → undo_edit.node-WsSsWWo7.js} +10 -10
  43. package/dist/{undo_edit.node-CHrrMPkn.js.map → undo_edit.node-WsSsWWo7.js.map} +1 -1
  44. package/package.json +1 -1
  45. package/dist/console-k3nh7b4U.js.map +0 -1
  46. package/dist/glob.node-BnKeKl9M.js +0 -1051
  47. package/dist/glob.node-BnKeKl9M.js.map +0 -1
  48. package/dist/main-DuPQOPga.js +0 -40843
  49. package/dist/main-DuPQOPga.js.map +0 -1
  50. package/dist/node-3m0J6gBv.js +0 -72
  51. package/dist/node-3m0J6gBv.js.map +0 -1
  52. package/dist/node-DuhaU87r.js.map +0 -1
@@ -1,35 +1,35 @@
1
1
  #!/usr/bin/env node
2
- import { ak as Y, V as $, am as k, W as L, an as C, aN as D, f as j, as as J, b7 as V, a0 as W, O as z, ai as M, J as Z, U as q, n as G } from "./console-k3nh7b4U.js";
3
- import { a as x, o as A, s as g, d as H, b as K, l as h, r as N, u as Q, e as X, c as _, p as ee, Z as te, g as se, h as F } from "./main-DuPQOPga.js";
4
- const S = A({
5
- context: X(["continue", "none"]).optional().default("continue"),
6
- tools: Q([h("all"), x(g())]).optional(),
2
+ import { q as x, o as A, n as g, y as B, r as j, l as h, x as I, u as J, w as V, A as k, aW as W, aX as z, aY as Z, aZ as C, a_ as L, a$ as _, b0 as D, av as M, f as q, b1 as X, b2 as G, b3 as F, b4 as H, O as K, b5 as N, _ as Q, at as ee, C as te } from "./console-Dz8kjLXq.js";
3
+ import { r as se } from "./main-BnHTihL6.js";
4
+ const v = A({
5
+ context: V(["continue", "none"]).optional().default("continue"),
6
+ tools: J([h("all"), x(g())]).optional(),
7
7
  prompt: g(),
8
- verify: N(_()).optional()
9
- }), oe = S.extend({
8
+ verify: I(k()).optional()
9
+ }), oe = v.extend({
10
10
  type: h("agent"),
11
11
  model: g().optional(),
12
12
  // Default could be set in implementation
13
- interactive_confirmation: K().optional()
14
- }), re = S.extend({
13
+ interactive_confirmation: j().optional()
14
+ }), re = v.extend({
15
15
  type: h("llm"),
16
16
  model: g().optional()
17
- }), ne = S.extend({
17
+ }), ne = v.extend({
18
18
  type: h("loop_agent"),
19
19
  model: g().optional(),
20
20
  input_file: g()
21
- }), ae = S.extend({
21
+ }), ae = v.extend({
22
22
  type: h("loop_llm"),
23
23
  model: g().optional(),
24
24
  input_file: g()
25
25
  }), ie = A({
26
26
  type: h("tool_call"),
27
27
  tool: g(),
28
- parameters: N(_()).optional()
28
+ parameters: I(k()).optional()
29
29
  }), le = A({
30
30
  type: h("bash"),
31
31
  command: g()
32
- }), pe = H("type", [
32
+ }), pe = B("type", [
33
33
  oe,
34
34
  re,
35
35
  ne,
@@ -43,10 +43,10 @@ const S = A({
43
43
  x(P);
44
44
  function ce(r) {
45
45
  try {
46
- const e = ee(r);
46
+ const e = W(r);
47
47
  return P.parse(e);
48
48
  } catch (e) {
49
- throw e instanceof te ? new Error(
49
+ throw e instanceof z ? new Error(
50
50
  `Invalid routine format: ${e.errors.map((t) => `${t.path.join(".")} - ${t.message}`).join(", ")}`
51
51
  ) : e instanceof Error ? new Error(`Failed to parse YAML: ${e.message}`) : new Error(`Unknown error during routine deserialization: ${String(e)}`);
52
52
  }
@@ -88,7 +88,7 @@ function de(r, e, t, s, o, a = new AbortController().signal) {
88
88
  }
89
89
  }
90
90
  async function ge(r, e, t, s, o, a) {
91
- const l = D();
91
+ const l = M();
92
92
  await se(l);
93
93
  const c = O(r.prompt, o);
94
94
  let i = e;
@@ -107,12 +107,12 @@ async function ge(r, e, t, s, o, a) {
107
107
  status: "in-progress",
108
108
  progress: { type: "message", speaker: "user", message: c }
109
109
  });
110
- const u = (await j(l.tools, a)).map((p) => p.spec), T = k;
110
+ const u = (await q(l.tools, a)).map((p) => p.spec), T = L;
111
111
  let f = 0;
112
112
  const d = 100;
113
113
  for (; f < d; ) {
114
114
  a.throwIfAborted(), f++;
115
- const p = new V(), w = await J(p, {
115
+ const p = new G(), w = await X(p, {
116
116
  enabledTodos: !1,
117
117
  threadEnv: t.threadEnvironment
118
118
  });
@@ -124,8 +124,8 @@ async function ge(r, e, t, s, o, a) {
124
124
  a.throwIfAborted();
125
125
  let b;
126
126
  try {
127
- const n = $.fromNativeThread(i);
128
- b = await L(
127
+ const n = C.fromNativeThread(i);
128
+ b = await _(
129
129
  n,
130
130
  u,
131
131
  U,
@@ -139,19 +139,19 @@ async function ge(r, e, t, s, o, a) {
139
139
  throw new Error("Unexpected response format from Anthropic");
140
140
  if (b.message.content.length === 0)
141
141
  break;
142
- const v = C(b.message);
143
- m(v);
142
+ const S = D(b.message);
143
+ m(S);
144
144
  const E = b.message.content.filter((n) => n.type === "text").map((n) => "text" in n ? n.text : "").join(" ").trim();
145
145
  if (E && s.update({
146
146
  status: "in-progress",
147
147
  progress: { type: "message", speaker: "assistant", message: E }
148
- }), v.type !== "assistant:message")
148
+ }), S.type !== "assistant:message")
149
149
  break;
150
- const B = ye(
150
+ const Y = ye(
151
151
  i,
152
- v.message
152
+ S.message
153
153
  );
154
- for (const n of B) {
154
+ for (const n of Y) {
155
155
  s.update({
156
156
  status: "in-progress",
157
157
  progress: {
@@ -171,13 +171,13 @@ async function ge(r, e, t, s, o, a) {
171
171
  a
172
172
  ), a.throwIfAborted(), y.status !== "done")
173
173
  throw new Error(JSON.stringify(y));
174
- } catch (I) {
174
+ } catch ($) {
175
175
  m({
176
176
  type: "tool:data",
177
177
  toolUse: n.id,
178
178
  data: {
179
179
  status: "error",
180
- error: { message: `Tool call error: ${I}` }
180
+ error: { message: `Tool call error: ${$}` }
181
181
  }
182
182
  }), s.update({
183
183
  status: "in-progress",
@@ -185,7 +185,7 @@ async function ge(r, e, t, s, o, a) {
185
185
  id: n.id,
186
186
  type: "toolResult",
187
187
  toolName: n.name,
188
- result: `Tool call error: ${I}`
188
+ result: `Tool call error: ${$}`
189
189
  }
190
190
  });
191
191
  continue;
@@ -225,7 +225,7 @@ async function fe(r, e, t, s, o) {
225
225
  status: "in-progress",
226
226
  progress: { type: "message", speaker: "user", message: a }
227
227
  });
228
- const i = $.fromNativeThread(l), m = r.model || k, u = await L(
228
+ const i = C.fromNativeThread(l), m = r.model || L, u = await _(
229
229
  i,
230
230
  [],
231
231
  // No tools for LLM-only step
@@ -236,7 +236,7 @@ async function fe(r, e, t, s, o) {
236
236
  );
237
237
  if (!u.message)
238
238
  throw new Error("Failed to get response from Anthropic");
239
- const T = C(u.message);
239
+ const T = D(u.message);
240
240
  c(T);
241
241
  const f = u.message.content.filter((d) => d.type === "text").map((d) => d.type === "text" ? d.text : "").join(" ").trim();
242
242
  return t.update({
@@ -245,7 +245,7 @@ async function fe(r, e, t, s, o) {
245
245
  }), l;
246
246
  }
247
247
  function ye(r, e) {
248
- const t = W(r);
248
+ const t = H(r);
249
249
  return e.content.filter((s) => s.type === "tool_use").filter((s) => !s.inputPartialJSON).filter(
250
250
  (s) => (
251
251
  // Only include tools that haven't been invoked yet.
@@ -258,7 +258,7 @@ async function R(r, e, t, s, o = new AbortController().signal, a) {
258
258
  let i = !1;
259
259
  const m = r.invokeTool(e, { args: t, userInput: a }, s).subscribe({
260
260
  next: (u) => {
261
- Y(u) && (m.unsubscribe(), i || (i = !0, l(u)));
261
+ Z(u) && (m.unsubscribe(), i || (i = !0, l(u)));
262
262
  },
263
263
  error: (u) => {
264
264
  i || (i = !0, c(u));
@@ -271,10 +271,10 @@ async function R(r, e, t, s, o = new AbortController().signal, a) {
271
271
  });
272
272
  });
273
273
  }
274
- const Te = ({ args: r }, e) => new z((t) => {
274
+ const Te = ({ args: r }, e) => new K((t) => {
275
275
  const s = new AbortController(), o = new me(t, s.signal);
276
276
  return he(r, e, o, s.signal).catch((a) => {
277
- M(a) ? (o.update({
277
+ N(a) ? (o.update({
278
278
  status: "cancelled",
279
279
  progress: { type: "meta", message: "Operation cancelled" }
280
280
  }), o.complete()) : o.error(a);
@@ -289,8 +289,8 @@ async function he(r, e, t, s) {
289
289
  status: "in-progress",
290
290
  progress: { type: "meta", message: `Loading routine: ${o} from ${l}` }
291
291
  });
292
- const c = D();
293
- c.registerTool(Z);
292
+ const c = M();
293
+ c.registerTool(Q);
294
294
  const i = await R(
295
295
  c,
296
296
  "read_file",
@@ -310,7 +310,7 @@ async function he(r, e, t, s) {
310
310
  if (!f)
311
311
  throw new Error(`Routine with id "${o}" not found in ${l}`);
312
312
  let d = {
313
- id: q(),
313
+ id: ee(),
314
314
  created: Date.now(),
315
315
  v: 0,
316
316
  messages: []
@@ -350,13 +350,13 @@ async function he(r, e, t, s) {
350
350
  // No output for now
351
351
  }), t.complete();
352
352
  } catch (o) {
353
- M(o) ? (t.update({
353
+ N(o) ? (t.update({
354
354
  status: "cancelled",
355
355
  progress: {
356
356
  type: "meta",
357
357
  message: "Operation cancelled"
358
358
  }
359
- }), t.complete()) : (G.error("Error in run_routine", {
359
+ }), t.complete()) : (te.error("Error in run_routine", {
360
360
  error: o,
361
361
  stack: o instanceof Error ? o.stack : ""
362
362
  }), t.error(o));
@@ -365,4 +365,4 @@ async function he(r, e, t, s) {
365
365
  export {
366
366
  Te as runRoutine
367
367
  };
368
- //# sourceMappingURL=node-B1RLuGfG.js.map
368
+ //# sourceMappingURL=node-BHe5RJPs.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"node-B1RLuGfG.js","sources":["../../core/src/tools/builtin/run_routine/types.ts","../../core/src/tools/builtin/run_routine/serialization.ts","../../core/src/tools/builtin/run_routine/util.ts","../../core/src/tools/builtin/run_routine/step.ts","../../core/src/tools/builtin/run_routine/node.ts"],"sourcesContent":["import { z } from 'zod'\n\n// Base Step interface\nconst BaseStep = z.object({\n\tcontext: z.enum(['continue', 'none']).optional().default('continue'),\n\ttools: z.union([z.literal('all'), z.array(z.string())]).optional(),\n\tprompt: z.string(),\n\tverify: z.record(z.any()).optional(),\n}) satisfies z.ZodType<{\n\tcontext?: 'continue' | 'none'\n\ttools?: 'all' | string[]\n\tprompt: string\n\tverify?: Record<string, any>\n}>\n\n// Agent Step\nconst AgentStep = BaseStep.extend({\n\ttype: z.literal('agent'),\n\tmodel: z.string().optional(), // Default could be set in implementation\n\tinteractive_confirmation: z.boolean().optional(),\n})\n\n// LLM Step\nconst LLMStep = BaseStep.extend({\n\ttype: z.literal('llm'),\n\tmodel: z.string().optional(),\n})\n\n// Loop Agent Step\nconst LoopAgentStep = BaseStep.extend({\n\ttype: z.literal('loop_agent'),\n\tmodel: z.string().optional(),\n\tinput_file: z.string(),\n})\n\n// Loop LLM Step\nconst LoopLLMStep = BaseStep.extend({\n\ttype: z.literal('loop_llm'),\n\tmodel: z.string().optional(),\n\tinput_file: z.string(),\n})\n\n// Tool Call Step\nconst ToolCallStep = z.object({\n\ttype: z.literal('tool_call'),\n\ttool: z.string(),\n\tparameters: z.record(z.any()).optional(),\n})\n\n// Bash Step\nconst BashStep = z.object({\n\ttype: z.literal('bash'),\n\tcommand: z.string(),\n})\n\n// Union of all step types\nconst Step = z.discriminatedUnion('type', [\n\tAgentStep,\n\tLLMStep,\n\tLoopAgentStep,\n\tLoopLLMStep,\n\tToolCallStep,\n\tBashStep,\n])\n\n// Routine Block\nconst RoutineBlock = z.object({\n\tid: z.string(),\n\tsteps: z.array(Step),\n})\n\n// Routine (array of RoutineBlocks)\nconst Routine = z.array(RoutineBlock)\n\nconst Routines = z.array(Routine)\n\nexport type RoutineSchema = z.infer<typeof Routine>\nexport type RoutinesSchema = z.infer<typeof Routines>\nexport type RoutineBlockSchema = z.infer<typeof RoutineBlock>\nexport type StepSchema = z.infer<typeof Step>\nexport type AgentStepSchema = z.infer<typeof AgentStep>\nexport type LLMStepSchema = z.infer<typeof LLMStep>\nexport type LoopAgentStepSchema = z.infer<typeof LoopAgentStep>\nexport type LoopLLMStepSchema = z.infer<typeof LoopLLMStep>\nexport type ToolCallStepSchema = z.infer<typeof ToolCallStep>\nexport type BashStepSchema = z.infer<typeof BashStep>\n\nexport { Routine, RoutineBlock, Routines, Step }\n","import { parse } from 'yaml'\nimport { z } from 'zod'\nimport type { RoutineSchema } from './types'\nimport { Routine } from './types'\n\n/**\n * Deserialize a YAML string into a Routine\n * @param yamlString The YAML string representation of a Routine\n * @returns The parsed and validated Routine\n * @throws Error if the YAML is invalid or doesn't match the Routine schema\n */\nexport function deserializeRoutineFromYAML(yamlString: string): RoutineSchema {\n\ttry {\n\t\t// Parse the YAML string to a JavaScript object\n\t\tconst parsedYaml = parse(yamlString)\n\n\t\t// Validate and transform the parsed YAML against the Routine schema\n\t\tconst validatedRoutine = Routine.parse(parsedYaml)\n\n\t\treturn validatedRoutine\n\t} catch (error) {\n\t\tif (error instanceof z.ZodError) {\n\t\t\t// Enhance Zod validation errors with better context\n\t\t\tthrow new Error(\n\t\t\t\t`Invalid routine format: ${error.errors\n\t\t\t\t\t.map((err) => `${err.path.join('.')} - ${err.message}`)\n\t\t\t\t\t.join(', ')}`,\n\t\t\t)\n\t\t} else if (error instanceof Error) {\n\t\t\t// Handle YAML parsing errors\n\t\t\tthrow new Error(`Failed to parse YAML: ${error.message}`)\n\t\t} else {\n\t\t\tthrow new Error(`Unknown error during routine deserialization: ${String(error)}`)\n\t\t}\n\t}\n}\n","import type { SubscriptionObserver } from '@sourcegraph/observable'\nimport type { ToolRun } from '../../tool-service'\nimport type { RunRoutineProgressMessage, RunRoutineToolDef } from './common'\n\n/**\n * Class that maintains state for status messages in run_routine implementation.\n * Keeps track of all status messages and reports them through the observer.\n */\nexport class ProgressReporter {\n\tprivate progressMessages: RunRoutineProgressMessage[] = []\n\n\tconstructor(\n\t\tprivate observer: SubscriptionObserver<ToolRun<RunRoutineToolDef>>,\n\t\tprivate signal: AbortSignal,\n\t) {}\n\n\t/**\n\t * Adds the latest message to the list of all status updates and then invokes the observer\n\t * with the updated 'in-progress' status.\n\t */\n\tupdate(update: ToolRun<RunRoutineToolDef>): void {\n\t\tthis.signal.throwIfAborted()\n\t\tif ('progress' in update && update.progress) {\n\t\t\tif (Array.isArray(update.progress)) {\n\t\t\t\tthis.progressMessages.push(...update.progress)\n\t\t\t} else {\n\t\t\t\tthis.progressMessages.push(update.progress)\n\t\t\t}\n\t\t\tthis.observer.next({\n\t\t\t\t...update,\n\t\t\t\tprogress: this.progressMessages,\n\t\t\t})\n\t\t} else {\n\t\t\tthis.observer.next(update)\n\t\t}\n\t}\n\n\terror(error: unknown): void {\n\t\tthis.observer.error(error)\n\t}\n\n\tcomplete(): void {\n\t\tthis.observer.complete()\n\t}\n}\n\n/**\n * Apply variable substitutions to a prompt string\n */\nexport function substitutePromptVars(prompt: string, vars: { userInput?: string }): string {\n\tlet result = prompt\n\n\t// Replace {{userInput}} with the actual user input if provided\n\tif (vars.userInput) {\n\t\tresult = result.replace(/\\{\\{\\s*userInput\\s*\\}\\}/g, vars.userInput)\n\t\tresult = result.replace(/\\{\\{\\s*user_input\\s*\\}\\}/g, vars.userInput)\n\t}\n\n\treturn result\n}\n","import { firstValueFrom } from '@sourcegraph/observable'\nimport {\n\tACTIVE_MODEL,\n\tAnthropicConverters,\n\tfromAnthropicResultToThreadDelta,\n\trunAnthropicSync,\n} from '../../../inference/backends/anthropic'\nimport { buildSystemPrompt, DefaultSystemPromptService } from '../../../threads/system-prompt'\nimport type { ToolUseBlock } from '../../../threads/thread'\nimport {\n\ttoolResultBlocks,\n\ttype Thread,\n\ttype ThreadAssistantMessage,\n\ttype ToolRunUserInput,\n} from '../../../threads/thread'\nimport type { ThreadDelta } from '../../../threads/thread-delta'\nimport { applyThreadDelta } from '../../../threads/thread-delta'\nimport type {\n\tToolDefinition,\n\tToolRun,\n\tToolRunEnvironment,\n\tToolService,\n} from '../../../tools/tool-service'\nimport { createToolService, isToolRunTerminalState } from '../../../tools/tool-service'\nimport { registerBuiltinToolsToToolService } from '../../tools'\nimport type { AgentStepSchema, LLMStepSchema, StepSchema } from './types'\nimport { substitutePromptVars, type ProgressReporter } from './util'\n\n/**\n * Run a step with the given conversation\n */\nexport function runStep(\n\tstep: StepSchema,\n\tconversation: Thread,\n\tenv: ToolRunEnvironment,\n\tprogressReporter: ProgressReporter,\n\tvars: { userInput?: string },\n\tsignal: AbortSignal = new AbortController().signal,\n): Promise<Thread> {\n\tswitch (step.type) {\n\t\tcase 'agent':\n\t\t\treturn runStepAgent(step, conversation, env, progressReporter, vars, signal)\n\t\t\tbreak\n\t\tcase 'llm':\n\t\t\treturn runStepLLM(step, conversation, progressReporter, vars, signal)\n\t\t\tbreak\n\t\tdefault:\n\t\t\tthrow new Error(`Unknown step type: ${(step as any).type}`)\n\t}\n}\n\n/**\n * Run an agent step that implements a full agentic loop\n * Follows the pattern: inference -> tool calls -> tool results -> inference\n * until there are no more tool calls or the process is complete\n */\nasync function runStepAgent(\n\tstep: AgentStepSchema,\n\torigConversation: Thread,\n\tenv: ToolRunEnvironment,\n\tprogressReporter: ProgressReporter,\n\tvars: { userInput?: string },\n\tsignal: AbortSignal,\n): Promise<Thread> {\n\tconst toolService = createToolService()\n\tawait registerBuiltinToolsToToolService(toolService)\n\n\t// Process prompt template with variables if provided\n\tconst promptText = substitutePromptVars(step.prompt, vars)\n\n\t// Clone convo\n\tlet conversation = origConversation\n\tconst recordThreadDelta = (delta: ThreadDelta) => {\n\t\tconversation = applyThreadDelta(conversation, delta)\n\t}\n\n\trecordThreadDelta({\n\t\ttype: 'user:message',\n\t\tmessage: {\n\t\t\tcontent: [{ type: 'text', text: promptText }],\n\t\t\tmeta: {\n\t\t\t\tsentAt: Date.now(),\n\t\t\t},\n\t\t},\n\t})\n\n\t// Update progress with user message added\n\tprogressReporter.update({\n\t\tstatus: 'in-progress',\n\t\tprogress: { type: 'message', speaker: 'user', message: promptText },\n\t})\n\n\t// Get enabled tools from toolService (all tools for now)\n\tconst enabledToolSpecs = (await firstValueFrom(toolService.tools, signal)).map((t) => t.spec)\n\n\t// Set up parameters for the initial API call\n\tconst model = ACTIVE_MODEL\n\n\t// The agent loop will continue until there are no more tool calls needed\n\tlet loopCount = 0\n\tconst maxLoops = 100 // Prevent infinite loops\n\n\twhile (loopCount < maxLoops) {\n\t\tsignal.throwIfAborted()\n\t\tloopCount++\n\n\t\t// Get system prompt blocks from the main system prompt builder\n\t\tconst systemPromptService = new DefaultSystemPromptService()\n\t\t// Get the main system prompt blocks\n\t\tconst systemPromptBlocks = await buildSystemPrompt(systemPromptService, {\n\t\t\tenabledTodos: false,\n\t\t\tthreadEnv: env.threadEnvironment,\n\t\t})\n\n\t\t// Add the subagent-specific instruction as the final block\n\t\tsystemPromptBlocks.push({\n\t\t\ttype: 'text' as const,\n\t\t\ttext: 'You are a helpful AI assistant running as a subagent within a larger system. Your task is to handle this specific step in a routine. You can use tools to complete your task. When you are completely done, do not ask to use more tools.',\n\t\t})\n\n\t\t// Use the combined system prompt\n\t\tconst systemPrompt = systemPromptBlocks\n\n\t\tsignal.throwIfAborted()\n\n\t\t// Use runAnthropicSync to get a response\n\t\tlet result\n\t\ttry {\n\t\t\tconst anthropicMessages = AnthropicConverters.fromNativeThread(conversation)\n\t\t\tresult = await runAnthropicSync(\n\t\t\t\tanthropicMessages,\n\t\t\t\tenabledToolSpecs,\n\t\t\t\tsystemPrompt,\n\t\t\t\tmodel,\n\t\t\t\tsignal,\n\t\t\t)\n\t\t} catch (error) {\n\t\t\tthrow new Error(`Anthropic API error: ${error}`)\n\t\t}\n\n\t\tif (!result.message || !('content' in result.message)) {\n\t\t\tthrow new Error('Unexpected response format from Anthropic')\n\t\t}\n\t\tif (result.message.content.length === 0) {\n\t\t\tbreak\n\t\t}\n\n\t\tconst assistantResponseDelta = fromAnthropicResultToThreadDelta(result.message)\n\t\trecordThreadDelta(assistantResponseDelta)\n\n\t\t// Extract text for progress reporting\n\t\tconst assistantText = result.message.content\n\t\t\t.filter((item) => item.type === 'text')\n\t\t\t.map((item) => ('text' in item ? item.text : ''))\n\t\t\t.join(' ')\n\t\t\t.trim()\n\t\tif (assistantText) {\n\t\t\t// Show assistant message\n\t\t\tprogressReporter.update({\n\t\t\t\tstatus: 'in-progress',\n\t\t\t\tprogress: { type: 'message', speaker: 'assistant', message: assistantText },\n\t\t\t})\n\t\t}\n\n\t\tif (assistantResponseDelta.type !== 'assistant:message') {\n\t\t\t// No tool calls\n\t\t\tbreak\n\t\t}\n\n\t\tconst toolCalls = findToolUsesNeedingInvocation(\n\t\t\tconversation,\n\t\t\tassistantResponseDelta.message,\n\t\t)\n\t\tfor (const toolCall of toolCalls) {\n\t\t\tprogressReporter.update({\n\t\t\t\tstatus: 'in-progress',\n\t\t\t\tprogress: {\n\t\t\t\t\tid: toolCall.id,\n\t\t\t\t\ttype: 'toolCall',\n\t\t\t\t\ttoolName: toolCall.name,\n\t\t\t\t\targs: JSON.stringify(toolCall.input),\n\t\t\t\t},\n\t\t\t})\n\n\t\t\tlet toolResult\n\t\t\ttry {\n\t\t\t\ttoolResult = await invokeToolAndWaitForResult(\n\t\t\t\t\ttoolService,\n\t\t\t\t\ttoolCall.name,\n\t\t\t\t\ttoolCall.input,\n\t\t\t\t\tenv,\n\t\t\t\t\tsignal,\n\t\t\t\t)\n\t\t\t\tsignal.throwIfAborted()\n\t\t\t\tif (toolResult.status !== 'done') {\n\t\t\t\t\tthrow new Error(JSON.stringify(toolResult))\n\t\t\t\t}\n\t\t\t} catch (error) {\n\t\t\t\trecordThreadDelta({\n\t\t\t\t\ttype: 'tool:data',\n\t\t\t\t\ttoolUse: toolCall.id,\n\t\t\t\t\tdata: {\n\t\t\t\t\t\tstatus: 'error',\n\t\t\t\t\t\terror: { message: `Tool call error: ${error}` },\n\t\t\t\t\t},\n\t\t\t\t})\n\t\t\t\tprogressReporter.update({\n\t\t\t\t\tstatus: 'in-progress',\n\t\t\t\t\tprogress: {\n\t\t\t\t\t\tid: toolCall.id,\n\t\t\t\t\t\ttype: 'toolResult',\n\t\t\t\t\t\ttoolName: toolCall.name,\n\t\t\t\t\t\tresult: `Tool call error: ${error}`,\n\t\t\t\t\t},\n\t\t\t\t})\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\trecordThreadDelta({\n\t\t\t\ttype: 'tool:data',\n\t\t\t\ttoolUse: toolCall.id,\n\t\t\t\tdata: toolResult,\n\t\t\t})\n\t\t\tprogressReporter.update({\n\t\t\t\tstatus: 'in-progress',\n\t\t\t\tprogress: {\n\t\t\t\t\tid: toolCall.id,\n\t\t\t\t\ttype: 'toolResult',\n\t\t\t\t\ttoolName: toolCall.name,\n\t\t\t\t\tresult:\n\t\t\t\t\t\ttypeof toolResult.result === 'string'\n\t\t\t\t\t\t\t? toolResult.result\n\t\t\t\t\t\t\t: JSON.stringify(toolResult.result),\n\t\t\t\t},\n\t\t\t})\n\t\t}\n\t}\n\treturn conversation\n}\n\n/**\n * Mock implementation of tool execution for the subagent\n * In a real implementation, this would connect to the actual tool execution system\n */\n// Removed mock implementation in favor of actual toolService\n\n/**\n * Run an LLM step\n */\nasync function runStepLLM(\n\tstep: LLMStepSchema,\n\torigConversation: Thread,\n\tprogressReporter: ProgressReporter,\n\tvars: { userInput?: string },\n\tsignal: AbortSignal,\n): Promise<Thread> {\n\t// Process prompt template with variables if provided\n\tconst promptText = substitutePromptVars(step.prompt, vars)\n\n\t// Create a copy of the conversation to avoid mutating the original\n\tlet conversation = origConversation\n\tconst recordThreadDelta = (delta: ThreadDelta) => {\n\t\tconversation = applyThreadDelta(conversation, delta)\n\t}\n\n\trecordThreadDelta({\n\t\ttype: 'user:message',\n\t\tmessage: {\n\t\t\tcontent: [{ type: 'text', text: promptText }],\n\t\t\tmeta: {\n\t\t\t\tsentAt: Date.now(),\n\t\t\t},\n\t\t},\n\t})\n\n\t// Update progress with user message added\n\tprogressReporter.update({\n\t\tstatus: 'in-progress',\n\t\tprogress: { type: 'message', speaker: 'user', message: promptText },\n\t})\n\n\t// Use runAnthropicSync to get a response\n\tconst anthropicMessages = AnthropicConverters.fromNativeThread(conversation)\n\tconst model = step.model || ACTIVE_MODEL\n\tconst result = await runAnthropicSync(\n\t\tanthropicMessages,\n\t\t[], // No tools for LLM-only step\n\t\t[], // No system prompt\n\t\tmodel,\n\t\tsignal,\n\t)\n\n\tif (!result.message) {\n\t\tthrow new Error('Failed to get response from Anthropic')\n\t}\n\n\tconst assistantResponseDelta = fromAnthropicResultToThreadDelta(result.message)\n\trecordThreadDelta(assistantResponseDelta)\n\n\t// Display message\n\tconst assistantText = result.message.content\n\t\t.filter((item) => item.type === 'text')\n\t\t.map((item) => (item.type === 'text' ? item.text : ''))\n\t\t.join(' ')\n\t\t.trim()\n\tprogressReporter.update({\n\t\tstatus: 'in-progress',\n\t\tprogress: { type: 'message', speaker: 'assistant', message: assistantText },\n\t})\n\treturn conversation\n}\n\nfunction findToolUsesNeedingInvocation(\n\tthread: Thread,\n\tmessage: ThreadAssistantMessage,\n): ToolUseBlock[] {\n\tconst toolResults = toolResultBlocks(thread)\n\treturn message.content\n\t\t.filter((block): block is ToolUseBlock => block.type === 'tool_use')\n\t\t.filter((block) => !block.inputPartialJSON)\n\t\t.filter(\n\t\t\t(block) =>\n\t\t\t\t// Only include tools that haven't been invoked yet.\n\t\t\t\t!toolResults.has(block.id),\n\t\t)\n}\n\n/**\n * Helper function that invokes a tool and returns a Promise with the final result\n */\nexport async function invokeToolAndWaitForResult<T extends ToolDefinition>(\n\ttoolService: ToolService,\n\ttoolName: string,\n\tinput: unknown,\n\tenv: ToolRunEnvironment,\n\tsignal: AbortSignal = new AbortController().signal,\n\tuserInput?: ToolRunUserInput,\n): Promise<ToolRun<T>> {\n\treturn new Promise((resolve, reject) => {\n\t\tlet settled = false\n\t\tconst sub = toolService\n\t\t\t.invokeTool(toolName, { args: input as any, userInput }, env)\n\t\t\t.subscribe({\n\t\t\t\tnext: (run: ToolRun) => {\n\t\t\t\t\tif (isToolRunTerminalState(run)) {\n\t\t\t\t\t\tsub.unsubscribe()\n\t\t\t\t\t\tif (!settled) {\n\t\t\t\t\t\t\tsettled = true\n\t\t\t\t\t\t\tresolve(run)\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t},\n\t\t\t\terror: (error) => {\n\t\t\t\t\tif (!settled) {\n\t\t\t\t\t\tsettled = true\n\t\t\t\t\t\treject(error)\n\t\t\t\t\t}\n\t\t\t\t},\n\t\t\t\tcomplete: () => {},\n\t\t\t})\n\n\t\t// Handle abort signal\n\t\tsignal.addEventListener('abort', () => {\n\t\t\tsub.unsubscribe()\n\t\t\tif (!settled) {\n\t\t\t\tsettled = true\n\t\t\t\treject(new Error('Tool execution was aborted'))\n\t\t\t}\n\t\t})\n\t})\n}\n","import { Observable } from '@sourcegraph/observable'\nimport { isAbortError } from '../../../common/abort'\nimport logger from '../../../common/logger'\nimport type { Thread } from '../../../threads/thread'\nimport { newThreadID } from '../../../threads/thread'\nimport type { ToolRunEnvironment } from '../../tool-service'\nimport { createToolService } from '../../tool-service'\nimport type { ReadFileToolDef } from '../filesystem/read_file.common'\nimport { readFileToolReg } from '../filesystem/read_file.common'\nimport type { runRoutineToolReg } from './common'\nimport { deserializeRoutineFromYAML } from './serialization'\nimport { invokeToolAndWaitForResult, runStep } from './step'\nimport { ProgressReporter } from './util'\n\nexport const runRoutine: NonNullable<(typeof runRoutineToolReg)['fn']> = ({ args }, env) => {\n\treturn new Observable((observer) => {\n\t\tconst abortController = new AbortController()\n\t\tconst progressReporter = new ProgressReporter(observer, abortController.signal)\n\n\t\trunRoutineImpl(args, env, progressReporter, abortController.signal).catch((error) => {\n\t\t\t// Don't report AbortError as an error - it's expected when cancelling\n\t\t\tif (!isAbortError(error)) {\n\t\t\t\tprogressReporter.error(error)\n\t\t\t} else {\n\t\t\t\tprogressReporter.update({\n\t\t\t\t\tstatus: 'cancelled' as const,\n\t\t\t\t\tprogress: { type: 'meta', message: 'Operation cancelled' },\n\t\t\t\t})\n\t\t\t\tprogressReporter.complete()\n\t\t\t}\n\t\t})\n\n\t\treturn () => {\n\t\t\tabortController.abort()\n\t\t}\n\t})\n}\n\nasync function runRoutineImpl(\n\targs: { id: string; file?: string; userInput?: string },\n\tenv: ToolRunEnvironment,\n\tprogressReporter: ProgressReporter,\n\tsignal: AbortSignal,\n) {\n\ttry {\n\t\tconst { id, file } = args\n\t\tconst routineFile = file || 'routines.amp.yaml'\n\n\t\t// Report initial progress\n\t\tprogressReporter.update({\n\t\t\tstatus: 'in-progress',\n\t\t\tprogress: { type: 'meta', message: `Loading routine: ${id} from ${routineFile}` },\n\t\t})\n\n\t\t// Create a tool service and register the read_file tool\n\t\tconst toolService = createToolService()\n\t\ttoolService.registerTool(readFileToolReg)\n\n\t\t// Read the routine file using the tool service\n\t\tconst readFileResult = await invokeToolAndWaitForResult<ReadFileToolDef>(\n\t\t\ttoolService,\n\t\t\t'read_file',\n\t\t\t{ path: routineFile },\n\t\t\tenv,\n\t\t\tsignal,\n\t\t)\n\n\t\t// Process the file content by removing line numbers that read_file adds\n\t\tif (readFileResult.status !== 'done') {\n\t\t\tthrow new Error(`Failed to read routine file: ${routineFile}`)\n\t\t}\n\t\t// At this point TypeScript knows readFileResult has a 'result' property\n\t\tconst fileContents =\n\t\t\ttypeof readFileResult.result === 'string'\n\t\t\t\t? readFileResult.result\n\t\t\t\t: readFileResult.result.content\n\t\tconst routineContent = String(fileContents)\n\t\t\t.split('\\n')\n\t\t\t.map((line: string) => line.replace(/^\\d+:\\s/, ''))\n\t\t\t.join('\\n')\n\n\t\tsignal.throwIfAborted()\n\n\t\t// Parse the routines\n\t\tconst routines = deserializeRoutineFromYAML(routineContent)\n\t\tsignal.throwIfAborted()\n\n\t\t// Find the requested routine\n\t\tconst routine = routines.find((routine) => routine.id === id)\n\t\tif (!routine) {\n\t\t\tthrow new Error(`Routine with id \"${id}\" not found in ${routineFile}`)\n\t\t}\n\n\t\t// Initialize a Thread for the conversation\n\t\tlet conversation: Thread = {\n\t\t\tid: newThreadID(),\n\t\t\tcreated: Date.now(),\n\t\t\tv: 0,\n\t\t\tmessages: [],\n\t\t}\n\n\t\t// Report progress before executing steps\n\t\tprogressReporter.update({\n\t\t\tstatus: 'in-progress',\n\t\t\tprogress: [\n\t\t\t\t{\n\t\t\t\t\ttype: 'meta',\n\t\t\t\t\tmessage: `Executing routine ${id}`,\n\t\t\t\t},\n\t\t\t],\n\t\t})\n\n\t\t// Execute each step in the routine\n\t\tfor (let i = 0; i < routine.steps.length; i++) {\n\t\t\tconst step = routine.steps[i]\n\t\t\tif (!step) continue // Skip undefined steps\n\n\t\t\tprogressReporter.update({\n\t\t\t\tstatus: 'in-progress',\n\t\t\t\tprogress: [\n\t\t\t\t\t{\n\t\t\t\t\t\ttype: 'meta',\n\t\t\t\t\t\tmessage: `Executing step ${i + 1}/${routine.steps.length}: ${step.type}`,\n\t\t\t\t\t\tvariant: 'header',\n\t\t\t\t\t},\n\t\t\t\t],\n\t\t\t})\n\n\t\t\tsignal.throwIfAborted()\n\n\t\t\t// Execute the step and update the conversation\n\t\t\tconversation = await runStep(step, conversation, env, progressReporter, {\n\t\t\t\tuserInput: args.userInput,\n\t\t\t})\n\t\t}\n\n\t\tprogressReporter.update({\n\t\t\tstatus: 'done' as const,\n\t\t\tprogress: {\n\t\t\t\ttype: 'meta',\n\t\t\t\tmessage: `Finished executing all ${routine.steps.length} steps of routine: ${id}.`,\n\t\t\t\tvariant: 'header',\n\t\t\t},\n\t\t\tresult: '', // No output for now\n\t\t})\n\n\t\tprogressReporter.complete()\n\t} catch (error) {\n\t\tif (isAbortError(error)) {\n\t\t\tprogressReporter.update({\n\t\t\t\tstatus: 'cancelled' as const,\n\t\t\t\tprogress: {\n\t\t\t\t\ttype: 'meta',\n\t\t\t\t\tmessage: 'Operation cancelled',\n\t\t\t\t},\n\t\t\t})\n\t\t\tprogressReporter.complete()\n\t\t} else {\n\t\t\tlogger.error('Error in run_routine', {\n\t\t\t\terror,\n\t\t\t\tstack: error instanceof Error ? error.stack : '',\n\t\t\t})\n\t\t\tprogressReporter.error(error)\n\t\t}\n\t}\n}\n"],"names":["BaseStep","z.object","z.enum","z.union","z.literal","z.array","z.string","z.record","z.any","AgentStep","z.boolean","LLMStep","LoopAgentStep","LoopLLMStep","ToolCallStep","BashStep","Step","z.discriminatedUnion","RoutineBlock","Routine","deserializeRoutineFromYAML","yamlString","parsedYaml","parse","error","z.ZodError","err","ProgressReporter","observer","signal","update","substitutePromptVars","prompt","vars","result","runStep","step","conversation","env","progressReporter","runStepAgent","runStepLLM","origConversation","toolService","createToolService","registerBuiltinToolsToToolService","promptText","recordThreadDelta","delta","applyThreadDelta","enabledToolSpecs","firstValueFrom","t","model","ACTIVE_MODEL","loopCount","maxLoops","systemPromptService","DefaultSystemPromptService","systemPromptBlocks","buildSystemPrompt","systemPrompt","anthropicMessages","AnthropicConverters","runAnthropicSync","assistantResponseDelta","fromAnthropicResultToThreadDelta","assistantText","item","toolCalls","findToolUsesNeedingInvocation","toolCall","toolResult","invokeToolAndWaitForResult","thread","message","toolResults","toolResultBlocks","block","toolName","input","userInput","resolve","reject","settled","sub","run","isToolRunTerminalState","runRoutine","args","Observable","abortController","runRoutineImpl","isAbortError","id","file","routineFile","readFileToolReg","readFileResult","fileContents","routineContent","line","routines","routine","newThreadID","i","logger"],"mappings":";;;AAGA,MAAMA,IAAWC,EAAS;AAAA,EACzB,SAASC,EAAO,CAAC,YAAY,MAAM,CAAC,EAAE,SAAA,EAAW,QAAQ,UAAU;AAAA,EACnE,OAAOC,EAAQ,CAACC,EAAU,KAAK,GAAGC,EAAQC,EAAU,CAAA,CAAC,CAAC,EAAE,SAAS;AAAA,EACjE,QAAQA,EAAS;AAAA,EACjB,QAAQC,EAASC,EAAO,CAAA,EAAE,SAAS;AACpC,CAAC,GAQKC,KAAYT,EAAS,OAAO;AAAA,EACjC,MAAMI,EAAU,OAAO;AAAA,EACvB,OAAOE,EAAS,EAAE,SAAS;AAAA;AAAA,EAC3B,0BAA0BI,EAAU,EAAE,SAAS;AAChD,CAAC,GAGKC,KAAUX,EAAS,OAAO;AAAA,EAC/B,MAAMI,EAAU,KAAK;AAAA,EACrB,OAAOE,EAAS,EAAE,SAAS;AAC5B,CAAC,GAGKM,KAAgBZ,EAAS,OAAO;AAAA,EACrC,MAAMI,EAAU,YAAY;AAAA,EAC5B,OAAOE,EAAS,EAAE,SAAS;AAAA,EAC3B,YAAYA,EAAS;AACtB,CAAC,GAGKO,KAAcb,EAAS,OAAO;AAAA,EACnC,MAAMI,EAAU,UAAU;AAAA,EAC1B,OAAOE,EAAS,EAAE,SAAS;AAAA,EAC3B,YAAYA,EAAS;AACtB,CAAC,GAGKQ,KAAeb,EAAS;AAAA,EAC7B,MAAMG,EAAU,WAAW;AAAA,EAC3B,MAAME,EAAS;AAAA,EACf,YAAYC,EAASC,EAAO,CAAA,EAAE,SAAS;AACxC,CAAC,GAGKO,KAAWd,EAAS;AAAA,EACzB,MAAMG,EAAU,MAAM;AAAA,EACtB,SAASE,EAAS;AACnB,CAAC,GAGKU,KAA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A,aAAiB,QAAQA,EAAM,QAAQ;AAAA,IAAA,CAC9C,GACDe,EAAiB,MAAMf,CAAK;AAAA,EAC7B;AAEF;"}
1
+ {"version":3,"file":"node-BHe5RJPs.js","sources":["../../core/src/tools/builtin/run_routine/types.ts","../../core/src/tools/builtin/run_routine/serialization.ts","../../core/src/tools/builtin/run_routine/util.ts","../../core/src/tools/builtin/run_routine/step.ts","../../core/src/tools/builtin/run_routine/node.ts"],"sourcesContent":["import { z } from 'zod'\n\n// Base Step interface\nconst BaseStep = z.object({\n\tcontext: z.enum(['continue', 'none']).optional().default('continue'),\n\ttools: z.union([z.literal('all'), z.array(z.string())]).optional(),\n\tprompt: z.string(),\n\tverify: z.record(z.any()).optional(),\n}) satisfies z.ZodType<{\n\tcontext?: 'continue' | 'none'\n\ttools?: 'all' | string[]\n\tprompt: string\n\tverify?: Record<string, any>\n}>\n\n// Agent Step\nconst AgentStep = BaseStep.extend({\n\ttype: z.literal('agent'),\n\tmodel: z.string().optional(), // Default could be set in implementation\n\tinteractive_confirmation: z.boolean().optional(),\n})\n\n// LLM Step\nconst LLMStep = BaseStep.extend({\n\ttype: z.literal('llm'),\n\tmodel: z.string().optional(),\n})\n\n// Loop Agent Step\nconst LoopAgentStep = BaseStep.extend({\n\ttype: z.literal('loop_agent'),\n\tmodel: z.string().optional(),\n\tinput_file: z.string(),\n})\n\n// Loop LLM Step\nconst LoopLLMStep = BaseStep.extend({\n\ttype: z.literal('loop_llm'),\n\tmodel: z.string().optional(),\n\tinput_file: z.string(),\n})\n\n// Tool Call Step\nconst ToolCallStep = z.object({\n\ttype: z.literal('tool_call'),\n\ttool: z.string(),\n\tparameters: z.record(z.any()).optional(),\n})\n\n// Bash Step\nconst BashStep = z.object({\n\ttype: z.literal('bash'),\n\tcommand: z.string(),\n})\n\n// Union of all step types\nconst Step = z.discriminatedUnion('type', [\n\tAgentStep,\n\tLLMStep,\n\tLoopAgentStep,\n\tLoopLLMStep,\n\tToolCallStep,\n\tBashStep,\n])\n\n// Routine Block\nconst RoutineBlock = z.object({\n\tid: z.string(),\n\tsteps: z.array(Step),\n})\n\n// Routine (array of RoutineBlocks)\nconst Routine = z.array(RoutineBlock)\n\nconst Routines = z.array(Routine)\n\nexport type RoutineSchema = z.infer<typeof Routine>\nexport type RoutinesSchema = z.infer<typeof Routines>\nexport type RoutineBlockSchema = z.infer<typeof RoutineBlock>\nexport type StepSchema = z.infer<typeof Step>\nexport type AgentStepSchema = z.infer<typeof AgentStep>\nexport type LLMStepSchema = z.infer<typeof LLMStep>\nexport type LoopAgentStepSchema = z.infer<typeof LoopAgentStep>\nexport type LoopLLMStepSchema = z.infer<typeof LoopLLMStep>\nexport type ToolCallStepSchema = z.infer<typeof ToolCallStep>\nexport type BashStepSchema = z.infer<typeof BashStep>\n\nexport { Routine, RoutineBlock, Routines, Step }\n","import { parse } from 'yaml'\nimport { z } from 'zod'\nimport type { RoutineSchema } from './types'\nimport { Routine } from './types'\n\n/**\n * Deserialize a YAML string into a Routine\n * @param yamlString The YAML string representation of a Routine\n * @returns The parsed and validated Routine\n * @throws Error if the YAML is invalid or doesn't match the Routine schema\n */\nexport function deserializeRoutineFromYAML(yamlString: string): RoutineSchema {\n\ttry {\n\t\t// Parse the YAML string to a JavaScript object\n\t\tconst parsedYaml = parse(yamlString)\n\n\t\t// Validate and transform the parsed YAML against the Routine schema\n\t\tconst validatedRoutine = Routine.parse(parsedYaml)\n\n\t\treturn validatedRoutine\n\t} catch (error) {\n\t\tif (error instanceof z.ZodError) {\n\t\t\t// Enhance Zod validation errors with better context\n\t\t\tthrow new Error(\n\t\t\t\t`Invalid routine format: ${error.errors\n\t\t\t\t\t.map((err) => `${err.path.join('.')} - ${err.message}`)\n\t\t\t\t\t.join(', ')}`,\n\t\t\t)\n\t\t} else if (error instanceof Error) {\n\t\t\t// Handle YAML parsing errors\n\t\t\tthrow new Error(`Failed to parse YAML: ${error.message}`)\n\t\t} else {\n\t\t\tthrow new Error(`Unknown error during routine deserialization: ${String(error)}`)\n\t\t}\n\t}\n}\n","import type { SubscriptionObserver } from '@sourcegraph/observable'\nimport type { ToolRun } from '../../tool-service'\nimport type { RunRoutineProgressMessage, RunRoutineToolDef } from './common'\n\n/**\n * Class that maintains state for status messages in run_routine implementation.\n * Keeps track of all status messages and reports them through the observer.\n */\nexport class ProgressReporter {\n\tprivate progressMessages: RunRoutineProgressMessage[] = []\n\n\tconstructor(\n\t\tprivate observer: SubscriptionObserver<ToolRun<RunRoutineToolDef>>,\n\t\tprivate signal: AbortSignal,\n\t) {}\n\n\t/**\n\t * Adds the latest message to the list of all status updates and then invokes the observer\n\t * with the updated 'in-progress' status.\n\t */\n\tupdate(update: ToolRun<RunRoutineToolDef>): void {\n\t\tthis.signal.throwIfAborted()\n\t\tif ('progress' in update && update.progress) {\n\t\t\tif (Array.isArray(update.progress)) {\n\t\t\t\tthis.progressMessages.push(...update.progress)\n\t\t\t} else {\n\t\t\t\tthis.progressMessages.push(update.progress)\n\t\t\t}\n\t\t\tthis.observer.next({\n\t\t\t\t...update,\n\t\t\t\tprogress: this.progressMessages,\n\t\t\t})\n\t\t} else {\n\t\t\tthis.observer.next(update)\n\t\t}\n\t}\n\n\terror(error: unknown): void {\n\t\tthis.observer.error(error)\n\t}\n\n\tcomplete(): void {\n\t\tthis.observer.complete()\n\t}\n}\n\n/**\n * Apply variable substitutions to a prompt string\n */\nexport function substitutePromptVars(prompt: string, vars: { userInput?: string }): string {\n\tlet result = prompt\n\n\t// Replace {{userInput}} with the actual user input if provided\n\tif (vars.userInput) {\n\t\tresult = result.replace(/\\{\\{\\s*userInput\\s*\\}\\}/g, vars.userInput)\n\t\tresult = result.replace(/\\{\\{\\s*user_input\\s*\\}\\}/g, vars.userInput)\n\t}\n\n\treturn result\n}\n","import { firstValueFrom } from '@sourcegraph/observable'\nimport {\n\tACTIVE_MODEL,\n\tAnthropicConverters,\n\tfromAnthropicResultToThreadDelta,\n\trunAnthropicSync,\n} from '../../../inference/backends/anthropic'\nimport { buildSystemPrompt, DefaultSystemPromptService } from '../../../threads/system-prompt'\nimport type { ToolUseBlock } from '../../../threads/thread'\nimport {\n\ttoolResultBlocks,\n\ttype Thread,\n\ttype ThreadAssistantMessage,\n\ttype ToolRunUserInput,\n} from '../../../threads/thread'\nimport type { ThreadDelta } from '../../../threads/thread-delta'\nimport { applyThreadDelta } from '../../../threads/thread-delta'\nimport type {\n\tToolDefinition,\n\tToolRun,\n\tToolRunEnvironment,\n\tToolService,\n} from '../../../tools/tool-service'\nimport { createToolService, isToolRunTerminalState } from '../../../tools/tool-service'\nimport { registerBuiltinToolsToToolService } from '../../tools'\nimport type { AgentStepSchema, LLMStepSchema, StepSchema } from './types'\nimport { substitutePromptVars, type ProgressReporter } from './util'\n\n/**\n * Run a step with the given conversation\n */\nexport function runStep(\n\tstep: StepSchema,\n\tconversation: Thread,\n\tenv: ToolRunEnvironment,\n\tprogressReporter: ProgressReporter,\n\tvars: { userInput?: string },\n\tsignal: AbortSignal = new AbortController().signal,\n): Promise<Thread> {\n\tswitch (step.type) {\n\t\tcase 'agent':\n\t\t\treturn runStepAgent(step, conversation, env, progressReporter, vars, signal)\n\t\t\tbreak\n\t\tcase 'llm':\n\t\t\treturn runStepLLM(step, conversation, progressReporter, vars, signal)\n\t\t\tbreak\n\t\tdefault:\n\t\t\tthrow new Error(`Unknown step type: ${(step as any).type}`)\n\t}\n}\n\n/**\n * Run an agent step that implements a full agentic loop\n * Follows the pattern: inference -> tool calls -> tool results -> inference\n * until there are no more tool calls or the process is complete\n */\nasync function runStepAgent(\n\tstep: AgentStepSchema,\n\torigConversation: Thread,\n\tenv: ToolRunEnvironment,\n\tprogressReporter: ProgressReporter,\n\tvars: { userInput?: string },\n\tsignal: AbortSignal,\n): Promise<Thread> {\n\tconst toolService = createToolService()\n\tawait registerBuiltinToolsToToolService(toolService)\n\n\t// Process prompt template with variables if provided\n\tconst promptText = substitutePromptVars(step.prompt, vars)\n\n\t// Clone convo\n\tlet conversation = origConversation\n\tconst recordThreadDelta = (delta: ThreadDelta) => {\n\t\tconversation = applyThreadDelta(conversation, delta)\n\t}\n\n\trecordThreadDelta({\n\t\ttype: 'user:message',\n\t\tmessage: {\n\t\t\tcontent: [{ type: 'text', text: promptText }],\n\t\t\tmeta: {\n\t\t\t\tsentAt: Date.now(),\n\t\t\t},\n\t\t},\n\t})\n\n\t// Update progress with user message added\n\tprogressReporter.update({\n\t\tstatus: 'in-progress',\n\t\tprogress: { type: 'message', speaker: 'user', message: promptText },\n\t})\n\n\t// Get enabled tools from toolService (all tools for now)\n\tconst enabledToolSpecs = (await firstValueFrom(toolService.tools, signal)).map((t) => t.spec)\n\n\t// Set up parameters for the initial API call\n\tconst model = ACTIVE_MODEL\n\n\t// The agent loop will continue until there are no more tool calls needed\n\tlet loopCount = 0\n\tconst maxLoops = 100 // Prevent infinite loops\n\n\twhile (loopCount < maxLoops) {\n\t\tsignal.throwIfAborted()\n\t\tloopCount++\n\n\t\t// Get system prompt blocks from the main system prompt builder\n\t\tconst systemPromptService = new DefaultSystemPromptService()\n\t\t// Get the main system prompt blocks\n\t\tconst systemPromptBlocks = await buildSystemPrompt(systemPromptService, {\n\t\t\tenabledTodos: false,\n\t\t\tthreadEnv: env.threadEnvironment,\n\t\t})\n\n\t\t// Add the subagent-specific instruction as the final block\n\t\tsystemPromptBlocks.push({\n\t\t\ttype: 'text' as const,\n\t\t\ttext: 'You are a helpful AI assistant running as a subagent within a larger system. Your task is to handle this specific step in a routine. You can use tools to complete your task. When you are completely done, do not ask to use more tools.',\n\t\t})\n\n\t\t// Use the combined system prompt\n\t\tconst systemPrompt = systemPromptBlocks\n\n\t\tsignal.throwIfAborted()\n\n\t\t// Use runAnthropicSync to get a response\n\t\tlet result\n\t\ttry {\n\t\t\tconst anthropicMessages = AnthropicConverters.fromNativeThread(conversation)\n\t\t\tresult = await runAnthropicSync(\n\t\t\t\tanthropicMessages,\n\t\t\t\tenabledToolSpecs,\n\t\t\t\tsystemPrompt,\n\t\t\t\tmodel,\n\t\t\t\tsignal,\n\t\t\t)\n\t\t} catch (error) {\n\t\t\tthrow new Error(`Anthropic API error: ${error}`)\n\t\t}\n\n\t\tif (!result.message || !('content' in result.message)) {\n\t\t\tthrow new Error('Unexpected response format from Anthropic')\n\t\t}\n\t\tif (result.message.content.length === 0) {\n\t\t\tbreak\n\t\t}\n\n\t\tconst assistantResponseDelta = fromAnthropicResultToThreadDelta(result.message)\n\t\trecordThreadDelta(assistantResponseDelta)\n\n\t\t// Extract text for progress reporting\n\t\tconst assistantText = result.message.content\n\t\t\t.filter((item) => item.type === 'text')\n\t\t\t.map((item) => ('text' in item ? item.text : ''))\n\t\t\t.join(' ')\n\t\t\t.trim()\n\t\tif (assistantText) {\n\t\t\t// Show assistant message\n\t\t\tprogressReporter.update({\n\t\t\t\tstatus: 'in-progress',\n\t\t\t\tprogress: { type: 'message', speaker: 'assistant', message: assistantText },\n\t\t\t})\n\t\t}\n\n\t\tif (assistantResponseDelta.type !== 'assistant:message') {\n\t\t\t// No tool calls\n\t\t\tbreak\n\t\t}\n\n\t\tconst toolCalls = findToolUsesNeedingInvocation(\n\t\t\tconversation,\n\t\t\tassistantResponseDelta.message,\n\t\t)\n\t\tfor (const toolCall of toolCalls) {\n\t\t\tprogressReporter.update({\n\t\t\t\tstatus: 'in-progress',\n\t\t\t\tprogress: {\n\t\t\t\t\tid: toolCall.id,\n\t\t\t\t\ttype: 'toolCall',\n\t\t\t\t\ttoolName: toolCall.name,\n\t\t\t\t\targs: JSON.stringify(toolCall.input),\n\t\t\t\t},\n\t\t\t})\n\n\t\t\tlet toolResult\n\t\t\ttry {\n\t\t\t\ttoolResult = await invokeToolAndWaitForResult(\n\t\t\t\t\ttoolService,\n\t\t\t\t\ttoolCall.name,\n\t\t\t\t\ttoolCall.input,\n\t\t\t\t\tenv,\n\t\t\t\t\tsignal,\n\t\t\t\t)\n\t\t\t\tsignal.throwIfAborted()\n\t\t\t\tif (toolResult.status !== 'done') {\n\t\t\t\t\tthrow new Error(JSON.stringify(toolResult))\n\t\t\t\t}\n\t\t\t} catch (error) {\n\t\t\t\trecordThreadDelta({\n\t\t\t\t\ttype: 'tool:data',\n\t\t\t\t\ttoolUse: toolCall.id,\n\t\t\t\t\tdata: {\n\t\t\t\t\t\tstatus: 'error',\n\t\t\t\t\t\terror: { message: `Tool call error: ${error}` },\n\t\t\t\t\t},\n\t\t\t\t})\n\t\t\t\tprogressReporter.update({\n\t\t\t\t\tstatus: 'in-progress',\n\t\t\t\t\tprogress: {\n\t\t\t\t\t\tid: toolCall.id,\n\t\t\t\t\t\ttype: 'toolResult',\n\t\t\t\t\t\ttoolName: toolCall.name,\n\t\t\t\t\t\tresult: `Tool call error: ${error}`,\n\t\t\t\t\t},\n\t\t\t\t})\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\trecordThreadDelta({\n\t\t\t\ttype: 'tool:data',\n\t\t\t\ttoolUse: toolCall.id,\n\t\t\t\tdata: toolResult,\n\t\t\t})\n\t\t\tprogressReporter.update({\n\t\t\t\tstatus: 'in-progress',\n\t\t\t\tprogress: {\n\t\t\t\t\tid: toolCall.id,\n\t\t\t\t\ttype: 'toolResult',\n\t\t\t\t\ttoolName: toolCall.name,\n\t\t\t\t\tresult:\n\t\t\t\t\t\ttypeof toolResult.result === 'string'\n\t\t\t\t\t\t\t? toolResult.result\n\t\t\t\t\t\t\t: JSON.stringify(toolResult.result),\n\t\t\t\t},\n\t\t\t})\n\t\t}\n\t}\n\treturn conversation\n}\n\n/**\n * Mock implementation of tool execution for the subagent\n * In a real implementation, this would connect to the actual tool execution system\n */\n// Removed mock implementation in favor of actual toolService\n\n/**\n * Run an LLM step\n */\nasync function runStepLLM(\n\tstep: LLMStepSchema,\n\torigConversation: Thread,\n\tprogressReporter: ProgressReporter,\n\tvars: { userInput?: string },\n\tsignal: AbortSignal,\n): Promise<Thread> {\n\t// Process prompt template with variables if provided\n\tconst promptText = substitutePromptVars(step.prompt, vars)\n\n\t// Create a copy of the conversation to avoid mutating the original\n\tlet conversation = origConversation\n\tconst recordThreadDelta = (delta: ThreadDelta) => {\n\t\tconversation = applyThreadDelta(conversation, delta)\n\t}\n\n\trecordThreadDelta({\n\t\ttype: 'user:message',\n\t\tmessage: {\n\t\t\tcontent: [{ type: 'text', text: promptText }],\n\t\t\tmeta: {\n\t\t\t\tsentAt: Date.now(),\n\t\t\t},\n\t\t},\n\t})\n\n\t// Update progress with user message added\n\tprogressReporter.update({\n\t\tstatus: 'in-progress',\n\t\tprogress: { type: 'message', speaker: 'user', message: promptText },\n\t})\n\n\t// Use runAnthropicSync to get a response\n\tconst anthropicMessages = AnthropicConverters.fromNativeThread(conversation)\n\tconst model = step.model || ACTIVE_MODEL\n\tconst result = await runAnthropicSync(\n\t\tanthropicMessages,\n\t\t[], // No tools for LLM-only step\n\t\t[], // No system prompt\n\t\tmodel,\n\t\tsignal,\n\t)\n\n\tif (!result.message) {\n\t\tthrow new Error('Failed to get response from Anthropic')\n\t}\n\n\tconst assistantResponseDelta = fromAnthropicResultToThreadDelta(result.message)\n\trecordThreadDelta(assistantResponseDelta)\n\n\t// Display message\n\tconst assistantText = result.message.content\n\t\t.filter((item) => item.type === 'text')\n\t\t.map((item) => (item.type === 'text' ? item.text : ''))\n\t\t.join(' ')\n\t\t.trim()\n\tprogressReporter.update({\n\t\tstatus: 'in-progress',\n\t\tprogress: { type: 'message', speaker: 'assistant', message: assistantText },\n\t})\n\treturn conversation\n}\n\nfunction findToolUsesNeedingInvocation(\n\tthread: Thread,\n\tmessage: ThreadAssistantMessage,\n): ToolUseBlock[] {\n\tconst toolResults = toolResultBlocks(thread)\n\treturn message.content\n\t\t.filter((block): block is ToolUseBlock => block.type === 'tool_use')\n\t\t.filter((block) => !block.inputPartialJSON)\n\t\t.filter(\n\t\t\t(block) =>\n\t\t\t\t// Only include tools that haven't been invoked yet.\n\t\t\t\t!toolResults.has(block.id),\n\t\t)\n}\n\n/**\n * Helper function that invokes a tool and returns a Promise with the final result\n */\nexport async function invokeToolAndWaitForResult<T extends ToolDefinition>(\n\ttoolService: ToolService,\n\ttoolName: string,\n\tinput: unknown,\n\tenv: ToolRunEnvironment,\n\tsignal: AbortSignal = new AbortController().signal,\n\tuserInput?: ToolRunUserInput,\n): Promise<ToolRun<T>> {\n\treturn new Promise((resolve, reject) => {\n\t\tlet settled = false\n\t\tconst sub = toolService\n\t\t\t.invokeTool(toolName, { args: input as any, userInput }, env)\n\t\t\t.subscribe({\n\t\t\t\tnext: (run: ToolRun) => {\n\t\t\t\t\tif (isToolRunTerminalState(run)) {\n\t\t\t\t\t\tsub.unsubscribe()\n\t\t\t\t\t\tif (!settled) {\n\t\t\t\t\t\t\tsettled = true\n\t\t\t\t\t\t\tresolve(run)\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t},\n\t\t\t\terror: (error) => {\n\t\t\t\t\tif (!settled) {\n\t\t\t\t\t\tsettled = true\n\t\t\t\t\t\treject(error)\n\t\t\t\t\t}\n\t\t\t\t},\n\t\t\t\tcomplete: () => {},\n\t\t\t})\n\n\t\t// Handle abort signal\n\t\tsignal.addEventListener('abort', () => {\n\t\t\tsub.unsubscribe()\n\t\t\tif (!settled) {\n\t\t\t\tsettled = true\n\t\t\t\treject(new Error('Tool execution was aborted'))\n\t\t\t}\n\t\t})\n\t})\n}\n","import { Observable } from '@sourcegraph/observable'\nimport { isAbortError } from '../../../common/abort'\nimport logger from '../../../common/logger'\nimport type { Thread } from '../../../threads/thread'\nimport { newThreadID } from '../../../threads/thread'\nimport type { ToolRunEnvironment } from '../../tool-service'\nimport { createToolService } from '../../tool-service'\nimport type { ReadFileToolDef } from '../filesystem/read_file.common'\nimport { readFileToolReg } from '../filesystem/read_file.common'\nimport type { runRoutineToolReg } from './common'\nimport { deserializeRoutineFromYAML } from './serialization'\nimport { invokeToolAndWaitForResult, runStep } from './step'\nimport { ProgressReporter } from './util'\n\nexport const runRoutine: NonNullable<(typeof runRoutineToolReg)['fn']> = ({ args }, env) => {\n\treturn new Observable((observer) => {\n\t\tconst abortController = new AbortController()\n\t\tconst progressReporter = new ProgressReporter(observer, abortController.signal)\n\n\t\trunRoutineImpl(args, env, progressReporter, abortController.signal).catch((error) => {\n\t\t\t// Don't report AbortError as an error - it's expected when cancelling\n\t\t\tif (!isAbortError(error)) {\n\t\t\t\tprogressReporter.error(error)\n\t\t\t} else {\n\t\t\t\tprogressReporter.update({\n\t\t\t\t\tstatus: 'cancelled' as const,\n\t\t\t\t\tprogress: { type: 'meta', message: 'Operation cancelled' },\n\t\t\t\t})\n\t\t\t\tprogressReporter.complete()\n\t\t\t}\n\t\t})\n\n\t\treturn () => {\n\t\t\tabortController.abort()\n\t\t}\n\t})\n}\n\nasync function runRoutineImpl(\n\targs: { id: string; file?: string; userInput?: string },\n\tenv: ToolRunEnvironment,\n\tprogressReporter: ProgressReporter,\n\tsignal: AbortSignal,\n) {\n\ttry {\n\t\tconst { id, file } = args\n\t\tconst routineFile = file || 'routines.amp.yaml'\n\n\t\t// Report initial progress\n\t\tprogressReporter.update({\n\t\t\tstatus: 'in-progress',\n\t\t\tprogress: { type: 'meta', message: `Loading routine: ${id} from ${routineFile}` },\n\t\t})\n\n\t\t// Create a tool service and register the read_file tool\n\t\tconst toolService = createToolService()\n\t\ttoolService.registerTool(readFileToolReg)\n\n\t\t// Read the routine file using the tool service\n\t\tconst readFileResult = await invokeToolAndWaitForResult<ReadFileToolDef>(\n\t\t\ttoolService,\n\t\t\t'read_file',\n\t\t\t{ path: routineFile },\n\t\t\tenv,\n\t\t\tsignal,\n\t\t)\n\n\t\t// Process the file content by removing line numbers that read_file adds\n\t\tif (readFileResult.status !== 'done') {\n\t\t\tthrow new Error(`Failed to read routine file: ${routineFile}`)\n\t\t}\n\t\t// At this point TypeScript knows readFileResult has a 'result' property\n\t\tconst fileContents =\n\t\t\ttypeof readFileResult.result === 'string'\n\t\t\t\t? readFileResult.result\n\t\t\t\t: readFileResult.result.content\n\t\tconst routineContent = String(fileContents)\n\t\t\t.split('\\n')\n\t\t\t.map((line: string) => line.replace(/^\\d+:\\s/, ''))\n\t\t\t.join('\\n')\n\n\t\tsignal.throwIfAborted()\n\n\t\t// Parse the routines\n\t\tconst routines = deserializeRoutineFromYAML(routineContent)\n\t\tsignal.throwIfAborted()\n\n\t\t// Find the requested routine\n\t\tconst routine = routines.find((routine) => routine.id === id)\n\t\tif (!routine) {\n\t\t\tthrow new Error(`Routine with id \"${id}\" not found in ${routineFile}`)\n\t\t}\n\n\t\t// Initialize a Thread for the conversation\n\t\tlet conversation: Thread = {\n\t\t\tid: newThreadID(),\n\t\t\tcreated: Date.now(),\n\t\t\tv: 0,\n\t\t\tmessages: [],\n\t\t}\n\n\t\t// Report progress before executing steps\n\t\tprogressReporter.update({\n\t\t\tstatus: 'in-progress',\n\t\t\tprogress: [\n\t\t\t\t{\n\t\t\t\t\ttype: 'meta',\n\t\t\t\t\tmessage: `Executing routine ${id}`,\n\t\t\t\t},\n\t\t\t],\n\t\t})\n\n\t\t// Execute each step in the routine\n\t\tfor (let i = 0; i < routine.steps.length; i++) {\n\t\t\tconst step = routine.steps[i]\n\t\t\tif (!step) continue // Skip undefined steps\n\n\t\t\tprogressReporter.update({\n\t\t\t\tstatus: 'in-progress',\n\t\t\t\tprogress: [\n\t\t\t\t\t{\n\t\t\t\t\t\ttype: 'meta',\n\t\t\t\t\t\tmessage: `Executing step ${i + 1}/${routine.steps.length}: ${step.type}`,\n\t\t\t\t\t\tvariant: 'header',\n\t\t\t\t\t},\n\t\t\t\t],\n\t\t\t})\n\n\t\t\tsignal.throwIfAborted()\n\n\t\t\t// Execute the step and update the conversation\n\t\t\tconversation = await runStep(step, conversation, env, progressReporter, {\n\t\t\t\tuserInput: args.userInput,\n\t\t\t})\n\t\t}\n\n\t\tprogressReporter.update({\n\t\t\tstatus: 'done' as const,\n\t\t\tprogress: {\n\t\t\t\ttype: 'meta',\n\t\t\t\tmessage: `Finished executing all ${routine.steps.length} steps of routine: ${id}.`,\n\t\t\t\tvariant: 'header',\n\t\t\t},\n\t\t\tresult: '', // No output for now\n\t\t})\n\n\t\tprogressReporter.complete()\n\t} catch (error) {\n\t\tif (isAbortError(error)) {\n\t\t\tprogressReporter.update({\n\t\t\t\tstatus: 'cancelled' as const,\n\t\t\t\tprogress: {\n\t\t\t\t\ttype: 'meta',\n\t\t\t\t\tmessage: 'Operation cancelled',\n\t\t\t\t},\n\t\t\t})\n\t\t\tprogressReporter.complete()\n\t\t} else {\n\t\t\tlogger.error('Error in run_routine', {\n\t\t\t\terror,\n\t\t\t\tstack: error instanceof Error ? error.stack : '',\n\t\t\t})\n\t\t\tprogressReporter.error(error)\n\t\t}\n\t}\n}\n"],"names":["BaseStep","z.object","z.enum","z.union","z.literal","z.array","z.string","z.record","z.any","AgentStep","z.boolean","LLMStep","LoopAgentStep","LoopLLMStep","ToolCallStep","BashStep","Step","z.discriminatedUnion","RoutineBlock","Routine","deserializeRoutineFromYAML","yamlString","parsedYaml","parse","error","z.ZodError","err","ProgressReporter","observer","signal","update","substitutePromptVars","prompt","vars","result","runStep","step","conversation","env","progressReporter","runStepAgent","runStepLLM","origConversation","toolService","createToolService","registerBuiltinToolsToToolService","promptText","recordThreadDelta","delta","applyThreadDelta","enabledToolSpecs","firstValueFrom","t","model","ACTIVE_MODEL","loopCount","maxLoops","systemPromptService","DefaultSystemPromptService","systemPromptBlocks","buildSystemPrompt","systemPrompt","anthropicMessages","AnthropicConverters","runAnthropicSync","assistantResponseDelta","fromAnthropicResultToThreadDelta","assistantText","item","toolCalls","findToolUsesNeedingInvocation","toolCall","toolResult","invokeToolAndWaitForResult","thread","message","toolResults","toolResultBlocks","block","toolName","input","userInput","resolve","reject","settled","sub","run","isToolRunTerminalState","runRoutine","args","Observable","abortController","runRoutineImpl","isAbortError","id","file","routineFile","readFileToolReg","readFileResult","fileContents","routineContent","line","routines","routine","newThreadID","i","logger"],"mappings":";;;AAGA,MAAMA,IAAWC,EAAS;AAAA,EACzB,SAASC,EAAO,CAAC,YAAY,MAAM,CAAC,EAAE,SAAA,EAA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