fwdloop 0.6.0 → 0.8.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/provider.js CHANGED
@@ -17,53 +17,36 @@
17
17
  // against src/'s ESM style; src never imports from poc/.
18
18
 
19
19
  import {
20
- appendFileSync, existsSync, mkdirSync, readFileSync,
20
+ appendFileSync, mkdirSync,
21
21
  } from 'node:fs';
22
- import { dirname } from 'node:path';
22
+ import { dirname, basename } from 'node:path';
23
+ import { readFileInside } from './flow.js';
23
24
  import { OpenAI } from 'bare-agent/providers';
24
25
 
25
26
  /**
26
- * F28 (2026-09-15): DeepSeek sometimes emits a tool-call whose
27
- * `function.arguments` is not valid JSON. bare-agent's own `generate()`
28
- * parses it unconditionally and throws a bare `SyntaxError` AFTER the HTTP
29
- * round already succeeded (`data.usage` is known) — the right class for
30
- * this is "no usable tool call" (metered, retried once, then red), never a
31
- * transport fault. This wrapper stashes the last HTTP response and, on a
32
- * `SyntaxError` whose response DID carry a tool call, returns a normal
33
- * `generate()`-shaped result with `toolCalls: []` and a `malformedToolCall`
34
- * extra field instead of throwing. Any other error rethrows unchanged.
27
+ * F28 (2026-09-15) / BA-27 (bare-agent >=0.47.0): DeepSeek sometimes emits a
28
+ * tool-call whose `function.arguments` is not valid JSON. Before 0.47,
29
+ * bare-agent's own `generate()` threw a bare `SyntaxError` AFTER the HTTP
30
+ * round already succeeded — losing the billed round and hanging metering.
31
+ * As of 0.47, `OpenAI.generate()` (bare-agent/src/provider-openai.js, via
32
+ * `provider-toolcalls.js`'s `parseToolCalls`) no longer throws: it resolves
33
+ * normally with `toolCalls: []` and a `malformedToolCall: { name, error }`
34
+ * field already on the result. As of 0.48 the constructor option
35
+ * `exposeMalformedArgs: true` (set in `makeProvider`) adds `rawArguments`
36
+ * (capped upstream at 500 chars, `rawTruncated: true` when clipped). `Loop.run()` does not forward unknown
37
+ * `generate()` fields into its own return, so this wrapper ALSO stashes the
38
+ * marker on the instance (`this.lastMalformedToolCall`, reset at the top of
39
+ * every `generate()` call) — the one channel `runModelStepOnPrimitives`
40
+ * (same provider reference) can read after `loop.run()` returns. We require
41
+ * bare-agent >=0.47 (package.json `^0.47.0`) and never patch around its
42
+ * private response internals.
35
43
  */
36
44
  class MalformedToolCallTolerantOpenAI extends OpenAI {
37
- async _request(path, body, timeoutMs, deadlineMs) {
38
- const data = await super._request(path, body, timeoutMs, deadlineMs);
39
- this._lastData = data;
40
- return data;
41
- }
42
-
43
45
  async generate(messages, tools = [], options = {}) {
44
46
  this.lastMalformedToolCall = null;
45
- try {
46
- return await super.generate(messages, tools, options);
47
- } catch (err) {
48
- if (!(err instanceof SyntaxError)) throw err;
49
- const msg = this._lastData?.choices?.[0]?.message;
50
- const toolCalls = msg?.tool_calls;
51
- if (!Array.isArray(toolCalls) || toolCalls.length === 0) throw err;
52
- const tc = toolCalls[0];
53
- const rawArguments = typeof tc?.function?.arguments === 'string'
54
- ? tc.function.arguments.slice(0, 500)
55
- : '';
56
- const malformedToolCall = { name: tc?.function?.name ?? null, rawArguments, error: err.message };
57
- this.lastMalformedToolCall = malformedToolCall;
58
- return {
59
- text: msg.content || '',
60
- toolCalls: [],
61
- model: this._lastData.model || this.model,
62
- stopReason: 'tool_use',
63
- usage: this._normalizeUsage(this._lastData.usage),
64
- malformedToolCall,
65
- };
66
- }
47
+ const result = await super.generate(messages, tools, options);
48
+ if (result.malformedToolCall) this.lastMalformedToolCall = result.malformedToolCall;
49
+ return result;
67
50
  }
68
51
  }
69
52
 
@@ -215,9 +198,17 @@ export function appendSpendRow(path, row) {
215
198
  appendFileSync(path, `${JSON.stringify({ ...row, modelMatch })}\n`);
216
199
  }
217
200
 
201
+ // F48 round 3: both readers below take a full path (`<runDir>/spend.jsonl`,
202
+ // as every call site already builds it) but go through `readFileInside`
203
+ // (`src/flow.js`) using `dirname(path)` as the containment boundary and
204
+ // `basename(path)` as the checked relative name — no call site changes, and
205
+ // a symlinked `spend.jsonl` (or a symlinked run-dir ancestor) reads as
206
+ // "missing", never as some outside file's content folded into a cap check
207
+ // or shown on the panel.
218
208
  function readSpendTotal(path) {
219
- if (!existsSync(path)) return 0;
220
- const lines = readFileSync(path, 'utf8').split('\n').filter((l) => l.trim());
209
+ const result = readFileInside(dirname(path), basename(path));
210
+ if (!result.ok) return 0;
211
+ const lines = result.text.split('\n').filter((l) => l.trim());
221
212
  let total = 0;
222
213
  for (const line of lines) {
223
214
  const row = JSON.parse(line);
@@ -226,6 +217,28 @@ function readSpendTotal(path) {
226
217
  return total;
227
218
  }
228
219
 
220
+ /**
221
+ * `appendSpendRow`'s own sibling reader (M4a piece 2, docs/wiki/the-module-
222
+ * ladder.md M4a scope item 2: "one reader per book") — every row as written,
223
+ * raw, in file order. `[]` when the file doesn't exist yet, and a malformed
224
+ * line is skipped rather than thrown on (an honest best-effort read, same
225
+ * posture as `src/books.js`'s readers — a caller that needs to know the row
226
+ * count decides how to treat a gap, this function never crashes over it).
227
+ * @param {string} path
228
+ * @returns {any[]}
229
+ */
230
+ export function readSpendRows(path) {
231
+ const result = readFileInside(dirname(path), basename(path));
232
+ if (!result.ok) return [];
233
+ const rows = [];
234
+ for (const line of result.text.split('\n')) {
235
+ const trimmed = line.trim();
236
+ if (trimmed.length === 0) continue;
237
+ try { rows.push(JSON.parse(trimmed)); } catch { /* malformed line: skip, never crash the read */ }
238
+ }
239
+ return rows;
240
+ }
241
+
229
242
  /** Throws once total spend (every null row repriced at its ceiling) is at
230
243
  * or over `capUsd`. */
231
244
  export function assertUnderGlobalCap(path, capUsd) {
@@ -274,11 +287,12 @@ export function checkKeyPreflight(slotName, env = process.env) {
274
287
  * values this project uses.
275
288
  *
276
289
  * @param {string} slotName
277
- * @param {{ model?: string, timeoutMs?: number, deadlineMs?: number }} [options]
290
+ * @param {{ model?: string, timeoutMs?: number, deadlineMs?: number, thinking?: object|null }} [options]
291
+ * `thinking` (bare-agent >=0.49) is sent verbatim as body.thinking; unset/null leaves the body unchanged.
278
292
  * @returns {{ provider: any, rates: {in:number, out:number}, modelId: string, suffix: string, slot: string }}
279
293
  */
280
294
  export function makeProvider(slotName, options = {}) {
281
- const { model, timeoutMs, deadlineMs } = options;
295
+ const { model, timeoutMs, deadlineMs, thinking } = options;
282
296
  const slot = PROVIDER_SLOTS[slotName];
283
297
  if (!slot) {
284
298
  throw new Error(`unknown provider slot "${slotName}" — known slots: ${Object.keys(PROVIDER_SLOTS).join(', ')}`);
@@ -296,8 +310,12 @@ export function makeProvider(slotName, options = {}) {
296
310
  model: modelId,
297
311
  baseUrl: slot.baseUrl,
298
312
  legacyMaxTokens: slot.legacyMaxTokens === true,
313
+ // bare-agent >=0.48: opt in to the raw broken tool-call arguments on
314
+ // `malformedToolCall` (capped upstream at 500 chars). Not exposeErrorBody.
315
+ exposeMalformedArgs: true,
299
316
  ...(timeoutMs !== undefined ? { timeoutMs } : {}),
300
317
  ...(deadlineMs !== undefined ? { deadlineMs } : {}),
318
+ ...(thinking != null ? { thinking } : {}),
301
319
  });
302
320
 
303
321
  return {