fwdloop 0.10.0 → 0.11.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/bin/fwdloop +15 -11
- package/package.json +1 -1
- package/src/ask.js +200 -8
- package/src/authoring.js +31 -5
- package/src/liveness.js +7 -7
- package/src/model-step.js +4 -3
- package/src/panel/data.js +200 -73
- package/src/panel/index.html +419 -120
- package/src/panel/lock.js +42 -0
- package/src/panel/resume.js +35 -4
- package/src/panel/server.js +259 -44
- package/src/provider.js +9 -1
- package/src/runner.js +47 -10
- package/types/ask.d.ts +70 -1
- package/types/authoring.d.ts +3 -2
- package/types/liveness.d.ts +2 -1
- package/types/panel/data.d.ts +108 -29
- package/types/panel/lock.d.ts +21 -0
- package/types/panel/resume.d.ts +4 -0
- package/types/panel/server.d.ts +30 -2
package/bin/fwdloop
CHANGED
|
@@ -31,7 +31,9 @@ import { makeLiveModelStep } from '../src/model-step.js';
|
|
|
31
31
|
import { sendViaPrimitive } from '../src/send.js';
|
|
32
32
|
import { resolvePrimitives } from '../src/primitives.js';
|
|
33
33
|
import { checkKeyPreflight } from '../src/provider.js';
|
|
34
|
-
import {
|
|
34
|
+
import {
|
|
35
|
+
answerAsk, readAskEvidence, normalizeDecision, stripControl, withReopen,
|
|
36
|
+
} from '../src/ask.js';
|
|
35
37
|
import { panelMain } from '../src/panel/server.js';
|
|
36
38
|
import { isInteractive, confirmTypedName, NEEDS_TTY } from '../src/sign-confirm.js';
|
|
37
39
|
import { draftToDir, signDraft, SIGN_LINE, costText } from '../src/authoring.js';
|
|
@@ -288,7 +290,7 @@ function cmdInbox(rest) {
|
|
|
288
290
|
if (!askRead.ok) continue; // eslint-disable-line no-continue -- missing (or refused) ask.json: nothing to show
|
|
289
291
|
let ask;
|
|
290
292
|
try {
|
|
291
|
-
ask = JSON.parse(askRead.text);
|
|
293
|
+
ask = withReopen(runDir, JSON.parse(askRead.text)); // the effective deadline (a reopened ask's new one)
|
|
292
294
|
} catch (err) {
|
|
293
295
|
// A malformed/unparseable ask.json must never crash inbox — show it
|
|
294
296
|
// naming the run as unreadable and move on to the next one.
|
|
@@ -342,11 +344,11 @@ function cmdInbox(rest) {
|
|
|
342
344
|
continue;
|
|
343
345
|
}
|
|
344
346
|
if (row.status === 'legacy') {
|
|
345
|
-
process.stdout.write(`flow=${row.flow} run=${row.runId} [legacy (not answerable)] — ${row.question}\n`);
|
|
347
|
+
process.stdout.write(`flow=${row.flow} run=${row.runId} [legacy (not answerable)] — ${stripControl(row.question)}\n`);
|
|
346
348
|
continue;
|
|
347
349
|
}
|
|
348
350
|
const timeLeft = row.status === 'expired' ? 'expired' : `${Math.max(0, Math.round(row.timeLeftMs / 1000))}s left`;
|
|
349
|
-
process.stdout.write(`${row.askId} flow=${row.flow} run=${row.runId} [${row.status}] ${timeLeft} — ${row.question}\n`);
|
|
351
|
+
process.stdout.write(`${row.askId} flow=${row.flow} run=${row.runId} [${row.status}] ${timeLeft} — ${stripControl(row.question)}\n`);
|
|
350
352
|
}
|
|
351
353
|
}
|
|
352
354
|
|
|
@@ -381,13 +383,13 @@ function cmdShow(rest) {
|
|
|
381
383
|
}
|
|
382
384
|
let ask;
|
|
383
385
|
try {
|
|
384
|
-
ask = JSON.parse(askRead.text);
|
|
386
|
+
ask = withReopen(runDir, JSON.parse(askRead.text)); // the effective deadline (a reopened ask's new one)
|
|
385
387
|
} catch (err) {
|
|
386
388
|
fail(`show: ask.json for askId "${askId}" is not valid JSON — ${err.message}`);
|
|
387
389
|
return;
|
|
388
390
|
}
|
|
389
391
|
|
|
390
|
-
process.stdout.write(`question: ${ask.question}\n`);
|
|
392
|
+
process.stdout.write(`question: ${stripControl(ask.question)}\n`);
|
|
391
393
|
process.stdout.write(`expiresAt: ${ask.expiresAt}\n`);
|
|
392
394
|
|
|
393
395
|
const { draft, unjudged, why } = readAskEvidence(ask);
|
|
@@ -396,10 +398,10 @@ function cmdShow(rest) {
|
|
|
396
398
|
return;
|
|
397
399
|
}
|
|
398
400
|
process.stdout.write('\n--- artifact under review ---\n');
|
|
399
|
-
process.stdout.write(`${draft.text}\n`);
|
|
401
|
+
process.stdout.write(`${stripControl(draft.text)}\n`);
|
|
400
402
|
for (const item of unjudged) {
|
|
401
|
-
process.stdout.write(`\n--- unjudged: ${item.step} ---\n`);
|
|
402
|
-
process.stdout.write(`${item.text}\n`);
|
|
403
|
+
process.stdout.write(`\n--- unjudged: ${stripControl(item.step)} ---\n`);
|
|
404
|
+
process.stdout.write(`${stripControl(item.text)}\n`);
|
|
403
405
|
}
|
|
404
406
|
}
|
|
405
407
|
|
|
@@ -516,8 +518,10 @@ async function cmdResume(rest) {
|
|
|
516
518
|
// panel — M4a piece 2 + M4b (docs/wiki/the-module-ladder.md, "M4a — read-only
|
|
517
519
|
// panel" and "M4b — inputs"): `fwdloop panel [--port 4800] [--root <dir>]`.
|
|
518
520
|
// Reads are GET/HEAD; the only writes are POST /api/answer and POST
|
|
519
|
-
// /api/resume (src/panel/server.js), each gated by Origin/Host +
|
|
520
|
-
//
|
|
521
|
+
// /api/resume (src/panel/server.js), each gated by Origin/Host + the panel's
|
|
522
|
+
// cookie. `fwdloop panel` writes its token to a 0600 file ($XDG_RUNTIME_DIR/fwdloop/
|
|
523
|
+
// panel-<port>.token, else ~/.cache/fwdloop/; reused across restarts while that file is 0600) and prints `http://127.0.0.1:<port>/?t=<token>` —
|
|
524
|
+
// open that link (it sets the cookie); every request needs it. Bound to 127.0.0.1 only. Never picks
|
|
521
525
|
// a different port on collision — a taken port is a loud, non-zero-exit
|
|
522
526
|
// failure.
|
|
523
527
|
// ---------------------------------------------------------------------------
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "fwdloop",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.11.0",
|
|
4
4
|
"description": "Describe a job as steps and guardrails; an agent builds the workflow, pauses for humans where you said, checks every step happened, and reruns it under budgets it cannot touch.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "./src/index.js",
|
package/src/ask.js
CHANGED
|
@@ -17,7 +17,7 @@
|
|
|
17
17
|
// not a second Checkpoint instance layered on top of the same file protocol.
|
|
18
18
|
|
|
19
19
|
import {
|
|
20
|
-
existsSync, mkdirSync, readFileSync, renameSync, writeFileSync,
|
|
20
|
+
existsSync, linkSync, mkdirSync, readFileSync, renameSync, unlinkSync, writeFileSync,
|
|
21
21
|
} from 'node:fs';
|
|
22
22
|
import { join } from 'node:path';
|
|
23
23
|
import { createHash, randomUUID } from 'node:crypto';
|
|
@@ -58,10 +58,25 @@ export function normalizeDecision(decision) {
|
|
|
58
58
|
return decision === 'reject' ? 'redo' : decision;
|
|
59
59
|
}
|
|
60
60
|
|
|
61
|
+
/** Terminal control codes out of text a model wrote, before it reaches a terminal: C0 (incl. ESC, which starts
|
|
62
|
+
* every CSI/OSC sequence), DEL and C1 (incl. the one-byte CSI, U+009B). Keeps \n and \t. A stripped ESC leaves the
|
|
63
|
+
* sequence's printable tail ("[2J") visible, which is inert. */
|
|
64
|
+
export function stripControl(text) {
|
|
65
|
+
// eslint-disable-next-line no-control-regex
|
|
66
|
+
return String(text).replace(/[\x00-\x08\x0B-\x1F\x7F-\x9F]/g, '');
|
|
67
|
+
}
|
|
68
|
+
|
|
61
69
|
/** The one decision -> status table, used by `listArchivedAsks` here and by the panel's legacy-ask rows.
|
|
62
70
|
* Look it up with `normalizeDecision(decision)`. */
|
|
63
71
|
export const DECISION_STATUS = { accept: 'accepted', redo: 'redo', rerun: 'reran' };
|
|
64
72
|
|
|
73
|
+
/** The status for a decision word read from disk, or undefined for anything that is not one of the table's OWN
|
|
74
|
+
* entries ("constructor", "toString" and the rest of Object.prototype read as unrecognised). */
|
|
75
|
+
export function decisionStatus(decision) {
|
|
76
|
+
const word = normalizeDecision(decision);
|
|
77
|
+
return typeof word === 'string' && Object.hasOwn(DECISION_STATUS, word) ? DECISION_STATUS[word] : undefined;
|
|
78
|
+
}
|
|
79
|
+
|
|
65
80
|
function sleep(ms) {
|
|
66
81
|
return new Promise((resolve) => { setTimeout(resolve, ms); });
|
|
67
82
|
}
|
|
@@ -262,9 +277,171 @@ export function sha256Hex(serialised) {
|
|
|
262
277
|
return createHash('sha256').update(Buffer.from(serialised, 'utf8')).digest('hex');
|
|
263
278
|
}
|
|
264
279
|
|
|
280
|
+
/**
|
|
281
|
+
* M4c-fix amendment 1 (a): why a saved `answer.json` is not a usable answer for the open ask `openAskId`, or `null`
|
|
282
|
+
* when it is usable. The resume refuses each of these by name before it consumes the file, so without a way aside
|
|
283
|
+
* the file would block every new answer (`answerAsk`'s exclusive create).
|
|
284
|
+
* @param {string} text the file's text @param {string} openAskId
|
|
285
|
+
* @returns {string|null}
|
|
286
|
+
*/
|
|
287
|
+
export function brokenAnswerWhy(text, openAskId) {
|
|
288
|
+
let a;
|
|
289
|
+
try { a = JSON.parse(text); } catch { return 'it is not valid JSON'; }
|
|
290
|
+
if (a === null || typeof a !== 'object' || Array.isArray(a)) return 'it is not a JSON object';
|
|
291
|
+
if (a.askId !== openAskId) return `it names another ask ("${a.askId}")`;
|
|
292
|
+
if (Number.isNaN(Date.parse(typeof a.answeredAt === 'string' ? a.answeredAt : ''))) return 'it carries no readable saved time';
|
|
293
|
+
return null;
|
|
294
|
+
}
|
|
295
|
+
|
|
296
|
+
/**
|
|
297
|
+
* Move `answer.json` aside as a record: `answer.<askId>.<kind>.<n>.json`, `n` the first free number. Write-once:
|
|
298
|
+
* the new name is created with a hard link (`EEXIST` = taken, try the next), then the old name is removed — never
|
|
299
|
+
* a rename, which would overwrite; never a delete of the content. A symlinked `answer.json` is refused, not followed.
|
|
300
|
+
* @param {string} runDir @param {string} askId @param {'broken'|'late'} kind
|
|
301
|
+
* @returns {{ ok: true, name: string } | { ok: false, red: string }}
|
|
302
|
+
*/
|
|
303
|
+
export function setAsideAnswer(runDir, askId, kind) {
|
|
304
|
+
const resolved = resolveInside(runDir, 'answer.json');
|
|
305
|
+
if (!resolved.ok) return { ok: false, red: `answer.json cannot be set aside — ${'red' in resolved ? resolved.red : 'it is missing'}` };
|
|
306
|
+
for (let n = 1; n < 1000; n += 1) {
|
|
307
|
+
const name = `answer.${askId}.${kind}.${n}.json`;
|
|
308
|
+
try {
|
|
309
|
+
linkSync(resolved.full, join(runDir, name));
|
|
310
|
+
} catch (err) {
|
|
311
|
+
if (err.code === 'EEXIST') continue; // eslint-disable-line no-continue
|
|
312
|
+
return { ok: false, red: `answer.json could not be set aside — ${err.message}` };
|
|
313
|
+
}
|
|
314
|
+
try { unlinkSync(resolved.full); } catch { /* already moved by another process: the record exists either way */ }
|
|
315
|
+
return { ok: true, name };
|
|
316
|
+
}
|
|
317
|
+
return { ok: false, red: 'answer.json could not be set aside — no free record name' };
|
|
318
|
+
}
|
|
319
|
+
|
|
320
|
+
// ---------------------------------------------------------------------------
|
|
321
|
+
// M4c-fix amendment 1 (b): an expired ask can be reopened — by a human only. A reopen never rewrites `ask.json`,
|
|
322
|
+
// `state.json` or the archive (nothing existing is rewritten): it is a new write-once record,
|
|
323
|
+
// `reopen.<askId>.<n>.json` (`wx`, `n` = the next free number), holding who/when/the new deadline. The deadline of
|
|
324
|
+
// an ask is read in ONE place, `effectiveExpiresAt`: the newest reopen record for that askId, else the ask's own
|
|
325
|
+
// `expiresAt`. Every reader of a deadline (answerAsk, the resume, the panel, the CLI) goes through it.
|
|
326
|
+
// ---------------------------------------------------------------------------
|
|
327
|
+
|
|
328
|
+
const REOPEN_RE = /^reopen\.(.+)\.(\d+)\.json$/;
|
|
329
|
+
|
|
330
|
+
/**
|
|
331
|
+
* The deadline an ask is judged against: the newest valid reopen record's `expiresAt`, else `original`.
|
|
332
|
+
* A record that is unreadable, names another ask, or holds no parseable `expiresAt` is ignored.
|
|
333
|
+
* @param {string} runDir @param {string} askId @param {string} original the ask's own `expiresAt`
|
|
334
|
+
* @returns {string}
|
|
335
|
+
*/
|
|
336
|
+
export function effectiveExpiresAt(runDir, askId, original) {
|
|
337
|
+
let best = null;
|
|
338
|
+
for (const name of readdirInside(runDir, '.')) {
|
|
339
|
+
const m = REOPEN_RE.exec(name);
|
|
340
|
+
if (!m || m[1] !== askId) continue; // eslint-disable-line no-continue
|
|
341
|
+
const n = Number(m[2]);
|
|
342
|
+
if (best && best.n >= n) continue; // eslint-disable-line no-continue
|
|
343
|
+
const r = readFileInside(runDir, name);
|
|
344
|
+
if (!r.ok) continue; // eslint-disable-line no-continue
|
|
345
|
+
let rec;
|
|
346
|
+
try { rec = JSON.parse(r.text); } catch { continue; } // eslint-disable-line no-continue
|
|
347
|
+
if (rec === null || typeof rec !== 'object' || rec.askId !== askId || typeof rec.expiresAt !== 'string' || Number.isNaN(Date.parse(rec.expiresAt))) continue; // eslint-disable-line no-continue
|
|
348
|
+
best = { n, expiresAt: rec.expiresAt };
|
|
349
|
+
}
|
|
350
|
+
return best ? best.expiresAt : original;
|
|
351
|
+
}
|
|
352
|
+
|
|
353
|
+
/**
|
|
354
|
+
* An `ask.json`-shaped object as every reader should see it: `expiresAt` is the effective deadline, and `waitMs`
|
|
355
|
+
* is the signed wait the ask was parked with (its own `expiresAt` minus `askedAt`, written from the signed ttl),
|
|
356
|
+
* which a reopen repeats. `waitMs` is `null` when either time cannot be read.
|
|
357
|
+
* @param {string} runDir @param {any} ask
|
|
358
|
+
* @returns {any}
|
|
359
|
+
*/
|
|
360
|
+
export function withReopen(runDir, ask) {
|
|
361
|
+
if (ask === null || typeof ask !== 'object' || typeof ask.askId !== 'string') return ask;
|
|
362
|
+
const waitMs = Date.parse(ask.expiresAt) - Date.parse(ask.askedAt);
|
|
363
|
+
return {
|
|
364
|
+
...ask,
|
|
365
|
+
expiresAt: typeof ask.expiresAt === 'string' ? effectiveExpiresAt(runDir, ask.askId, ask.expiresAt) : ask.expiresAt,
|
|
366
|
+
waitMs: Number.isFinite(waitMs) && waitMs > 0 ? waitMs : null,
|
|
367
|
+
};
|
|
368
|
+
}
|
|
369
|
+
|
|
370
|
+
/**
|
|
371
|
+
* Reopen an expired ask: a fresh window of the same signed length, starting now, on the same ask (the same draft;
|
|
372
|
+
* nothing about the run changes). Human only — the caller names who (`by`); no runner, agent or resume path calls this.
|
|
373
|
+
* Refused, by name, when: there is no such open ask, its answer was already taken, it has not expired, or a saved
|
|
374
|
+
* answer made in time is waiting (that one is resumed, not reopened). A late or broken saved answer is moved aside
|
|
375
|
+
* as a record (`answer.<askId>.late.<n>.json`, never deleted). Two clicks race on the record's exclusive create:
|
|
376
|
+
* the loser is refused "already reopened", so a double click opens one window, not two.
|
|
377
|
+
* @param {{ runDir: string, askId: string, by: string, clock?: () => string }} opts
|
|
378
|
+
* @returns {{ ok: true, expiresAt: string, n: number, setAside: string|null } | { ok: false, red: string }}
|
|
379
|
+
*/
|
|
380
|
+
export function reopenAsk({
|
|
381
|
+
runDir, askId, by, clock,
|
|
382
|
+
}) {
|
|
383
|
+
const nowIso = (typeof clock === 'function' ? clock : () => new Date().toISOString())();
|
|
384
|
+
if (typeof runDir !== 'string' || runDir.length === 0) return { ok: false, red: 'reopenAsk: "runDir" must be a non-empty string' };
|
|
385
|
+
if (typeof askId !== 'string' || askId.length === 0) return { ok: false, red: 'reopenAsk: "askId" must be a non-empty string' };
|
|
386
|
+
if (typeof by !== 'string' || by.length === 0) return { ok: false, red: 'reopenAsk: "by" must name who reopened it' };
|
|
387
|
+
const askRead = readFileInside(runDir, 'ask.json');
|
|
388
|
+
if (!askRead.ok) return { ok: false, red: `reopenAsk: no open ask for run ${runDir}` };
|
|
389
|
+
let raw;
|
|
390
|
+
try { raw = JSON.parse(askRead.text); } catch (err) { return { ok: false, red: `reopenAsk: ask.json for run ${runDir} is not valid JSON — ${err.message}` }; }
|
|
391
|
+
if (raw === null || typeof raw !== 'object' || raw.askId !== askId) return { ok: false, red: `reopenAsk: askId "${askId}" is unknown for run ${runDir}` };
|
|
392
|
+
const ask = withReopen(runDir, raw);
|
|
393
|
+
if (Number.isNaN(Date.parse(ask.expiresAt))) return { ok: false, red: `reopenAsk: askId "${askId}" has an unparseable expiresAt — refusing` };
|
|
394
|
+
if (ask.waitMs === null) return { ok: false, red: `reopenAsk: askId "${askId}" carries no readable wait (askedAt/expiresAt) to repeat — refusing` };
|
|
395
|
+
if (existsSync(join(runDir, `answer.${askId}.consumed.json`))) return { ok: false, red: `reopenAsk: askId "${askId}" already answered for run ${runDir}` };
|
|
396
|
+
if (Date.parse(nowIso) <= Date.parse(ask.expiresAt)) return { ok: false, red: `reopenAsk: askId "${askId}" has not expired (it runs until ${ask.expiresAt})` };
|
|
397
|
+
const saved = readFileInside(runDir, 'answer.json');
|
|
398
|
+
let timing = null;
|
|
399
|
+
if (saved.ok) {
|
|
400
|
+
let a = null;
|
|
401
|
+
try { a = JSON.parse(saved.text); } catch { /* broken: set aside below */ }
|
|
402
|
+
timing = a !== null && typeof a === 'object' && a.askId === askId ? answerTiming(a.answeredAt, ask.expiresAt) : 'unreadable';
|
|
403
|
+
if (timing === 'on-time') return { ok: false, red: `reopenAsk: askId "${askId}" has an answer saved in time — resume it, it is not expired` };
|
|
404
|
+
}
|
|
405
|
+
// Amendment 3 (b): the stale answer is moved aside FIRST. If that fails nothing is written (no record, no audit
|
|
406
|
+
// row, the clock stays), so a stale answer can never count as fresh under a new deadline. If the record write then
|
|
407
|
+
// fails, the answer stays set aside: it was late or broken anyway, and the ask is simply still expired.
|
|
408
|
+
let setAside = null;
|
|
409
|
+
if (saved.ok) {
|
|
410
|
+
const moved = setAsideAnswer(runDir, askId, timing === 'late' ? 'late' : 'broken');
|
|
411
|
+
if (!moved.ok) return { ok: false, red: 'Could not clear the late answer; nothing was reopened.' };
|
|
412
|
+
setAside = moved.name;
|
|
413
|
+
}
|
|
414
|
+
// The record: write-once, keyed by askId and its number. The exclusive create is the one gate.
|
|
415
|
+
let n = 1;
|
|
416
|
+
for (const name of readdirInside(runDir, '.')) {
|
|
417
|
+
const m = REOPEN_RE.exec(name);
|
|
418
|
+
if (m && m[1] === askId) n = Math.max(n, Number(m[2]) + 1);
|
|
419
|
+
}
|
|
420
|
+
const expiresAt = new Date(Date.parse(nowIso) + ask.waitMs).toISOString();
|
|
421
|
+
const record = {
|
|
422
|
+
askId, n, by, at: nowIso, previousExpiresAt: ask.expiresAt, expiresAt, waitMs: ask.waitMs,
|
|
423
|
+
};
|
|
424
|
+
try {
|
|
425
|
+
writeFileSync(join(runDir, `reopen.${askId}.${n}.json`), JSON.stringify(record, null, 2), { flag: 'wx' });
|
|
426
|
+
} catch (err) {
|
|
427
|
+
if (err.code === 'EEXIST') return { ok: false, red: `reopenAsk: askId "${askId}" was already reopened (record ${n} exists)` };
|
|
428
|
+
return { ok: false, red: `reopenAsk: could not write the reopen record — ${err.message}` };
|
|
429
|
+
}
|
|
430
|
+
// The run's audit book names the reopen too (amendment 1 (b): "the audit records who reopened it and when"),
|
|
431
|
+
// through the one audit writer; a pure note (cost 0, no model), shaped like the stale-answer row.
|
|
432
|
+
appendAudit(runDir, {
|
|
433
|
+
step: 'ask', attempt: raw.attempt ?? null, class: null, verdict: 'ask-reopened',
|
|
434
|
+
gap: `reopened by ${by} at ${nowIso} (ask ${askId}); deadline ${ask.expiresAt} -> ${expiresAt}`,
|
|
435
|
+
usd: 0, spendComplete: true, wallMs: 0, model: null, modelMatch: null, strike: false, at: nowIso, tokens: null, tools: null, refused: [],
|
|
436
|
+
});
|
|
437
|
+
return {
|
|
438
|
+
ok: true, expiresAt, n, setAside,
|
|
439
|
+
};
|
|
440
|
+
}
|
|
441
|
+
|
|
265
442
|
/**
|
|
266
443
|
* @param {{ runDir: string, askId: string, decision: 'accept'|'redo'|'reject'|'rerun', reason?: string, clock?: () => string }} opts
|
|
267
|
-
* @returns {{ ok: true } | { ok: false, red: string }}
|
|
444
|
+
* @returns {{ ok: true, setAside: string|null } | { ok: false, red: string }}
|
|
268
445
|
*/
|
|
269
446
|
export function answerAsk({
|
|
270
447
|
runDir, askId, decision: givenDecision, reason, clock,
|
|
@@ -310,8 +487,10 @@ export function answerAsk({
|
|
|
310
487
|
if (Number.isNaN(Date.parse(ask.expiresAt))) {
|
|
311
488
|
return { ok: false, red: `answerAsk: askId "${askId}" has an unparseable expiresAt "${ask.expiresAt}" for run ${runDir} — refusing rather than treating it as not-expired` };
|
|
312
489
|
}
|
|
313
|
-
|
|
314
|
-
|
|
490
|
+
// The deadline is the reopened one when the ask was reopened (`effectiveExpiresAt`, the one reader).
|
|
491
|
+
const expiresAt = effectiveExpiresAt(runDir, askId, ask.expiresAt);
|
|
492
|
+
if (Date.parse(nowIso) > Date.parse(expiresAt)) {
|
|
493
|
+
return { ok: false, red: `answerAsk: askId "${askId}" expired at ${expiresAt} for run ${runDir}` };
|
|
315
494
|
}
|
|
316
495
|
|
|
317
496
|
const answerPath = join(runDir, 'answer.json');
|
|
@@ -349,6 +528,18 @@ export function answerAsk({
|
|
|
349
528
|
// the exclusive gate (fails EEXIST if the file already exists), so there
|
|
350
529
|
// is no window between "is it answered" and "answer it" for a second
|
|
351
530
|
// caller to land in.
|
|
531
|
+
// M4c-fix amendment 1 (a): a saved answer that is broken (not JSON, not an object, names another ask, no readable
|
|
532
|
+
// time) would block this write for good — it is moved aside as a record first (never deleted). Only a broken one.
|
|
533
|
+
let setAside = null;
|
|
534
|
+
const savedRead = readFileInside(runDir, 'answer.json');
|
|
535
|
+
if (savedRead.ok) {
|
|
536
|
+
const why = brokenAnswerWhy(savedRead.text, askId);
|
|
537
|
+
if (why !== null) {
|
|
538
|
+
const moved = setAsideAnswer(runDir, askId, 'broken');
|
|
539
|
+
if (!moved.ok) return { ok: false, red: `answerAsk: askId "${askId}" — a broken saved answer (${why}) is in the way — ${moved.red}` };
|
|
540
|
+
setAside = moved.name;
|
|
541
|
+
}
|
|
542
|
+
}
|
|
352
543
|
try {
|
|
353
544
|
writeFileSync(answerPath, JSON.stringify(payload, null, 2), { flag: 'wx' });
|
|
354
545
|
} catch (err) {
|
|
@@ -357,7 +548,7 @@ export function answerAsk({
|
|
|
357
548
|
}
|
|
358
549
|
return { ok: false, red: `answerAsk: could not write ${answerPath} — ${err.message}` };
|
|
359
550
|
}
|
|
360
|
-
return { ok: true };
|
|
551
|
+
return { ok: true, setAside };
|
|
361
552
|
}
|
|
362
553
|
|
|
363
554
|
// ---------------------------------------------------------------------------
|
|
@@ -538,7 +729,7 @@ export function listArchivedAsks(runDir) {
|
|
|
538
729
|
try {
|
|
539
730
|
parsed = JSON.parse(consumedRead.text);
|
|
540
731
|
answer = {
|
|
541
|
-
status:
|
|
732
|
+
status: decisionStatus(parsed.decision) ?? `unrecognised: ${parsed.decision}`,
|
|
542
733
|
answeredAt: parsed.answeredAt,
|
|
543
734
|
};
|
|
544
735
|
if (typeof parsed.reason === 'string') answer.reason = parsed.reason;
|
|
@@ -546,7 +737,7 @@ export function listArchivedAsks(runDir) {
|
|
|
546
737
|
answer = { status: 'open', why: `${join(runDir, consumedRelPath)} is not valid JSON — ${err.message}` };
|
|
547
738
|
}
|
|
548
739
|
} else if (typeof ask.expiresAt === 'string' && !Number.isNaN(Date.parse(ask.expiresAt))
|
|
549
|
-
&& Date.now() > Date.parse(ask.expiresAt)) {
|
|
740
|
+
&& Date.now() > Date.parse(effectiveExpiresAt(runDir, askId, ask.expiresAt))) {
|
|
550
741
|
answer = { status: 'expired' };
|
|
551
742
|
} else {
|
|
552
743
|
answer = { status: 'unanswered' };
|
|
@@ -556,7 +747,8 @@ export function listArchivedAsks(runDir) {
|
|
|
556
747
|
askId,
|
|
557
748
|
question: ask.question,
|
|
558
749
|
askedAt: ask.askedAt,
|
|
559
|
-
expiresAt: ask.expiresAt,
|
|
750
|
+
expiresAt: typeof ask.expiresAt === 'string' ? effectiveExpiresAt(runDir, askId, ask.expiresAt) : ask.expiresAt,
|
|
751
|
+
waitMs: withReopen(runDir, ask).waitMs ?? null,
|
|
560
752
|
evidence: readAskEvidence(ask),
|
|
561
753
|
answer,
|
|
562
754
|
...(typeof ask.emits === 'string' ? { emits: ask.emits } : {}),
|
package/src/authoring.js
CHANGED
|
@@ -15,7 +15,7 @@
|
|
|
15
15
|
|
|
16
16
|
import { createHash } from 'node:crypto';
|
|
17
17
|
import {
|
|
18
|
-
existsSync, mkdirSync, readFileSync, rmdirSync, writeFileSync,
|
|
18
|
+
existsSync, mkdirSync, readFileSync, realpathSync, rmdirSync, writeFileSync,
|
|
19
19
|
} from 'node:fs';
|
|
20
20
|
import path from 'node:path';
|
|
21
21
|
|
|
@@ -97,10 +97,13 @@ export const costText = (n, spendComplete = true) => {
|
|
|
97
97
|
const usd = costText;
|
|
98
98
|
|
|
99
99
|
/** Plain-text readout of what the human is about to sign. Pure. */
|
|
100
|
-
export function buildReadout({
|
|
100
|
+
export function buildReadout({
|
|
101
|
+
declaration, arbiter, lines, name, modelId, costUsd, rounds, spendComplete, root,
|
|
102
|
+
}) {
|
|
101
103
|
const out = [];
|
|
102
104
|
out.push(`DRAFT READOUT — NOT SIGNED — flow "${name}"`, '');
|
|
103
105
|
out.push(`Drafted by: ${modelId ?? '?'} in ${rounds} round(s), cost ${usd(costUsd, spendComplete)}`);
|
|
106
|
+
if (typeof root === 'string') out.push(`Flows root: ${root} (the flow is written to <flows root>/${name} when you sign)`);
|
|
104
107
|
out.push(`Cap per run (signed by you in the prose): $${arbiter.capUsd}`, '');
|
|
105
108
|
out.push('INPUTS');
|
|
106
109
|
for (const s of arbiter.sources) {
|
|
@@ -128,6 +131,20 @@ export function buildReadout({ declaration, arbiter, lines, name, modelId, costU
|
|
|
128
131
|
return `${out.join('\n')}\n`;
|
|
129
132
|
}
|
|
130
133
|
|
|
134
|
+
/** realpath of a path that may not exist yet: the real path of its nearest existing ancestor plus the rest. */
|
|
135
|
+
function realpathOfNew(p) {
|
|
136
|
+
const rest = [];
|
|
137
|
+
let cur = path.resolve(p);
|
|
138
|
+
for (;;) {
|
|
139
|
+
try { return path.join(realpathSync(cur), ...rest.reverse()); } catch (e) {
|
|
140
|
+
const up = path.dirname(cur);
|
|
141
|
+
if (up === cur || e.code === 'EACCES') return path.resolve(p);
|
|
142
|
+
rest.push(path.basename(cur));
|
|
143
|
+
cur = up;
|
|
144
|
+
}
|
|
145
|
+
}
|
|
146
|
+
}
|
|
147
|
+
|
|
131
148
|
/** Read the prose file. Refuses (a red, never a throw) on unreadable or blank. */
|
|
132
149
|
export function readProseFile(file) {
|
|
133
150
|
let text;
|
|
@@ -153,6 +170,13 @@ export async function draftToDir({
|
|
|
153
170
|
if (!nameCheck.ok) return refuse([nameCheck.red]);
|
|
154
171
|
if (typeof root !== 'string' || root === '') return refuse(['draft: --root <flows dir> is required']);
|
|
155
172
|
if (!(budgetUsd > 0)) return refuse(['draft: budget must be a positive number']);
|
|
173
|
+
// An unsigned draft folder inside the flows root would list as a flow in the panel and Inbox (checked by realpath, at use time).
|
|
174
|
+
const realRoot = realpathOfNew(root);
|
|
175
|
+
const realDir = realpathOfNew(dir);
|
|
176
|
+
const rel = path.relative(realRoot, realDir);
|
|
177
|
+
if (rel === '' || (rel !== '..' && !rel.startsWith(`..${path.sep}`) && !path.isAbsolute(rel))) {
|
|
178
|
+
return refuse([`draft: "${dir}" is inside the flows root "${root}" — an unsigned draft would show as a flow; use a --out outside the flows root`]);
|
|
179
|
+
}
|
|
156
180
|
const read = readProseFile(proseFile);
|
|
157
181
|
if (!read.ok) return refuse([String(read.red)]);
|
|
158
182
|
const prose = { text: String(read.text) };
|
|
@@ -164,6 +188,8 @@ export async function draftToDir({
|
|
|
164
188
|
}
|
|
165
189
|
const secrets = secretVar && env[secretVar] ? [env[secretVar]] : [];
|
|
166
190
|
if (secrets.some((s) => s.length >= 8 && prose.text.includes(s))) return refuse(['prose: contains an API key value — refused']);
|
|
191
|
+
// Red messages can echo what a provider's error body echoed (a key): scrubbed like every file, before anything prints them.
|
|
192
|
+
const cleanReds = (reds) => (reds ?? []).map((r) => scrub(String(r), secrets));
|
|
167
193
|
// Claim the dir BEFORE the paid round (exclusive mkdir: a race or an existing path refuses at $0).
|
|
168
194
|
const exists = () => refuse([`draft: "${dir}" already exists — never overwritten, use a new dir`]);
|
|
169
195
|
if (existsSync(dir)) return exists();
|
|
@@ -179,7 +205,7 @@ export async function draftToDir({
|
|
|
179
205
|
});
|
|
180
206
|
if (result.stop === 'pre-flight') {
|
|
181
207
|
try { rmdirSync(dir); } catch { /* the claimed dir is still empty; leave it rather than mask the refusal */ }
|
|
182
|
-
return refuse(result.reds);
|
|
208
|
+
return refuse(cleanReds(result.reds));
|
|
183
209
|
}
|
|
184
210
|
|
|
185
211
|
// After a paid round: never a silent throw. The cost is returned so the caller prints it; the dir is claimed and stays.
|
|
@@ -203,7 +229,7 @@ export async function draftToDir({
|
|
|
203
229
|
const declarationText = scrub(dj(result.declaration), secrets);
|
|
204
230
|
const inputFactsText = scrub(dj(result.declaration.inputFacts), secrets);
|
|
205
231
|
const readoutText = scrub(buildReadout({
|
|
206
|
-
declaration: result.declaration, arbiter: parsed.arbiter, lines: parsed.lines, name, modelId: result.modelId, costUsd: result.costUsd, rounds: result.rounds, spendComplete: result.spendComplete,
|
|
232
|
+
declaration: result.declaration, arbiter: parsed.arbiter, lines: parsed.lines, name, modelId: result.modelId, costUsd: result.costUsd, rounds: result.rounds, spendComplete: result.spendComplete, root,
|
|
207
233
|
}), secrets);
|
|
208
234
|
files['declaration.json'] = declarationText;
|
|
209
235
|
files['input-facts.json'] = inputFactsText;
|
|
@@ -244,7 +270,7 @@ export async function draftToDir({
|
|
|
244
270
|
return paidFail(`write failed after the paid round (${e.code ?? e.message}); the draft dir is incomplete and never signable`);
|
|
245
271
|
}
|
|
246
272
|
return {
|
|
247
|
-
ok: result.ok, wrote: true, dir, hash, reds: result.reds, costUsd: result.costUsd, spendComplete: result.spendComplete, stop: result.stop, rounds: result.rounds, calls: result.calls, leaks: 0,
|
|
273
|
+
ok: result.ok, wrote: true, dir, hash, reds: cleanReds(result.reds), costUsd: result.costUsd, spendComplete: result.spendComplete, stop: result.stop, rounds: result.rounds, calls: result.calls, leaks: 0,
|
|
248
274
|
};
|
|
249
275
|
}
|
|
250
276
|
|
package/src/liveness.js
CHANGED
|
@@ -118,22 +118,22 @@ export const LOCK_NO_HOLDER = 'with no recorded holder';
|
|
|
118
118
|
* unknown - liveness cannot be told (no /proc): never treated as dead
|
|
119
119
|
* empty - a lock with no readable holder (pre-amendment resumer, torn write)
|
|
120
120
|
* @param {string} runDir
|
|
121
|
-
* @returns {{state: 'none'|'live'|'dead'|'unknown'|'empty', pid: number|null, path: string}}
|
|
121
|
+
* @returns {{state: 'none'|'live'|'dead'|'unknown'|'empty', pid: number|null, procStart: string|null, path: string}}
|
|
122
122
|
*/
|
|
123
123
|
export function readResumeLock(runDir) {
|
|
124
124
|
const path = join(runDir, 'resume.lock');
|
|
125
125
|
let st;
|
|
126
|
-
try { st = lstatSync(path); } catch { return { state: 'none', pid: null, path }; }
|
|
127
|
-
if (!st.isFile()) return { state: 'empty', pid: null, path };
|
|
126
|
+
try { st = lstatSync(path); } catch { return { state: 'none', pid: null, procStart: null, path }; }
|
|
127
|
+
if (!st.isFile()) return { state: 'empty', pid: null, procStart: null, path };
|
|
128
128
|
let h;
|
|
129
|
-
try { h = JSON.parse(readFileSync(path, 'utf8')); } catch { return { state: 'empty', pid: null, path }; }
|
|
130
|
-
if (!h || !Number.isInteger(h.pid) || h.pid <= 0) return { state: 'empty', pid: null, path };
|
|
129
|
+
try { h = JSON.parse(readFileSync(path, 'utf8')); } catch { return { state: 'empty', pid: null, procStart: null, path }; }
|
|
130
|
+
if (!h || !Number.isInteger(h.pid) || h.pid <= 0) return { state: 'empty', pid: null, procStart: null, path };
|
|
131
131
|
const procStart = typeof h.procStart === 'string' ? h.procStart : null;
|
|
132
132
|
// This very process holds it (two resumeRun calls in one process): alive by definition,
|
|
133
133
|
// whatever its command line says.
|
|
134
|
-
if (h.pid === process.pid && procStart === procStartOf('self')) return { state: 'live', pid: h.pid, path };
|
|
134
|
+
if (h.pid === process.pid && procStart === procStartOf('self')) return { state: 'live', pid: h.pid, procStart, path };
|
|
135
135
|
const alive = isFwdloopAlive(h.pid, procStart);
|
|
136
|
-
return { state: alive === true ? 'live' : alive === false ? 'dead' : 'unknown', pid: h.pid, path };
|
|
136
|
+
return { state: alive === true ? 'live' : alive === false ? 'dead' : 'unknown', pid: h.pid, procStart, path };
|
|
137
137
|
}
|
|
138
138
|
|
|
139
139
|
/** The run's books, for the 10-minute fallback: state, audit, model log, spend ledger, and the pid file itself. */
|
package/src/model-step.js
CHANGED
|
@@ -251,11 +251,12 @@ export function makeLiveModelStep({
|
|
|
251
251
|
({ provider, rates, modelId } = makeProvider(slot, { model, ...LIVE_PROVIDER_OPTIONS }));
|
|
252
252
|
} catch (err) {
|
|
253
253
|
// No provider was ever built, so no round could possibly have run —
|
|
254
|
-
// `tokens: null`
|
|
254
|
+
// `model: null`, `tokens: null` and `tools: null` (M4a-3) here are the one honest
|
|
255
255
|
// "no model call at all" case (never a zeroed object standing in for
|
|
256
|
-
// a call that never happened).
|
|
256
|
+
// a call that never happened). A row that names a model must carry its
|
|
257
|
+
// tokens (appendAudit refuses it otherwise), so the model is not named.
|
|
257
258
|
return {
|
|
258
|
-
ok: false, red: `key: ${err.message}`, costUsd: null, model:
|
|
259
|
+
ok: false, red: `key: ${err.message}`, costUsd: null, model: null, tokens: null, tools: null,
|
|
259
260
|
};
|
|
260
261
|
}
|
|
261
262
|
}
|