narrarium-engine 0.1.13 → 0.1.15

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 (69) hide show
  1. package/README.md +55 -1
  2. package/dist/ai/fetch-client.d.ts.map +1 -1
  3. package/dist/ai/fetch-client.js +27 -5
  4. package/dist/ai/fetch-client.js.map +1 -1
  5. package/dist/ai/types.d.ts +11 -0
  6. package/dist/ai/types.d.ts.map +1 -1
  7. package/dist/ai/types.js.map +1 -1
  8. package/dist/autopilot/calls/index.d.ts +8 -0
  9. package/dist/autopilot/calls/index.d.ts.map +1 -0
  10. package/dist/autopilot/calls/index.js +8 -0
  11. package/dist/autopilot/calls/index.js.map +1 -0
  12. package/dist/autopilot/calls/memory-store.d.ts +38 -0
  13. package/dist/autopilot/calls/memory-store.d.ts.map +1 -0
  14. package/dist/autopilot/calls/memory-store.js +279 -0
  15. package/dist/autopilot/calls/memory-store.js.map +1 -0
  16. package/dist/autopilot/calls/port.d.ts +76 -0
  17. package/dist/autopilot/calls/port.d.ts.map +1 -0
  18. package/dist/autopilot/calls/port.js +28 -0
  19. package/dist/autopilot/calls/port.js.map +1 -0
  20. package/dist/autopilot/calls/recorder.d.ts +120 -0
  21. package/dist/autopilot/calls/recorder.d.ts.map +1 -0
  22. package/dist/autopilot/calls/recorder.js +400 -0
  23. package/dist/autopilot/calls/recorder.js.map +1 -0
  24. package/dist/autopilot/calls/retention.d.ts +27 -0
  25. package/dist/autopilot/calls/retention.d.ts.map +1 -0
  26. package/dist/autopilot/calls/retention.js +33 -0
  27. package/dist/autopilot/calls/retention.js.map +1 -0
  28. package/dist/autopilot/calls/run-calls.d.ts +106 -0
  29. package/dist/autopilot/calls/run-calls.d.ts.map +1 -0
  30. package/dist/autopilot/calls/run-calls.js +251 -0
  31. package/dist/autopilot/calls/run-calls.js.map +1 -0
  32. package/dist/autopilot/calls/types.d.ts +232 -0
  33. package/dist/autopilot/calls/types.d.ts.map +1 -0
  34. package/dist/autopilot/calls/types.js +53 -0
  35. package/dist/autopilot/calls/types.js.map +1 -0
  36. package/dist/autopilot/calls/utf8.d.ts +19 -0
  37. package/dist/autopilot/calls/utf8.d.ts.map +1 -0
  38. package/dist/autopilot/calls/utf8.js +91 -0
  39. package/dist/autopilot/calls/utf8.js.map +1 -0
  40. package/dist/autopilot/live.d.ts +26 -0
  41. package/dist/autopilot/live.d.ts.map +1 -0
  42. package/dist/autopilot/live.js +67 -0
  43. package/dist/autopilot/live.js.map +1 -0
  44. package/dist/autopilot/runner.d.ts +10 -0
  45. package/dist/autopilot/runner.d.ts.map +1 -1
  46. package/dist/autopilot/runner.js +118 -9
  47. package/dist/autopilot/runner.js.map +1 -1
  48. package/dist/autopilot/session.d.ts +12 -0
  49. package/dist/autopilot/session.d.ts.map +1 -1
  50. package/dist/autopilot/session.js +8 -2
  51. package/dist/autopilot/session.js.map +1 -1
  52. package/dist/autopilot/types.d.ts +54 -9
  53. package/dist/autopilot/types.d.ts.map +1 -1
  54. package/dist/autopilot/types.js.map +1 -1
  55. package/dist/index.d.ts +2 -0
  56. package/dist/index.d.ts.map +1 -1
  57. package/dist/index.js +2 -0
  58. package/dist/index.js.map +1 -1
  59. package/dist/server/client.d.ts +42 -1
  60. package/dist/server/client.d.ts.map +1 -1
  61. package/dist/server/client.js +69 -1
  62. package/dist/server/client.js.map +1 -1
  63. package/dist/server/protocol.d.ts +44 -0
  64. package/dist/server/protocol.d.ts.map +1 -1
  65. package/dist/server/protocol.js +19 -0
  66. package/dist/server/protocol.js.map +1 -1
  67. package/dist/version.d.ts +1 -1
  68. package/dist/version.js +1 -1
  69. package/package.json +1 -1
@@ -0,0 +1,91 @@
1
+ /**
2
+ * UTF-8 sizes and cuts of a JavaScript string, without encoding it: the recorder counts and cuts the text it receives in place. A lone surrogate
3
+ * counts as the replacement character (three bytes), as `TextEncoder` writes it; a pair counts as four. Cuts never split a pair.
4
+ */
5
+ function isHigh(code) {
6
+ return code >= 0xd800 && code <= 0xdbff;
7
+ }
8
+ function isLow(code) {
9
+ return code >= 0xdc00 && code <= 0xdfff;
10
+ }
11
+ /** The UTF-8 bytes of `text` from index `from` to `to` (default: the end). */
12
+ export function utf8Length(text, from = 0, to = text.length) {
13
+ let bytes = 0;
14
+ let index = from;
15
+ while (index < to) {
16
+ const code = text.charCodeAt(index);
17
+ if (code < 0x80)
18
+ bytes += 1;
19
+ else if (code < 0x800)
20
+ bytes += 2;
21
+ else if (isHigh(code) && index + 1 < to && isLow(text.charCodeAt(index + 1))) {
22
+ bytes += 4;
23
+ index += 1;
24
+ }
25
+ else
26
+ bytes += 3;
27
+ index += 1;
28
+ }
29
+ return bytes;
30
+ }
31
+ /**
32
+ * The index where the longest run of whole characters from `from` that fits in `maxBytes` ends. It never splits a pair, so the text before
33
+ * it is valid UTF-8 and exactly `utf8Length(text, from, index)` bytes long (at most `maxBytes`).
34
+ */
35
+ export function cutHead(text, from, maxBytes) {
36
+ let bytes = 0;
37
+ let index = from;
38
+ while (index < text.length) {
39
+ const code = text.charCodeAt(index);
40
+ let width;
41
+ let units = 1;
42
+ if (code < 0x80)
43
+ width = 1;
44
+ else if (code < 0x800)
45
+ width = 2;
46
+ else if (isHigh(code) && index + 1 < text.length && isLow(text.charCodeAt(index + 1))) {
47
+ width = 4;
48
+ units = 2;
49
+ }
50
+ else
51
+ width = 3;
52
+ if (bytes + width > maxBytes)
53
+ break;
54
+ bytes += width;
55
+ index += units;
56
+ }
57
+ return index;
58
+ }
59
+ /**
60
+ * The index where the longest run of whole characters at the end of `text` that fits in `maxBytes` starts: `text.slice(index)` is valid UTF-8
61
+ * and at most `maxBytes` bytes long.
62
+ */
63
+ export function suffixStart(text, maxBytes) {
64
+ let bytes = 0;
65
+ let index = text.length;
66
+ while (index > 0) {
67
+ const code = text.charCodeAt(index - 1);
68
+ let width;
69
+ let units = 1;
70
+ if (isLow(code) && index >= 2 && isHigh(text.charCodeAt(index - 2))) {
71
+ width = 4;
72
+ units = 2;
73
+ }
74
+ else if (code < 0x80)
75
+ width = 1;
76
+ else if (code < 0x800)
77
+ width = 2;
78
+ else
79
+ width = 3;
80
+ if (bytes + width > maxBytes)
81
+ break;
82
+ bytes += width;
83
+ index -= units;
84
+ }
85
+ return index;
86
+ }
87
+ /** Whether the text ends with a high surrogate that a low one may still complete: the text is not cut there. */
88
+ export function endsWithHighSurrogate(text, end = text.length) {
89
+ return end > 0 && isHigh(text.charCodeAt(end - 1));
90
+ }
91
+ //# sourceMappingURL=utf8.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"utf8.js","sourceRoot":"","sources":["../../../src/autopilot/calls/utf8.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAEH,SAAS,MAAM,CAAC,IAAY;IAC1B,OAAO,IAAI,IAAI,MAAM,IAAI,IAAI,IAAI,MAAM,CAAC;AAC1C,CAAC;AAED,SAAS,KAAK,CAAC,IAAY;IACzB,OAAO,IAAI,IAAI,MAAM,IAAI,IAAI,IAAI,MAAM,CAAC;AAC1C,CAAC;AAED,8EAA8E;AAC9E,MAAM,UAAU,UAAU,CAAC,IAAY,EAAE,IAAI,GAAG,CAAC,EAAE,EAAE,GAAG,IAAI,CAAC,MAAM;IACjE,IAAI,KAAK,GAAG,CAAC,CAAC;IACd,IAAI,KAAK,GAAG,IAAI,CAAC;IACjB,OAAO,KAAK,GAAG,EAAE,EAAE,CAAC;QAClB,MAAM,IAAI,GAAG,IAAI,CAAC,UAAU,CAAC,KAAK,CAAC,CAAC;QACpC,IAAI,IAAI,GAAG,IAAI;YAAE,KAAK,IAAI,CAAC,CAAC;aACvB,IAAI,IAAI,GAAG,KAAK;YAAE,KAAK,IAAI,CAAC,CAAC;aAC7B,IAAI,MAAM,CAAC,IAAI,CAAC,IAAI,KAAK,GAAG,CAAC,GAAG,EAAE,IAAI,KAAK,CAAC,IAAI,CAAC,UAAU,CAAC,KAAK,GAAG,CAAC,CAAC,CAAC,EAAE,CAAC;YAC7E,KAAK,IAAI,CAAC,CAAC;YACX,KAAK,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C,UAAU,CAAC,KAAK,GAAG,CAAC,CAAC,CAAC;QACxC,IAAI,KAAa,CAAC;QAClB,IAAI,KAAK,GAAG,CAAC,CAAC;QACd,IAAI,KAAK,CAAC,IAAI,CAAC,IAAI,KAAK,IAAI,CAAC,IAAI,MAAM,CAAC,IAAI,CAAC,UAAU,CAAC,KAAK,GAAG,CAAC,CAAC,CAAC,EAAE,CAAC;YACpE,KAAK,GAAG,CAAC,CAAC;YACV,KAAK,GAAG,CAAC,CAAC;QACZ,CAAC;aAAM,IAAI,IAAI,GAAG,IAAI;YAAE,KAAK,GAAG,CAAC,CAAC;aAC7B,IAAI,IAAI,GAAG,KAAK;YAAE,KAAK,GAAG,CAAC,CAAC;;YAC5B,KAAK,GAAG,CAAC,CAAC;QACf,IAAI,KAAK,GAAG,KAAK,GAAG,QAAQ;YAAE,MAAM;QACpC,KAAK,IAAI,KAAK,CAAC;QACf,KAAK,IAAI,KAAK,CAAC;IACjB,CAAC;IACD,OAAO,KAAK,CAAC;AACf,CAAC;AAED,gHAAgH;AAChH,MAAM,UAAU,qBAAqB,CAAC,IAAY,EAAE,GAAG,GAAG,IAAI,CAAC,MAAM;IACnE,OAAO,GAAG,GAAG,CAAC,IAAI,MAAM,CAAC,IAAI,CAAC,UAAU,CAAC,GAAG,GAAG,CAAC,CAAC,CAAC,CAAC;AACrD,CAAC"}
@@ -0,0 +1,26 @@
1
+ import type { AutopilotActivity, AutopilotEventBody, AutopilotLive } from "./types.js";
2
+ /** A `task-progress` event, as `applyLiveProgress` reads it (with or without the fields of the stream). */
3
+ export type AutopilotTaskProgress = Omit<Extract<AutopilotEventBody, {
4
+ type: "task-progress";
5
+ }>, "type">;
6
+ /** The live part of a step that has just started: no call of it has said anything yet. */
7
+ export declare function startLive(activity: AutopilotActivity): AutopilotLive;
8
+ /**
9
+ * How a `task-progress` of the step that runs changes what is shown of it. One rule for every host (the session's `snapshot().live`, the panels of the
10
+ * web app), so that what is shown never flickers:
11
+ * - A call of the step starts from nothing: a progress of another call (`callSeq` or `callId` changed; from an engine that names no calls, prose after a
12
+ * structured reply, a structured reply after prose, or bytes that went back) shows nothing of the call before it.
13
+ * - Prose (`preview` and `characters`, no `bytes`, no `kind`) is the text so far of a prose call: it replaces what was shown. A shorter one is a new
14
+ * attempt of the call, which takes the place of the one before; the empty text that says a new attempt begins changes nothing, so the text of the
15
+ * attempt before stays on screen until the new one has written something.
16
+ * - The JSON of a structured reply (`kind: "json"`) is shown as its text, with its count, by the same rule, and marks the text as JSON (`json`). It does
17
+ * not take away the bytes the reply said, unless it is shorter: then the bytes were the ones of the attempt before.
18
+ * - The numbers of a structured reply (`bytes`) set the bytes, and the count while no JSON is shown, never lower. They never change the text: the tail
19
+ * they carry is the one the JSON already said (or, from an older engine, the one of the call before), so a reply that streams its JSON keeps it on
20
+ * screen while its numbers arrive, and a reply that does not shows «answering» with its bytes.
21
+ * A progress of another step changes nothing.
22
+ */
23
+ export declare function applyLiveProgress(live: AutopilotLive, event: AutopilotTaskProgress): AutopilotLive;
24
+ /** A live part read from somewhere else (a snapshot of another host, an older one): its fields as `AutopilotLive` has them, or null. */
25
+ export declare function normalizeLive(value: unknown): AutopilotLive | null;
26
+ //# sourceMappingURL=live.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"live.d.ts","sourceRoot":"","sources":["../../src/autopilot/live.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,iBAAiB,EAAE,kBAAkB,EAAE,aAAa,EAAE,MAAM,YAAY,CAAC;AAEvF,2GAA2G;AAC3G,MAAM,MAAM,qBAAqB,GAAG,IAAI,CAAC,OAAO,CAAC,kBAAkB,EAAE;IAAE,IAAI,EAAE,eAAe,CAAA;CAAE,CAAC,EAAE,MAAM,CAAC,CAAC;AAEzG,0FAA0F;AAC1F,wBAAgB,SAAS,CAAC,QAAQ,EAAE,iBAAiB,GAAG,aAAa,CAEpE;AASD;;;;;;;;;;;;;;GAcG;AACH,wBAAgB,iBAAiB,CAAC,IAAI,EAAE,aAAa,EAAE,KAAK,EAAE,qBAAqB,GAAG,aAAa,CAqBlG;AAED,wIAAwI;AACxI,wBAAgB,aAAa,CAAC,KAAK,EAAE,OAAO,GAAG,aAAa,GAAG,IAAI,CAalE"}
@@ -0,0 +1,67 @@
1
+ /** The live part of a step that has just started: no call of it has said anything yet. */
2
+ export function startLive(activity) {
3
+ return { activity, characters: 0, preview: "" };
4
+ }
5
+ const count = (value) => (typeof value === "number" && Number.isFinite(value) && value >= 0 ? value : undefined);
6
+ /** The names of the call an event or a live part belongs to. */
7
+ function callOf(source) {
8
+ return { ...(source.callSeq !== undefined ? { callSeq: source.callSeq } : {}), ...(source.callId !== undefined ? { callId: source.callId } : {}) };
9
+ }
10
+ /**
11
+ * How a `task-progress` of the step that runs changes what is shown of it. One rule for every host (the session's `snapshot().live`, the panels of the
12
+ * web app), so that what is shown never flickers:
13
+ * - A call of the step starts from nothing: a progress of another call (`callSeq` or `callId` changed; from an engine that names no calls, prose after a
14
+ * structured reply, a structured reply after prose, or bytes that went back) shows nothing of the call before it.
15
+ * - Prose (`preview` and `characters`, no `bytes`, no `kind`) is the text so far of a prose call: it replaces what was shown. A shorter one is a new
16
+ * attempt of the call, which takes the place of the one before; the empty text that says a new attempt begins changes nothing, so the text of the
17
+ * attempt before stays on screen until the new one has written something.
18
+ * - The JSON of a structured reply (`kind: "json"`) is shown as its text, with its count, by the same rule, and marks the text as JSON (`json`). It does
19
+ * not take away the bytes the reply said, unless it is shorter: then the bytes were the ones of the attempt before.
20
+ * - The numbers of a structured reply (`bytes`) set the bytes, and the count while no JSON is shown, never lower. They never change the text: the tail
21
+ * they carry is the one the JSON already said (or, from an older engine, the one of the call before), so a reply that streams its JSON keeps it on
22
+ * screen while its numbers arrive, and a reply that does not shows «answering» with its bytes.
23
+ * A progress of another step changes nothing.
24
+ */
25
+ export function applyLiveProgress(live, event) {
26
+ if (event.activityId !== live.activity.id)
27
+ return live;
28
+ const bytes = count(event.bytes);
29
+ const kind = event.kind === "json" ? "json" : bytes !== undefined ? "bytes" : "prose";
30
+ const characters = count(event.characters) ?? 0;
31
+ // An event without a preview (a host that leaves it out) keeps the text that is shown.
32
+ const preview = typeof event.preview === "string" ? event.preview : undefined;
33
+ const named = event.callSeq !== undefined || event.callId !== undefined;
34
+ const anotherCall = (event.callSeq !== undefined && event.callSeq !== live.callSeq) || (event.callId !== undefined && event.callId !== live.callId);
35
+ const structured = live.json === true || live.bytes !== undefined;
36
+ const wentBack = kind === "bytes" && live.bytes !== undefined && bytes !== undefined && bytes < live.bytes;
37
+ const otherKind = !named && (kind === "prose" ? structured : (!structured && (live.preview !== "" || live.characters > 0)) || wentBack);
38
+ const base = anotherCall || otherKind ? { activity: live.activity, characters: 0, preview: "", ...callOf(event) } : { ...live, ...callOf(event) };
39
+ // A new attempt begins (its text is empty): what the attempt before wrote stays until the new one writes.
40
+ if (kind !== "bytes" && preview === "" && characters === 0 && !(anotherCall || otherKind))
41
+ return base;
42
+ if (kind === "prose")
43
+ return { activity: base.activity, characters, preview: preview ?? base.preview, ...callOf(base) };
44
+ if (kind === "json") {
45
+ const { bytes: _before, ...text } = base;
46
+ return { ...(base.json && characters < base.characters ? text : base), json: true, characters, preview: preview ?? base.preview };
47
+ }
48
+ return { ...base, bytes, ...(base.json ? {} : { characters: Math.max(base.characters, characters) }) };
49
+ }
50
+ /** A live part read from somewhere else (a snapshot of another host, an older one): its fields as `AutopilotLive` has them, or null. */
51
+ export function normalizeLive(value) {
52
+ if (!value || typeof value !== "object")
53
+ return null;
54
+ const live = value;
55
+ if (!live.activity || typeof live.activity !== "object" || typeof live.activity.id !== "string")
56
+ return null;
57
+ const bytes = count(live.bytes);
58
+ return {
59
+ activity: live.activity,
60
+ characters: count(live.characters) ?? 0,
61
+ preview: typeof live.preview === "string" ? live.preview : "",
62
+ ...(live.json === true ? { json: true } : {}),
63
+ ...(bytes !== undefined ? { bytes } : {}),
64
+ ...callOf({ ...(typeof live.callSeq === "number" ? { callSeq: live.callSeq } : {}), ...(typeof live.callId === "string" ? { callId: live.callId } : {}) }),
65
+ };
66
+ }
67
+ //# sourceMappingURL=live.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"live.js","sourceRoot":"","sources":["../../src/autopilot/live.ts"],"names":[],"mappings":"AAKA,0FAA0F;AAC1F,MAAM,UAAU,SAAS,CAAC,QAA2B;IACnD,OAAO,EAAE,QAAQ,EAAE,UAAU,EAAE,CAAC,EAAE,OAAO,EAAE,EAAE,EAAE,CAAC;AAClD,CAAC;AAED,MAAM,KAAK,GAAG,CAAC,KAAc,EAAsB,EAAE,CAAC,CAAC,OAAO,KAAK,KAAK,QAAQ,IAAI,MAAM,CAAC,QAAQ,CAAC,KAAK,CAAC,IAAI,KAAK,IAAI,CAAC,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,SAAS,CAAC,CAAC;AAE9I,gEAAgE;AAChE,SAAS,MAAM,CAAC,MAA6C;IAC3D,OAAO,EAAE,GAAG,CAAC,MAAM,CAAC,OAAO,KAAK,SAAS,CAAC,CAAC,CAAC,EAAE,OAAO,EAAE,MAAM,CAAC,OAAO,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC,EAAE,GAAG,CAAC,MAAM,CAAC,MAAM,KAAK,SAAS,CAAC,CAAC,CAAC,EAAE,MAAM,EAAE,MAAM,CAAC,MAAM,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC,EAAE,CAAC;AACrJ,CAAC;AAED;;;;;;;;;;;;;;GAcG;AACH,MAAM,UAAU,iBAAiB,CAAC,IAAmB,EAAE,KAA4B;IACjF,IAAI,KAAK,CAAC,UAAU,KAAK,IAAI,CAAC,QAAQ,CAAC,EAAE;QAAE,OAAO,IAAI,CAAC;IACvD,MAAM,KAAK,GAAG,KAAK,CAAC,KAAK,CAAC,KAAK,CAAC,CAAC;IACjC,MAAM,IAAI,GAAG,KAAK,CAAC,IAAI,KAAK,MAAM,CAAC,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC,KAAK,KAAK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B,CAAC;IAC7C,IAAI,CAAC,IAAI,CAAC,QAAQ,IAAI,OAAO,IAAI,CAAC,QAAQ,KAAK,QAAQ,IAAI,OAAO,IAAI,CAAC,QAAQ,CAAC,EAAE,KAAK,QAAQ;QAAE,OAAO,IAAI,CAAC;IAC7G,MAAM,KAAK,GAAG,KAAK,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC;IAChC,OAAO;QACL,QAAQ,EAAE,IAAI,CAAC,QAAQ;QACvB,UAAU,EAAE,KAAK,CAAC,IAAI,CAAC,UAAU,CAAC,IAAI,CAAC;QACvC,OAAO,EAAE,OAAO,IAAI,CAAC,OAAO,KAAK,QAAQ,CAAC,CAAC,CAAC,IAAI,CAAC,OAAO,CAAC,CAAC,CAAC,EAAE;QAC7D,GAAG,CAAC,IAAI,CAAC,IAAI,KAAK,IAAI,CAAC,CAAC,CAAC,EAAE,IAAI,EAAE,IAAI,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC;QAC7C,GAAG,CAAC,KAAK,KAAK,SAAS,CAAC,CAAC,CAAC,EAAE,KAAK,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC;QACzC,GAAG,MAAM,CAAC,EAAE,GAAG,CAAC,OAAO,IAAI,CAAC,OAAO,KAAK,QAAQ,CAAC,CAAC,CAAC,EAAE,OAAO,EAAE,IAAI,CAAC,OAAO,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC,EAAE,GAAG,CAAC,OAAO,IAAI,CAAC,MAAM,KAAK,QAAQ,CAAC,CAAC,CAAC,EAAE,MAAM,EAAE,IAAI,CAAC,MAAM,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC,EAAE,CAAC;KAC3J,CAAC;AACJ,CAAC"}
@@ -1,5 +1,6 @@
1
1
  import { type AiPort } from "../ai/types.js";
2
2
  import { type BookFileChange, type BookStore } from "../book/store.js";
3
+ import type { AiCallStore } from "./calls/port.js";
3
4
  import { type TaskDescriptor } from "./planner.js";
4
5
  import { type AutopilotActivity, type AutopilotEventBody, type AutopilotLimitsSummary, type AutopilotPausePending, type AutopilotPublishMode, type AutopilotRetryInfo, type AutopilotState, type InterventionInput, type QuestionAnswer, type StartOptions } from "./types.js";
5
6
  /**
@@ -53,6 +54,11 @@ export interface AutopilotRunConfig {
53
54
  * so that another host does not take a long step for a dead run. 0 switches it off. Default 300 000 (5 minutes).
54
55
  */
55
56
  persistHeartbeatMs?: number;
57
+ /** Where the AI call records are kept (see `AutopilotSessionConfig.calls`). */
58
+ calls?: AiCallStore;
59
+ callsSecrets?: () => string[];
60
+ callsBudgetBytes?: number;
61
+ callsAccountScope?: string | null;
56
62
  }
57
63
  /** The longest a step may go without the run writing its state: a quarter of the 20 minutes after which another host takes the run for dead. */
58
64
  export declare const DEFAULT_PERSIST_HEARTBEAT_MS = 300000;
@@ -167,6 +173,8 @@ export declare class AutopilotRun {
167
173
  private readonly outlineCache;
168
174
  private readonly store;
169
175
  private readonly now;
176
+ /** The records of the AI calls of this run, when the host keeps them; stopped by the first store failure. */
177
+ private readonly calls;
170
178
  /** Steps this run saved, and chapters it closed: what the limits of the run count. A step that failed or was abandoned is not one. */
171
179
  private stepsThisRun;
172
180
  private chaptersThisRun;
@@ -320,6 +328,8 @@ export declare class AutopilotRun {
320
328
  * Close the run with a final status, persisted together with any queued intervention and with what the author saved since the run last read the state.
321
329
  * `code` is the reason a client can say in its language (`run-ended`'s `code`), when there is one.
322
330
  */
331
+ /** Saves the header of a task in the records (its title, kind, chapter, scene and status); a finished task makes room for the budget. */
332
+ private recordTask;
323
333
  private finish;
324
334
  }
325
335
  //# sourceMappingURL=runner.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"runner.d.ts","sourceRoot":"","sources":["../../src/autopilot/runner.ts"],"names":[],"mappings":"AACA,OAAO,EAAyC,KAAK,MAAM,EAAkE,MAAM,gBAAgB,CAAC;AAKpJ,OAAO,EAA4D,KAAK,cAAc,EAAE,KAAK,SAAS,EAAE,MAAM,kBAAkB,CAAC;AAajI,OAAO,EAAo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E;IAcpJ,+GAA+G;IAC/G,IAAI,aAAa,IAAI,MAAM,GAAG,IAAI,CAEjC;IAED,yJAAyJ;IACzJ,OAAO,CAAC,SAAS;IAOjB,iJAAiJ;IACjJ,SAAS,CAAC,KAAK,EAAE,iBAAiB,GAAG,IAAI;IAOzC,oIAAoI;IACpI,SAAS,IAAI,IAAI;IAMjB,OAAO,CAAC,IAAI;YAQE,WAAW;IAsBzB,OAAO,CAAC,QAAQ;IAMhB;;;;OAIG;YACW,eAAe;IAyB7B,OAAO,CAAC,UAAU;IAMlB,4IAA4I;IAC5I,OAAO,CAAC,YAAY;IAepB,OAAO,CAAC,eAAe;IAKvB,oHAAoH;YACtG,aAAa;IAM3B,OAAO,CAAC,gBAAgB;IAKxB;;;;OAIG;YACW,gBAAgB;IAwB9B,4FAA4F;YAC9E,eAAe;IAKvB,OAAO,CAAC,KAAK,GAAE,YAAY,GAAG;QAAE,YAAY,CAAC,EAAE,OAAO,CAAA;KAAO,GAAG,OAAO,CAAC,cAAc,CAAC;IA0C7F,iGAAiG;YACnF,QAAQ;IA8etB;;;;;;OAMG;YACW,UAAU;IAgCxB,2IAA2I;IAC3I,OAAO,CAAC,SAAS;IAKjB,+EAA+E;IAC/E,OAAO,CAAC,SAAS;IAMjB;;;OAGG;YACW,cAAc;IA4B5B;;;OAGG;IACH,yIAAyI;IACzI,OAAO,CAAC,UAAU;YAMJ,MAAM;CA8CrB"}
@@ -10,6 +10,7 @@ import { randomId } from "../util/hash.js";
10
10
  import { StructuredReplyError } from "../util/json.js";
11
11
  import { currentRequest, unescapePromptDataDeep } from "../prompt/trust.js";
12
12
  import { isItalian, languageCode, tail, truncate } from "../util/text.js";
13
+ import { RunCalls, schemaHashOf, statusOf } from "./calls/run-calls.js";
13
14
  import { autopilotErrorFields } from "./errors.js";
14
15
  import { readBrief } from "./brief.js";
15
16
  import { applyFrozenDecision, frozenAnswerAction, isFrozenQuestion, settleFrozenChanges } from "./frozen.js";
@@ -263,6 +264,12 @@ export function extendPlanIfNeeded(state, targetChapters = 0) {
263
264
  };
264
265
  }
265
266
  /** An error as text for the state, the activity log and the events: never with a credential in it. */
267
+ function callsStoreFailedTitle(italian, error) {
268
+ const full = error instanceof Error && (error.name === "AiCallDiskFullError" || error.name === "QuotaExceededError");
269
+ if (full)
270
+ return italian ? "Non c'è spazio per le registrazioni delle chiamate AI: la registrazione si ferma per questa corsa." : "There is no room to keep the AI call records: recording stops for this run.";
271
+ return italian ? "Non è stato possibile conservare le registrazioni delle chiamate AI: la registrazione si ferma per questa corsa." : "The AI call records could not be kept: recording stops for this run.";
272
+ }
266
273
  function describeError(error) {
267
274
  return redactSecrets(error instanceof Error ? error.message : String(error));
268
275
  }
@@ -544,6 +551,8 @@ export class AutopilotRun {
544
551
  outlineCache = new OutlineCache();
545
552
  store;
546
553
  now;
554
+ /** The records of the AI calls of this run, when the host keeps them; stopped by the first store failure. */
555
+ calls;
547
556
  /** Steps this run saved, and chapters it closed: what the limits of the run count. A step that failed or was abandoned is not one. */
548
557
  stepsThisRun = 0;
549
558
  chaptersThisRun = 0;
@@ -590,6 +599,18 @@ export class AutopilotRun {
590
599
  this.store = transientStore(config.store);
591
600
  this.defaultPublish = hostDefaultPublish(config.host, config.defaultPublish);
592
601
  this.persistHeartbeatMs = typeof config.persistHeartbeatMs === "number" && Number.isFinite(config.persistHeartbeatMs) ? config.persistHeartbeatMs : DEFAULT_PERSIST_HEARTBEAT_MS;
602
+ this.calls = config.calls
603
+ ? new RunCalls({
604
+ store: config.calls,
605
+ bookId: config.bookId,
606
+ accountScope: config.callsAccountScope ?? null,
607
+ host: config.host,
608
+ budgetBytes: config.callsBudgetBytes,
609
+ secrets: () => config.callsSecrets?.() ?? [],
610
+ now: this.now,
611
+ onFailure: (error) => this.emit({ type: "insight", tone: "warning", code: "callsStoreFailed", title: callsStoreFailedTitle(isItalian(this.language), error), detail: describeError(error) }),
612
+ })
613
+ : null;
593
614
  }
594
615
  get activity() {
595
616
  return this.current;
@@ -928,6 +949,9 @@ export class AutopilotRun {
928
949
  async runSteps(initial) {
929
950
  const { store } = this;
930
951
  let state = initial;
952
+ /** The attempt of the step that is running (a retry of a step that failed), and the step that failed last. */
953
+ let stepCount = 0;
954
+ let stepFailedKey = null;
931
955
  let conflictRetries = 0;
932
956
  /** Retries used since the last success: provider failures (up to three) and everything else (one). */
933
957
  let transientRetries = 0;
@@ -1046,6 +1070,9 @@ export class AutopilotRun {
1046
1070
  this.inChapter = chapterInProgress(state, task);
1047
1071
  const boostKey = step.task.kind;
1048
1072
  const key = taskKey(task);
1073
+ // A retry of a step is a new activity: its attempt counts from 1 and goes up while the same step fails again.
1074
+ const stepAttempt = stepFailedKey === key ? ++stepCount : (stepCount = 1);
1075
+ stepFailedKey = null;
1049
1076
  if (key === lastSuccessKey && successRepeats >= 2)
1050
1077
  throw new Error(`The autopilot is not making progress on "${task.title}".`);
1051
1078
  const correction = retry?.key === key ? retry : null;
@@ -1070,32 +1097,99 @@ export class AutopilotRun {
1070
1097
  };
1071
1098
  this.current = activity;
1072
1099
  this.emit({ type: "task-started", activity });
1073
- let lastProgress = 0;
1074
- let lastStructuredProgress;
1100
+ this.recordTask(activity, "running");
1101
+ let callSeq = 0;
1075
1102
  const ai = async (request) => {
1076
1103
  lastLabel = request.label;
1077
- const onText = request.json ? undefined : (text) => {
1104
+ const user = correction?.label === request.label ? `${request.user}\n\n${currentRequest(correction.note)}` : request.user;
1105
+ const seq = ++callSeq;
1106
+ // What this call says of itself while it answers: its own text, its own pace, nothing of the call before it.
1107
+ let lastProgress = 0;
1108
+ let lastStructuredProgress;
1109
+ let lastJsonTail;
1110
+ let structuredTail = "";
1111
+ let structuredLength;
1112
+ const call = this.calls?.start({
1113
+ runId: this.runId,
1114
+ activityId: activity.id,
1115
+ seq,
1116
+ stepAttempt,
1117
+ task: activity.task,
1118
+ chapter: activity.chapterNumber ?? null,
1119
+ scene: activity.sceneNumber ?? null,
1120
+ label: request.label,
1121
+ capability: request.capability,
1122
+ system: request.system,
1123
+ user,
1124
+ structured: Boolean(request.json),
1125
+ tool: request.json?.name ?? null,
1126
+ toolSchemaHash: request.json ? schemaHashOf(request.json.parameters) : null,
1127
+ maxOutputTokens: request.maxOutputTokens ?? null,
1128
+ temperature: request.temperature ?? null,
1129
+ }) ?? null;
1130
+ if (call)
1131
+ this.emit({ type: "call-started", activityId: activity.id, callId: call.callId, seq: call.seq, label: request.label, capability: request.capability, structured: Boolean(request.json), systemBytes: call.systemBytes, userBytes: call.userBytes });
1132
+ const callId = { ...(call ? { callId: call.callId } : {}), callSeq: seq };
1133
+ const finishCall = (status, outcome = {}) => {
1134
+ if (!call)
1135
+ return;
1136
+ const info = call.end(status, outcome);
1137
+ this.emit({ type: "call-ended", activityId: activity.id, callId: info.callId, status: info.status, attempts: info.attempts, characters: info.characters, storedBytes: info.storedBytes, partial: info.partial, durationMs: info.durationMs, dropped: info.dropped });
1138
+ };
1139
+ const onText = (text) => {
1140
+ call?.onText(text);
1141
+ if (request.onText) {
1142
+ request.onText(text);
1143
+ return;
1144
+ }
1145
+ if (request.json)
1146
+ return;
1078
1147
  const at = Date.now();
1079
1148
  if (text.length > 0 && at - lastProgress < 350)
1080
1149
  return;
1081
1150
  lastProgress = at;
1082
- this.emit({ type: "task-progress", activityId: activity.id, characters: text.length, preview: tail(text, 700) });
1151
+ this.emit({ type: "task-progress", activityId: activity.id, ...callId, characters: text.length, preview: tail(text, 700) });
1083
1152
  };
1084
- // A structured reply has no text to show: the client reports how much has arrived (up to four times a second), and one report a second is said, as numbers only.
1153
+ // A structured reply streams its JSON: its tail is said as the text of a prose step is, at most about three times a second, and the
1154
+ // arguments themselves are never kept by the runner (the records keep them when the book keeps records). A shorter JSON (`""` too) is a new
1155
+ // attempt of the call: it is said at once, so that what a client shows starts again with it.
1156
+ const onStructuredText = request.json ? (text) => {
1157
+ call?.onText(text);
1158
+ request.onStructuredText?.(text);
1159
+ const restart = structuredLength !== undefined && text.length < structuredLength;
1160
+ structuredTail = tail(text, 700);
1161
+ structuredLength = text.length;
1162
+ const at = Date.now();
1163
+ if (!restart && lastJsonTail !== undefined && at - lastJsonTail < 350)
1164
+ return;
1165
+ lastJsonTail = at;
1166
+ this.emit({ type: "task-progress", activityId: activity.id, ...callId, kind: "json", characters: text.length, preview: structuredTail });
1167
+ } : undefined;
1168
+ // The client reports how much of a structured reply has arrived (up to four times a second), and one report a second is said, as numbers. Its
1169
+ // characters are the JSON's once the JSON streams (one count for the call, the one its tail says), the client's count before.
1085
1170
  const onProgress = request.json ? (progress) => {
1086
1171
  const at = this.now().getTime();
1087
1172
  if (lastStructuredProgress !== undefined && at - lastStructuredProgress < STRUCTURED_PROGRESS_INTERVAL_MS)
1088
1173
  return;
1089
1174
  lastStructuredProgress = at;
1090
- this.emit({ type: "task-progress", activityId: activity.id, characters: progress.characters, bytes: progress.bytes, preview: "" });
1175
+ this.emit({ type: "task-progress", activityId: activity.id, ...callId, bytes: progress.bytes, characters: structuredLength ?? progress.characters, preview: structuredTail });
1091
1176
  } : undefined;
1092
- const user = correction?.label === request.label ? `${request.user}\n\n${currentRequest(correction.note)}` : request.user;
1093
1177
  let response;
1094
1178
  const boost = this.outputBoosts.get(boostKey) ?? 1;
1095
1179
  try {
1096
- response = await this.config.ai.complete({ ...request, user, signal: stepController.signal, onText: request.onText ?? onText, ...(onProgress ? { onProgress: request.onProgress ?? onProgress } : {}), ...(boost > 1 ? { outputBoost: boost } : {}) });
1180
+ response = await this.config.ai.complete({
1181
+ ...request,
1182
+ user,
1183
+ signal: stepController.signal,
1184
+ onText,
1185
+ ...(onStructuredText ? { onStructuredText } : {}),
1186
+ ...(onProgress ? { onProgress: request.onProgress ?? onProgress } : {}),
1187
+ ...(call ? { onAttempt: call.onAttempt, onAttemptEnd: call.onAttemptEnd } : {}),
1188
+ ...(boost > 1 ? { outputBoost: boost } : {}),
1189
+ });
1097
1190
  }
1098
1191
  catch (error) {
1192
+ finishCall(statusOf(error, stepController.signal.aborted), { error });
1099
1193
  // A failed attempt may still have been billed: count what the provider reported.
1100
1194
  if (error instanceof AiProviderError && (error.usage || error.cost !== undefined || error.model))
1101
1195
  recordSpend(spend, error);
@@ -1113,8 +1207,11 @@ export class AutopilotRun {
1113
1207
  this.emit({ type: "insight", activityId: activity.id, tone: "warning", code: "budgetNotApplicable", title: italian ? `Il budget in denaro non è applicabile: il modello ${model} non ha prezzo.` : `The money budget does not apply: the model ${model} has no price.`, detail: italian ? "Imposta un budget in token: vale per ogni modello." : "Set a token budget instead: it works for every model." });
1114
1208
  }
1115
1209
  if (response.truncated) {
1116
- throw new AiProviderError(`${[response.provider, response.model].filter(Boolean).join(" ") || "The model"}: the reply was cut by the output token limit. Nothing was applied.`, undefined, false, { truncated: true });
1210
+ const failure = new AiProviderError(`${[response.provider, response.model].filter(Boolean).join(" ") || "The model"}: the reply was cut by the output token limit. Nothing was applied.`, undefined, false, { truncated: true });
1211
+ finishCall("failed", { response, error: failure });
1212
+ throw failure;
1117
1213
  }
1214
+ finishCall("ok", { response });
1118
1215
  // The model repeats what it read, and what it read was escaped: the book gets the text as written.
1119
1216
  return response.json === undefined ? response : { ...response, json: unescapePromptDataDeep(response.json) };
1120
1217
  };
@@ -1203,6 +1300,7 @@ export class AutopilotRun {
1203
1300
  this.chaptersThisRun += 1;
1204
1301
  this.closedChapter = task.kind === "consolidate" ? task.chapterNumber ?? null : null;
1205
1302
  this.emit({ type: "task-finished", activity: done });
1303
+ this.recordTask(done, "done");
1206
1304
  this.emit({ type: "state", state: this.summarize(state) });
1207
1305
  // Where the book is published is read from the state this step saved, which holds what the author changed while it ran: a change takes hold at the end of the step that is running.
1208
1306
  const publish = effectivePublish(state.options, this.defaultPublish);
@@ -1254,6 +1352,9 @@ export class AutopilotRun {
1254
1352
  ...(spent ? { model: spend.model, provider: spend.provider, usage: spend.usage, cost: spend.cost || undefined } : {}),
1255
1353
  };
1256
1354
  this.emit({ type: "task-finished", activity: failed });
1355
+ this.recordTask(failed, failed.status === "cancelled" ? "stopped" : "failed");
1356
+ if (task)
1357
+ stepFailedKey = taskKey(task);
1257
1358
  const saved = await this.persistFailure(failed, spent ? spend : null).catch(() => null);
1258
1359
  if (spent)
1259
1360
  state = { ...state, stats: saved?.stats ?? withSpend(state.stats, spend) };
@@ -1464,6 +1565,14 @@ export class AutopilotRun {
1464
1565
  * Close the run with a final status, persisted together with any queued intervention and with what the author saved since the run last read the state.
1465
1566
  * `code` is the reason a client can say in its language (`run-ended`'s `code`), when there is one.
1466
1567
  */
1568
+ /** Saves the header of a task in the records (its title, kind, chapter, scene and status); a finished task makes room for the budget. */
1569
+ recordTask(activity, status) {
1570
+ if (!this.calls)
1571
+ return;
1572
+ this.calls.saveTask({ bookId: this.config.bookId, activityId: activity.id, title: activity.title, kind: activity.task, chapter: activity.chapterNumber ?? null, scene: activity.sceneNumber ?? null, status, startedAt: activity.startedAt, endedAt: activity.endedAt ?? null });
1573
+ if (status !== "running")
1574
+ this.calls.prune();
1575
+ }
1467
1576
  async finish(state, status, message, code) {
1468
1577
  const ending = state.question ? "waiting-author" : status;
1469
1578
  // A pause that the server's stop caused (and nothing else: a limit, a budget, the end of a chapter have their own words) says so, so that the