@autumnsgrove/lyra 0.1.0 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (173) hide show
  1. package/dist/adapters/cloudflare/index.d.ts +1 -0
  2. package/dist/adapters/cloudflare/index.d.ts.map +1 -1
  3. package/dist/adapters/cloudflare/index.js +1 -0
  4. package/dist/adapters/cloudflare/index.js.map +1 -1
  5. package/dist/adapters/cloudflare/session.d.ts +102 -0
  6. package/dist/adapters/cloudflare/session.d.ts.map +1 -0
  7. package/dist/adapters/cloudflare/session.js +595 -0
  8. package/dist/adapters/cloudflare/session.js.map +1 -0
  9. package/dist/adapters/openai/errors.d.ts +36 -0
  10. package/dist/adapters/openai/errors.d.ts.map +1 -0
  11. package/dist/adapters/openai/errors.js +117 -0
  12. package/dist/adapters/openai/errors.js.map +1 -0
  13. package/dist/adapters/openai/index.d.ts +18 -0
  14. package/dist/adapters/openai/index.d.ts.map +1 -0
  15. package/dist/adapters/openai/index.js +18 -0
  16. package/dist/adapters/openai/index.js.map +1 -0
  17. package/dist/adapters/openai/model.d.ts +50 -0
  18. package/dist/adapters/openai/model.d.ts.map +1 -0
  19. package/dist/adapters/openai/model.js +169 -0
  20. package/dist/adapters/openai/model.js.map +1 -0
  21. package/dist/adapters/openai/presets.d.ts +36 -0
  22. package/dist/adapters/openai/presets.d.ts.map +1 -0
  23. package/dist/adapters/openai/presets.js +43 -0
  24. package/dist/adapters/openai/presets.js.map +1 -0
  25. package/dist/adapters/openai/request.d.ts +47 -0
  26. package/dist/adapters/openai/request.d.ts.map +1 -0
  27. package/dist/adapters/openai/request.js +93 -0
  28. package/dist/adapters/openai/request.js.map +1 -0
  29. package/dist/adapters/openai/sse.d.ts +44 -0
  30. package/dist/adapters/openai/sse.d.ts.map +1 -0
  31. package/dist/adapters/openai/sse.js +410 -0
  32. package/dist/adapters/openai/sse.js.map +1 -0
  33. package/dist/core/approval.d.ts +38 -0
  34. package/dist/core/approval.d.ts.map +1 -0
  35. package/dist/core/approval.js +47 -0
  36. package/dist/core/approval.js.map +1 -0
  37. package/dist/core/compaction.d.ts +193 -0
  38. package/dist/core/compaction.d.ts.map +1 -0
  39. package/dist/core/compaction.js +460 -0
  40. package/dist/core/compaction.js.map +1 -0
  41. package/dist/core/define-recipe.d.ts +8 -1
  42. package/dist/core/define-recipe.d.ts.map +1 -1
  43. package/dist/core/define-recipe.js +13 -0
  44. package/dist/core/define-recipe.js.map +1 -1
  45. package/dist/core/events.d.ts +32 -2
  46. package/dist/core/events.d.ts.map +1 -1
  47. package/dist/core/events.js +16 -1
  48. package/dist/core/events.js.map +1 -1
  49. package/dist/core/execute-tools.d.ts +7 -0
  50. package/dist/core/execute-tools.d.ts.map +1 -1
  51. package/dist/core/execute-tools.js +6 -0
  52. package/dist/core/execute-tools.js.map +1 -1
  53. package/dist/core/hash.d.ts +10 -0
  54. package/dist/core/hash.d.ts.map +1 -0
  55. package/dist/core/hash.js +14 -0
  56. package/dist/core/hash.js.map +1 -0
  57. package/dist/core/model.d.ts +12 -0
  58. package/dist/core/model.d.ts.map +1 -1
  59. package/dist/core/propose.d.ts +29 -0
  60. package/dist/core/propose.d.ts.map +1 -0
  61. package/dist/core/propose.js +75 -0
  62. package/dist/core/propose.js.map +1 -0
  63. package/dist/core/recipe.d.ts +2 -0
  64. package/dist/core/recipe.d.ts.map +1 -1
  65. package/dist/core/recipe.js +5 -8
  66. package/dist/core/recipe.js.map +1 -1
  67. package/dist/core/resume.d.ts +19 -1
  68. package/dist/core/resume.d.ts.map +1 -1
  69. package/dist/core/resume.js +64 -6
  70. package/dist/core/resume.js.map +1 -1
  71. package/dist/core/retry.d.ts +9 -0
  72. package/dist/core/retry.d.ts.map +1 -0
  73. package/dist/core/retry.js +9 -0
  74. package/dist/core/retry.js.map +1 -0
  75. package/dist/core/run-handle.d.ts +5 -0
  76. package/dist/core/run-handle.d.ts.map +1 -1
  77. package/dist/core/run-handle.js +1 -0
  78. package/dist/core/run-handle.js.map +1 -1
  79. package/dist/core/run.d.ts +29 -2
  80. package/dist/core/run.d.ts.map +1 -1
  81. package/dist/core/run.js +526 -132
  82. package/dist/core/run.js.map +1 -1
  83. package/dist/core/runtime.d.ts +12 -0
  84. package/dist/core/runtime.d.ts.map +1 -1
  85. package/dist/core/runtime.js +34 -2
  86. package/dist/core/runtime.js.map +1 -1
  87. package/dist/core/system-clock.d.ts.map +1 -1
  88. package/dist/core/system-clock.js +5 -1
  89. package/dist/core/system-clock.js.map +1 -1
  90. package/dist/core/tool.d.ts +55 -0
  91. package/dist/core/tool.d.ts.map +1 -1
  92. package/dist/core/tool.js +16 -0
  93. package/dist/core/tool.js.map +1 -1
  94. package/dist/core/usage.d.ts +27 -0
  95. package/dist/core/usage.d.ts.map +1 -0
  96. package/dist/core/usage.js +67 -0
  97. package/dist/core/usage.js.map +1 -0
  98. package/dist/index.d.ts +7 -0
  99. package/dist/index.d.ts.map +1 -1
  100. package/dist/index.js +7 -0
  101. package/dist/index.js.map +1 -1
  102. package/dist/protocol/answers.d.ts +33 -0
  103. package/dist/protocol/answers.d.ts.map +1 -0
  104. package/dist/protocol/answers.js +86 -0
  105. package/dist/protocol/answers.js.map +1 -0
  106. package/dist/protocol/commands.d.ts +84 -0
  107. package/dist/protocol/commands.d.ts.map +1 -0
  108. package/dist/protocol/commands.js +232 -0
  109. package/dist/protocol/commands.js.map +1 -0
  110. package/dist/protocol/events.d.ts +145 -0
  111. package/dist/protocol/events.d.ts.map +1 -0
  112. package/dist/protocol/events.js +195 -0
  113. package/dist/protocol/events.js.map +1 -0
  114. package/dist/protocol/frames.d.ts +72 -0
  115. package/dist/protocol/frames.d.ts.map +1 -0
  116. package/dist/protocol/frames.js +134 -0
  117. package/dist/protocol/frames.js.map +1 -0
  118. package/dist/protocol/http.d.ts +52 -0
  119. package/dist/protocol/http.d.ts.map +1 -0
  120. package/dist/protocol/http.js +357 -0
  121. package/dist/protocol/http.js.map +1 -0
  122. package/dist/protocol/reader.d.ts +35 -0
  123. package/dist/protocol/reader.d.ts.map +1 -0
  124. package/dist/protocol/reader.js +71 -0
  125. package/dist/protocol/reader.js.map +1 -0
  126. package/dist/protocol/session.d.ts +85 -0
  127. package/dist/protocol/session.d.ts.map +1 -0
  128. package/dist/protocol/session.js +801 -0
  129. package/dist/protocol/session.js.map +1 -0
  130. package/dist/record/entries.d.ts +110 -2
  131. package/dist/record/entries.d.ts.map +1 -1
  132. package/dist/record/entries.js +337 -10
  133. package/dist/record/entries.js.map +1 -1
  134. package/dist/record/replay.d.ts +6 -0
  135. package/dist/record/replay.d.ts.map +1 -1
  136. package/dist/record/replay.js +11 -3
  137. package/dist/record/replay.js.map +1 -1
  138. package/dist/record/truncate.d.ts +12 -0
  139. package/dist/record/truncate.d.ts.map +1 -1
  140. package/dist/record/truncate.js +72 -1
  141. package/dist/record/truncate.js.map +1 -1
  142. package/dist/testkit/cassette.d.ts +91 -0
  143. package/dist/testkit/cassette.d.ts.map +1 -0
  144. package/dist/testkit/cassette.js +250 -0
  145. package/dist/testkit/cassette.js.map +1 -0
  146. package/dist/testkit/fake-model-server.d.ts +104 -0
  147. package/dist/testkit/fake-model-server.d.ts.map +1 -0
  148. package/dist/testkit/fake-model-server.js +251 -0
  149. package/dist/testkit/fake-model-server.js.map +1 -0
  150. package/dist/testkit/index.d.ts +5 -2
  151. package/dist/testkit/index.d.ts.map +1 -1
  152. package/dist/testkit/index.js +5 -2
  153. package/dist/testkit/index.js.map +1 -1
  154. package/dist/testkit/misbehaving-model.d.ts +40 -0
  155. package/dist/testkit/misbehaving-model.d.ts.map +1 -0
  156. package/dist/testkit/misbehaving-model.js +134 -0
  157. package/dist/testkit/misbehaving-model.js.map +1 -0
  158. package/dist/testkit/model.d.ts +20 -0
  159. package/dist/testkit/model.d.ts.map +1 -1
  160. package/dist/testkit/model.js +50 -3
  161. package/dist/testkit/model.js.map +1 -1
  162. package/dist/testkit/scenario.d.ts +36 -2
  163. package/dist/testkit/scenario.d.ts.map +1 -1
  164. package/dist/testkit/scenario.js +98 -13
  165. package/dist/testkit/scenario.js.map +1 -1
  166. package/dist/testkit/timeline-recipe.d.ts.map +1 -1
  167. package/dist/testkit/timeline-recipe.js +3 -0
  168. package/dist/testkit/timeline-recipe.js.map +1 -1
  169. package/dist/testkit/tools.d.ts +15 -1
  170. package/dist/testkit/tools.d.ts.map +1 -1
  171. package/dist/testkit/tools.js +19 -0
  172. package/dist/testkit/tools.js.map +1 -1
  173. package/package.json +5 -1
@@ -0,0 +1 @@
1
+ {"version":3,"file":"request.js","sourceRoot":"","sources":["../../../src/adapters/openai/request.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;GAcG;AAcH,SAAS,WAAW,CAAC,OAA4B;IAChD,QAAQ,OAAO,CAAC,IAAI,EAAE,CAAC;QACtB,KAAK,MAAM;YACV,OAAO,EAAE,IAAI,EAAE,MAAM,EAAE,OAAO,EAAE,OAAO,CAAC,IAAI,EAAE,CAAC;QAChD,KAAK,WAAW;YACf,2EAA2E;YAC3E,6EAA6E;YAC7E,yDAAyD;YACzD,IAAI,OAAO,CAAC,SAAS,CAAC,MAAM,KAAK,CAAC,EAAE,CAAC;gBACpC,OAAO,EAAE,IAAI,EAAE,WAAW,EAAE,OAAO,EAAE,OAAO,CAAC,IAAI,EAAE,CAAC;YACrD,CAAC;YACD,OAAO;gBACN,IAAI,EAAE,WAAW;gBACjB,OAAO,EAAE,OAAO,CAAC,IAAI;gBACrB,UAAU,EAAE,OAAO,CAAC,SAAS,CAAC,GAAG,CAAC,CAAC,IAAI,EAAE,EAAE,CAAC,CAAC;oBAC5C,EAAE,EAAE,IAAI,CAAC,EAAE;oBACX,IAAI,EAAE,UAAU;oBAChB,QAAQ,EAAE,EAAE,IAAI,EAAE,IAAI,CAAC,IAAI,EAAE,SAAS,EAAE,IAAI,CAAC,SAAS,EAAE;iBACxD,CAAC,CAAC;aACH,CAAC;QACH,KAAK,MAAM;YACV,2EAA2E;YAC3E,kEAAkE;YAClE,OAAO,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AmF;IACnF,iFAAiF;IACjF,KAAK,MAAM,CAAC,IAAI,EAAE,KAAK,CAAC,IAAI,MAAM,CAAC,OAAO,CAAC,OAAO,CAAC,KAAK,IAAI,EAAE,CAAC,EAAE,CAAC;QACjE,OAAO,CAAC,IAAI,CAAC,WAAW,EAAE,CAAC,GAAG,KAAK,CAAC;IACrC,CAAC;IACD,OAAO,CAAC,cAAc,CAAC,GAAG,kBAAkB,CAAC;IAC7C,OAAO,CAAC,QAAQ,CAAC,GAAG,mBAAmB,CAAC;IACxC,OAAO,CAAC,eAAe,CAAC,GAAG,UAAU,OAAO,CAAC,MAAM,EAAE,CAAC;IACtD,IAAI,OAAO,CAAC,OAAO,KAAK,SAAS,EAAE,CAAC;QACnC,OAAO,CAAC,oBAAoB,CAAC,GAAG,OAAO,CAAC,OAAO,CAAC;IACjD,CAAC;IACD,OAAO,OAAO,CAAC;AAChB,CAAC"}
@@ -0,0 +1,44 @@
1
+ /**
2
+ * The server-sent-event parser for chat completions (docs/adapters.md, OAI01 to
3
+ * OAI13).
4
+ *
5
+ * A model reply arrives as a stream of `data:` events, each holding one JSON
6
+ * chunk. This file turns that stream into one `ModelReply` without touching the
7
+ * network or the clock, so all of it is testable as a pure function, and the
8
+ * assembled reply goes through the core's `decodeReply` before it leaves. What
9
+ * comes out is a reply the loop already trusts.
10
+ *
11
+ * It is written to be tolerant of everything a provider may leave out and strict
12
+ * about anything that would make the reply a lie: a stream with no ending is an
13
+ * error rather than a short reply, two calls cannot share an id, and a stream
14
+ * that grows past the cap stops being assembled instead of being kept in memory.
15
+ */
16
+ import type { ModelError, ModelReply } from "../../core/model.js";
17
+ import { type Result } from "../../core/result.js";
18
+ /** One assembled reply is capped at 1 MiB, the same as a record entry (decision 90). */
19
+ export declare const DEFAULT_STREAM_CAP_BYTES = 1048576;
20
+ export interface SseOptions {
21
+ /** How many bytes of stream to accept before giving up. */
22
+ maxBytes?: number;
23
+ }
24
+ export interface SseReader {
25
+ /**
26
+ * Feed the next piece of decoded text. A reply means the stream ended, an error
27
+ * means it cannot be assembled; `undefined` means keep reading.
28
+ */
29
+ push(text: string): Result<ModelReply | undefined, ModelError>;
30
+ /** Finish the stream, which fails unless a finish reason or `[DONE]` arrived. */
31
+ end(): Result<ModelReply, ModelError>;
32
+ }
33
+ export declare function sseReader(options?: SseOptions): SseReader;
34
+ export interface ReadReplyOptions extends SseOptions {
35
+ /** The caller's signal, so a stop that arrives mid-read is not read as a network fault. */
36
+ signal?: AbortSignal;
37
+ }
38
+ /**
39
+ * Read a body to one reply, decoding bytes as they arrive. The stream is always
40
+ * closed when this returns, whether it ended, failed or was refused, so a
41
+ * provider is never left sending into a reader nobody holds.
42
+ */
43
+ export declare function readReply(body: ReadableStream<Uint8Array> | null, options?: ReadReplyOptions): Promise<Result<ModelReply, ModelError>>;
44
+ //# sourceMappingURL=sse.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"sse.d.ts","sourceRoot":"","sources":["../../../src/adapters/openai/sse.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;GAcG;AAIH,OAAO,KAAK,EAAE,UAAU,EAAE,UAAU,EAAmB,MAAM,qBAAqB,CAAC;AACnF,OAAO,EAAM,KAAK,MAAM,EAAE,MAAM,sBAAsB,CAAC;AAGvD,wFAAwF;AACxF,eAAO,MAAM,wBAAwB,UAAY,CAAC;AAOlD,MAAM,WAAW,UAAU;IAC1B,2DAA2D;IAC3D,QAAQ,CAAC,EAAE,MAAM,CAAC;CAClB;AAED,MAAM,WAAW,SAAS;IACzB;;;OAGG;IACH,IAAI,CAAC,IAAI,EAAE,MAAM,GAAG,MAAM,CAAC,UAAU,GAAG,SAAS,EAAE,UAAU,CAAC,CAAC;IAC/D,iFAAiF;IACjF,GAAG,IAAI,MAAM,CAAC,UAAU,EAAE,UAAU,CAAC,CAAC;CACtC;AAkDD,wBAAgB,SAAS,CAAC,OAAO,GAAE,UAAe,GAAG,SAAS,CA8T7D;AAED,MAAM,WAAW,gBAAiB,SAAQ,UAAU;IACnD,2FAA2F;IAC3F,MAAM,CAAC,EAAE,WAAW,CAAC;CACrB;AAqBD;;;;GAIG;AACH,wBAAsB,SAAS,CAC9B,IAAI,EAAE,cAAc,CAAC,UAAU,CAAC,GAAG,IAAI,EACvC,OAAO,GAAE,gBAAqB,GAC5B,OAAO,CAAC,MAAM,CAAC,UAAU,EAAE,UAAU,CAAC,CAAC,CAoDzC"}
@@ -0,0 +1,410 @@
1
+ /**
2
+ * The server-sent-event parser for chat completions (docs/adapters.md, OAI01 to
3
+ * OAI13).
4
+ *
5
+ * A model reply arrives as a stream of `data:` events, each holding one JSON
6
+ * chunk. This file turns that stream into one `ModelReply` without touching the
7
+ * network or the clock, so all of it is testable as a pure function, and the
8
+ * assembled reply goes through the core's `decodeReply` before it leaves. What
9
+ * comes out is a reply the loop already trusts.
10
+ *
11
+ * It is written to be tolerant of everything a provider may leave out and strict
12
+ * about anything that would make the reply a lie: a stream with no ending is an
13
+ * error rather than a short reply, two calls cannot share an id, and a stream
14
+ * that grows past the cap stops being assembled instead of being kept in memory.
15
+ */
16
+ import { decodeFinishReason, decodeReply } from "../../core/decode-reply.js";
17
+ import { isPlainObject } from "../../core/json.js";
18
+ import { ok } from "../../core/result.js";
19
+ import { utf8Length } from "../../record/truncate.js";
20
+ /** One assembled reply is capped at 1 MiB, the same as a record entry (decision 90). */
21
+ export const DEFAULT_STREAM_CAP_BYTES = 1_048_576;
22
+ const DONE_MARKER = "[DONE]";
23
+ /** Statuses where trying again cannot help, so an in-stream error is not retried. */
24
+ const PERMANENT_STATUSES = new Set([400, 401, 403, 404, 422]);
25
+ function providerError(message, retryable = true) {
26
+ return { code: "provider_error", message, retryable };
27
+ }
28
+ /** A token count, or nothing when the provider did not send one. */
29
+ function tokenCount(value) {
30
+ return typeof value === "number" && Number.isSafeInteger(value) && value >= 0
31
+ ? value
32
+ : undefined;
33
+ }
34
+ /** A cost in credits, which OpenRouter reports in dollars. */
35
+ function costAmount(value) {
36
+ return typeof value === "number" && Number.isFinite(value) && value >= 0 ? value : undefined;
37
+ }
38
+ function truncate(text) {
39
+ return text.length > 300 ? `${text.slice(0, 300)}…` : text;
40
+ }
41
+ /** The next complete line, and how many characters it took, including its ending. */
42
+ function nextLine(text, atEnd) {
43
+ for (let index = 0; index < text.length; index += 1) {
44
+ const character = text[index];
45
+ if (character === "\n") {
46
+ return { line: text.slice(0, index), length: index + 1 };
47
+ }
48
+ if (character === "\r") {
49
+ // A carriage return at the very end of one chunk may be the first half of
50
+ // a CRLF that arrives in the next, so it waits unless the stream is over.
51
+ if (index + 1 < text.length) {
52
+ const width = text[index + 1] === "\n" ? 2 : 1;
53
+ return { line: text.slice(0, index), length: index + width };
54
+ }
55
+ return atEnd ? { line: text.slice(0, index), length: index + 1 } : undefined;
56
+ }
57
+ }
58
+ return undefined;
59
+ }
60
+ export function sseReader(options = {}) {
61
+ const maxBytes = options.maxBytes ?? DEFAULT_STREAM_CAP_BYTES;
62
+ let buffer = "";
63
+ /** The `data:` lines of the event being read. */
64
+ let dataLines = [];
65
+ let bytes = 0;
66
+ let text = "";
67
+ let reasoning = "";
68
+ const calls = new Map();
69
+ let inputTokens;
70
+ let outputTokens;
71
+ let cost;
72
+ let finish;
73
+ let model = "";
74
+ let outcome;
75
+ const asPushResult = (settled) => "reply" in settled ? ok(settled.reply) : { ok: false, error: settled.error };
76
+ const asEndResult = (settled) => "reply" in settled ? ok(settled.reply) : { ok: false, error: settled.error };
77
+ const settleError = (error) => {
78
+ const settled = { error };
79
+ outcome = settled;
80
+ return settled;
81
+ };
82
+ /** The reply, once it is complete. Everything it claims is checked by the core's decoder. */
83
+ const buildReply = () => {
84
+ const ordered = [...calls.entries()].sort(([left], [right]) => left - right);
85
+ // Ids must be unique within a reply, because the loop pairs a result to its
86
+ // call by id. An id a provider sent for exactly one call is reserved for it,
87
+ // so a synthetic id never takes a real one's place.
88
+ const counts = new Map();
89
+ for (const [, state] of ordered) {
90
+ if (state.id !== undefined && state.id !== "") {
91
+ counts.set(state.id, (counts.get(state.id) ?? 0) + 1);
92
+ }
93
+ }
94
+ const reserved = new Set([...counts.entries()].filter(([, count]) => count === 1).map(([id]) => id));
95
+ const used = new Set();
96
+ const toolCalls = ordered.map(([, state], position) => {
97
+ const preferred = state.id ?? "";
98
+ let id = preferred;
99
+ // A call with no id, or one repeating an id already taken, gets one from its
100
+ // position, which is stable for a resume. A repeat keeps the first call's.
101
+ if (id === "" || used.has(id)) {
102
+ id = `call_${position + 1}`;
103
+ while (used.has(id) || reserved.has(id)) {
104
+ id = `${id}_`;
105
+ }
106
+ }
107
+ used.add(id);
108
+ return { id, name: state.name, arguments: state.arguments };
109
+ });
110
+ const usage = { inputTokens: inputTokens ?? 0, outputTokens: outputTokens ?? 0 };
111
+ if (cost !== undefined) {
112
+ usage.cost = { amount: cost, currency: "USD", source: "provider" };
113
+ }
114
+ const reply = {
115
+ text,
116
+ toolCalls,
117
+ usage,
118
+ finishReason: decodeFinishReason(finish),
119
+ model,
120
+ };
121
+ if (reasoning !== "") {
122
+ reply.reasoning = reasoning;
123
+ }
124
+ return reply;
125
+ };
126
+ const settleReply = () => {
127
+ const decoded = decodeReply(buildReply());
128
+ if (!decoded.ok) {
129
+ // The assembled reply is not one the loop could act on. Trying again with
130
+ // the same model would send the same broken thing, so this is not retryable.
131
+ return settleError({
132
+ code: "provider_error",
133
+ message: decoded.error.message,
134
+ retryable: false,
135
+ });
136
+ }
137
+ const settled = { reply: decoded.value };
138
+ outcome = settled;
139
+ return settled;
140
+ };
141
+ const applyDelta = (delta) => {
142
+ const content = delta["content"];
143
+ if (typeof content === "string" && content !== "") {
144
+ text += content;
145
+ }
146
+ // OpenRouter calls it `reasoning`; other OpenAI-style endpoints use `reasoning_content`.
147
+ const reasoningPiece = delta["reasoning"] ?? delta["reasoning_content"];
148
+ if (typeof reasoningPiece === "string" && reasoningPiece !== "") {
149
+ reasoning += reasoningPiece;
150
+ }
151
+ const rawCalls = delta["tool_calls"];
152
+ if (rawCalls === undefined) {
153
+ return undefined;
154
+ }
155
+ if (!Array.isArray(rawCalls)) {
156
+ return providerError("the model's stream sent tool_calls that are not a list");
157
+ }
158
+ for (const [position, rawCall] of rawCalls.entries()) {
159
+ if (!isPlainObject(rawCall)) {
160
+ return providerError("the model's stream sent a tool call that is not an object");
161
+ }
162
+ const rawIndex = rawCall["index"];
163
+ const index = typeof rawIndex === "number" && Number.isSafeInteger(rawIndex) && rawIndex >= 0
164
+ ? rawIndex
165
+ : position;
166
+ const state = calls.get(index) ?? { name: "", arguments: "" };
167
+ const id = rawCall["id"];
168
+ if (typeof id === "string" && id !== "") {
169
+ state.id = id;
170
+ }
171
+ const name = rawCall["function"];
172
+ if (isPlainObject(name)) {
173
+ // The name arrives once; the arguments arrive in as many pieces as the
174
+ // provider likes, and their exact text is what the model meant to send.
175
+ const rawName = name["name"];
176
+ if (typeof rawName === "string" && rawName !== "" && state.name === "") {
177
+ state.name = rawName;
178
+ }
179
+ const rawArguments = name["arguments"];
180
+ if (typeof rawArguments === "string") {
181
+ state.arguments += rawArguments;
182
+ }
183
+ }
184
+ calls.set(index, state);
185
+ }
186
+ return undefined;
187
+ };
188
+ const applyUsage = (rawUsage) => {
189
+ const prompt = tokenCount(rawUsage["prompt_tokens"]);
190
+ if (prompt !== undefined) {
191
+ inputTokens = prompt;
192
+ }
193
+ const completion = tokenCount(rawUsage["completion_tokens"]);
194
+ if (completion !== undefined) {
195
+ outputTokens = completion;
196
+ }
197
+ const reported = costAmount(rawUsage["cost"]);
198
+ if (reported !== undefined) {
199
+ cost = reported;
200
+ }
201
+ };
202
+ const handlePayload = (payload) => {
203
+ if (payload.trim() === DONE_MARKER) {
204
+ // `[DONE]` is the provider saying the stream is over, so it is an ending in
205
+ // its own right: a compatible endpoint may send it without a finish reason,
206
+ // and the core already turns a reason it does not model into `other`.
207
+ settleReply();
208
+ return;
209
+ }
210
+ let parsed;
211
+ try {
212
+ parsed = JSON.parse(payload);
213
+ }
214
+ catch {
215
+ settleError(providerError("the model's stream sent a chunk that is not JSON"));
216
+ return;
217
+ }
218
+ if (!isPlainObject(parsed)) {
219
+ settleError(providerError("the model's stream sent a chunk that is not an object"));
220
+ return;
221
+ }
222
+ // A provider that fails in the middle of a stream sends the failure as a
223
+ // chunk with an HTTP status inside it, because the status line already went.
224
+ const rawError = parsed["error"];
225
+ if (isPlainObject(rawError)) {
226
+ const status = typeof rawError["code"] === "number" ? rawError["code"] : 0;
227
+ const message = typeof rawError["message"] === "string"
228
+ ? rawError["message"]
229
+ : "the model's provider reported an error";
230
+ settleError({
231
+ code: "provider_error",
232
+ message: truncate(message),
233
+ retryable: !PERMANENT_STATUSES.has(status),
234
+ });
235
+ return;
236
+ }
237
+ const rawModel = parsed["model"];
238
+ if (typeof rawModel === "string") {
239
+ model = rawModel;
240
+ }
241
+ const rawUsage = parsed["usage"];
242
+ if (isPlainObject(rawUsage)) {
243
+ applyUsage(rawUsage);
244
+ }
245
+ const choices = parsed["choices"];
246
+ if (choices === undefined) {
247
+ return;
248
+ }
249
+ if (!Array.isArray(choices)) {
250
+ settleError(providerError("the model's stream sent choices that are not a list"));
251
+ return;
252
+ }
253
+ for (const choice of choices) {
254
+ if (!isPlainObject(choice)) {
255
+ settleError(providerError("the model's stream sent a choice that is not an object"));
256
+ return;
257
+ }
258
+ // One completion was asked for, so a choice for another index says nothing.
259
+ const index = choice["index"];
260
+ if (typeof index === "number" && index !== 0) {
261
+ continue;
262
+ }
263
+ const rawFinish = choice["finish_reason"];
264
+ if (typeof rawFinish === "string" && rawFinish !== "" && rawFinish !== "error") {
265
+ finish = rawFinish;
266
+ }
267
+ const delta = choice["delta"];
268
+ if (isPlainObject(delta)) {
269
+ const problem = applyDelta(delta);
270
+ if (problem !== undefined) {
271
+ settleError(problem);
272
+ return;
273
+ }
274
+ }
275
+ }
276
+ };
277
+ const handleLine = (line) => {
278
+ if (line === "") {
279
+ // A blank line is the end of the event, which is where its data is read.
280
+ if (dataLines.length === 0) {
281
+ return;
282
+ }
283
+ const payload = dataLines.join("\n");
284
+ dataLines = [];
285
+ handlePayload(payload);
286
+ return;
287
+ }
288
+ if (line.startsWith(":")) {
289
+ // A comment, which OpenRouter sends as a keep-alive.
290
+ return;
291
+ }
292
+ const colon = line.indexOf(":");
293
+ const field = colon === -1 ? line : line.slice(0, colon);
294
+ if (field === "data") {
295
+ const value = colon === -1 ? "" : line.slice(colon + 1);
296
+ dataLines.push(value.startsWith(" ") ? value.slice(1) : value);
297
+ }
298
+ // `event:`, `id:` and `retry:` carry nothing a chat completion needs.
299
+ };
300
+ return {
301
+ push(chunk) {
302
+ if (outcome !== undefined) {
303
+ return asPushResult(outcome);
304
+ }
305
+ bytes += utf8Length(chunk);
306
+ if (bytes > maxBytes) {
307
+ return asPushResult(settleError(providerError(`the model's stream passed ${maxBytes} bytes, so it was given up on`, false)));
308
+ }
309
+ buffer += chunk;
310
+ for (;;) {
311
+ const found = nextLine(buffer, false);
312
+ if (found === undefined) {
313
+ return ok(undefined);
314
+ }
315
+ buffer = buffer.slice(found.length);
316
+ handleLine(found.line);
317
+ if (outcome !== undefined) {
318
+ return asPushResult(outcome);
319
+ }
320
+ }
321
+ },
322
+ end() {
323
+ if (outcome !== undefined) {
324
+ return asEndResult(outcome);
325
+ }
326
+ if (buffer.trim() !== "" || dataLines.length > 0) {
327
+ return asEndResult(settleError(providerError("the model's stream ended in the middle of an event")));
328
+ }
329
+ if (finish === undefined) {
330
+ return asEndResult(settleError(providerError("the model's stream ended without a finish reason")));
331
+ }
332
+ return asEndResult(settleReply());
333
+ },
334
+ };
335
+ }
336
+ /** A promise that rejects the moment a stop is signalled, so a read cannot hang through one. */
337
+ function abortPromise(signal) {
338
+ return new Promise((_, reject) => {
339
+ const stop = () => reject(providerError("the model's reply stopped", false));
340
+ if (signal.aborted) {
341
+ stop();
342
+ return;
343
+ }
344
+ signal.addEventListener("abort", stop, { once: true });
345
+ });
346
+ }
347
+ function reasonOf(error) {
348
+ if (error instanceof Error) {
349
+ return error.message;
350
+ }
351
+ return String(error);
352
+ }
353
+ /**
354
+ * Read a body to one reply, decoding bytes as they arrive. The stream is always
355
+ * closed when this returns, whether it ended, failed or was refused, so a
356
+ * provider is never left sending into a reader nobody holds.
357
+ */
358
+ export async function readReply(body, options = {}) {
359
+ if (body === null) {
360
+ return { ok: false, error: providerError("the model's response had no body") };
361
+ }
362
+ const stream = body.getReader();
363
+ const decoder = new TextDecoder();
364
+ const reader = sseReader(options);
365
+ const stop = options.signal === undefined ? undefined : abortPromise(options.signal);
366
+ const push = (text) => {
367
+ const pushed = reader.push(text);
368
+ if (!pushed.ok) {
369
+ return pushed;
370
+ }
371
+ return pushed.value === undefined ? undefined : ok(pushed.value);
372
+ };
373
+ try {
374
+ for (;;) {
375
+ const read = stop === undefined
376
+ ? await stream.read()
377
+ : await Promise.race([stream.read(), stop]);
378
+ if (read.done) {
379
+ break;
380
+ }
381
+ if (read.value === undefined) {
382
+ continue;
383
+ }
384
+ const settled = push(decoder.decode(read.value, { stream: true }));
385
+ if (settled !== undefined) {
386
+ return settled;
387
+ }
388
+ }
389
+ const tail = decoder.decode();
390
+ if (tail !== "") {
391
+ const settled = push(tail);
392
+ if (settled !== undefined) {
393
+ return settled;
394
+ }
395
+ }
396
+ return reader.end();
397
+ }
398
+ catch (error) {
399
+ return {
400
+ ok: false,
401
+ error: providerError(`the model's reply stopped: ${reasonOf(error)}`),
402
+ };
403
+ }
404
+ finally {
405
+ // Closing a stream that already ended is harmless, and it releases one that
406
+ // was given up on early.
407
+ void stream.cancel().catch(() => undefined);
408
+ }
409
+ }
410
+ //# sourceMappingURL=sse.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"sse.js","sourceRoot":"","sources":["../../../src/adapters/openai/sse.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;GAcG;AAEH,OAAO,EAAE,kBAAkB,EAAE,WAAW,EAAE,MAAM,4BAA4B,CAAC;AAC7E,OAAO,EAAE,aAAa,EAAE,MAAM,oBAAoB,CAAC;AAEnD,OAAO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AAa,CAAC,8BAA8B,QAAQ,CAAC,KAAK,CAAC,EAAE,CAAC;SACrE,CAAC;IACH,CAAC;YAAS,CAAC;QACV,4EAA4E;QAC5E,yBAAyB;QACzB,KAAK,MAAM,CAAC,MAAM,EAAE,CAAC,KAAK,CAAC,GAAG,EAAE,CAAC,SAAS,CAAC,CAAC;IAC7C,CAAC;AACF,CAAC"}
@@ -0,0 +1,38 @@
1
+ /**
2
+ * What a tool may do without a person, and how a run asks (docs/approvals.md,
3
+ * decisions 34, 35 and 85).
4
+ *
5
+ * One mechanism covers both an approval of a risky call and a question only a
6
+ * person can answer: the run saves a request in the record and parks, and the
7
+ * answer decides what happens next. This module is the part that is a pure
8
+ * decision — which policy governs one call — so the loop and the tests agree on
9
+ * one rule rather than each reading the fields for itself.
10
+ */
11
+ import type { Tool, ToolOutcome } from "./tool.js";
12
+ /** The three answers a recipe can give for a call (decision 35). */
13
+ export type ToolPolicy = "allow" | "ask" | "deny";
14
+ /** What a tool does to the world, which sets its default policy (decision 35). */
15
+ export type ToolRisk = "reads" | "changes" | "dangerous";
16
+ export declare const TOOL_POLICIES: readonly ToolPolicy[];
17
+ export declare const TOOL_RISKS: readonly ToolRisk[];
18
+ export declare function isToolPolicy(value: unknown): value is ToolPolicy;
19
+ export declare function isToolRisk(value: unknown): value is ToolRisk;
20
+ /** How a risk label shapes the default: a change or a danger asks, a read does not. */
21
+ export declare function policyFromRisk(risk: ToolRisk | undefined): ToolPolicy | undefined;
22
+ /**
23
+ * The policy that governs one call.
24
+ *
25
+ * The tool's own word wins, then its risk label, then the recipe's default, and a
26
+ * tool that says nothing is allowed. That last rule is deliberate: every tool built
27
+ * before this slice is silent, and silence meaning "ask" would stop every existing
28
+ * recipe at its first call. A caller who wants asking says so (decision 135's
29
+ * sibling, recorded with this slice).
30
+ */
31
+ export declare function policyOf(tool: Tool, recipeDefault: ToolPolicy | undefined): ToolPolicy;
32
+ /** What the model reads when a call was not run, and why. */
33
+ export declare function deniedOutcome(reason: string): ToolOutcome;
34
+ /** The reason a denied call gives, which names the tool so a model can adapt. */
35
+ export declare function deniedByRecipe(tool: Tool): string;
36
+ /** The reason a call that needed a person gives when there is nobody to ask. */
37
+ export declare function deniedWithoutAPerson(tool: Tool): string;
38
+ //# sourceMappingURL=approval.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"approval.d.ts","sourceRoot":"","sources":["../../src/core/approval.ts"],"names":[],"mappings":"AAAA;;;;;;;;;GASG;AAEH,OAAO,KAAK,EAAE,IAAI,EAAE,WAAW,EAAE,MAAM,WAAW,CAAC;AAEnD,oEAAoE;AACpE,MAAM,MAAM,UAAU,GAAG,OAAO,GAAG,KAAK,GAAG,MAAM,CAAC;AAElD,kFAAkF;AAClF,MAAM,MAAM,QAAQ,GAAG,OAAO,GAAG,SAAS,GAAG,WAAW,CAAC;AAEzD,eAAO,MAAM,aAAa,EAAE,SAAS,UAAU,EAA6B,CAAC;AAC7E,eAAO,MAAM,UAAU,EAAE,SAAS,QAAQ,EAAsC,CAAC;AAEjF,wBAAgB,YAAY,CAAC,KAAK,EAAE,OAAO,GAAG,KAAK,IAAI,UAAU,CAEhE;AAED,wBAAgB,UAAU,CAAC,KAAK,EAAE,OAAO,GAAG,KAAK,IAAI,QAAQ,CAE5D;AAED,uFAAuF;AACvF,wBAAgB,cAAc,CAAC,IAAI,EAAE,QAAQ,GAAG,SAAS,GAAG,UAAU,GAAG,SAAS,CAEjF;AAED;;;;;;;;GAQG;AACH,wBAAgB,QAAQ,CAAC,IAAI,EAAE,IAAI,EAAE,aAAa,EAAE,UAAU,GAAG,SAAS,GAAG,UAAU,CAEtF;AAED,6DAA6D;AAC7D,wBAAgB,aAAa,CAAC,MAAM,EAAE,MAAM,GAAG,WAAW,CAEzD;AAED,iFAAiF;AACjF,wBAAgB,cAAc,CAAC,IAAI,EAAE,IAAI,GAAG,MAAM,CAEjD;AAED,gFAAgF;AAChF,wBAAgB,oBAAoB,CAAC,IAAI,EAAE,IAAI,GAAG,MAAM,CAEvD"}
@@ -0,0 +1,47 @@
1
+ /**
2
+ * What a tool may do without a person, and how a run asks (docs/approvals.md,
3
+ * decisions 34, 35 and 85).
4
+ *
5
+ * One mechanism covers both an approval of a risky call and a question only a
6
+ * person can answer: the run saves a request in the record and parks, and the
7
+ * answer decides what happens next. This module is the part that is a pure
8
+ * decision — which policy governs one call — so the loop and the tests agree on
9
+ * one rule rather than each reading the fields for itself.
10
+ */
11
+ export const TOOL_POLICIES = ["allow", "ask", "deny"];
12
+ export const TOOL_RISKS = ["reads", "changes", "dangerous"];
13
+ export function isToolPolicy(value) {
14
+ return TOOL_POLICIES.some((known) => known === value);
15
+ }
16
+ export function isToolRisk(value) {
17
+ return TOOL_RISKS.some((known) => known === value);
18
+ }
19
+ /** How a risk label shapes the default: a change or a danger asks, a read does not. */
20
+ export function policyFromRisk(risk) {
21
+ return risk === "changes" || risk === "dangerous" ? "ask" : undefined;
22
+ }
23
+ /**
24
+ * The policy that governs one call.
25
+ *
26
+ * The tool's own word wins, then its risk label, then the recipe's default, and a
27
+ * tool that says nothing is allowed. That last rule is deliberate: every tool built
28
+ * before this slice is silent, and silence meaning "ask" would stop every existing
29
+ * recipe at its first call. A caller who wants asking says so (decision 135's
30
+ * sibling, recorded with this slice).
31
+ */
32
+ export function policyOf(tool, recipeDefault) {
33
+ return tool.policy ?? policyFromRisk(tool.risk) ?? recipeDefault ?? "allow";
34
+ }
35
+ /** What the model reads when a call was not run, and why. */
36
+ export function deniedOutcome(reason) {
37
+ return { isError: true, content: `this call was denied and did not run: ${reason}` };
38
+ }
39
+ /** The reason a denied call gives, which names the tool so a model can adapt. */
40
+ export function deniedByRecipe(tool) {
41
+ return `the recipe does not allow the ${tool.spec.name} tool, so nothing ran`;
42
+ }
43
+ /** The reason a call that needed a person gives when there is nobody to ask. */
44
+ export function deniedWithoutAPerson(tool) {
45
+ return `the ${tool.spec.name} tool needs a person's approval and nothing can deliver the question, so nothing ran`;
46
+ }
47
+ //# sourceMappingURL=appro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