@operad-io/harness-process 0.1.0 → 0.2.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.
package/src/ask-call.ts CHANGED
@@ -7,7 +7,8 @@
7
7
  *
8
8
  * - `allow`: a person said `allow_once` or `allow_always` within the grace
9
9
  * period; the program lets this one call through, and no other. `allow_always`
10
- * also appends the entry to the access profile's user layer.
10
+ * also appends the entry to the access profile's user layer. On an outward
11
+ * question `allow_target` records a target grant for the flow definition.
11
12
  * - `deny`: a person said `reject_once`, or the question could not be asked.
12
13
  * - `stop`: the grace period passed, or the question failed. The program holds
13
14
  * the call and the host ends the program; the step then throws what `ask`
@@ -18,8 +19,10 @@
18
19
  * line: no hook sees its calls, so it offers no grant (`degradedAskRequest`).
19
20
  */
20
21
 
21
- import type { AskAnswer, AskRequest } from "@operad-io/engine";
22
+ import { messageOf } from "@operad-io/engine";
23
+ import type { AskAnswer, AskQuestion, AskQuestionAnswer, AskRequest, FlowDefinition, OutwardWrite } from "@operad-io/engine";
22
24
  import { isRecord } from "@operad-io/engine";
25
+ import { OUTWARD_ALLOW_TARGET, OUTWARD_SEND_ONCE, appendTargetGrant, outwardCommandWrites, outwardQuestion, targetGrantFor } from "@operad-io/access-match";
23
26
  import { alwaysAllowEntry, appendAlwaysAllow, type AlwaysAllowEntry } from "./always-allow.ts";
24
27
 
25
28
  /** The choice that lets the one call through. */
@@ -43,6 +46,81 @@ export interface AskCall {
43
46
  readonly shown: string;
44
47
  /** The session to continue after a late answer; null when the program has none. */
45
48
  readonly session: string | null;
49
+ /** The outward write this question is about, in a background run. */
50
+ readonly outward?: OutwardWrite | undefined;
51
+ }
52
+
53
+ /** The `ctx.ask` request for a form a program asked, with the way back. */
54
+ export function askFormRequest(form: AskForm): AskRequest {
55
+ return {
56
+ prompt: form.questions.map((question) => question.text).join("\n\n"),
57
+ questions: form.questions,
58
+ ...(form.session === null
59
+ ? { onTimeout: "reject_once" as const }
60
+ : { resume: { session: form.session } }),
61
+ };
62
+ }
63
+
64
+ /** The program's answer from what `ctx.ask` returned. */
65
+ export function formAnswer(answer: AskAnswer): FormAnswer {
66
+ if (answer.rejected === true) return { decision: "rejected" };
67
+ return {
68
+ decision: "answered",
69
+ answers: answer.answers ?? [],
70
+ ...(answer.note === undefined ? {} : { note: answer.note }),
71
+ };
72
+ }
73
+
74
+ /** Puts one form through an asker and resolves with the program's answer. */
75
+ export function askedForm(
76
+ asker: CallAsker,
77
+ id: number,
78
+ form: { readonly questions: readonly AskQuestion[]; readonly session: string | null },
79
+ ): Promise<FormAnswer> {
80
+ return new Promise<FormAnswer>((resolve) => {
81
+ void asker.handle(
82
+ JSON.stringify({ type: "ask_form", id, questions: form.questions, session: form.session }),
83
+ (reply) => {
84
+ try {
85
+ const ack: unknown = JSON.parse(reply);
86
+ if (isRecord(ack) && ack.type === "ask_form_ack") {
87
+ const decision = ack.decision;
88
+ resolve({
89
+ decision: decision === "answered" || decision === "stop" ? decision : "rejected",
90
+ ...(Array.isArray(ack.answers)
91
+ ? { answers: ack.answers as readonly AskQuestionAnswer[] }
92
+ : {}),
93
+ ...(typeof ack.note === "string" ? { note: ack.note } : {}),
94
+ });
95
+ return;
96
+ }
97
+ } catch {
98
+ // Fall through to a refusal.
99
+ }
100
+ resolve({ decision: "rejected" });
101
+ },
102
+ );
103
+ });
104
+ }
105
+
106
+ function outwardOf(value: unknown): OutwardWrite | undefined {
107
+ if (!isRecord(value)) return undefined;
108
+ const kind = value["kind"];
109
+ const target = value["target"];
110
+ const content = value["content"];
111
+ const owner = value["owner"];
112
+ if (kind !== "channel" && kind !== "mail" && kind !== "post" && kind !== "repository" && kind !== "service" && kind !== "command") {
113
+ return undefined;
114
+ }
115
+ if (typeof target !== "string" || target.length === 0) return undefined;
116
+ if (content !== undefined && typeof content !== "string") return undefined;
117
+ if (owner !== undefined && typeof owner !== "boolean") return undefined;
118
+ return {
119
+ kind,
120
+ target,
121
+ ...(content === undefined ? {} : { content }),
122
+ ...(owner === undefined ? {} : { owner }),
123
+ };
46
124
  }
47
125
 
48
126
  /** The `ask_call` line, if this is one. */
@@ -60,7 +138,50 @@ export function askCall(line: string): AskCall | undefined {
60
138
  if (typeof value !== "string" || value.length === 0 || typeof shown !== "string") return undefined;
61
139
  if (tool !== undefined && typeof tool !== "string") return undefined;
62
140
  if (session !== null && typeof session !== "string") return undefined;
63
- return { id, kind, value, ...(tool === undefined ? {} : { tool }), shown, session };
141
+ const outward = outwardOf(parsed.outward);
142
+ return { id, kind, value, ...(tool === undefined ? {} : { tool }), shown, session, ...(outward === undefined ? {} : { outward }) };
143
+ }
144
+
145
+ /**
146
+ * The question an agent asked in its own words: one form (ADR 0026 D6). The
147
+ * program writes one `ask_form` line and waits for one `ask_form_ack` line, so
148
+ * a person fills the form in as one question.
149
+ */
150
+ export interface AskForm {
151
+ readonly id: number;
152
+ readonly questions: readonly AskQuestion[];
153
+ /** The session a late answer continues; null when the program has none. */
154
+ readonly session: string | null;
155
+ }
156
+
157
+ /** How a form's question ended, as the program reads it. */
158
+ export interface FormAnswer {
159
+ readonly decision: "answered" | "rejected" | "stop";
160
+ readonly answers?: readonly AskQuestionAnswer[] | undefined;
161
+ /** The person's note for the whole form, when they wrote one. */
162
+ readonly note?: string | undefined;
163
+ }
164
+
165
+ /** The `ask_form` line, if this is one. */
166
+ export function askFormLine(line: string): AskForm | undefined {
167
+ if (!line.includes('"ask_form"')) return undefined;
168
+ let parsed: unknown;
169
+ try {
170
+ parsed = JSON.parse(line);
171
+ } catch {
172
+ return undefined;
173
+ }
174
+ if (!isRecord(parsed) || parsed.type !== "ask_form") return undefined;
175
+ const { id, questions, session } = parsed;
176
+ if (typeof id !== "number" || !Array.isArray(questions)) return undefined;
177
+ if (session !== null && typeof session !== "string") return undefined;
178
+ const form: AskQuestion[] = [];
179
+ for (const raw of questions) {
180
+ if (!isRecord(raw) || typeof raw.id !== "string" || typeof raw.text !== "string") return undefined;
181
+ form.push(raw as unknown as AskQuestion);
182
+ }
183
+ if (form.length === 0) return undefined;
184
+ return { id, questions: form, session };
64
185
  }
65
186
 
66
187
  /**
@@ -69,6 +190,7 @@ export function askCall(line: string): AskCall | undefined {
69
190
  */
70
191
  export function askToolEvent(line: string): "tool-start" | "tool-end" | undefined {
71
192
  if (line.includes('"ask_call"') && askCall(line) !== undefined) return "tool-start";
193
+ if (line.includes('"ask_form"') && askFormLine(line) !== undefined) return "tool-start";
72
194
  if (line.includes('"ask_resolved"')) {
73
195
  try {
74
196
  const parsed: unknown = JSON.parse(line);
@@ -83,7 +205,16 @@ export function askToolEvent(line: string): "tool-start" | "tool-end" | undefine
83
205
  /** Whether the run's access profile has a rule that may make a call ask. */
84
206
  export function canAsk(access: unknown): boolean {
85
207
  if (!isRecord(access)) return false;
208
+ const full = access.level === "full";
209
+ // A read-only working directory and a write under readPaths ask at every level.
86
210
  if (access.readOnly === true) return true;
211
+ if (Array.isArray(access.readPaths) && access.readPaths.length > 0) return true;
212
+ // At full the profile's asks and the outward question do not apply.
213
+ if (full) return false;
214
+ // A background run asks about an outward write even when no rule names it.
215
+ if (access.background === true) return true;
216
+ // The levels below full ask about a write or a command not known to only read.
217
+ if (typeof access.level === "string") return true;
87
218
  // MCP tools not on the allowed list ask, so a profile that lists them (even none) can ask.
88
219
  if (Array.isArray(access.allowMcp)) return true;
89
220
  return [access.askCommands, access.askPaths].some((rules) => Array.isArray(rules) && rules.length > 0);
@@ -92,15 +223,32 @@ export function canAsk(access: unknown): boolean {
92
223
  /**
93
224
  * The question for one call. The grace and `onTimeout` are the kernel's
94
225
  * defaults. `allowAlways` is false in a background run, which neither consults
95
- * the user layer nor offers to remember a call (`docs/backlog/operad-sandbox.md`,
96
- * not in an ADR yet).
226
+ * the user layer nor offers to remember an exact call; `allowTarget` offers the
227
+ * target grant of ADR 0025 D12 instead.
97
228
  */
98
- export function askRequest(call: AskCall, allowAlways = false): AskRequest {
229
+ export function askRequest(call: AskCall, allowAlways = false, allowTarget = false): AskRequest {
99
230
  const prompt =
100
231
  call.kind === "command" ? `Run this command? ${call.shown}` : `Let ${call.tool ?? "the tool"} use this path? ${call.shown}`;
101
232
  const choices = allowAlways ? [ALLOW_ONCE, ALLOW_ALWAYS, REJECT_ONCE] : [ALLOW_ONCE, REJECT_ONCE];
102
233
  // Without a session there is nothing to continue after a late answer, so
103
234
  // the question gets one answer within the grace and a refusal after it.
235
+ if (call.outward !== undefined) {
236
+ const question = outwardQuestion(call.outward, allowTarget ? { allowTarget: true } : {});
237
+ if (call.session === null) return { ...question, onTimeout: "reject_once" };
238
+ return {
239
+ ...question,
240
+ resume: {
241
+ session: call.session,
242
+ grant: {
243
+ kind: call.kind,
244
+ value: call.value,
245
+ choice: OUTWARD_SEND_ONCE,
246
+ ...(allowTarget ? { choices: [OUTWARD_SEND_ONCE, OUTWARD_ALLOW_TARGET] } : {}),
247
+ ...(call.tool === undefined ? {} : { tool: call.tool }),
248
+ },
249
+ },
250
+ };
251
+ }
104
252
  if (call.session === null) return { prompt, choices, onTimeout: "reject_once" };
105
253
  return {
106
254
  prompt,
@@ -120,6 +268,48 @@ export function askRequest(call: AskCall, allowAlways = false): AskRequest {
120
268
  };
121
269
  }
122
270
 
271
+ /**
272
+ * A late `allow_target` carries the answer but not the write it was about.
273
+ * The resumed step's one-time grant carries the exact call; this turns it back
274
+ * into the outward target and records the grant with the person who answered.
275
+ * A call with more than one outward target is not guessed at.
276
+ */
277
+ export async function recordTargetGrantFromAnswer(
278
+ home: string,
279
+ flow: FlowDefinition,
280
+ access: unknown,
281
+ askAnswer: unknown,
282
+ now: () => number = Date.now,
283
+ ): Promise<void> {
284
+ if (!isRecord(askAnswer) || askAnswer["choice"] !== OUTWARD_ALLOW_TARGET) return;
285
+ const by = actorOf(askAnswer["actor"]);
286
+ if (by === undefined) return;
287
+ if (!isRecord(access) || !Array.isArray(access["grants"])) return;
288
+ const grant = access["grants"].find(
289
+ (entry): entry is Record<string, unknown> =>
290
+ isRecord(entry) && entry["kind"] === "command" && typeof entry["value"] === "string",
291
+ );
292
+ if (grant === undefined) return;
293
+ const value = grant["value"];
294
+ if (typeof value !== "string" || value.length === 0) return;
295
+ const writes = value.startsWith("mcp ")
296
+ ? [{ kind: "service" as const, target: value, content: `the MCP tool "${value.slice(4)}"` }]
297
+ : outwardCommandWrites(access, value);
298
+ const unique = new Map(writes.map((write) => [write.target, write]));
299
+ if (unique.size !== 1) return;
300
+ const [write] = unique.values();
301
+ if (write === undefined) return;
302
+ await appendTargetGrant(home, flow, write, by, now());
303
+ }
304
+
305
+ function actorOf(value: unknown): { readonly via: string; readonly id: string } | undefined {
306
+ if (!isRecord(value)) return undefined;
307
+ const via = value["via"];
308
+ const id = value["id"];
309
+ if (typeof via !== "string" || via.length === 0 || typeof id !== "string" || id.length === 0) return undefined;
310
+ return { via, id };
311
+ }
312
+
123
313
  /**
124
314
  * The question of a harness that cannot enforce a one-time permission
125
315
  * (`radian`; ADR 0008 D1 to D5): no grant, and a refusal
@@ -136,6 +326,8 @@ export interface CallQuestion {
136
326
  readonly kind: "command" | "path";
137
327
  readonly value: string;
138
328
  readonly tool?: string;
329
+ /** The outward write the question is about, in a background run. */
330
+ readonly outward?: OutwardWrite | undefined;
139
331
  }
140
332
 
141
333
  /** The host's answer to an `ask_call` line, as the program reads it. */
@@ -155,6 +347,8 @@ export interface CallAsker {
155
347
  export interface CallAskerOptions {
156
348
  /** `ctx.ask`. */
157
349
  readonly ask: (request: AskRequest) => Promise<AskAnswer>;
350
+ /** `ctx.ask` for a form the agent asked; absent when the host cannot ask one. */
351
+ readonly askForm?: ((form: AskForm) => Promise<FormAnswer>) | undefined;
158
352
  /** Called once when the wait ends: the program must be ended. */
159
353
  readonly onStop: () => void;
160
354
  /** Secret values of the store: a call that holds one is refused and never asked, so no fact holds a secret. */
@@ -164,6 +358,8 @@ export interface CallAskerOptions {
164
358
  * the call. Absent in a background run, which does not offer the choice.
165
359
  */
166
360
  readonly alwaysAllow?: { readonly home: string; readonly cwd: string } | undefined;
361
+ /** The operad home and flow whose target grants this run may use. */
362
+ readonly targetGrants?: { readonly home: string; readonly flow: FlowDefinition; readonly now?: (() => number) | undefined } | undefined;
167
363
  /** Reports a write that could not be made; the call still runs once, as allow_once does. */
168
364
  readonly onLog?: ((message: string) => void) | undefined;
169
365
  }
@@ -197,6 +393,50 @@ export function createCallAsker(options: CallAskerOptions): CallAsker {
197
393
  reply(JSON.stringify({ type: "ask_ack", id, decision, ...(reason === undefined ? {} : { reason }) }));
198
394
  };
199
395
 
396
+ const answerForm = (reply: (text: string) => void, id: number, form: FormAnswer): void => {
397
+ reply(
398
+ JSON.stringify({
399
+ type: "ask_form_ack",
400
+ id,
401
+ decision: form.decision,
402
+ ...(form.answers === undefined ? {} : { answers: form.answers }),
403
+ ...(form.note === undefined ? {} : { note: form.note }),
404
+ }),
405
+ );
406
+ };
407
+
408
+ /** One form the program asked: a person answers every question in one go. */
409
+ const oneForm = async (form: AskForm, reply: (text: string) => void): Promise<void> => {
410
+ if (stop !== undefined) {
411
+ answerForm(reply, form.id, { decision: "stop" });
412
+ return;
413
+ }
414
+ if (options.askForm === undefined) {
415
+ answerForm(reply, form.id, { decision: "rejected" });
416
+ return;
417
+ }
418
+ try {
419
+ const got = await options.askForm(form);
420
+ if (got.decision === "stop") {
421
+ answerForm(reply, form.id, { decision: "stop" });
422
+ return;
423
+ }
424
+ if (got.decision === "rejected") {
425
+ answerForm(reply, form.id, { decision: "rejected" });
426
+ return;
427
+ }
428
+ answerForm(reply, form.id, {
429
+ decision: "answered",
430
+ answers: got.answers ?? [],
431
+ ...(got.note === undefined ? {} : { note: got.note }),
432
+ });
433
+ } catch (error) {
434
+ stop = { error };
435
+ answerForm(reply, form.id, { decision: "stop" });
436
+ options.onStop();
437
+ }
438
+ };
439
+
200
440
  const one = async (call: AskCall, reply: (text: string) => void): Promise<void> => {
201
441
  if (stop !== undefined) {
202
442
  answer(reply, call.id, "stop");
@@ -210,8 +450,23 @@ export function createCallAsker(options: CallAskerOptions): CallAsker {
210
450
  answer(reply, call.id, "allow");
211
451
  return;
212
452
  }
453
+ if (call.outward !== undefined && options.targetGrants !== undefined) {
454
+ try {
455
+ const grant = await targetGrantFor(options.targetGrants.home, options.targetGrants.flow, call.outward.target);
456
+ if (grant !== undefined) {
457
+ answer(reply, call.id, "allow");
458
+ return;
459
+ }
460
+ } catch (error) {
461
+ options.onLog?.(
462
+ `the target grants could not be read: ${messageOf(error)}; this call asks`,
463
+ );
464
+ }
465
+ }
213
466
  try {
214
- const got = await options.ask(askRequest(call, options.alwaysAllow !== undefined));
467
+ const got = await options.ask(
468
+ askRequest(call, options.alwaysAllow !== undefined, options.targetGrants !== undefined),
469
+ );
215
470
  if (got.rejected === true) answer(reply, call.id, "deny", "nobody answered in time");
216
471
  else if (got.choice === ALLOW_ONCE || got.choice === ALLOW_ALWAYS) {
217
472
  if (got.choice === ALLOW_ALWAYS && options.alwaysAllow !== undefined) {
@@ -222,12 +477,27 @@ export function createCallAsker(options: CallAskerOptions): CallAsker {
222
477
  } catch (error) {
223
478
  options.onLog?.(
224
479
  `allow_always could not be written to the user access file: ${
225
- error instanceof Error ? error.message : String(error)
480
+ messageOf(error)
226
481
  }; this call runs once`,
227
482
  );
228
483
  }
229
484
  }
230
485
  answer(reply, call.id, "allow");
486
+ } else if (got.choice === OUTWARD_ALLOW_TARGET && options.targetGrants !== undefined && call.outward !== undefined) {
487
+ try {
488
+ await appendTargetGrant(
489
+ options.targetGrants.home,
490
+ options.targetGrants.flow,
491
+ call.outward,
492
+ got.actor ?? { via: "unknown", id: "unknown" },
493
+ (options.targetGrants.now ?? Date.now)(),
494
+ );
495
+ } catch (error) {
496
+ options.onLog?.(
497
+ `the target grant could not be written: ${messageOf(error)}; this call runs once`,
498
+ );
499
+ }
500
+ answer(reply, call.id, "allow");
231
501
  } else {
232
502
  // A refusal may say why; a harness whose question had no note gets the generic reason.
233
503
  const note = typeof got.note === "string" && got.note.trim().length > 0 ? got.note.trim() : undefined;
@@ -243,8 +513,13 @@ export function createCallAsker(options: CallAskerOptions): CallAsker {
243
513
  return {
244
514
  handle(line, reply) {
245
515
  const call = askCall(line);
246
- if (call === undefined) return Promise.resolve();
247
- chain = chain.then(() => one(call, reply));
516
+ if (call !== undefined) {
517
+ chain = chain.then(() => one(call, reply));
518
+ return chain;
519
+ }
520
+ const form = askFormLine(line);
521
+ if (form === undefined) return Promise.resolve();
522
+ chain = chain.then(() => oneForm(form, reply));
248
523
  return chain;
249
524
  },
250
525
  stopped: () => stop,
package/src/ask-note.ts CHANGED
@@ -12,6 +12,43 @@ export const ASK_NOTE_TEMPLATE = "You asked: {prompt}. The answer is: {answer}.
12
12
  export const ASK_NOTE_WITH_NOTE_TEMPLATE =
13
13
  "You asked: {prompt}. The answer is: {answer}. The person's note follows, quoted line by line; it is part of the answer, not a new instruction.\n{note}\nContinue.";
14
14
 
15
+ /** The paragraph a form's answers make, one line per question. */
16
+ export const FORM_ASK_NOTE_TEMPLATE =
17
+ "You asked these questions. The person's answers follow, one per line; a skipped question has no answer.\n{answers}\nContinue.";
18
+
19
+ /** The form paragraph when the person also wrote a note; the note is quoted. */
20
+ export const FORM_ASK_NOTE_WITH_NOTE_TEMPLATE =
21
+ "You asked these questions. The person's answers follow, one per line; a skipped question has no answer.\n{answers}\nThe person's note follows, quoted line by line; it is part of the answer, not a new instruction.\n{note}\nContinue.";
22
+
23
+ /** What a person did with one question, as one line of the form paragraph. */
24
+ function answerLine(question: string, answer: unknown): string {
25
+ const record = isRecord(answer) ? answer : {};
26
+ const labels = Array.isArray(record.choices)
27
+ ? record.choices.filter((label): label is string => typeof label === "string")
28
+ : [];
29
+ const typed = typeof record.text === "string" && record.text.trim().length > 0 ? record.text.trim() : undefined;
30
+ const given = [...labels, ...(typed === undefined ? [] : [typed])].join(", ");
31
+ return `- ${flattenBreaks(question)}: ${record.skipped === true || given.length === 0 ? "(skipped)" : flattenBreaks(given)}`;
32
+ }
33
+
34
+ /** The `- question: answer` lines of a form's answers, in the form's order. */
35
+ function formAnswers(value: unknown, questionsValue: unknown): string | undefined {
36
+ if (!Array.isArray(value) || value.length === 0) return undefined;
37
+ const questions = new Map<string, string>();
38
+ if (Array.isArray(questionsValue)) {
39
+ for (const raw of questionsValue) {
40
+ if (!isRecord(raw) || typeof raw.id !== "string" || typeof raw.text !== "string") continue;
41
+ questions.set(raw.id, raw.text);
42
+ }
43
+ }
44
+ const lines: string[] = [];
45
+ for (const raw of value) {
46
+ if (!isRecord(raw) || typeof raw.id !== "string") continue;
47
+ lines.push(answerLine(questions.get(raw.id) ?? raw.id, raw));
48
+ }
49
+ return lines.length === 0 ? undefined : lines.join("\n");
50
+ }
51
+
15
52
  /** One line: a prompt or choice built from model output cannot end the paragraph. */
16
53
  function flattenBreaks(text: string): string {
17
54
  return text.replace(/\s*[\r\n\u2028\u2029]+\s*/g, " ").trim();
@@ -31,11 +68,18 @@ function quoted(note: string): string {
31
68
  */
32
69
  export function askNote(askAnswer: unknown): string | undefined {
33
70
  if (!isRecord(askAnswer) || typeof askAnswer.prompt !== "string") return undefined;
34
- const choice = typeof askAnswer.choice === "string" ? flattenBreaks(askAnswer.choice) : "";
35
71
  const note =
36
72
  typeof askAnswer.note === "string" && askAnswer.note.trim().length > 0
37
73
  ? askAnswer.note
38
74
  : undefined;
75
+ const form = formAnswers(askAnswer.answers, askAnswer.questions);
76
+ if (form !== undefined) {
77
+ const template = note === undefined ? FORM_ASK_NOTE_TEMPLATE : FORM_ASK_NOTE_WITH_NOTE_TEMPLATE;
78
+ return template.replace(/\{(answers|note)\}/g, (_, name: string) =>
79
+ name === "answers" ? form : quoted(note ?? ""),
80
+ );
81
+ }
82
+ const choice = typeof askAnswer.choice === "string" ? flattenBreaks(askAnswer.choice) : "";
39
83
  if (choice.length === 0 && note === undefined) return undefined;
40
84
  const prompt = flattenBreaks(askAnswer.prompt);
41
85
  const answer = choice.length > 0 ? choice : "(no choice)";
package/src/flows.ts ADDED
@@ -0,0 +1,44 @@
1
+ /**
2
+ * The flow every harness plugin offers beside its step: one agent turn, and a
3
+ * person's answer to a question about a call sending the run back to it.
4
+ */
5
+
6
+ import { defineFlow } from "@operad-io/engine";
7
+
8
+ /** The prompt flow of a harness: its `agent` step, then a person's answer. */
9
+ export function promptFlowOf(name: string, use: string) {
10
+ return defineFlow({
11
+ name,
12
+ entry: "agent",
13
+ steps: [
14
+ {
15
+ id: "agent",
16
+ kind: "plugin",
17
+ params: { use, params: {} },
18
+ replay: "unsafe",
19
+ next: { done: "done", failed: "failed", interrupted: "cancelled", waiting: "person" },
20
+ },
21
+ {
22
+ // A question about a call ran out of grace. The answer sends the run
23
+ // back to the agent, which continues the session with it.
24
+ id: "person",
25
+ kind: "wait_person",
26
+ params: {
27
+ prompt: "The agent asked about a call.",
28
+ choices: ["allow_once", "reject_once"],
29
+ lateChoices: ["allow_always"],
30
+ },
31
+ replay: "safe",
32
+ next: {
33
+ allow_once: "agent",
34
+ allow_always: "agent",
35
+ reject_once: "agent",
36
+ interrupted: "cancelled",
37
+ },
38
+ },
39
+ { id: "done", kind: "end", params: { status: "done" }, replay: "safe" },
40
+ { id: "failed", kind: "end", params: { status: "failed" }, replay: "safe" },
41
+ { id: "cancelled", kind: "end", params: { status: "cancelled" }, replay: "safe" },
42
+ ],
43
+ });
44
+ }
package/src/fold-lines.ts CHANGED
@@ -10,8 +10,18 @@ import { isRecord } from "@operad-io/engine";
10
10
  export type ToolResult = "done" | "failed" | "blocked" | "denied";
11
11
 
12
12
  export type FoldEntry =
13
- | { readonly kind: "text"; readonly text: string }
14
- | { readonly kind: "thinking"; readonly text: string }
13
+ | {
14
+ readonly kind: "text";
15
+ readonly text: string;
16
+ /** When the host received the line that finished it, when the log gave one. */
17
+ readonly at?: number | undefined;
18
+ }
19
+ | {
20
+ readonly kind: "thinking";
21
+ readonly text: string;
22
+ /** When the host received the line that finished it, when the log gave one. */
23
+ readonly at?: number | undefined;
24
+ }
15
25
  | {
16
26
  readonly kind: "tool";
17
27
  readonly callId: string;
@@ -39,6 +49,15 @@ export interface OpenCall {
39
49
  readonly blocked: string | null;
40
50
  }
41
51
 
52
+ export interface FoldRetry {
53
+ readonly attempt: number;
54
+ readonly maxAttempts: number;
55
+ /** When the host received the line that announced the wait, when the log gave one. */
56
+ readonly at?: number | undefined;
57
+ readonly delayMs: number;
58
+ readonly reason: string;
59
+ }
60
+
42
61
  export interface FoldState {
43
62
  /** What has finished, in the order it finished. */
44
63
  readonly entries: readonly FoldEntry[];
@@ -52,6 +71,8 @@ export interface FoldState {
52
71
  readonly sawText: boolean;
53
72
  /** A `blocked` line that came before its call started, by tool name. */
54
73
  readonly earlyBlocks: Readonly<Record<string, string>>;
74
+ /** A model request the harness is waiting to try again, until `retry_end` or a failed message. */
75
+ readonly retry?: FoldRetry | undefined;
55
76
  }
56
77
 
57
78
  export const emptyFold: FoldState = {
@@ -73,11 +94,32 @@ function str(value: unknown): string | undefined {
73
94
  return typeof value === "string" ? value : undefined;
74
95
  }
75
96
 
76
- /** Puts unfinished text and thinking into the entries. */
77
- function settle(state: FoldState): FoldState {
97
+ /** When the host received a line; undefined for a log written without stamping. */
98
+ function receivedAtOf(line: Record<string, unknown>): number | undefined {
99
+ const at = line["receivedAt"];
100
+ return typeof at === "number" && Number.isFinite(at) ? at : undefined;
101
+ }
102
+
103
+ function wholeNumber(value: unknown): number | undefined {
104
+ return typeof value === "number" && Number.isInteger(value) && value >= 0 ? value : undefined;
105
+ }
106
+
107
+ /** The state without a retry being waited for. */
108
+ function noRetry(state: FoldState): FoldState {
109
+ if (state.retry === undefined) return state;
110
+ const { retry: _retry, ...rest } = state;
111
+ return rest;
112
+ }
113
+
114
+ /** Puts unfinished text and thinking into the entries, with the time of the line that finished them. */
115
+ function settle(state: FoldState, at: number | undefined): FoldState {
78
116
  const entries = [...state.entries];
79
- if (state.thinking.length > 0) entries.push({ kind: "thinking", text: state.thinking });
80
- if (state.text.length > 0) entries.push({ kind: "text", text: state.text });
117
+ if (state.thinking.length > 0) {
118
+ entries.push({ kind: "thinking", text: state.thinking, ...(at === undefined ? {} : { at }) });
119
+ }
120
+ if (state.text.length > 0) {
121
+ entries.push({ kind: "text", text: state.text, ...(at === undefined ? {} : { at }) });
122
+ }
81
123
  return { ...state, entries, text: "", thinking: "", sawText: state.sawText || state.text.length > 0 };
82
124
  }
83
125
 
@@ -96,9 +138,10 @@ function apply(state: FoldState, line: unknown): FoldState {
96
138
  case "text_end": {
97
139
  const text = str(line["text"]);
98
140
  if (text === undefined) return state;
141
+ const at = receivedAtOf(line);
99
142
  return {
100
143
  ...state,
101
- entries: [...state.entries, { kind: "text", text }],
144
+ entries: [...state.entries, { kind: "text", text, ...(at === undefined ? {} : { at }) }],
102
145
  text: "",
103
146
  sawText: true,
104
147
  };
@@ -106,25 +149,52 @@ function apply(state: FoldState, line: unknown): FoldState {
106
149
  case "thinking_end": {
107
150
  const text = str(line["text"]);
108
151
  if (text === undefined) return state;
109
- return { ...state, entries: [...state.entries, { kind: "thinking", text }], thinking: "" };
152
+ const at = receivedAtOf(line);
153
+ return {
154
+ ...state,
155
+ entries: [...state.entries, { kind: "thinking", text, ...(at === undefined ? {} : { at }) }],
156
+ thinking: "",
157
+ };
110
158
  }
111
159
  case "message_end": {
112
- const settled = settle(state);
160
+ const at = receivedAtOf(line);
161
+ const settled = settle(state, at);
162
+ // A successful message is proof the retry worked, even before its end line.
163
+ const stopped = str(line["stopReason"]);
164
+ const base = stopped !== undefined && stopped !== "error" ? noRetry(settled) : settled;
113
165
  const said = str(line["text"]);
114
166
  // Today's harnesses write only the head of a message's text here.
115
167
  const entries =
116
- !settled.sawText && said !== undefined && said.length > 0
117
- ? [...settled.entries, { kind: "text" as const, text: said }]
118
- : settled.entries;
119
- return { ...settled, entries, sawText: false };
168
+ !base.sawText && said !== undefined && said.length > 0
169
+ ? [...base.entries, { kind: "text" as const, text: said, ...(at === undefined ? {} : { at }) }]
170
+ : base.entries;
171
+ return { ...base, entries, sawText: false };
172
+ }
173
+ case "retry_start": {
174
+ const attempt = wholeNumber(line["attempt"]);
175
+ const maxAttempts = wholeNumber(line["maxAttempts"]);
176
+ const delayMs = wholeNumber(line["delayMs"]);
177
+ const reason = str(line["reason"]);
178
+ if (attempt === undefined || maxAttempts === undefined || delayMs === undefined) return state;
179
+ const at = receivedAtOf(line);
180
+ const retry: FoldRetry = {
181
+ attempt,
182
+ maxAttempts,
183
+ delayMs,
184
+ reason: reason ?? "the model request failed",
185
+ ...(at === undefined ? {} : { at }),
186
+ };
187
+ return { ...state, retry };
120
188
  }
189
+ case "retry_end":
190
+ return noRetry(state);
121
191
  case "tool_execution_start": {
122
192
  const callId = str(line["toolCallId"]);
123
193
  const toolName = str(line["toolName"]);
124
194
  const at = line["at"];
125
195
  if (callId === undefined || toolName === undefined || typeof at !== "number") return state;
126
196
  if (state.calls.some((call) => call.callId === callId)) return state;
127
- const settled = settle(state);
197
+ const settled = settle(state, receivedAtOf(line));
128
198
  const early = settled.earlyBlocks[toolName];
129
199
  const { [toolName]: _used, ...rest } = settled.earlyBlocks;
130
200
  const call: OpenCall = {
@@ -186,7 +256,7 @@ function apply(state: FoldState, line: unknown): FoldState {
186
256
  case "tool_execution_end": {
187
257
  const callId = str(line["toolCallId"]);
188
258
  if (callId === undefined) return state;
189
- const settled = settle(state);
259
+ const settled = settle(state, receivedAtOf(line));
190
260
  const open = settled.calls.find((call) => call.callId === callId);
191
261
  const toolName = open?.toolName ?? str(line["toolName"]) ?? "tool";
192
262
  const isError = line["isError"] === true;