@plimsollmark/client 0.28.0 → 0.29.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/README.md CHANGED
@@ -57,7 +57,7 @@ import { PlimsollClient } from "@plimsollmark/client";
57
57
 
58
58
  const plimsoll = new PlimsollClient({ baseUrl: "https://plimsoll.internal:8443", token: process.env.PLIMSOLL_TOKEN });
59
59
 
60
- const info = await plimsoll.describe(); // provider, tier, supportsSessions, ...
60
+ const info = await plimsoll.describe(); // sandbox, isolation, supportsSessions, ...
61
61
  const r = await plimsoll.runJavaScript("console.log(6 * 7)", { minimumIsolation: "container", timeoutMs: 10_000 });
62
62
  r.stdout; // "42\n"; a non-zero r.exitCode is a normal result, not an error
63
63
 
@@ -107,18 +107,26 @@ await t.runCell({ language: "python", code: "x" }); // the same interpreter
107
107
  is `CheckpointMismatchError`, and nothing moves. An answer that does not repeat the
108
108
  checkpoint is `data_loss`, and the session is not closed. A failed or aborted attach is
109
109
  never retried.
110
+ - Every call states the head it expects to run on (the generation, the count of calls and
111
+ the last record), and the daemon runs it only on that head. A call refused because the
112
+ daemon's head is another (`HeadMismatchError`, marked not dispatched, with the daemon's
113
+ head) means another holder of the session ran a call between this client's: the session
114
+ stops and sends nothing more.
110
115
  - **A call whose answer was lost.** After a call ends with no answer this client could
111
116
  check, `session.lostRequestSha256` names it. `attachSession(checkpoint, {
112
117
  lostRequestSha256 })` from the checkpoint saved before that call then takes the session
113
118
  over across that one call (the *explained gap*), when the daemon's last record is that
114
- call, and `session.lostCall` holds its record; its output is lost. The record says whether
115
- the daemon answered it: a result digest when the daemon answered, which does not show that
116
- the call ran to its end (a step stopped at its time limit and a setup that failed are
117
- answers too), an `unanswered` code when it ended without an answer, so that it may have
118
- done none, part or all of its work. The new session's first call is refused, with nothing sent, if it repeats that
119
- call, which was already sent once (`CallAlreadySentError`). Only the first call is checked,
120
- so a different first call spends the check and the lost call can then run again; the rule
121
- is this client's, not the daemon's.
119
+ call. The new session is *recovering*: every call is refused before it is sent
120
+ (`RecoveringError`) until you have read `session.lostCall` and called
121
+ `session.resolveLostCall()`. `lostCall.record` says whether the daemon answered the call:
122
+ a result digest when it answered, which does not show that the call ran to its end (a
123
+ step stopped at its time limit and a setup that failed are answers too), an `unanswered`
124
+ code when it ended without an answer, so that it may have done none, part or all of its
125
+ work. `lostCall.answer` is the call's result when the daemon kept it (it keeps the last
126
+ answer in memory until the next call starts or the session suspends or ends, unless the
127
+ session was opened with `keepNoAnswer: true`), checked against the record. A checkpoint
128
+ saved while recovering carries the state (`recoveringRequestSha256`), so the worker that
129
+ attaches from it is recovering too, knowing the lost call by its request digest alone.
122
130
  - **The limit:** with no store, this client can name a lost call only when the answer was
123
131
  lost in the same process. A process that died mid-call leaves a gap the next one cannot
124
132
  explain unless your application recorded the call's request digest before sending.
@@ -18,13 +18,14 @@ export type SessionCheckpoint = {
18
18
  expiresUnixMs: number;
19
19
  idleTimeoutMs: number;
20
20
  /**
21
- * The request digest of a call that was sent once with no answer reaching any worker (an
22
- * attach explained the gap it left), which the session's next call is refused for
23
- * repeating (CallAlreadySentError); "" for none. A checkpoint carries it until that next
24
- * call, unless the daemon refused that call with the not-dispatched mark: nothing ran, so
25
- * the call after it is still the next.
21
+ * The request digest of the lost call the session was recovering from when the
22
+ * checkpoint was saved (session.lostCall), "" when it was not recovering. A session
23
+ * attached from such a checkpoint is recovering too: every call is refused before it is
24
+ * sent (RecoveringError) until session.resolveLostCall(). It knows the lost call by this
25
+ * digest alone; the record and the answer stayed with the worker that attached across
26
+ * the gap. The head (calls, lastRecordSha256) already counts the lost call.
26
27
  */
27
- lostCallSha256: string;
28
+ recoveringRequestSha256: string;
28
29
  };
29
30
  /** @internal Whether name is a daemon name: 1 to 64 of [A-Za-z0-9._-], never a URL. */
30
31
  export declare function validDaemonName(name: unknown): name is string;
@@ -58,8 +58,9 @@ export function checkpointProblem(cp) {
58
58
  return "the expiry is not a positive time";
59
59
  if (!whole(cp.idleTimeoutMs, 0, 2 ** 32 - 1))
60
60
  return "the idle timeout is not a 32-bit number";
61
- if (typeof cp.lostCallSha256 !== "string" || (cp.lostCallSha256 !== "" && (!HEX64.test(cp.lostCallSha256) || cp.calls === 0n))) {
62
- return "the lost call is not a request digest of a call the session ran";
61
+ const rec = cp.recoveringRequestSha256;
62
+ if (typeof rec !== "string" || (rec !== "" && (!HEX64.test(rec) || cp.calls === 0n))) {
63
+ return "the lost call it recovers from is not a request digest of a call the session ran";
63
64
  }
64
65
  return undefined;
65
66
  }
@@ -88,7 +89,7 @@ const KEYS = [
88
89
  ["open_rule", "openRule"],
89
90
  ["expires_unix_ms", "expiresUnixMs"],
90
91
  ["idle_timeout_ms", "idleTimeoutMs"],
91
- ["lost_call_sha256", "lostCallSha256"],
92
+ ["recovering_request_sha256", "recoveringRequestSha256"],
92
93
  ];
93
94
  /**
94
95
  * The JSON form every official client reads: these snake_case keys, every one present,
package/dist/client.d.ts CHANGED
@@ -264,8 +264,52 @@ export type SessionOptions = {
264
264
  * call needs no session of its own: runCell with preferWarm.
265
265
  */
266
266
  warmOnly?: boolean;
267
+ /**
268
+ * Ask the daemon to keep no call's answer. By default it keeps the last answered call's
269
+ * answer in memory, until the next call starts or the session suspends or ends, so that
270
+ * a worker taking the session over across that call's lost answer gets it back
271
+ * (session.lostCall.answer). Set it when the application promises its users that the
272
+ * daemon retains no output; it holds for the whole session.
273
+ */
274
+ keepNoAnswer?: boolean;
267
275
  signal?: AbortSignal;
268
276
  };
277
+ /**
278
+ * A call that was sent once and whose answer never reached the worker that sent it, as a
279
+ * session taken over across it knows it (session.lostCall; Go: client.LostCall).
280
+ */
281
+ export type LostCall = {
282
+ /** The lost call's request digest. */
283
+ requestSha256: string;
284
+ /**
285
+ * The lost call's record, as the attach returned it and this client checked it, or
286
+ * undefined on a session attached from a checkpoint saved while recovering, which carries
287
+ * the request digest alone. It says whether the daemon answered the call: a result digest
288
+ * when it answered, which does not show that the call ran to its end (a step stopped at
289
+ * its time limit and a setup that failed are answers too), or an unanswered code when it
290
+ * ended without an answer, so that it may have done none, part or all of its work.
291
+ */
292
+ record?: RunRecord;
293
+ /**
294
+ * The lost call's answer when the daemon kept it and the attach returned it, checked
295
+ * against record (the same record, its result digest recomputed), or undefined: the call
296
+ * ended unanswered, the answer was above the daemon's cap, the session was opened with
297
+ * keepNoAnswer, or the daemon dropped it (a call started, or the session suspended,
298
+ * after the lost one).
299
+ */
300
+ answer?: LostAnswer;
301
+ };
302
+ /** A lost call's answer, by the kind of call it was: the result that call would have returned. */
303
+ export type LostAnswer = {
304
+ kind: "javascript";
305
+ result: JavaScriptResult;
306
+ } | {
307
+ kind: "project";
308
+ result: ProjectResult;
309
+ } | {
310
+ kind: "cell";
311
+ result: CellResult;
312
+ };
269
313
  /**
270
314
  * What an owner is sent as: hex(HMAC-SHA256(key = SHA-256("plimsoll session owner key
271
315
  * v2\n" + the client's token), message = "plimsoll session owner v2\n" + owner)), the
@@ -369,11 +413,15 @@ export declare class PlimsollClient {
369
413
  * answer reaching it (session.lostRequestSha256 gives it for a call of this process).
370
414
  * With it, the daemon takes the session over from a checkpoint exactly one call behind
371
415
  * its head when its last record is that call, following cp (the explained gap), and
372
- * returns the record; it must check on its own, be the call named, at cp's next place,
373
- * stating the evidence the session stated at open, and be the new head
374
- * (session.lostCall). The attached session then refuses its first call if it repeats
375
- * that call (CallAlreadySentError). A lost call's record the attach did not name is refused
376
- * as data_loss.
416
+ * returns the record, and the call's answer when the daemon still keeps it. The record
417
+ * must check on its own, be the call named, at cp's next place, stating the evidence the
418
+ * session stated at open, and be the new head; the answer must carry that same record
419
+ * and a result whose digest is the record's. A lost call's record the attach did not
420
+ * name, and a lost answer with no lost record, are refused as data_loss.
421
+ *
422
+ * A session attached across a lost call, or from a checkpoint saved while recovering, is
423
+ * recovering: session.lostCall says what it knows of the lost call, and every call is
424
+ * refused before it is sent (RecoveringError) until session.resolveLostCall().
377
425
  */
378
426
  attachSession(cp: SessionCheckpoint, opts?: {
379
427
  traceId?: string;
@@ -419,8 +467,7 @@ export declare class Session {
419
467
  generation: bigint;
420
468
  calls: bigint;
421
469
  last: string;
422
- lostCall: string;
423
- lostRecord: RunRecord | undefined;
470
+ recovering: LostCall | undefined;
424
471
  });
425
472
  /**
426
473
  * Why this client sends nothing more on the session, once a call ended without an
@@ -434,19 +481,27 @@ export declare class Session {
434
481
  */
435
482
  get lostRequestSha256(): string;
436
483
  /**
437
- * The record of the call that was sent once and whose answer was lost, on a session attached
438
- * across an explained gap; its output is lost. The record says whether the daemon answered
439
- * it: a result digest when the daemon answered, which does not show that the call ran to its
440
- * end (a step stopped at its time limit and a setup that failed are answers too), an
441
- * unanswered code when it ended without an answer, so that it may have done none, part or all
442
- * of its work.
484
+ * The call this session is recovering from, or undefined when it is not recovering: after
485
+ * an attach across an explained gap (attachSession with lostRequestSha256), or from a
486
+ * checkpoint saved while recovering, until resolveLostCall(). While it is defined every
487
+ * call is refused before it is sent (RecoveringError). Its record says whether the daemon
488
+ * answered the call, and its answer, when the daemon kept it, is that call's result.
489
+ */
490
+ get lostCall(): LostCall | undefined;
491
+ /**
492
+ * Ends the recovering state: the application has read the lost call (lostCall) and
493
+ * handled its outcome, or accepts it as unknown, and the session's calls are sent again.
494
+ * Taking the session over, or copying its head, does not resolve it. On a session that is
495
+ * not recovering it does nothing (Go: Session.ResolveLostCall).
443
496
  */
444
- get lostCall(): RunRecord | undefined;
497
+ resolveLostCall(): void;
445
498
  /**
446
499
  * The session's checkpoint (Go: Session.Checkpoint), for the application to save where
447
500
  * only it can write, so another process can attachSession. It waits for a call in
448
501
  * flight, so the head it states follows that call. Refused when the client has no
449
- * daemonName and when the session is stopped, closed or ended.
502
+ * daemonName and when the session is stopped, closed or ended. A session recovering from
503
+ * a lost call saves that state (recoveringRequestSha256), so the worker that attaches
504
+ * from it is recovering too.
450
505
  */
451
506
  checkpoint(): Promise<SessionCheckpoint>;
452
507
  /** The session's end once a response reported it, else undefined. */
package/dist/client.js CHANGED
@@ -6,11 +6,11 @@
6
6
  // records so a call it did not make is caught.
7
7
  import { createHash, createHmac, randomBytes } from "node:crypto";
8
8
  import { isIP } from "node:net";
9
- import { checkRecord, checkUnanswered, recordDigest, recordFromWire, requestDigest, sessionFingerprint, softwareRuleAllows, softwareRuleId, statesOnlyProblem, } from "./record.js";
10
- import { CALL_ALREADY_SENT_TEXT, LANGUAGES, MAX_RESPONSE_BYTES, MAX_SOFTWARE_IDENTITIES, MAX_SOFTWARE_IDENTITY_BYTES, NOT_DISPATCHED_HEADER, OUTCOME_NAMES, PROTOCOL, RECORD_VERSION, REQUEST_ID_HEADER, SOFTWARE_IDENTITY_PATTERN, TIERS, } from "./tables.gen.js";
9
+ import { checkLostAnswer, checkRecord, checkUnanswered, recordDigest, recordFromWire, requestDigest, sessionFingerprint, softwareRuleAllows, softwareRuleId, statesOnlyProblem, } from "./record.js";
10
+ import { LANGUAGES, MAX_RESPONSE_BYTES, MAX_SOFTWARE_IDENTITIES, MAX_SOFTWARE_IDENTITY_BYTES, NOT_DISPATCHED_HEADER, OUTCOME_NAMES, CHECKPOINT_VERSION, PROTOCOL, RECORD_VERSION, RECOVERING_TEXT, REQUEST_ID_HEADER, SOFTWARE_IDENTITY_PATTERN, TIERS, } from "./tables.gen.js";
11
11
  import { checkpointProblem, validDaemonName } from "./checkpoint.js";
12
- import { CallAlreadySentError, errorFromWire, PlimsollError, sessionEndFromWire, StaleOwnerError, unboundSuccess } from "./errors.js";
13
- import { trailing, wireBytes } from "./wire.js";
12
+ import { errorFromWire, HeadMismatchError, PlimsollError, RecoveringError, sessionEndFromWire, StaleOwnerError, unboundSuccess, } from "./errors.js";
13
+ import { INT64, trailing, UINT32, UINT64, wholeInt, wireBytes } from "./wire.js";
14
14
  // PROTOCOL, the wire protocol number this client speaks, and MAX_RESPONSE_BYTES, above the
15
15
  // largest legitimate project response so a misbehaving daemon cannot make the client buffer
16
16
  // without bound, are generated from the Go protocol and client packages (tables.gen.ts).
@@ -444,6 +444,9 @@ export class PlimsollClient {
444
444
  if (opts.warmOnly !== undefined && typeof opts.warmOnly !== "boolean") {
445
445
  throw new PlimsollError("invalid_argument", "plimsoll: warmOnly must be a boolean", { notDispatched: "request" });
446
446
  }
447
+ if (opts.keepNoAnswer !== undefined && typeof opts.keepNoAnswer !== "boolean") {
448
+ throw new PlimsollError("invalid_argument", "plimsoll: keepNoAnswer must be a boolean", { notDispatched: "request" });
449
+ }
447
450
  const m = await this.call("OpenSession", {
448
451
  protocol: PROTOCOL,
449
452
  minimumIsolation: opts.minimumIsolation,
@@ -454,6 +457,7 @@ export class PlimsollClient {
454
457
  languages: opts.languages?.length ? [...new Set(opts.languages)] : undefined,
455
458
  owner: opts.owner === undefined ? undefined : ownerDigest(this.token, opts.owner),
456
459
  warmOnly: opts.warmOnly || undefined,
460
+ keepNoAnswer: opts.keepNoAnswer || undefined,
457
461
  }, opts.signal);
458
462
  const s = decoded(() => new Session(this, m, rule, opts.minimumIsolation));
459
463
  if (m.generation !== "1" && m.generation !== 1) {
@@ -461,6 +465,11 @@ export class PlimsollClient {
461
465
  await s.close().catch(() => undefined);
462
466
  throw new PlimsollError("data_loss", "plimsoll: the daemon's answer to the open states an ownership generation other than 1; the session was closed");
463
467
  }
468
+ if (wholeInt(m.expiresUnixMs, INT64) === undefined || wholeInt(m.idleTimeoutMs, UINT32) === undefined) {
469
+ // A checkpoint states both, and an attach answer must repeat them exactly.
470
+ await s.close().catch(() => undefined);
471
+ throw new PlimsollError("data_loss", "plimsoll: the daemon's answer to the open states an expiry or idle timeout that is not one whole decimal; the session was closed");
472
+ }
464
473
  if (decoded(() => s.fingerprint !== sessionFingerprint(m.sessionId ?? ""))) {
465
474
  // The session exists on the daemon either way, and nothing else holds its ID.
466
475
  await s.close().catch(() => undefined);
@@ -503,11 +512,15 @@ export class PlimsollClient {
503
512
  * answer reaching it (session.lostRequestSha256 gives it for a call of this process).
504
513
  * With it, the daemon takes the session over from a checkpoint exactly one call behind
505
514
  * its head when its last record is that call, following cp (the explained gap), and
506
- * returns the record; it must check on its own, be the call named, at cp's next place,
507
- * stating the evidence the session stated at open, and be the new head
508
- * (session.lostCall). The attached session then refuses its first call if it repeats
509
- * that call (CallAlreadySentError). A lost call's record the attach did not name is refused
510
- * as data_loss.
515
+ * returns the record, and the call's answer when the daemon still keeps it. The record
516
+ * must check on its own, be the call named, at cp's next place, stating the evidence the
517
+ * session stated at open, and be the new head; the answer must carry that same record
518
+ * and a result whose digest is the record's. A lost call's record the attach did not
519
+ * name, and a lost answer with no lost record, are refused as data_loss.
520
+ *
521
+ * A session attached across a lost call, or from a checkpoint saved while recovering, is
522
+ * recovering: session.lostCall says what it knows of the lost call, and every call is
523
+ * refused before it is sent (RecoveringError) until session.resolveLostCall().
511
524
  */
512
525
  async attachSession(cp, opts = {}) {
513
526
  const problem = checkpointProblem(cp);
@@ -531,33 +544,47 @@ export class PlimsollClient {
531
544
  return decoded(() => this.attached(cp, m, lost));
532
545
  }
533
546
  // The attached session, once the answer repeats the checkpoint exactly, or carries the
534
- // record of the call lost names at the checkpoint's next place and a head after it.
547
+ // record of the call lost names at the checkpoint's next place and a head after it (and,
548
+ // beside that record, the call's answer, when the daemon kept it).
535
549
  attached(cp, m, lost) {
536
550
  const info = m.sessionInfo;
537
551
  const head = m.checkpoint;
538
552
  let problem;
553
+ let recovering = cp.recoveringRequestSha256 ? { requestSha256: cp.recoveringRequestSha256 } : undefined;
539
554
  let lostCall;
540
- if (m.lostRecord) {
555
+ if (m.lostAnswer !== undefined && m.lostAnswer !== null && !m.lostRecord) {
556
+ problem = "carries a lost call's answer without the lost call's record";
557
+ }
558
+ else if (m.lostRecord) {
541
559
  const checked = lostRecord(cp, lost, m.lostRecord);
542
560
  if ("problem" in checked)
543
561
  problem = checked.problem;
544
- else
562
+ else {
545
563
  lostCall = checked.record;
564
+ recovering = { requestSha256: lostCall.requestSha256, record: lostCall };
565
+ if (m.lostAnswer !== undefined && m.lostAnswer !== null) {
566
+ const answer = checkLostAnswer(m.lostAnswer, lostCall);
567
+ if ("problem" in answer)
568
+ problem = `carries a lost call's answer that does not check against its record (${answer.problem})`;
569
+ else
570
+ recovering.answer = lostAnswerResult(m.lostAnswer, lostCall, answer.kind);
571
+ }
572
+ }
546
573
  }
547
574
  const calls = lostCall ? lostCall.sequence : cp.calls;
548
575
  const last = lostCall ? lostCall.sha256 : cp.lastRecordSha256;
549
576
  if (problem) {
550
- // the lost call's record does not check
577
+ // the lost call's record or answer does not check
551
578
  }
552
579
  else if (!info || !head)
553
580
  problem = "lacks the session or its checkpoint";
554
581
  else if ((info.session ?? "") !== cp.session || sessionFingerprint(info.sessionId ?? "") !== cp.session) {
555
582
  problem = "names another session, or a session ID whose SHA-256 is not the fingerprint";
556
583
  }
557
- else if (BigInt(info.generation ?? 0) !== cp.generation + 1n || BigInt(head.generation ?? 0) !== cp.generation + 1n) {
584
+ else if (wholeInt(info.generation, UINT64) !== cp.generation + 1n || wholeInt(head.generation, UINT64) !== cp.generation + 1n) {
558
585
  problem = "states a generation other than one past the checkpoint's";
559
586
  }
560
- else if (BigInt(head.calls ?? 0) !== calls || (head.lastRecordSha256 ?? "") !== last) {
587
+ else if (wholeInt(head.calls, UINT64) !== calls || (head.lastRecordSha256 ?? "") !== last) {
561
588
  problem = "states another chain head than the checkpoint's (or, across an explained gap, than the lost call's)";
562
589
  }
563
590
  else if ((info.sandbox ?? "") !== cp.provider || (info.isolation ?? "") !== cp.isolation ||
@@ -567,20 +594,14 @@ export class PlimsollClient {
567
594
  else if ((info.minimumIsolation ?? "") !== cp.openFloor || wireRuleId(info.softwareRule) !== cp.openRule) {
568
595
  problem = "states another floor or software rule than the session was opened with";
569
596
  }
570
- else if (num(info.expiresUnixMs) !== cp.expiresUnixMs || (info.idleTimeoutMs ?? 0) !== cp.idleTimeoutMs) {
597
+ else if (wholeInt(info.expiresUnixMs, INT64) !== BigInt(cp.expiresUnixMs) || wholeInt(info.idleTimeoutMs, UINT32) !== BigInt(cp.idleTimeoutMs)) {
571
598
  problem = "states another lifetime or idle timeout than the session's";
572
599
  }
573
600
  if (problem || !info)
574
601
  throw new PlimsollError("data_loss", `plimsoll: the daemon's answer to the attach ${problem}; the session was left as it is`);
575
602
  const rule = cp.openRule && info.softwareRule ? { mode: info.softwareRule.mode, identities: [...info.softwareRule.identities] } : undefined;
576
603
  const floor = cp.openFloor === "" ? undefined : cp.openFloor;
577
- return new Session(this, info, rule, floor, {
578
- generation: cp.generation + 1n,
579
- calls,
580
- last,
581
- lostCall: lostCall ? lostCall.requestSha256 : cp.lostCallSha256,
582
- lostRecord: lostCall,
583
- });
604
+ return new Session(this, info, rule, floor, { generation: cp.generation + 1n, calls, last, recovering });
584
605
  }
585
606
  /** @internal */
586
607
  envelope(opts, rule) {
@@ -634,6 +655,15 @@ export function lostRecord(cp, lost, m) {
634
655
  }
635
656
  return { record: r };
636
657
  }
658
+ // A lost call's checked answer as the result its kind maps to, as the call would have
659
+ // returned it.
660
+ function lostAnswerResult(resp, record, kind) {
661
+ if (kind === "javascript")
662
+ return { kind, result: javascriptResult(resp, record) };
663
+ if (kind === "project")
664
+ return { kind, result: projectResult(resp, record) };
665
+ return { kind, result: cellResult(resp, record) };
666
+ }
637
667
  // The ID of a software rule as the daemon sent it, "" for none; a rule this client would
638
668
  // not send (an unknown mode, a malformed identity) has an ID no checkpoint states.
639
669
  function wireRuleId(r) {
@@ -718,14 +748,16 @@ export class Session {
718
748
  // Set once the daemon refused a call or close because another worker attached the
719
749
  // session: this worker must not use it again.
720
750
  #stale;
751
+ // Set once the daemon refused a call because the head it carried is not the session's
752
+ // (HeadMismatchError): the chain this client tracks no longer follows the daemon's.
753
+ #diverged;
721
754
  // Set once the daemon answered this client's close.
722
755
  #closed = false;
723
- // The request digest the session's next call is refused for repeating, set by an attach
724
- // across an explained gap (or inherited with a checkpoint) and spent by the next call;
725
- // the record of that lost call; and the request digest of the call after which this
726
- // session stopped with no answer it could check.
727
- #lostCall = "";
728
- #lostRecord;
756
+ // The lost call this session is recovering from, set by an attach across an explained
757
+ // gap or from a checkpoint saved while recovering: while it is set every call is refused
758
+ // before anything is sent, until resolveLostCall(). And the request digest of the call
759
+ // after which this session stopped with no answer it could check.
760
+ #recovering;
729
761
  #lostRequest = "";
730
762
  #queue = Promise.resolve();
731
763
  #closing;
@@ -740,8 +772,7 @@ export class Session {
740
772
  if (attached) {
741
773
  this.#calls = attached.calls;
742
774
  this.#last = attached.last;
743
- this.#lostCall = attached.lostCall;
744
- this.#lostRecord = attached.lostRecord;
775
+ this.#recovering = attached.recovering;
745
776
  }
746
777
  this.#rule = rule;
747
778
  this.#floor = floor;
@@ -750,15 +781,17 @@ export class Session {
750
781
  this.isolationQualification = m.isolationQualification ?? "";
751
782
  this.sandbox = m.sandbox ?? "";
752
783
  this.softwareIdentity = m.softwareIdentity ?? "";
753
- this.expiresAtMs = num(m.expiresUnixMs);
754
- this.idleTimeoutMs = m.idleTimeoutMs ?? 0;
784
+ // openSession refuses an answer whose expiry or idle timeout is not one whole decimal,
785
+ // after closing the session with this one; attached() compares both with the checkpoint.
786
+ this.expiresAtMs = Number(wholeInt(m.expiresUnixMs, INT64) ?? 0n);
787
+ this.idleTimeoutMs = Number(wholeInt(m.idleTimeoutMs, UINT32) ?? 0n);
755
788
  }
756
789
  /**
757
790
  * Why this client sends nothing more on the session, once a call ended without an
758
791
  * answer it could check (the call may have run); undefined while it is usable.
759
792
  */
760
793
  get stopped() {
761
- return this.#stale ?? this.#unknown;
794
+ return this.#stale ?? this.#unknown ?? this.#diverged;
762
795
  }
763
796
  /**
764
797
  * The request digest of the call after which this session stopped with no answer it could
@@ -769,21 +802,32 @@ export class Session {
769
802
  return this.#lostRequest;
770
803
  }
771
804
  /**
772
- * The record of the call that was sent once and whose answer was lost, on a session attached
773
- * across an explained gap; its output is lost. The record says whether the daemon answered
774
- * it: a result digest when the daemon answered, which does not show that the call ran to its
775
- * end (a step stopped at its time limit and a setup that failed are answers too), an
776
- * unanswered code when it ended without an answer, so that it may have done none, part or all
777
- * of its work.
805
+ * The call this session is recovering from, or undefined when it is not recovering: after
806
+ * an attach across an explained gap (attachSession with lostRequestSha256), or from a
807
+ * checkpoint saved while recovering, until resolveLostCall(). While it is defined every
808
+ * call is refused before it is sent (RecoveringError). Its record says whether the daemon
809
+ * answered the call, and its answer, when the daemon kept it, is that call's result.
778
810
  */
779
811
  get lostCall() {
780
- return this.#lostRecord;
812
+ const lc = this.#recovering;
813
+ return lc === undefined ? undefined : { ...lc };
814
+ }
815
+ /**
816
+ * Ends the recovering state: the application has read the lost call (lostCall) and
817
+ * handled its outcome, or accepts it as unknown, and the session's calls are sent again.
818
+ * Taking the session over, or copying its head, does not resolve it. On a session that is
819
+ * not recovering it does nothing (Go: Session.ResolveLostCall).
820
+ */
821
+ resolveLostCall() {
822
+ this.#recovering = undefined;
781
823
  }
782
824
  /**
783
825
  * The session's checkpoint (Go: Session.Checkpoint), for the application to save where
784
826
  * only it can write, so another process can attachSession. It waits for a call in
785
827
  * flight, so the head it states follows that call. Refused when the client has no
786
- * daemonName and when the session is stopped, closed or ended.
828
+ * daemonName and when the session is stopped, closed or ended. A session recovering from
829
+ * a lost call saves that state (recoveringRequestSha256), so the worker that attaches
830
+ * from it is recovering too.
787
831
  */
788
832
  checkpoint() {
789
833
  return this.#serial(async () => {
@@ -798,7 +842,7 @@ export class Session {
798
842
  if (this.#end !== undefined && this.#end.reason !== "open")
799
843
  throw refuse(`it ended (${this.#end.reason})`);
800
844
  return {
801
- version: 1,
845
+ version: CHECKPOINT_VERSION,
802
846
  daemon,
803
847
  session: this.fingerprint,
804
848
  generation: this.#generation,
@@ -812,7 +856,7 @@ export class Session {
812
856
  openRule: softwareRuleId(this.#rule),
813
857
  expiresUnixMs: this.expiresAtMs,
814
858
  idleTimeoutMs: this.idleTimeoutMs,
815
- lostCallSha256: this.#lostCall,
859
+ recoveringRequestSha256: this.#recovering?.requestSha256 ?? "",
816
860
  };
817
861
  });
818
862
  }
@@ -872,31 +916,35 @@ export class Session {
872
916
  if (this.#unknown !== undefined) {
873
917
  throw new PlimsollError("failed_precondition", `plimsoll: an earlier call of this session ended without an answer this client could check (${this.#unknown}); it may have run, so this client sends nothing more on the session: open a new one`, { notDispatched: "request" });
874
918
  }
919
+ if (this.#diverged !== undefined) {
920
+ throw new PlimsollError("failed_precondition", `plimsoll: ${this.#diverged}; this client sends nothing more on the session: open a new one`, {
921
+ notDispatched: "request",
922
+ });
923
+ }
924
+ // A session recovering from a lost call sends nothing until the application has
925
+ // resolved it: every call is refused here, whatever it is.
926
+ if (this.#recovering !== undefined)
927
+ throw new RecoveringError(`plimsoll: ${RECOVERING_TEXT}; nothing was sent`);
875
928
  const env = this.#client.envelope(opts, rule);
876
929
  // Before the digest, which cannot encode such text either.
877
930
  refuseIllFormed({ ...env, ...payload }, "the request");
878
931
  const digest = requestDigest({ protocol: env.protocol, minimumIsolation: env.minimumIsolation ?? "", timeoutMs: env.timeoutMs ?? 0, softwareRule: rule, payload: digestPayload(payload) });
879
- // The first call after an attach across an explained gap: a repeat of the lost call is
880
- // a retry of a call that was already sent once, refused here with nothing sent, and the
881
- // refusal spends the note. Only the first call is checked: any other call spends the
882
- // note once it is sent, unless the daemon refuses it with the not-dispatched mark,
883
- // since then nothing ran, the head is where it was, and the next call is still the
884
- // first.
885
- if (this.#lostCall !== "" && digest === this.#lostCall) {
886
- this.#lostCall = "";
887
- throw new CallAlreadySentError(`plimsoll: ${CALL_ALREADY_SENT_TEXT}; nothing was sent`);
888
- }
889
932
  try {
890
- const answered = await this.#exchange(payload, opts, rule, env, digest);
891
- this.#lostCall = "";
892
- return answered;
933
+ return await this.#exchange(payload, opts, rule, env, digest);
893
934
  }
894
935
  catch (e) {
895
936
  if (e instanceof StaleOwnerError)
896
937
  this.#stale = "another worker attached the session";
938
+ if (e instanceof HeadMismatchError) {
939
+ // The daemon's own word that its chain holds a call this client did not send (or
940
+ // counts one it did not see): this client's chain no longer follows the daemon's,
941
+ // so it sends nothing more. Nothing ran, so no call is lost (lostRequestSha256).
942
+ this.#diverged =
943
+ `the session's head on the daemon is not this client's: the daemon's is call ${e.head.calls} ending "${e.head.lastRecordSha256}", ` +
944
+ `this client sent call ${this.#calls} ending "${this.#last}"`;
945
+ }
897
946
  if (e instanceof PlimsollError && e.notDispatched)
898
947
  throw e;
899
- this.#lostCall = "";
900
948
  if (e instanceof PlimsollError && e.unanswered) {
901
949
  // The call may have run, and the daemon chained its record: check it and keep
902
950
  // it in the chain, so the session goes on and the call is not hidden.
@@ -931,7 +979,10 @@ export class Session {
931
979
  async #exchange(payload, opts, rule, env, digest) {
932
980
  let m;
933
981
  try {
934
- const body = { ...env, sessionId: this.#id, generation: this.#generation.toString(), ...payload };
982
+ // The head this call expects to run on, filled in here, inside the queue that
983
+ // serializes the session's calls, so it is the one the call before it left.
984
+ const head = { generation: this.#generation.toString(), calls: this.#calls.toString(), lastRecordSha256: this.#last };
985
+ const body = { ...env, sessionId: this.#id, head, ...payload };
935
986
  m = await this.#client.call("SessionRun", body, opts.signal);
936
987
  }
937
988
  catch (e) {
@@ -998,7 +1049,7 @@ export class Session {
998
1049
  try {
999
1050
  sum = decoded(() => ({
1000
1051
  session: m.session ?? "",
1001
- calls: BigInt(m.calls ?? 0),
1052
+ calls: closeCount(m.calls),
1002
1053
  lastRecordSha256: m.lastRecordSha256 ?? "",
1003
1054
  end: sessionEndFromWire(m.ended),
1004
1055
  }));
@@ -1015,6 +1066,14 @@ export class Session {
1015
1066
  });
1016
1067
  }
1017
1068
  }
1069
+ // The count a close answer states, read as one whole decimal; anything else is an answer
1070
+ // this client cannot read.
1071
+ function closeCount(v) {
1072
+ const n = wholeInt(v, UINT64);
1073
+ if (n === undefined)
1074
+ throw new PlimsollError("data_loss", "plimsoll: the daemon's count of calls is not one whole decimal");
1075
+ return n;
1076
+ }
1018
1077
  // Reads the answer under the call's signal itself, since a fetch implementation
1019
1078
  // need not tie its body to the signal it was given.
1020
1079
  async function readCapped(res, signal) {
package/dist/errors.d.ts CHANGED
@@ -83,15 +83,35 @@ export declare class CheckpointMismatchError extends PlimsollError {
83
83
  constructor(message: string, opts?: ConstructorParameters<typeof PlimsollError>[2]);
84
84
  }
85
85
  /**
86
- * The first call of a session taken over across an explained gap repeats the lost call:
87
- * that call was already sent once and its answer was lost, so this is a retry of it.
88
- * Refused before anything was sent (notDispatched "request"), and never a retry signal.
89
- * Only the first call is checked (Go: client.ErrCallAlreadySent, in the same words).
90
- * The lost call's record says whether the daemon answered it (session.lostCall).
86
+ * A session call refused before anything was sent, because the session is recovering
87
+ * from a call whose answer was lost: it was taken over across that call (attachSession
88
+ * with lostRequestSha256), or attached from a checkpoint saved while recovering. Every
89
+ * call is refused (notDispatched "request") until the application has read
90
+ * session.lostCall and called session.resolveLostCall(). It is never a retry signal: the
91
+ * lost call was sent once and may have run (Go: client.ErrRecovering, in the same words).
92
+ * The lost call's record says whether the daemon answered it: a result digest when it did,
93
+ * an unanswered code when it ended without an answer.
91
94
  */
92
- export declare class CallAlreadySentError extends PlimsollError {
95
+ export declare class RecoveringError extends PlimsollError {
93
96
  constructor(message: string);
94
97
  }
98
+ /** A session's head: the ownership generation, the count of calls and the last record's digest. */
99
+ export type SessionHead = {
100
+ generation: bigint;
101
+ calls: bigint;
102
+ lastRecordSha256: string;
103
+ };
104
+ /**
105
+ * A session call the daemon refused, before running anything, because the head this
106
+ * client sent (its generation, count of calls and last record) is not the session's:
107
+ * another holder of the session ran a call between this client's, or a bug. head is the
108
+ * daemon's, from the refusal's SessionHeadMismatch detail. This client tracks the head
109
+ * exactly, so the session stops here and sends nothing more (Go: client.ErrHeadMismatch).
110
+ */
111
+ export declare class HeadMismatchError extends PlimsollError {
112
+ readonly head: SessionHead;
113
+ constructor(message: string, head: SessionHead, opts?: ConstructorParameters<typeof PlimsollError>[2]);
114
+ }
95
115
  /** The error for a success answer that is not bound to its request: the call may have run. */
96
116
  export declare function unboundSuccess(method: string): PlimsollError;
97
117
  export declare function sessionEndFromWire(v: string | number | undefined): SessionEnd;
package/dist/errors.js CHANGED
@@ -74,16 +74,34 @@ export class CheckpointMismatchError extends PlimsollError {
74
74
  }
75
75
  }
76
76
  /**
77
- * The first call of a session taken over across an explained gap repeats the lost call:
78
- * that call was already sent once and its answer was lost, so this is a retry of it.
79
- * Refused before anything was sent (notDispatched "request"), and never a retry signal.
80
- * Only the first call is checked (Go: client.ErrCallAlreadySent, in the same words).
81
- * The lost call's record says whether the daemon answered it (session.lostCall).
77
+ * A session call refused before anything was sent, because the session is recovering
78
+ * from a call whose answer was lost: it was taken over across that call (attachSession
79
+ * with lostRequestSha256), or attached from a checkpoint saved while recovering. Every
80
+ * call is refused (notDispatched "request") until the application has read
81
+ * session.lostCall and called session.resolveLostCall(). It is never a retry signal: the
82
+ * lost call was sent once and may have run (Go: client.ErrRecovering, in the same words).
83
+ * The lost call's record says whether the daemon answered it: a result digest when it did,
84
+ * an unanswered code when it ended without an answer.
82
85
  */
83
- export class CallAlreadySentError extends PlimsollError {
86
+ export class RecoveringError extends PlimsollError {
84
87
  constructor(message) {
85
88
  super("failed_precondition", message, { notDispatched: "request" });
86
- this.name = "CallAlreadySentError";
89
+ this.name = "RecoveringError";
90
+ }
91
+ }
92
+ /**
93
+ * A session call the daemon refused, before running anything, because the head this
94
+ * client sent (its generation, count of calls and last record) is not the session's:
95
+ * another holder of the session ran a call between this client's, or a bug. head is the
96
+ * daemon's, from the refusal's SessionHeadMismatch detail. This client tracks the head
97
+ * exactly, so the session stops here and sends nothing more (Go: client.ErrHeadMismatch).
98
+ */
99
+ export class HeadMismatchError extends PlimsollError {
100
+ head;
101
+ constructor(message, head, opts = {}) {
102
+ super("failed_precondition", message, opts);
103
+ this.name = "HeadMismatchError";
104
+ this.head = head;
87
105
  }
88
106
  }
89
107
  const NOT_BOUND = `the answer does not carry this request's ${REQUEST_ID_HEADER} back (a daemon older than protocol 3, or an intermediary ` +
@@ -169,6 +187,76 @@ function bigVarint(b, i) {
169
187
  }
170
188
  throw new Error("bad varint");
171
189
  }
190
+ // The index after a field of wire type wire whose value starts at b[i]: how a field this
191
+ // client does not know is skipped, as Go and Python skip it.
192
+ function skipField(b, i, wire) {
193
+ if (wire === 0)
194
+ return varint(b, i)[1];
195
+ if (wire === 2) {
196
+ const [n, k] = varint(b, i);
197
+ if (k + n > b.length)
198
+ throw new Error("bad detail");
199
+ return k + n;
200
+ }
201
+ if (wire === 1 || wire === 5) {
202
+ const next = i + (wire === 1 ? 8 : 4);
203
+ if (next > b.length)
204
+ throw new Error("bad detail");
205
+ return next;
206
+ }
207
+ throw new Error("unexpected wire type");
208
+ }
209
+ // Decodes a SessionHeadMismatch detail (field 1, a SessionCheckpoint: generation 1, calls 2,
210
+ // last_record_sha256 3) by hand; undefined when it holds no head, which leaves the refusal
211
+ // an attach's checkpoint mismatch, as in Go (headMismatchDetail).
212
+ function decodeHeadMismatch(b) {
213
+ let head;
214
+ for (let i = 0; i < b.length;) {
215
+ const [tag, j] = varint(b, i);
216
+ const wire = tag & 7;
217
+ if (tag >>> 3 === 1 && wire === 2) {
218
+ const [n, k] = varint(b, j);
219
+ if (k + n > b.length)
220
+ throw new Error("bad detail");
221
+ head = decodeHead(b.subarray(k, k + n));
222
+ i = k + n;
223
+ }
224
+ else {
225
+ i = skipField(b, j, wire);
226
+ }
227
+ }
228
+ return head;
229
+ }
230
+ function decodeHead(b) {
231
+ const h = { generation: 0n, calls: 0n, lastRecordSha256: "" };
232
+ for (let i = 0; i < b.length;) {
233
+ const [tag, j] = varint(b, i);
234
+ const field = tag >>> 3;
235
+ const wire = tag & 7;
236
+ if ((field === 1 || field === 2) && wire === 0) {
237
+ const [v, k] = bigVarint(b, j);
238
+ // Go's protowire refuses a varint past 64 bits; so does this decoder.
239
+ if (v >> 64n !== 0n)
240
+ throw new Error("bad varint");
241
+ if (field === 1)
242
+ h.generation = v;
243
+ else
244
+ h.calls = v;
245
+ i = k;
246
+ }
247
+ else if (field === 3 && wire === 2) {
248
+ const [n, k] = varint(b, j);
249
+ if (k + n > b.length)
250
+ throw new Error("bad detail");
251
+ h.lastRecordSha256 = new TextDecoder("utf-8", { fatal: true }).decode(b.subarray(k, k + n));
252
+ i = k + n;
253
+ }
254
+ else {
255
+ i = skipField(b, j, wire);
256
+ }
257
+ }
258
+ return h;
259
+ }
172
260
  const RECORD_STRINGS = {
173
261
  2: "requestSha256", 3: "resultSha256", 4: "provider", 5: "isolation", 6: "environment", 7: "policy",
174
262
  10: "session", 12: "previousSha256", 13: "recordSha256", 14: "softwareIdentity", 15: "softwareRuleId", 16: "unanswered", 17: "instance",
@@ -280,6 +368,7 @@ export function errorFromWire(httpStatus, body, answer) {
280
368
  let notDispatched;
281
369
  let sessionEnded;
282
370
  let unanswered;
371
+ let head;
283
372
  for (const d of (unreadable ? [] : details)) {
284
373
  try {
285
374
  const bytes = wireBytes(d.value);
@@ -295,6 +384,9 @@ export function errorFromWire(httpStatus, body, answer) {
295
384
  else if (d.type === "plimsoll.v1.UnansweredCall") {
296
385
  unanswered = decodeUnanswered(bytes);
297
386
  }
387
+ else if (d.type === "plimsoll.v1.SessionHeadMismatch") {
388
+ head = decodeHeadMismatch(bytes);
389
+ }
298
390
  }
299
391
  catch {
300
392
  // An undecodable detail states nothing; in particular not that nothing ran.
@@ -308,11 +400,12 @@ export function errorFromWire(httpStatus, body, answer) {
308
400
  const opts = { notDispatched, sessionEnded, unanswered: notDispatched ? undefined : unanswered };
309
401
  // The ownership refusals of a session's run, close or attach (protocol 6): reason
310
402
  // permission is a stale worker; reason request with the daemon's constant text is a
311
- // checkpoint that is not the head.
403
+ // checkpoint that is not the head: an attach's, or, with the daemon's head as a
404
+ // SessionHeadMismatch detail (protocol 8), a call's.
312
405
  if (code === "failed_precondition" && !sessionEnded && notDispatched === "permission")
313
406
  return new StaleOwnerError(message, opts);
314
407
  if (code === "failed_precondition" && !sessionEnded && notDispatched === "request" && message === CHECKPOINT_MISMATCH_TEXT) {
315
- return new CheckpointMismatchError(message, opts);
408
+ return head ? new HeadMismatchError(message, head, opts) : new CheckpointMismatchError(message, opts);
316
409
  }
317
410
  return new PlimsollError(code, message, opts);
318
411
  }
package/dist/index.d.ts CHANGED
@@ -1,5 +1,5 @@
1
- export { PlimsollClient, Session, PROTOCOL, meets, type AdviceFinding, type CellRequest, type CellResult, type ClientOptions, type Evidence, type Info, type Isolation, type JavaScriptResult, type Language, type PayloadEnvironment, type ProjectOutcome, type ProjectRequest, type ProjectResult, type GrantRunOptions, type RunOptions, type SessionOptions, type SessionSummary, type SoftwareRule, type StepResult, } from "./client.ts";
2
- export { CallAlreadySentError, CheckpointMismatchError, PlimsollError, StaleOwnerError, type Code, type Refusal, type SessionEnd } from "./errors.ts";
1
+ export { PlimsollClient, Session, PROTOCOL, meets, type AdviceFinding, type CellRequest, type CellResult, type ClientOptions, type Evidence, type Info, type Isolation, type JavaScriptResult, type Language, type LostAnswer, type LostCall, type PayloadEnvironment, type ProjectOutcome, type ProjectRequest, type ProjectResult, type GrantRunOptions, type RunOptions, type SessionOptions, type SessionSummary, type SoftwareRule, type StepResult, } from "./client.ts";
2
+ export { CheckpointMismatchError, HeadMismatchError, PlimsollError, RecoveringError, StaleOwnerError, type Code, type Refusal, type SessionEnd, type SessionHead, } from "./errors.ts";
3
3
  export { checkpointProblem, checkpointToJSON, parseCheckpoint, validateCheckpoint, type SessionCheckpoint } from "./checkpoint.ts";
4
4
  export type { RunRecord } from "./record.ts";
5
5
  export { CodeSandboxes, DEFAULT_LANGUAGES, type CodeSandboxesOptions, type ExecuteCodeInput, type ExecuteCodeOutput, type GrantPlan, type SessionMode, type ToolGrant, type ToolLanguages, } from "./sandboxes.ts";
package/dist/index.js CHANGED
@@ -1,4 +1,4 @@
1
1
  export { PlimsollClient, Session, PROTOCOL, meets, } from "./client.js";
2
- export { CallAlreadySentError, CheckpointMismatchError, PlimsollError, StaleOwnerError } from "./errors.js";
2
+ export { CheckpointMismatchError, HeadMismatchError, PlimsollError, RecoveringError, StaleOwnerError, } from "./errors.js";
3
3
  export { checkpointProblem, checkpointToJSON, parseCheckpoint, validateCheckpoint } from "./checkpoint.js";
4
4
  export { CodeSandboxes, DEFAULT_LANGUAGES, } from "./sandboxes.js";
package/dist/record.d.ts CHANGED
@@ -89,7 +89,19 @@ export declare function recordFromWire(m: WireRecord): RunRecord;
89
89
  /** A record's own digest, over the fields its version covers (every field but its digest for an unknown version). */
90
90
  export declare function recordDigest(r: RunRecord): string;
91
91
  /**
92
- * The fields a record's version does not cover are unset, it states a result digest or,
92
+ * Which calls each published record version records (record.published's answered and
93
+ * unanswered flags): versions 1 and 2 answered calls only, version 3 unanswered session
94
+ * calls only, versions 4 and 5 both. Published versions are frozen, so this is too; a
95
+ * version missing here records nothing, so a new one is refused until it is added, and a
96
+ * test holds the keys to RECORD_FIELDS' (finding release-85).
97
+ */
98
+ export declare const RECORD_KINDS: Readonly<Record<number, {
99
+ answered: boolean;
100
+ unanswered: boolean;
101
+ }>>;
102
+ /**
103
+ * The record records a kind of call its version records, the fields its version does not
104
+ * cover are unset, it states a result digest or,
93
105
  * for an unanswered call, an error code, exactly one, and the code is one of the closed
94
106
  * set, its tier is one of TIERS (never "unknown" or empty, whatever floor the request
95
107
  * named), it does not end before it starts, answered or not, its qualification and daemon
@@ -128,3 +140,17 @@ export declare function checkRecord(reqDigest: string, kind: "javascript" | "pro
128
140
  } | {
129
141
  problem: string;
130
142
  };
143
+ /**
144
+ * Checks the answer an attach returned for a lost call (AttachSessionResponse.lostAnswer)
145
+ * against that call's record, which the caller has already checked against its
146
+ * checkpoint and the request digest it named (record.CheckLostAnswer): the answer carries
147
+ * exactly that record, which is a live answered call's, and one result of a session call's
148
+ * kind whose result digest is the record's, stating the evidence the record states. The
149
+ * request itself is not at hand, only its digest, so the record's request digest and
150
+ * software rule stand for it. Returns the result's kind, or the reason it does not check.
151
+ */
152
+ export declare function checkLostAnswer(resp: WireRunResponse, lost: RunRecord): {
153
+ kind: "javascript" | "project" | "cell";
154
+ } | {
155
+ problem: string;
156
+ };
package/dist/record.js CHANGED
@@ -7,7 +7,7 @@ import { PlimsollError } from "./errors.js";
7
7
  // for an answered call and an unanswered session call alike), its layouts and bounds,
8
8
  // generated from the Go record and sandbox packages.
9
9
  import { DAEMON_VERSION_PATTERN, INSTANCE_PATTERN, LAST_WALL_CLOCK_END_VERSION, MAX_DAEMON_VERSION_BYTES, MAX_QUALIFICATION_BYTES, OUTCOMES, QUALIFICATION_FORBIDDEN, RECORD_FIELDS, RECORD_VERSION, RETIRED_END_BEFORE_START_TEXT, TIERS, UNANSWERED_CODES as UNANSWERED_CODE_LIST, } from "./tables.gen.js";
10
- import { wireBytes, WireShapeError } from "./wire.js";
10
+ import { INT64, UINT32, UINT64, wholeInt, wireBytes, WireShapeError } from "./wire.js";
11
11
  const INSTANCE_FORM = new RegExp(INSTANCE_PATTERN);
12
12
  /** A record's instance: "" (the provider names none) or a typed reference such as `k8s-pod-uid:` and a pod's UID. */
13
13
  export function validInstance(s) {
@@ -212,12 +212,11 @@ export function resultDigest(resp) {
212
212
  // big reads a 64-bit integer field the JSON codec sends as a decimal string (or a
213
213
  // number). Anything else is an answer this client cannot read, a PlimsollError,
214
214
  // never BigInt's own SyntaxError or RangeError.
215
- function big(v, name) {
216
- if (v === undefined)
217
- return 0n;
218
- if ((typeof v === "string" && /^-?[0-9]{1,20}$/.test(v)) || (typeof v === "number" && Number.isSafeInteger(v)))
219
- return BigInt(v);
220
- throw new PlimsollError("data_loss", `plimsoll: the record's ${name} is not an integer`);
215
+ function big(v, name, range = INT64) {
216
+ const n = wholeInt(v, range);
217
+ if (n === undefined)
218
+ throw new PlimsollError("data_loss", `plimsoll: the record's ${name} is not an integer in one whole decimal`);
219
+ return n;
221
220
  }
222
221
  // text and flag read a record field the JSON codec sends as a string or a boolean: absent is "" or false, and any
223
222
  // other JSON type is an answer this client cannot read, a PlimsollError (Go's protojson and Python's typed reads
@@ -238,7 +237,7 @@ function flag(v, name) {
238
237
  }
239
238
  export function recordFromWire(m) {
240
239
  return {
241
- version: m.version ?? 0,
240
+ version: Number(big(m.version, "version", UINT32)),
242
241
  requestSha256: text(m.requestSha256, "requestSha256"),
243
242
  resultSha256: text(m.resultSha256, "resultSha256"),
244
243
  provider: text(m.provider, "provider"),
@@ -250,7 +249,7 @@ export function recordFromWire(m) {
250
249
  startedUnixMs: big(m.startedUnixMs, "startedUnixMs"),
251
250
  endedUnixMs: big(m.endedUnixMs, "endedUnixMs"),
252
251
  session: text(m.session, "session"),
253
- sequence: big(m.sequence, "sequence"),
252
+ sequence: big(m.sequence, "sequence", UINT64),
254
253
  previousSha256: text(m.previousSha256, "previousSha256"),
255
254
  unanswered: text(m.unanswered, "unanswered"),
256
255
  instance: text(m.instance, "instance"),
@@ -275,7 +274,22 @@ export function recordDigest(r) {
275
274
  return e.sum();
276
275
  }
277
276
  /**
278
- * The fields a record's version does not cover are unset, it states a result digest or,
277
+ * Which calls each published record version records (record.published's answered and
278
+ * unanswered flags): versions 1 and 2 answered calls only, version 3 unanswered session
279
+ * calls only, versions 4 and 5 both. Published versions are frozen, so this is too; a
280
+ * version missing here records nothing, so a new one is refused until it is added, and a
281
+ * test holds the keys to RECORD_FIELDS' (finding release-85).
282
+ */
283
+ export const RECORD_KINDS = {
284
+ 1: { answered: true, unanswered: false },
285
+ 2: { answered: true, unanswered: false },
286
+ 3: { answered: false, unanswered: true },
287
+ 4: { answered: true, unanswered: true },
288
+ 5: { answered: true, unanswered: true },
289
+ };
290
+ /**
291
+ * The record records a kind of call its version records, the fields its version does not
292
+ * cover are unset, it states a result digest or,
279
293
  * for an unanswered call, an error code, exactly one, and the code is one of the closed
280
294
  * set, its tier is one of TIERS (never "unknown" or empty, whatever floor the request
281
295
  * named), it does not end before it starts, answered or not, its qualification and daemon
@@ -288,13 +302,20 @@ export function statesOnlyProblem(r) {
288
302
  if (typeof text !== "string" || !validText(text))
289
303
  return `the record's ${name} is not UTF-8 or holds a control or bidirectional format character`;
290
304
  }
305
+ const unanswered = r.unanswered !== "";
306
+ const kinds = RECORD_KINDS[r.version];
307
+ if (!kinds)
308
+ return `a version ${r.version} record is not of a published version`;
309
+ if (unanswered && !kinds.unanswered)
310
+ return `a version ${r.version} record cannot record an unanswered call`;
311
+ if (!unanswered && !kinds.answered)
312
+ return `a version ${r.version} record records only an unanswered call`;
291
313
  const covered = RECORD_FIELDS[r.version] ?? [];
292
314
  for (const name of RECORD_FIELDS[RECORD_VERSION]) {
293
315
  const v = recordField(r, name);
294
316
  if (!covered.includes(name) && v !== "" && v !== false && v !== 0n)
295
317
  return `a version ${r.version} record does not cover ${name}, so it cannot state one`;
296
318
  }
297
- const unanswered = r.unanswered !== "";
298
319
  if (unanswered === (r.resultSha256 !== ""))
299
320
  return "a record states a result or, for an unanswered call, an error code, exactly one";
300
321
  if (unanswered && !UNANSWERED_CODES.has(r.unanswered))
@@ -450,3 +471,56 @@ export function checkRecord(reqDigest, kind, rule, resp) {
450
471
  return { problem: `record digest ${r.sha256}, its fields digest to ${recordDigest(r)}` };
451
472
  return { record: r };
452
473
  }
474
+ /**
475
+ * Checks the answer an attach returned for a lost call (AttachSessionResponse.lostAnswer)
476
+ * against that call's record, which the caller has already checked against its
477
+ * checkpoint and the request digest it named (record.CheckLostAnswer): the answer carries
478
+ * exactly that record, which is a live answered call's, and one result of a session call's
479
+ * kind whose result digest is the record's, stating the evidence the record states. The
480
+ * request itself is not at hand, only its digest, so the record's request digest and
481
+ * software rule stand for it. Returns the result's kind, or the reason it does not check.
482
+ */
483
+ export function checkLostAnswer(resp, lost) {
484
+ if (resp === null || typeof resp !== "object" || Array.isArray(resp))
485
+ return { problem: "the lost call's answer is not an object" };
486
+ if (!resp.record)
487
+ return { problem: "the lost call's answer carries no run record" };
488
+ const r = recordFromWire(resp.record);
489
+ if (!sameRecord(r, lost))
490
+ return { problem: "the lost call's answer carries another record than the lost call's" };
491
+ if (r.version !== RECORD_VERSION)
492
+ return { problem: versionProblem(r.version) };
493
+ if (r.unanswered !== "")
494
+ return { problem: `an answer came for a call whose record states it ended unanswered (${r.unanswered})` };
495
+ const bounds = statesOnlyProblem(r);
496
+ if (bounds !== undefined)
497
+ return { problem: bounds };
498
+ if (r.sha256 !== recordDigest(r))
499
+ return { problem: `record digest ${r.sha256}, its fields digest to ${recordDigest(r)}` };
500
+ const kinds = ["javascript", "project", "module", "cell"].filter((k) => resp[k] !== undefined && resp[k] !== null);
501
+ const kind = kinds[0];
502
+ if (kinds.length !== 1 || kind === "module" || kind === undefined)
503
+ return { problem: "the lost call's answer holds no one result of a session call's kind" };
504
+ let result;
505
+ try {
506
+ result = resultDigest(resp);
507
+ }
508
+ catch (e) {
509
+ if (e instanceof WireShapeError)
510
+ return { problem: `the lost call's answer is malformed: ${e.message}` };
511
+ throw e;
512
+ }
513
+ if (r.resultSha256 !== result)
514
+ return { problem: `result digest ${r.resultSha256}, the lost call's answer digests to ${result}` };
515
+ if (r.provider !== (resp.sandbox ?? "") || r.isolation !== (resp.isolation ?? "") || r.environment !== (resp.environment ?? "") ||
516
+ r.instance !== (resp.instance ?? "") || r.isolationQualification !== (resp.isolationQualification ?? "") || r.warm !== (resp.warm ?? false) ||
517
+ r.daemonVersion !== (resp.daemonVersion ?? "") || r.softwareIdentity !== (resp.softwareIdentity ?? "")) {
518
+ return { problem: "the lost call's answer states other evidence than its record" };
519
+ }
520
+ return { kind };
521
+ }
522
+ // Whether two records read off the wire are the same record, field by field (Go: proto.Equal
523
+ // on the wire messages).
524
+ function sameRecord(a, b) {
525
+ return Object.keys(a).every((k) => a[k] === b[k]);
526
+ }
@@ -12,7 +12,7 @@ export declare const TIERS: readonly ["none", "process", "container", "kernel",
12
12
  /** The languages plimsoll keeps an interpreter for (sandbox.Languages). */
13
13
  export declare const LANGUAGES: readonly ["javascript", "python"];
14
14
  /** The wire protocol number a client states on every request (protocol.Number). */
15
- export declare const PROTOCOL = 7;
15
+ export declare const PROTOCOL = 8;
16
16
  /** The header carrying a client's ID for one request, which the daemon echoes (protocol.RequestIDHeader). */
17
17
  export declare const REQUEST_ID_HEADER = "Plimsoll-Request-Id";
18
18
  /** The daemon's mark on an answer written before any handler ran (protocol.NotDispatchedHeader). */
@@ -21,7 +21,7 @@ export declare const NOT_DISPATCHED_HEADER = "Plimsoll-Not-Dispatched";
21
21
  export declare const TRACE_ID_PATTERN = "^[A-Za-z0-9._:-]{1,64}$";
22
22
  /** The text of a session call, close or attach refused because another worker attached (protocol.StaleOwnerText). */
23
23
  export declare const STALE_OWNER_TEXT = "session ownership generation is stale";
24
- /** The text of an attach refused because its checkpoint is not the session's head (protocol.CheckpointMismatchText). */
24
+ /** The text of an attach refused because its checkpoint is not the session's head, and of a call refused because its head is not (protocol.CheckpointMismatchText). */
25
25
  export declare const CHECKPOINT_MISMATCH_TEXT = "session checkpoint does not match";
26
26
  /** The tiers a request may state as its floor, weakest first: every tier but none. */
27
27
  export declare const FLOORS: readonly ["process", "container", "kernel", "vm"];
@@ -80,10 +80,10 @@ export declare const SOFTWARE_IDENTITY_PATTERN = "^[A-Za-z0-9._:/@+-]+$";
80
80
  /** The largest answer a client reads (client.MaxResponseBytes). */
81
81
  export declare const MAX_RESPONSE_BYTES = 33554432;
82
82
  /** The one version of a session checkpoint the clients write and read (client.CheckpointVersion). */
83
- export declare const CHECKPOINT_VERSION = 1;
83
+ export declare const CHECKPOINT_VERSION = 2;
84
84
  /** A daemon name's grammar: the application's own name for a daemon, never a URL (client.DaemonNamePattern). */
85
85
  export declare const DAEMON_NAME_PATTERN = "^[A-Za-z0-9._-]{1,64}$";
86
86
  /** A software rule's ID as a checkpoint states it (client.SoftwareRuleIDPattern). */
87
87
  export declare const SOFTWARE_RULE_ID_PATTERN = "^(?:exact:[A-Za-z0-9._:/@+-]{1,256}|approved:sha256:[0-9a-f]{64})$";
88
- /** What a client says when it refuses a repeat of a call lost across a takeover (client.CallAlreadySentText). */
89
- export declare const CALL_ALREADY_SENT_TEXT = "this call was already sent once in the session, and its answer was lost";
88
+ /** What a client says when it refuses a call on a session recovering from a call lost across a takeover (client.RecoveringText). */
89
+ export declare const RECOVERING_TEXT = "this session is recovering from a call whose answer was lost: read the lost call and resolve it before sending another call";
@@ -44,7 +44,7 @@ export const TIERS = ["none", "process", "container", "kernel", "vm"];
44
44
  /** The languages plimsoll keeps an interpreter for (sandbox.Languages). */
45
45
  export const LANGUAGES = ["javascript", "python"];
46
46
  /** The wire protocol number a client states on every request (protocol.Number). */
47
- export const PROTOCOL = 7;
47
+ export const PROTOCOL = 8;
48
48
  /** The header carrying a client's ID for one request, which the daemon echoes (protocol.RequestIDHeader). */
49
49
  export const REQUEST_ID_HEADER = "Plimsoll-Request-Id";
50
50
  /** The daemon's mark on an answer written before any handler ran (protocol.NotDispatchedHeader). */
@@ -53,7 +53,7 @@ export const NOT_DISPATCHED_HEADER = "Plimsoll-Not-Dispatched";
53
53
  export const TRACE_ID_PATTERN = "^[A-Za-z0-9._:-]{1,64}$";
54
54
  /** The text of a session call, close or attach refused because another worker attached (protocol.StaleOwnerText). */
55
55
  export const STALE_OWNER_TEXT = "session ownership generation is stale";
56
- /** The text of an attach refused because its checkpoint is not the session's head (protocol.CheckpointMismatchText). */
56
+ /** The text of an attach refused because its checkpoint is not the session's head, and of a call refused because its head is not (protocol.CheckpointMismatchText). */
57
57
  export const CHECKPOINT_MISMATCH_TEXT = "session checkpoint does not match";
58
58
  /** The tiers a request may state as its floor, weakest first: every tier but none. */
59
59
  export const FLOORS = ["process", "container", "kernel", "vm"];
@@ -118,10 +118,10 @@ export const SOFTWARE_IDENTITY_PATTERN = "^[A-Za-z0-9._:/@+-]+$";
118
118
  /** The largest answer a client reads (client.MaxResponseBytes). */
119
119
  export const MAX_RESPONSE_BYTES = 33554432;
120
120
  /** The one version of a session checkpoint the clients write and read (client.CheckpointVersion). */
121
- export const CHECKPOINT_VERSION = 1;
121
+ export const CHECKPOINT_VERSION = 2;
122
122
  /** A daemon name's grammar: the application's own name for a daemon, never a URL (client.DaemonNamePattern). */
123
123
  export const DAEMON_NAME_PATTERN = "^[A-Za-z0-9._-]{1,64}$";
124
124
  /** A software rule's ID as a checkpoint states it (client.SoftwareRuleIDPattern). */
125
125
  export const SOFTWARE_RULE_ID_PATTERN = "^(?:exact:[A-Za-z0-9._:/@+-]{1,256}|approved:sha256:[0-9a-f]{64})$";
126
- /** What a client says when it refuses a repeat of a call lost across a takeover (client.CallAlreadySentText). */
127
- export const CALL_ALREADY_SENT_TEXT = "this call was already sent once in the session, and its answer was lost";
126
+ /** What a client says when it refuses a call on a session recovering from a call lost across a takeover (client.RecoveringText). */
127
+ export const RECOVERING_TEXT = "this session is recovering from a call whose answer was lost: read the lost call and resolve it before sending another call";
package/dist/wire.d.ts CHANGED
@@ -38,10 +38,14 @@ export type WireRunRequest = WireEnvelope & {
38
38
  project?: WireProjectRun;
39
39
  cell?: WireCellRun;
40
40
  };
41
- /** A session call: the run request with the session ID and the current ownership generation (a uint64, as a decimal string). */
41
+ /**
42
+ * A session call: the run request with the session ID and the head the call expects to run
43
+ * on (the current ownership generation, the count of calls and the last record's digest);
44
+ * the daemon runs it only on that head (protocol 8).
45
+ */
42
46
  export type WireSessionRunRequest = WireRunRequest & {
43
47
  sessionId: string;
44
- generation: string;
48
+ head: WireSessionCheckpoint;
45
49
  };
46
50
  export type WireRecord = {
47
51
  version?: number;
@@ -182,6 +186,8 @@ export type WireOpenSessionRequest = {
182
186
  languages?: string[];
183
187
  owner?: string;
184
188
  warmOnly?: boolean;
189
+ /** Keep no call's answer for a takeover (protocol 8): the daemon then retains no output. */
190
+ keepNoAnswer?: boolean;
185
191
  };
186
192
  export type WireOpenSessionResponse = {
187
193
  generation?: string | number;
@@ -215,10 +221,12 @@ export type WireAttachSessionRequest = {
215
221
  traceId?: string;
216
222
  lostRequestSha256?: string;
217
223
  };
224
+ /** lostAnswer comes only beside lostRecord: the lost call's answer, when the daemon kept it (protocol 8). */
218
225
  export type WireAttachSessionResponse = {
219
226
  sessionInfo?: WireOpenSessionResponse;
220
227
  checkpoint?: WireSessionCheckpoint;
221
228
  lostRecord?: WireRecord;
229
+ lostAnswer?: WireRunResponse;
222
230
  };
223
231
  export type WireCloseSessionResponse = {
224
232
  session?: string;
@@ -235,6 +243,21 @@ export type WireError = {
235
243
  value?: string;
236
244
  }[];
237
245
  };
246
+ /**
247
+ * Reads an integer field of the daemon's answer: a JSON number that is a safe integer, or a
248
+ * string that is one whole decimal (an optional minus and digits with no leading zero, the
249
+ * form every client writes), within [lo, hi]. Anything else ("5 6", "5,", "5" and a zero
250
+ * byte, "05", " 5", "5.0", "5e0", "0x5") is not read: undefined, never a value read from its
251
+ * leading digits or by BigInt's and Number's looser grammars. Absent is 0. Go reads integer
252
+ * strings the same way (record.UnmarshalJSON), where protojson alone reads "5 6" as 5
253
+ * (finding release-90).
254
+ */
255
+ export declare function wholeInt(v: unknown, [lo, hi]: readonly [bigint, bigint]): bigint | undefined;
256
+ /** The ranges of the protobuf integer kinds, for wholeInt. */
257
+ export declare const UINT32: readonly [bigint, bigint];
258
+ export declare const INT32: readonly [bigint, bigint];
259
+ export declare const UINT64: readonly [bigint, bigint];
260
+ export declare const INT64: readonly [bigint, bigint];
238
261
  /** A bytes field that is not base64 text: the answer is not the protocol's. */
239
262
  export declare class WireShapeError extends Error {
240
263
  }
@@ -243,7 +266,7 @@ export declare class WireShapeError extends Error {
243
266
  * accepted: the answer is parsed JSON, and Buffer.from given an object with a
244
267
  * "length" allocates that many bytes and reads each index, so a 30-byte
245
268
  * {"length":2000000000} would cost 2 GB and a blocked event loop past the
246
- * response's 32 MiB cap (Claude Security scan, 2026-10-27).
269
+ * response's 32 MiB cap (security scan, 2026-10-27).
247
270
  *
248
271
  * The text must be base64 throughout, standard or URL-safe, padded or not, as protobuf
249
272
  * JSON and Connect error details may carry it, and as the Python client reads it:
package/dist/wire.js CHANGED
@@ -3,6 +3,32 @@
3
3
  // JSON names; bytes are base64; 64-bit integers arrive as strings; enums as their
4
4
  // names; a field at its zero value is omitted, which is why everything read is
5
5
  // optional.
6
+ // At most 20 digits: a 64-bit number has no more, and the test stays one short pass.
7
+ const WHOLE_DECIMAL = /^-?(?:0|[1-9][0-9]{0,19})$/;
8
+ /**
9
+ * Reads an integer field of the daemon's answer: a JSON number that is a safe integer, or a
10
+ * string that is one whole decimal (an optional minus and digits with no leading zero, the
11
+ * form every client writes), within [lo, hi]. Anything else ("5 6", "5,", "5" and a zero
12
+ * byte, "05", " 5", "5.0", "5e0", "0x5") is not read: undefined, never a value read from its
13
+ * leading digits or by BigInt's and Number's looser grammars. Absent is 0. Go reads integer
14
+ * strings the same way (record.UnmarshalJSON), where protojson alone reads "5 6" as 5
15
+ * (finding release-90).
16
+ */
17
+ export function wholeInt(v, [lo, hi]) {
18
+ let n;
19
+ if (v === undefined || v === null)
20
+ n = 0n;
21
+ else if (typeof v === "number" && Number.isSafeInteger(v))
22
+ n = BigInt(v);
23
+ else if (typeof v === "string" && WHOLE_DECIMAL.test(v))
24
+ n = BigInt(v);
25
+ return n !== undefined && n >= lo && n <= hi ? n : undefined;
26
+ }
27
+ /** The ranges of the protobuf integer kinds, for wholeInt. */
28
+ export const UINT32 = [0n, (1n << 32n) - 1n];
29
+ export const INT32 = [-(1n << 31n), (1n << 31n) - 1n];
30
+ export const UINT64 = [0n, (1n << 64n) - 1n];
31
+ export const INT64 = [-(1n << 63n), (1n << 63n) - 1n];
6
32
  /** A bytes field that is not base64 text: the answer is not the protocol's. */
7
33
  export class WireShapeError extends Error {
8
34
  }
@@ -11,7 +37,7 @@ export class WireShapeError extends Error {
11
37
  * accepted: the answer is parsed JSON, and Buffer.from given an object with a
12
38
  * "length" allocates that many bytes and reads each index, so a 30-byte
13
39
  * {"length":2000000000} would cost 2 GB and a blocked event loop past the
14
- * response's 32 MiB cap (Claude Security scan, 2026-10-27).
40
+ * response's 32 MiB cap (security scan, 2026-10-27).
15
41
  *
16
42
  * The text must be base64 throughout, standard or URL-safe, padded or not, as protobuf
17
43
  * JSON and Connect error details may carry it, and as the Python client reads it:
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@plimsollmark/client",
3
- "version": "0.28.0",
3
+ "version": "0.29.0",
4
4
  "description": "TypeScript client for plimsolld, with AI SDK, Trigger.dev and Mastra executeCode add-ons",
5
5
  "license": "Apache-2.0",
6
6
  "homepage": "https://github.com/plimsollmark/plimsoll/tree/main/clients/typescript#readme",