fwdloop 0.15.0 → 0.17.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 (72) hide show
  1. package/README.md +2 -0
  2. package/bin/fwdloop +113 -36
  3. package/package.json +2 -2
  4. package/src/authoring.js +27 -15
  5. package/src/catalogue.json +9 -3
  6. package/src/closers.js +5 -0
  7. package/src/config.js +66 -4
  8. package/src/ctx-tools.js +245 -0
  9. package/src/declaration.js +25 -1
  10. package/src/draft-steps.js +138 -0
  11. package/src/drafter.js +81 -18
  12. package/src/draftspend.js +109 -3
  13. package/src/flowmodel.js +30 -0
  14. package/src/input-facts.js +12 -3
  15. package/src/keysfile.js +51 -16
  16. package/src/liveness.js +34 -10
  17. package/src/model-step.js +13 -11
  18. package/src/monthly.js +9 -1
  19. package/src/panel/author.js +170 -43
  20. package/src/panel/authorcard.js +32 -20
  21. package/src/panel/authorflows.js +34 -19
  22. package/src/panel/authorresume.js +11 -9
  23. package/src/panel/authorstart.js +11 -9
  24. package/src/panel/authorvalues.js +5 -3
  25. package/src/panel/data.js +20 -8
  26. package/src/panel/index.html +584 -182
  27. package/src/panel/resume.js +3 -3
  28. package/src/panel/server.js +12 -6
  29. package/src/panel/settings.js +138 -80
  30. package/src/panel/spawn.js +15 -9
  31. package/src/plain-checks.js +51 -0
  32. package/src/primitives.js +34 -3
  33. package/src/provider.js +148 -181
  34. package/src/providershapes.js +7 -7
  35. package/src/run-store.js +47 -0
  36. package/src/runner.js +40 -22
  37. package/src/setup.js +3 -0
  38. package/src/thinking.js +55 -0
  39. package/src/version.js +13 -0
  40. package/types/authoring.d.ts +11 -6
  41. package/types/closers.d.ts +2 -0
  42. package/types/config.d.ts +9 -1
  43. package/types/ctx-tools.d.ts +18 -0
  44. package/types/draft-steps.d.ts +47 -0
  45. package/types/drafter.d.ts +15 -12
  46. package/types/draftspend.d.ts +56 -0
  47. package/types/flowmodel.d.ts +16 -0
  48. package/types/input-facts.d.ts +6 -1
  49. package/types/keysfile.d.ts +23 -6
  50. package/types/liveness.d.ts +7 -1
  51. package/types/model-step.d.ts +1 -1
  52. package/types/monthly.d.ts +1 -0
  53. package/types/panel/author.d.ts +47 -9
  54. package/types/panel/authorcard.d.ts +33 -10
  55. package/types/panel/authorflows.d.ts +32 -9
  56. package/types/panel/authorresume.d.ts +2 -1
  57. package/types/panel/authorstart.d.ts +16 -6
  58. package/types/panel/authorvalues.d.ts +3 -1
  59. package/types/panel/data.d.ts +2 -2
  60. package/types/panel/resume.d.ts +2 -1
  61. package/types/panel/server.d.ts +6 -2
  62. package/types/panel/settings.d.ts +3 -1
  63. package/types/panel/spawn.d.ts +13 -4
  64. package/types/plain-checks.d.ts +22 -0
  65. package/types/primitives.d.ts +0 -6
  66. package/types/provider.d.ts +100 -284
  67. package/types/providershapes.d.ts +3 -4
  68. package/types/run-store.d.ts +11 -0
  69. package/types/runner.d.ts +2 -4
  70. package/types/setup.d.ts +8 -0
  71. package/types/thinking.d.ts +25 -0
  72. package/types/version.d.ts +2 -0
@@ -42,7 +42,7 @@ import { tmpdir } from 'node:os';
42
42
  import { dirname, join } from 'node:path';
43
43
  import { fileURLToPath } from 'node:url';
44
44
  import { scrub } from '../authoring.js';
45
- import { PROVIDER_SLOTS } from '../provider.js';
45
+ import { keyValues } from '../keysfile.js';
46
46
  import { spawnDetached } from './spawn.js';
47
47
 
48
48
  const HERE = dirname(fileURLToPath(import.meta.url));
@@ -76,7 +76,7 @@ function ensureLogDir(dir) {
76
76
  }
77
77
 
78
78
  /**
79
- * @param {{ root: string, env?: Record<string, string|undefined>, loadEnv?: () => { ok: boolean, env: Record<string, string|undefined>, refusal: string|null }, bin?: string, logDir?: string,
79
+ * @param {{ root: string, env?: Record<string, string|undefined>, loadEnv?: () => { ok: boolean, env: Record<string, string|undefined>, refusal: string|null, keyNames?: string[] }, bin?: string, logDir?: string,
80
80
  * maxTries?: number, windowMs?: number, slotMs?: number }} opts
81
81
  * `loadEnv` (M4d: the keys-file door, called before EVERY spawn so editing the file needs no panel restart) returns the merged env
82
82
  * that is BOTH the child's spawn env AND its scrub list, or a refusal sentence that becomes the attempt's refusal (nothing spawns).
@@ -123,7 +123,7 @@ export function createResumer(opts) {
123
123
  child.once('error', release);
124
124
  // The child's output is quoted in a refusal (`reason`) that reaches HTTP responses and the books: the
125
125
  // provider key(s) of this panel's env are scrubbed here, the one place that reads the log slice (amendment 1 (e)(3)).
126
- const keys = Object.values(PROVIDER_SLOTS).map((p) => runEnv[p.envVar]).filter(Boolean);
126
+ const keys = keyValues(runEnv, loaded.keyNames);
127
127
  const sliceOfLog = () => {
128
128
  try { return scrub(readFileSync(logPath).subarray(offset).toString('utf8').trim(), keys); } catch { return ''; } // offset is in BYTES
129
129
  };
@@ -48,6 +48,8 @@
48
48
 
49
49
  import { createServer } from 'node:http';
50
50
  import { readFileSync, realpathSync } from 'node:fs';
51
+ import { pageRules } from '../plain-checks.js';
52
+ import { readOwnVersion } from '../version.js';
51
53
  import path, { dirname, join } from 'node:path';
52
54
  import { fileURLToPath } from 'node:url';
53
55
 
@@ -351,7 +353,7 @@ function authorPost(res, url, body, author) {
351
353
  * real listening socket where that is simpler.
352
354
  * @param {import('node:http').IncomingMessage} req
353
355
  * @param {import('node:http').ServerResponse} res
354
- * @param {{ root: string, port: number, resumer: ReturnType<typeof createResumer>, settings: ReturnType<typeof createSettings>, author: ReturnType<typeof createAuthor> }} opts
356
+ * @param {{ root: string, port: number, packagePath?: string, resumer: ReturnType<typeof createResumer>, settings: ReturnType<typeof createSettings>, author: ReturnType<typeof createAuthor> }} opts
355
357
  */
356
358
  export function handleRequest(req, res, opts) {
357
359
  const method = req.method ?? 'GET';
@@ -456,7 +458,8 @@ export function handleRequest(req, res, opts) {
456
458
  if (pathname === '/api/author/live') r = opts.author.live();
457
459
  else if (pathname === '/api/author/flows') r = opts.author.flows();
458
460
  else if (pathname === '/api/author/run-again') r = opts.author.runAgain(url.searchParams.get('flow'), url.searchParams.get('runId'));
459
- else if (pathname === '/api/author/monthly-check') r = opts.author.monthlyCheck(url.searchParams.get('cap'), url.searchParams.get('spent'));
461
+ else if (pathname === '/api/author/monthly-check') r = opts.author.monthlyCheck(url.searchParams.get('cap'), url.searchParams.get('spent'), { provider: url.searchParams.get('provider') ?? undefined, model: url.searchParams.get('model') ?? undefined, flow: url.searchParams.get('flow') ?? undefined }, url.searchParams.get('kind') ?? 'drafting', url.searchParams.get('draft'));
462
+ else if (pathname === '/api/author/models') r = opts.author.models();
460
463
  else if (pathname === '/api/author/resume-form') r = opts.author.resumeForm(url.searchParams.get('flow'), url.searchParams.get('runId'));
461
464
  else if (sm) r = opts.author.startGet(sm[1]);
462
465
  else if (am) r = opts.author.get(am[1]);
@@ -482,6 +485,9 @@ export function handleRequest(req, res, opts) {
482
485
  return;
483
486
  }
484
487
  html = html.replace(/__FWDLOOP_PANEL_PORT__/g, String(opts.port));
488
+ const version = readOwnVersion(opts.packagePath); // M4d am17: the header's number, read from fwdloop's own package.json at serve time
489
+ html = version === null ? html.replace(/v__FWDLOOP_VERSION__/g, 'version unknown').replace(/__FWDLOOP_VERSION__/g, '') : html.replace(/__FWDLOOP_VERSION__/g, version);
490
+ html = html.replace(/__FWDLOOP_PLAN_CHECK_RULES__/g, () => JSON.stringify(pageRules())); // M4d am15: the one copy of the plain words
485
491
  if (method === 'HEAD') {
486
492
  res.writeHead(200, { 'content-type': 'text/html; charset=utf-8', 'content-length': Buffer.byteLength(html) });
487
493
  res.end();
@@ -507,7 +513,7 @@ export function handleRequest(req, res, opts) {
507
513
 
508
514
  if (pathname === '/api/inbox') {
509
515
  const rows = listStops({ root: opts.root, resumeAttempt, catalogue });
510
- send(200, { rows, openCount: inboxOpenCount(rows) });
516
+ send(200, { rows, openCount: inboxOpenCount(rows), version: readOwnVersion(opts.packagePath) }); // M4d am18: the page compares it with the version it was served with
511
517
  return;
512
518
  }
513
519
 
@@ -569,7 +575,7 @@ export function handleRequest(req, res, opts) {
569
575
  * header). Resolves once actually listening; rejects on a bind error
570
576
  * (including `EADDRINUSE`) with a `.port` field on the error for the
571
577
  * caller's message.
572
- * @param {{ port?: number, root: string, settings?: { home?: string, env?: Record<string,string|undefined>, fetch?: typeof fetch, now?: () => number }, resume?: { env?: Record<string,string|undefined>, bin?: string, logDir?: string, maxTries?: number, windowMs?: number, slotMs?: number }, author?: { env?: Record<string,string|undefined>, loadEnv?: () => any, bin?: string } }} opts
578
+ * @param {{ port?: number, root: string, packagePath?: string, settings?: { home?: string, env?: Record<string,string|undefined>, fetch?: typeof fetch, now?: () => number, openFolderSpawn?: Function, platform?: string }, resume?: { env?: Record<string,string|undefined>, bin?: string, logDir?: string, maxTries?: number, windowMs?: number, slotMs?: number }, author?: { env?: Record<string,string|undefined>, loadEnv?: () => any, bin?: string } }} opts
573
579
  * `resume` and `author` are for tests only (a fake env/bin, a short retry window); the CLI passes none.
574
580
  * @returns {Promise<{ server: import('node:http').Server, port: number, close: () => Promise<void> }>}
575
581
  */
@@ -591,7 +597,7 @@ export function createPanelServer(opts) {
591
597
  // Settings reads and writes only under the one config home: an injected one (tests), else the door's — under a test
592
598
  // process with no FWDLOOP_CONFIG_HOME, Settings is switched off rather than touch the real ~/.config/fwdloop.
593
599
  const settings = createSettings({
594
- home: opts.settings?.home ?? door.home, skip: opts.settings?.home === undefined && door.skip, env: opts.settings?.env, fetch: opts.settings?.fetch, now: opts.settings?.now,
600
+ home: opts.settings?.home ?? door.home, skip: opts.settings?.home === undefined && door.skip, env: opts.settings?.env, fetch: opts.settings?.fetch, now: opts.settings?.now, openFolderSpawn: opts.settings?.openFolderSpawn, platform: opts.settings?.platform,
595
601
  });
596
602
  return new Promise((resolve, reject) => {
597
603
  // Bound port is resolved from the live socket (`server.address().port`)
@@ -603,7 +609,7 @@ export function createPanelServer(opts) {
603
609
  const server = createServer((req, res) => {
604
610
  try {
605
611
  handleRequest(req, res, {
606
- root, port: boundPort, resumer, settings, author,
612
+ root, port: boundPort, resumer, settings, author, packagePath: opts.packagePath,
607
613
  });
608
614
  } catch (e) {
609
615
  sendText(res, 500, 'internal error');
@@ -7,31 +7,32 @@
7
7
  // What it never does (negatives (i) (ii) (ix) (xiv)):
8
8
  // - no route WRITES the keys file, and no response carries a key value: a key is read from the merged
9
9
  // env only to put in an `Authorization` header, then forgotten;
10
- // - Test and Balance are one GET each (`<baseUrl>/models`, DeepSeek's `/user/balance`), never a
10
+ // - Test and the model list are one GET (`<baseUrl>/models`), never a
11
11
  // completion, and write no spend row;
12
12
  // - no route reads or writes a flow or its cap. The only files touched are config.json (via
13
13
  // `updateConfig`) and the keys file (read through `keysForDoor`), both under the one config home.
14
14
  // Every refusal is a plain sentence in `say`; nothing here puts an HTTP code, an id or a path on the page.
15
- import { PROVIDER_SLOTS, resolvePrices, resolveSlot, checkKeyPreflight } from '../provider.js';
16
15
  import {
17
- readConfig, updateConfig, ConfigError, providerFieldProblem, cleanBaseUrl,
16
+ effectiveModels, resolveSlot, checkKeyPreflight,
17
+ } from '../provider.js';
18
+ import {
19
+ readConfig, updateConfig, ConfigError, providerFieldProblem, cleanBaseUrl, modelsProblem,
18
20
  } from '../config.js';
19
21
  import { SHAPES } from '../providershapes.js';
20
- import { keysForDoor } from '../keysfile.js';
22
+ import { keysForDoor, isKeyName } from '../keysfile.js';
21
23
  import { spendSummary } from '../monthly.js';
24
+ import { spawnOpener as realSpawn } from './spawn.js';
25
+ import { dirname } from 'node:path';
26
+ import { homedir } from 'node:os';
22
27
 
23
- const DEEPSEEK_BALANCE_URL = 'https://api.deepseek.com/user/balance';
24
28
  const TIMEOUT_MS = 4000;
25
29
 
26
- /** Plain words for each price field (the page's two boxes; cached input is priced as input, M4d amendment 2). */
27
- const FIELD_LABEL = Object.freeze({ inPerM: 'Input', outPerM: 'Output' });
28
-
29
30
  const BROKEN_CONFIG = 'Your settings file (config.json) cannot be read. Fix or remove it, then look again.';
30
31
 
31
32
  const isNumberAbove0 = (v) => typeof v === 'number' && Number.isFinite(v) && v > 0;
32
33
 
33
34
  /**
34
- * @param {{ home?: string, skip?: boolean, env?: Record<string,string|undefined>, fetch?: typeof fetch, now?: () => number }} cfg
35
+ * @param {{ home?: string, skip?: boolean, env?: Record<string,string|undefined>, fetch?: typeof fetch, now?: () => number, openFolderSpawn?: Function, platform?: string }} cfg
35
36
  * `home` the config home (undefined = the real `~/.config/fwdloop`); `skip` true under a test process
36
37
  * with no `FWDLOOP_CONFIG_HOME` (Settings then touches nothing); `env` the shell side (tests only);
37
38
  * `fetch` and `now` are test seams.
@@ -45,14 +46,15 @@ export function createSettings(cfg) {
45
46
  /** @param {string} refused @param {string} say @param {number} [status] */
46
47
  const refuse = (refused, say, status = 400) => reply(status, { ok: false, refused, say });
47
48
 
48
- /** The slot named by a request, or null. @param {unknown} slot */
49
- const slotOf = (slot) => (typeof slot === 'string' && Object.hasOwn(PROVIDER_SLOTS, slot) ? slot : null);
49
+ /** The row names: every key in the file with a value, plus a set-up key only the shell holds (M4d amendment 6 item 1). */
50
+ const rowNames = (k) => [...new Set([...k.names, ...k.shellOnly])].sort();
50
51
 
51
- /** Balance is offered only on an OpenAI-compatible slot whose host is api.deepseek.com (bareloop's rule). @param {{ shape: string, baseUrl: string }} eff */
52
- function canBalance(eff) {
53
- if (eff.shape !== 'openai-api') return false;
54
- try { return new URL(eff.baseUrl).host === 'api.deepseek.com'; } catch { return false; }
55
- }
52
+ /** The plain-words refusal for a slot that is not a key name at all, or null (the one rule is `isKeyName`). @param {unknown} slot */
53
+ const notKeyName = (slot) => (typeof slot === 'string' && slot !== '' && !isKeyName(slot)
54
+ ? refuse('not-a-key-name', `${slot} is not a key name. A key name ends in _KEY, like MY_API_KEY. Nothing was saved.`) : null);
55
+
56
+ /** The row named by a request, or null: only a key that is in the keys file (or the shell) is a row. @param {any} slot */
57
+ const slotOf = (slot) => (rowNames(keys()).includes(slot) ? slot : null);
56
58
 
57
59
  /** config.json, or `{problem}` in plain words when it is broken (never read as "nothing set"). */
58
60
  function config() {
@@ -66,30 +68,28 @@ export function createSettings(cfg) {
66
68
  const k = keys();
67
69
  const c = config();
68
70
  const spend = spendSummary({ home: cfg.home, now: cfg.now });
69
- const rows = Object.entries(PROVIDER_SLOTS).map(([slot, def]) => {
71
+ const rows = rowNames(k).map((slot) => {
70
72
  const eff = resolveSlot(slot, { config: c.config });
71
- const p = resolvePrices(eff.model, { slot, config: c.config });
72
- const one = (value, source) => ({ value, source });
73
+ const own = spend.byModel[slot] ?? {};
74
+ const models = effectiveModels(slot, c.config).map(({ model, use, inPerM, outPerM }) => ({
75
+ model, use, ...(inPerM === undefined ? {} : { inPerM }), ...(outPerM === undefined ? {} : { outPerM }),
76
+ // this model's own tokens from the spend rows that name it; absent = no row names it (never 0)
77
+ ...(Object.hasOwn(own, model) ? { tokens: own[model] } : {}),
78
+ }));
73
79
  let keyStatus = 'not set';
74
80
  if (!k.ok) keyStatus = 'refused';
75
- else if (k.names.includes(def.envVar)) keyStatus = 'set in file';
76
- else if (k.shellOnly.includes(def.envVar)) keyStatus = 'found in shell';
81
+ else if (k.names.includes(slot)) keyStatus = 'set in file';
82
+ else if (k.shellOnly.includes(slot)) keyStatus = 'found in shell';
77
83
  return {
78
84
  slot,
79
85
  label: slot,
80
- envVar: def.envVar,
86
+ envVar: slot,
81
87
  keyStatus,
82
- model: eff.model,
83
88
  shape: eff.shape,
84
89
  baseUrl: eff.baseUrl,
85
- savedBaseUrl: /** @type {Record<string, any>} */ (c.config).providers?.[slot]?.baseUrl ?? '',
86
- defaults: eff.defaults,
90
+ legacyMaxTokens: eff.legacyMaxTokens,
87
91
  tokens: spend.byProvider[slot]?.total.tokens ?? 0,
88
- price: {
89
- inPerM: one(p.perM.inPerM, p.source.in),
90
- outPerM: one(p.perM.outPerM, p.source.out),
91
- },
92
- canBalance: canBalance(eff),
92
+ models,
93
93
  };
94
94
  });
95
95
  return reply(200, {
@@ -105,8 +105,7 @@ export function createSettings(cfg) {
105
105
  function keyFor(slot) {
106
106
  const k = keys();
107
107
  if (!k.ok) return { why: String(k.refusal) };
108
- const def = PROVIDER_SLOTS[slot];
109
- const value = k.env[def.envVar];
108
+ const value = k.env[slot];
110
109
  if (value === undefined || value === '') return { why: 'No key set for this provider.' };
111
110
  if (!checkKeyPreflight(slot, k.env).ok) return { why: 'The key has a space or a line break in it. Fix it in your keys file, then reload keys.' };
112
111
  return { key: value };
@@ -120,7 +119,7 @@ export function createSettings(cfg) {
120
119
  }
121
120
 
122
121
  /** One $0 GET with a 4 s deadline and the key only in the header. @param {string} url @param {string} key @returns {Promise<{ body?: any, why?: string }>} */
123
- async function getWithKey(url, key, shape = 'openai-api') {
122
+ async function getWithKey(url, key, shape) {
124
123
  const ctl = new AbortController();
125
124
  const timer = setTimeout(() => ctl.abort(), TIMEOUT_MS);
126
125
  try {
@@ -139,59 +138,116 @@ export function createSettings(cfg) {
139
138
  }
140
139
  }
141
140
 
142
- async function test(body) {
143
- const slot = slotOf(body?.slot);
144
- if (!slot) return refuse('unknown-provider', 'That provider is not known.');
145
- const k = keyFor(slot);
146
- if (k.why) return reply(200, { ok: false, why: k.why });
141
+ /** The model ids a provider's list answer holds, per API shape (`data[].id` for two shapes; the third shape: `models[].name`, minus its `models/` prefix). @param {string} shape @param {any} body @returns {string[]} */
142
+ function idsOf(shape, body) {
143
+ const list = shape === 'gemini-api' ? body?.models : body?.data;
144
+ const key = shape === 'gemini-api' ? 'name' : 'id';
145
+ const ids = (Array.isArray(list) ? list : []).map((m) => (typeof m?.[key] === 'string' ? m[key].replace(/^models\//, '') : '')).filter((id) => id !== '');
146
+ return [...new Set(ids)].sort();
147
+ }
148
+
149
+ /**
150
+ * The ONE model-list call (M4d amendment 6 item 3): one free GET of `<Base URL>/models` with the key in the header only. Test and the page's list
151
+ * both read it. `{ ok:true, models, ms }` or `{ ok:false, why }` in plain words. Writes nothing.
152
+ * @param {unknown} rawSlot
153
+ */
154
+ async function listModels(rawSlot) {
155
+ const slot = slotOf(rawSlot);
156
+ if (!slot) return { unknown: true };
147
157
  const started = Date.now();
148
158
  const c = config();
149
- if (c.problem) return reply(200, { ok: false, why: c.problem });
159
+ if (c.problem) return { ok: false, why: c.problem };
150
160
  const eff = resolveSlot(slot, { config: c.config });
151
- const base = eff.baseUrl !== '' ? eff.baseUrl : 'https://generativelanguage.googleapis.com/v1beta'; // bare-agent's own Gemini address
152
- const r = await getWithKey(`${base}/models`, String(k.key), eff.shape);
153
- if (r.why) return reply(200, { ok: false, why: r.why });
154
- return reply(200, { ok: true, ms: Date.now() - started });
161
+ // the address comes first: a key reaches the env only once its row is set up, so a row with no address has nothing to send yet
162
+ if (eff.baseUrl === '') return { ok: false, why: `Type a Base URL for ${slot} in Settings.` };
163
+ const k = keyFor(slot);
164
+ if (k.why) return { ok: false, why: k.why };
165
+ const r = await getWithKey(`${eff.baseUrl}/models`, String(k.key), eff.shape);
166
+ if (r.why) return { ok: false, why: r.why };
167
+ return { ok: true, models: idsOf(eff.shape, r.body), ms: Date.now() - started };
155
168
  }
156
169
 
157
- async function balance(query) {
158
- const slot = slotOf(query.get('slot'));
159
- if (!slot) return refuse('unknown-provider', 'That provider is not known.');
160
- const c = config();
161
- if (c.problem) return reply(200, { ok: false, why: c.problem });
162
- if (!canBalance(resolveSlot(slot, { config: c.config }))) return reply(200, { ok: false, why: 'Not offered by this provider.' });
163
- const k = keyFor(slot);
164
- if (k.why) return reply(200, { ok: false, why: k.why });
165
- const r = await getWithKey(DEEPSEEK_BALANCE_URL, String(k.key));
166
- if (r.why) return reply(200, { ok: false, why: r.why });
167
- const infos = Array.isArray(r.body?.balance_infos) ? r.body.balance_infos : [];
168
- const balances = infos
169
- .filter((b) => b && typeof b.currency === 'string' && b.total_balance !== undefined)
170
- .map((b) => ({ currency: b.currency, total: String(b.total_balance) }));
171
- if (balances.length === 0) return reply(200, { ok: false, why: 'The provider did not report a balance.' });
172
- return reply(200, { ok: true, balances });
170
+ /**
171
+ * borrowed-from: bareloop src/panel/settingsroutes.js@07c298f (the open-keys-folder route), adapted to fwdloop's reply shape.
172
+ * Opens the FOLDER of the server's own keys file path (never a file, never an editor, never a path from the request) in the OS file
173
+ * manager: argv array, no shell, detached. Another OS, a failed spawn, or a test process with no injected opener: `opened:false` and
174
+ * the folder path, which the page shows as text. `openFolderSpawn` / `platform` are test seams.
175
+ * @param {any} body
176
+ */
177
+ function openKeysFolder(body) {
178
+ if (body !== null && typeof body === 'object' && Object.keys(body).length > 0) {
179
+ return Promise.resolve(refuse('no-path-allowed', 'The keys folder is opened from the panel\'s own settings; a path cannot be sent. Nothing was opened.'));
180
+ }
181
+ const shown = keys().path;
182
+ const dir = dirname(shown.startsWith('~') ? homedir() + shown.slice(1) : shown);
183
+ const cannot = () => reply(200, { ok: true, opened: false, path: dir });
184
+ const platform = cfg.platform ?? process.platform;
185
+ const cmd = platform === 'linux' ? 'xdg-open' : (platform === 'darwin' ? 'open' : null);
186
+ const opener = cfg.openFolderSpawn ?? (process.env.NODE_ENV === 'test' ? null : realSpawn);
187
+ if (!cmd || !opener) return Promise.resolve(cannot());
188
+ return new Promise((resolve) => {
189
+ let child;
190
+ try { child = opener(cmd, [dir], { detached: true, stdio: 'ignore' }); } catch { resolve(cannot()); return; }
191
+ let settled = false;
192
+ child.once('error', () => { if (!settled) { settled = true; resolve(cannot()); } });
193
+ child.once('spawn', () => {
194
+ if (settled) return;
195
+ settled = true;
196
+ if (typeof child.unref === 'function') child.unref();
197
+ resolve(reply(200, { ok: true, opened: true, path: dir }));
198
+ });
199
+ });
200
+ }
201
+
202
+ async function test(body) {
203
+ const bad = notKeyName(body?.slot);
204
+ if (bad) return bad;
205
+ const r = await listModels(body?.slot);
206
+ if (r.unknown) return refuse('unknown-provider', 'That provider is not known.');
207
+ return reply(200, r.ok ? { ok: true, ms: r.ms } : r);
208
+ }
209
+
210
+ async function models(body) {
211
+ const bad = notKeyName(body?.slot);
212
+ if (bad) return bad;
213
+ const r = await listModels(body?.slot);
214
+ if (r.unknown) return refuse('unknown-provider', 'That provider is not known.');
215
+ if (!r.ok) return reply(200, r);
216
+ const ids = r.models ?? [];
217
+ return reply(200, ids.length === 0 ? { ok: false, why: 'The provider did not list any models.' } : { ok: true, models: ids });
173
218
  }
174
219
 
175
- /** Validate EVERY field first; write only if all pass. */
176
- function price(body) {
220
+ /**
221
+ * Save one model line: {slot, model, use?, inPerM?, outPerM?} (a field left out keeps the line's value; a price
222
+ * `null` clears it). The whole slot list is judged by `modelsProblem` (the one rule) BEFORE anything is written;
223
+ * Idea borrowed from bareloop src/panel/settingsroutes.js@caf019b (both prices or neither, :165-179), not copied: the
224
+ * rule here is `modelsProblem` (tick needs both, 0 / 0 allowed, exact sentence).
225
+ */
226
+ function model(body) {
227
+ const bad = notKeyName(body?.slot);
228
+ if (bad) return bad;
177
229
  const slot = slotOf(body?.slot);
178
230
  if (!slot) return refuse('unknown-provider', 'That provider is not known.');
179
- /** @type {Record<string, number|null>} */
180
- const patch = {};
231
+ const c = config();
232
+ if (c.problem) return refuse('config-broken', `${BROKEN_CONFIG} Nothing was saved.`);
181
233
  if (Object.hasOwn(body, 'cachedInPerM')) {
182
234
  return refuse('bad-price', 'Cached input has no price of its own: it is priced as input. Nothing was saved.');
183
235
  }
236
+ if (typeof body.model !== 'string') return refuse('bad-model', 'Pick a model line. Nothing was saved.');
237
+ // the saved list as it is, minus an older file's `thinkingOff` (read by nothing; dropped here, amendment 7)
238
+ const list = effectiveModels(slot, c.config).map((m) => { const { thinkingOff, ...rest } = /** @type {Record<string, any>} */ (m); return { ...rest }; });
239
+ let line = list.find((m) => m.model === body.model);
240
+ if (!line) { line = { model: body.model, use: false }; list.push(line); }
241
+ if (Object.hasOwn(body, 'use')) line.use = body.use;
184
242
  for (const f of /** @type {const} */ (['inPerM', 'outPerM'])) {
185
243
  if (!Object.hasOwn(body, f)) continue;
186
- const v = body[f];
187
- if (v !== null && !isNumberAbove0(v)) {
188
- return refuse('bad-price', `${FIELD_LABEL[f]} price must be a number above 0, or empty to use the default. Nothing was saved.`);
189
- }
190
- patch[f] = v;
244
+ if (body[f] === null) delete line[f];
245
+ else line[f] = body[f];
191
246
  }
192
- if (Object.keys(patch).length === 0) return refuse('bad-price', 'Nothing to save.');
247
+ const problem = modelsProblem(list);
248
+ if (problem) return refuse('bad-model', problem);
193
249
  try {
194
- updateConfig({ prices: { [slot]: patch } }, { home: cfg.home });
250
+ updateConfig({ models: { [slot]: list } }, { home: cfg.home });
195
251
  } catch (e) {
196
252
  if (!(e instanceof ConfigError)) throw e;
197
253
  return refuse('config-broken', `${BROKEN_CONFIG} Nothing was saved.`);
@@ -199,20 +255,21 @@ export function createSettings(cfg) {
199
255
  return reply(200, { ok: true, slot });
200
256
  }
201
257
 
202
- /** Save a provider slot's name (model id), shape and Base URL. Validate EVERY field first; write only if all pass. */
258
+ /** Save a row's shape, Base URL and legacyMaxTokens tick. Validate EVERY field first; write only if all pass. */
203
259
  function provider(body) {
260
+ const bad = notKeyName(body?.slot);
261
+ if (bad) return bad;
204
262
  const slot = slotOf(body?.slot);
205
263
  if (!slot) return refuse('unknown-provider', 'That provider is not known.');
206
- const fields = { name: 'model', shape: 'shape', baseUrl: 'baseUrl' };
207
- const say = { name: 'The name must be a model id: 1 to 200 characters, no spaces.', shape: 'Pick an API shape from the list.', baseUrl: 'The Base URL must be empty (use the default) or start with http:// or https://.' };
208
- /** @type {Record<string, string|null>} */
264
+ const say = { shape: 'Pick an API shape from the list.', baseUrl: 'The Base URL must start with http:// or https://.', legacyMaxTokens: 'The legacy max_tokens tick must be on or off.' };
265
+ /** @type {Record<string, string|boolean|null>} */
209
266
  const patch = {};
210
- for (const [key, field] of Object.entries(fields)) {
267
+ for (const key of Object.keys(say)) {
211
268
  if (!Object.hasOwn(body, key)) continue;
212
269
  const v = body[key];
213
270
  const clearUrl = key === 'baseUrl' && v === '';
214
- if (!clearUrl && providerFieldProblem(field, v) !== null) return refuse('bad-provider', `${say[key]} Nothing was saved.`);
215
- patch[field] = clearUrl ? null : (key === 'baseUrl' ? cleanBaseUrl(v) : v);
271
+ if (!clearUrl && providerFieldProblem(key, v) !== null) return refuse('bad-provider', `${say[key]} Nothing was saved.`);
272
+ patch[key] = clearUrl ? null : (key === 'baseUrl' ? cleanBaseUrl(v) : v);
216
273
  }
217
274
  if (Object.keys(patch).length === 0) return refuse('bad-provider', 'Nothing to save.');
218
275
  try {
@@ -253,15 +310,16 @@ export function createSettings(cfg) {
253
310
  */
254
311
  async function handle({ method, pathname, query, body }) {
255
312
  if (cfg.skip) return refuse('settings-unavailable', 'Settings is not available here.', 404);
256
- const known = { GET: ['/api/settings/providers', '/api/settings/balance', '/api/settings/money'], POST: ['/api/settings/test', '/api/settings/price', '/api/settings/provider', '/api/settings/money'] };
313
+ const known = { GET: ['/api/settings/providers', '/api/settings/money'], POST: ['/api/settings/open-keys-folder', '/api/settings/test', '/api/settings/models', '/api/settings/model', '/api/settings/provider', '/api/settings/money'] };
257
314
  if (!(known[method] ?? []).includes(pathname)) return refuse('no-such-settings-route', 'Settings cannot do that. Keys are typed into your keys file by hand.', 404);
258
315
  if (method === 'GET') {
259
316
  if (pathname === '/api/settings/providers') return providers();
260
- if (pathname === '/api/settings/balance') return balance(query);
261
317
  return moneyGet();
262
318
  }
319
+ if (pathname === '/api/settings/open-keys-folder') return openKeysFolder(body);
263
320
  if (pathname === '/api/settings/test') return test(body);
264
- if (pathname === '/api/settings/price') return price(body);
321
+ if (pathname === '/api/settings/models') return models(body);
322
+ if (pathname === '/api/settings/model') return model(body);
265
323
  if (pathname === '/api/settings/provider') return provider(body);
266
324
  return moneyPost(body);
267
325
  }
@@ -12,11 +12,20 @@ import { join } from 'node:path';
12
12
 
13
13
  import { readFileInside } from '../flow.js';
14
14
  import { isFwdloopAlive, procStartOf } from '../liveness.js';
15
- import { PROVIDER_SLOTS } from '../provider.js';
15
+ import { keyValues } from '../keysfile.js';
16
16
 
17
17
  /** A pid whose liveness cannot be told (no /proc) counts as running only while its pid.json is this fresh (M4c's 10-minute rule). */
18
18
  const UNKNOWN_FRESH_MS = 10 * 60 * 1000;
19
19
 
20
+ /**
21
+ * The ONE spawn for the Settings "Open keys folder" button (borrowed-from: bareloop src/panel/settingsroutes.js@07c298f): the OS file manager
22
+ * (`xdg-open` / `open`) on a folder the server chose, argv array, no shell, detached. Settings calls it only through its injected seam.
23
+ * @param {string} cmd @param {string[]} args @param {import('node:child_process').SpawnOptions} o
24
+ */
25
+ export function spawnOpener(cmd, args, o) {
26
+ return spawn(cmd, args, o);
27
+ }
28
+
20
29
  /**
21
30
  * @param {{ bin: string, argv: string[], env: Record<string, string|undefined>, logPath: string }} a
22
31
  * @returns {import('node:child_process').ChildProcess} the child (already `unref()`ed; the log fd is closed here)
@@ -65,13 +74,10 @@ export function childRunning(dir) {
65
74
  }
66
75
 
67
76
  /**
68
- * The provider key VALUES in the merged env — the scrub list. The env that holds them is the SAME object that is the child's
69
- * spawn env (POC (a), M4d wiring rule), so the list can never differ from what the child was given.
70
- * @param {Record<string, string|undefined>} env
77
+ * The provider key VALUES of a keys load (`keysForDoor`) — the scrub list. The env that holds them is the SAME object that is the child's
78
+ * spawn env (POC (a), M4d wiring rule), and the names are the load's own `keyNames`, so the list can never differ from what the child was given.
79
+ * @param {{ env: Record<string, string|undefined>, keyNames?: string[] }} loaded
71
80
  */
72
- export function providerKeys(env) {
73
- /** @type {string[]} */
74
- const out = [];
75
- for (const p of Object.values(PROVIDER_SLOTS)) { const k = env[p.envVar]; if (typeof k === 'string' && k !== '') out.push(k); }
76
- return out;
81
+ export function providerKeys(loaded) {
82
+ return keyValues(loaded.env, loaded.keyNames);
77
83
  }
@@ -0,0 +1,51 @@
1
+ // M4d amendment 15: the plain words for a plan-check refusal. ONE copy of them: the Chat list (src/draft-steps.js), the Audit Draft rows
2
+ // (src/panel/data.js) and the page (the server hands it the same rules in index.html, see src/panel/server.js) all read this file.
3
+ // Moved here from the page's `plainPlanCheck` (M4e am41 item 7), sentences unchanged.
4
+ //
5
+ // `say` is the plain sentence(s) the page's revise lines show. `reason` is `say` without its fix. `fix` is the one short sentence that tells the human what to
6
+ // change (the job line, the guardrail, the inputs, the destination) or to Draft again when it is the AI's own form error; every rule has one (am15 item 3).
7
+ // The first two rules' `say` already ends with their fix, as the page has always shown them.
8
+
9
+ /** @type {ReadonlyArray<{re: RegExp, say: string|null, fix: string}>} `say` null = the checker's own sentence, as it is without its "declaration: " prefix */
10
+ export const PLAN_CHECK_RULES = Object.freeze([
11
+ { re: /which is not in the job line's words/, say: "A section name in the plan's check is not in your job line. Change the job line to use the section words you want.", fix: 'Change the job line to use the section words you want.' },
12
+ { re: /the job line says .*; the check says/, say: "The sections in the plan's check come in a different order than your job line. Change the job line to change the order.", fix: 'Change the job line to change the order.' },
13
+ { re: /the guardrail says \d+ sections; the check has/, say: "The number of sections in your guardrail is not the number in the plan's check.", fix: 'Make the guardrail and the job line say the same number of sections, then Draft again.' },
14
+ { re: /section name is a short phrase|which is the job line or most of it/, say: "A section name in the plan's check is too long; it must be a short phrase from your job line.", fix: 'Use a short phrase from your job line for each section, then Draft again.' },
15
+ { re: /one section name may not contain another/, say: 'One section name in the plan\'s check contains another, which cannot be checked.', fix: 'Rename the sections in your job line so none contains another, then Draft again.' },
16
+ { re: /wordsPerSection/, say: "The words for each section in your guardrail and in the plan's check do not match.", fix: 'Give each section one clear number of words in your guardrail, then Draft again.' },
17
+ { re: /work as a pair/, say: "The plan's check has one part of a pair without the other, so it cannot be checked.", fix: 'Draft again; if it repeats, simplify the guardrail on that line.' },
18
+ { re: /is blank|characters; the most one entry|ends in ":"/, say: "A name in the plan's check is empty, too long or ends in a colon, so it cannot be matched.", fix: 'Shorten the section names in your job line, then Draft again.' },
19
+ { re: /cannot be built into a check/, say: "The plan's check cannot be built from what the AI wrote.", fix: 'Draft again; if it repeats, simplify the guardrail on that line.' },
20
+ { re: /is not its signed line/, say: 'A step does not use your job line word for word as its goal.', fix: 'Draft again.' },
21
+ { re: /not in the catalogue|not wired|which is not signed|checkpoint/, say: 'A step uses a tool that is not available for this job.', fix: 'Draft again; if it repeats, say in the job line what that step should do.' },
22
+ { re: /reads artifact|is a duplicate|\.reads must|\.emits must/, say: 'The steps do not pass their results to each other in a workable order.', fix: 'Draft again.' },
23
+ { re: /ask at line \d+|signed ask at line|ask slot/, say: 'The ask on one of your lines is not set up as a plain stop where you decide.', fix: 'Check the line that starts with Ask in your job, then Draft again.' },
24
+ { re: /send at line \d+|signed send at line|send slot/, say: 'The send step is not set up to follow your accept and write only to your destination.', fix: 'Check the Destination on the card, then Draft again.' },
25
+ { re: /hitl after the last signed ask/, say: 'A step after your last ask would leave without your seeing it, so it is refused.', fix: 'Move the lines you want to check before your last Ask line, then Draft again.' },
26
+ { re: /is a pause .* unsigned line/, say: 'A step pauses at a line you did not sign as an ask.', fix: 'Mark the line you want to stop at with Ask, then Draft again.' },
27
+ { re: /neither served by any step/, say: 'A line of your job is not covered by any step.', fix: 'Make every line of your job say one thing to do, then Draft again.' },
28
+ { re: /picks|inputFacts|invented name/, say: 'The plan names a field that is not in your input.', fix: 'Check the names in your Inputs and job line, then Draft again.' },
29
+ { re: /guardrailClasses|unjudgeable|refused/, say: "The AI's notes on which lines it can check are not in a form the checker accepts.", fix: 'Draft again.' },
30
+ { re: /^line \d+'s (guardrail|check)|can't write files/, say: null, fix: 'Change the guardrail on that line the way the sentence says, then Draft again.' },
31
+ { re: /must be an? |is required|must name|does not name/, say: 'The plan the AI wrote is not in the shape the checker needs.', fix: 'Draft again.' },
32
+ ]);
33
+
34
+ export const GENERIC_SAY = 'One of the checks on the plan failed.';
35
+ export const GENERIC_FIX = 'Draft again.';
36
+
37
+ /** The rules as the page takes them: JSON, the regex as its source text. */
38
+ export const pageRules = () => PLAN_CHECK_RULES.map((r) => ({ re: r.re.source, say: r.say }));
39
+
40
+ /**
41
+ * @param {unknown} raw one raw refusal text
42
+ * @returns {{ say: string, reason: string, fix: string, raw: string }}
43
+ */
44
+ export function plainPlanCheck(raw) {
45
+ const text = typeof raw === 'string' ? raw : '';
46
+ const rule = PLAN_CHECK_RULES.find((r) => r.re.test(text));
47
+ const say = rule === undefined ? GENERIC_SAY : (rule.say === null ? text.replace(/^declaration: /, '') : rule.say);
48
+ const fix = rule === undefined ? GENERIC_FIX : rule.fix;
49
+ const reason = (say.endsWith(fix) ? say.slice(0, -fix.length) : say).trim().replace(/\.$/, '');
50
+ return { say, reason, fix, raw: text };
51
+ }
package/src/primitives.js CHANGED
@@ -31,6 +31,7 @@ import { Gate } from 'bareguard';
31
31
  import { primitiveFor, loadCatalogue } from './catalogue.js';
32
32
  import { readDocxText } from './docx.js';
33
33
  import { parseCsv } from './csv.js';
34
+ import { makeCtxTools } from './ctx-tools.js';
34
35
 
35
36
  // bare-agent >=0.47.0: `noFollowSymlinks: true` makes shell_read/write/edit/
36
37
  // grep throw `err.code === 'ELOOP'` when the path's FINAL component is a
@@ -80,7 +81,8 @@ async function resolveAndGate(gate, verb, tool, runDir, rawPath) {
80
81
  }
81
82
  const joined = (rawPath.startsWith('~') || path.isAbsolute(rawPath)) ? rawPath : path.join(runDir, rawPath);
82
83
  const resolved = resolveToolPath(joined);
83
- const type = verb === 'write' ? 'write' : 'read';
84
+ // `edit` is judged as bareguard's own 'edit' action type: the SAME fs.writeScope fence as `write` (M7 item 3)
85
+ const type = verb === 'write' || verb === 'edit' ? verb : 'read';
84
86
  const decision = await gate.check({ type, tool, path: resolved });
85
87
  if (decision.outcome !== 'allow') {
86
88
  throw new GateRefusal(verb, resolved, decision.rule);
@@ -214,6 +216,20 @@ function sandboxedWriteTool(gate, runDir, outDir) {
214
216
  };
215
217
  }
216
218
 
219
+ function sandboxedEditTool(gate, runDir) {
220
+ const real = shellTool('shell_edit');
221
+ return {
222
+ name: 'edit',
223
+ description: `${real.description} Sandboxed exactly like write: only files under <runDir>/out can be edited; `
224
+ + 'the run records and the frozen inputs are never editable.',
225
+ parameters: real.parameters,
226
+ execute: async (args) => {
227
+ const resolvedPath = await resolveAndGate(gate, 'edit', 'edit', runDir, args?.path);
228
+ return real.execute({ ...args, path: resolvedPath });
229
+ },
230
+ };
231
+ }
232
+
217
233
  /** `readDocx`/`addressCells` take a `role` naming one of the run's frozen
218
234
  * inputs (never a raw path — the model is never handed a filesystem path
219
235
  * to type back, so there is nothing to sandbox-check on the way in). */
@@ -259,7 +275,11 @@ function addressCellsPrimitiveTool(inputsByRole) {
259
275
  * catalogue-present-but-unwired verb, e.g. litectx's `compress`, must
260
276
  * refuse before any model call or spend) imports this SAME set rather than
261
277
  * keeping a second copy of the list. */
262
- export const WIRED_VERBS = new Set(['read', 'grep', 'write', 'readDocx', 'addressCells']);
278
+ /** M7: the in-run tools over this run's own store (src/ctx-tools.js). `remember`/`forget` are
279
+ * deliberately absent: memory lasts one run (PRD: no learning between flows). */
280
+ const CTX_VERBS = Object.freeze(['recall', 'get', 'recent', 'related', 'impact', 'compress', 'peek', 'stash']);
281
+
282
+ export const WIRED_VERBS = new Set(['read', 'grep', 'write', 'edit', 'readDocx', 'addressCells', ...CTX_VERBS]);
263
283
 
264
284
  /** The wired menu, one place: the catalogue entries whose verb is in
265
285
  * WIRED_VERBS (and, when `skills` is given, in a signed skill). Absence,
@@ -308,6 +328,13 @@ export function resolvePrimitives(catalogue, grantedVerbs, ctx) {
308
328
 
309
329
  const tools = {};
310
330
  const reds = [];
331
+ // Built on demand, once: nothing is opened or created here (the store is opened per call, inside a tool).
332
+ // A path a tool names goes through the SAME read gate as `read` before litectx sees it.
333
+ let ctxTools;
334
+ const ctxTool = (verb) => {
335
+ ctxTools ??= makeCtxTools({ runDir, gatePath: (v, rawPath) => resolveAndGate(gate, v, v, runDir, rawPath) });
336
+ return ctxTools[verb];
337
+ };
311
338
 
312
339
  for (const verb of grantedVerbs ?? []) {
313
340
  const entry = primitiveFor(catalogue, verb);
@@ -338,6 +365,9 @@ export function resolvePrimitives(catalogue, grantedVerbs, ctx) {
338
365
  // even for a run `runFlow` goes on to refuse.
339
366
  tools.write = sandboxedWriteTool(gate, runDir, outDir);
340
367
  break;
368
+ case 'edit':
369
+ tools.edit = sandboxedEditTool(gate, runDir);
370
+ break;
341
371
  case 'readDocx':
342
372
  tools.readDocx = readDocxPrimitiveTool(inputsByRole);
343
373
  break;
@@ -345,7 +375,8 @@ export function resolvePrimitives(catalogue, grantedVerbs, ctx) {
345
375
  tools.addressCells = addressCellsPrimitiveTool(inputsByRole);
346
376
  break;
347
377
  default:
348
- reds.push(`primitives: verb "${verb}" is in the catalogue but has no M2 implementation yet`);
378
+ if (CTX_VERBS.includes(verb)) tools[verb] = ctxTool(verb);
379
+ else reds.push(`primitives: verb "${verb}" is in the catalogue but has no M2 implementation yet`);
349
380
  }
350
381
  }
351
382