@linxin666/dsh-remote-bridge 0.4.7 → 0.4.8

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/lib/index.js CHANGED
@@ -1,6 +1,7 @@
1
1
  import { dirname, isAbsolute, join } from "node:path";
2
2
  import { createHash, createPublicKey, randomBytes, timingSafeEqual, verify } from "node:crypto";
3
3
  import { chmod, mkdir, open, readFile, rename } from "node:fs/promises";
4
+ import { deflateRawSync } from "node:zlib";
4
5
  import { homedir } from "node:os";
5
6
  import { isAbsolute as isAbsolute$1, join as join$1 } from "node:path/posix";
6
7
  import { readFileSync } from "node:fs";
@@ -111,6 +112,24 @@ var ApprovalRegistry = class {
111
112
  return this.#pending.size;
112
113
  }
113
114
  /**
115
+ * Every question still waiting for a phone, in claim order.
116
+ *
117
+ * Only a live claim can be named here: {@link #settle} is the single path out
118
+ * of the pending map, and an answer, the bridge's own timeout, the agent's
119
+ * cancellation and every withdrawal all pass through it before this reads the
120
+ * map again. A question this bridge released therefore cannot come back to a
121
+ * client that reconnects.
122
+ * @returns the fields a second delivery republishes, oldest claim first.
123
+ */
124
+ openPrompts() {
125
+ return [...this.#pending].map(([id, entry]) => ({
126
+ id,
127
+ sessionId: entry.sessionId,
128
+ toolName: entry.toolName,
129
+ summary: entry.summary
130
+ }));
131
+ }
132
+ /**
114
133
  * Claim one question.
115
134
  * @param input - session identity, tool name, presentation summary, and the agent's own lifetime.
116
135
  * @returns the prompt to publish, with its answer promise.
@@ -132,6 +151,9 @@ var ApprovalRegistry = class {
132
151
  };
133
152
  signal?.addEventListener("abort", withdraw, { once: true });
134
153
  this.#pending.set(id, {
154
+ sessionId: input.sessionId,
155
+ toolName: input.toolName,
156
+ summary: input.summary,
135
157
  settle,
136
158
  timer,
137
159
  detached
@@ -335,17 +357,788 @@ var DeviceRoster = class {
335
357
  await chmod(this.#file, 384);
336
358
  }
337
359
  };
360
+ //#endregion
361
+ //#region src/core/protocol.ts
362
+ /**
363
+ * The frozen protocol surface: method names, topic names, refusal codes, and
364
+ * the one authorization rule the dispatcher enforces before any method runs.
365
+ * @module dsh-remote-bridge/core/protocol
366
+ */
367
+ /** Client-callable methods of protocol v1. */
368
+ const METHOD_HELLO = "hello";
369
+ const METHOD_SESSION_LIST = "session.list";
370
+ const METHOD_SESSION_TITLES = "session.titles";
371
+ const METHOD_SESSION_SNAPSHOT = "session.snapshot";
372
+ const METHOD_SESSION_HISTORY = "session.history";
373
+ const METHOD_SESSION_HISTORY_DEEP = "session.history.deep";
374
+ const METHOD_SESSION_PROMPT = "session.prompt";
375
+ const METHOD_SESSION_INTERRUPT = "session.interrupt";
376
+ const METHOD_SESSION_ATTACHMENT = "session.attachment";
377
+ const METHOD_SESSION_PERMISSIONS = "session.permissions";
378
+ const METHOD_SESSION_SET_PERMISSION = "session.setPermission";
379
+ const METHOD_SESSION_MODELS = "session.models";
380
+ const METHOD_SESSION_SET_MODEL = "session.setModel";
381
+ const METHOD_SESSION_CREATE = "session.create";
382
+ const METHOD_SESSION_FORK = "session.fork";
383
+ const METHOD_PRESETS_LIST = "presets.list";
384
+ const METHOD_PAIR_BEGIN = "pair.begin";
385
+ const METHOD_PAIR_FINISH = "pair.finish";
386
+ const METHOD_APPROVAL_RESOLVE = "approval.resolve";
387
+ const METHOD_QUESTION_ANSWER = "question.answer";
388
+ const METHOD_JOBS_LIST = "jobs.list";
389
+ /** Server-pushed topics of protocol v1. */
390
+ const TOPIC_SESSION_DELTA = "session.delta";
391
+ const TOPIC_APPROVAL_REQUEST = "approval.request";
392
+ const TOPIC_QUESTION_REQUEST = "question.request";
393
+ const TOPIC_JOBS_CHANGED = "jobs.changed";
394
+ /**
395
+ * Capability a client declares in `hello`'s `cap` array to ask for a trimmed
396
+ * `session.snapshot` baseline. A client that does not declare it — including
397
+ * every client written before this capability existed — is served exactly the
398
+ * baseline protocol v1 always served.
399
+ */
400
+ const CAP_SESSION_SNAPSHOT_TRIM = "session.snapshot.trim.v1";
401
+ /**
402
+ * Capability a client declares in `hello`'s `cap` array to have
403
+ * `session.snapshot` answer with one bounded page instead of the whole opening
404
+ * window. Declaring it is what makes an opening screen cost one page rather
405
+ * than a whole session; a client that does not declare it — including every
406
+ * client written before this capability existed — receives byte for byte the
407
+ * snapshot protocol v1 always served.
408
+ */
409
+ const CAP_SESSION_SNAPSHOT_PAGE = "session.snapshot.page.v1";
410
+ /**
411
+ * Capability a client declares in `hello`'s `cap` array to have
412
+ * `session.snapshot` answer a reconnect with only what it missed.
413
+ *
414
+ * The declaration and the request's `sinceSeq` are what it takes together: a
415
+ * snapshot that carries no `sinceSeq` is answered, byte for byte, the body
416
+ * protocol v1 always served, whether or not the client declared this. Behind
417
+ * both, the client names the durable `lastSeq` of a snapshot it already holds
418
+ * and the answer is either that same reply in an incremental form —
419
+ * `{turns, lastSeq, mode:"since", reset:false}` carrying only the entries above
420
+ * that watermark — or a full baseline with `mode:"full"` and `reset:true`,
421
+ * which is the one answer that tells a client to throw its copy away. The
422
+ * estimate is only served when the bridge can PROVE nothing was lost: the
423
+ * current follow window's oldest entry must sit at or below `sinceSeq + 1`, so a
424
+ * window that has already scrolled past the watermark answers the baseline
425
+ * instead of a delta with a hole in it. It exists because a reconnect on the
426
+ * phone re-paid 0.86-1.06 s of baseline five times in one measured run.
427
+ */
428
+ const CAP_SESSION_SNAPSHOT_SINCE = "session.snapshot.since.v1";
429
+ /**
430
+ * Capability a client declares in `hello`'s `cap` array to be shown the
431
+ * host's pending user questions and to answer them with `question.answer`.
432
+ *
433
+ * Declaring it is what makes `question.request` reachable and what makes the
434
+ * method part of that client's protocol at all: a client that does not declare
435
+ * it — including every client written before this channel existed — receives no
436
+ * such event, and its `question.answer` is refused as an unknown method,
437
+ * exactly as that frame was refused before.
438
+ */
439
+ const CAP_QUESTIONS = "questions.v1";
440
+ /**
441
+ * Capability a client declares in `hello`'s `cap` array to be told where a
442
+ * message came from and that an agent spawned a child session.
443
+ *
444
+ * Declaring it is what makes the `subagent` delta part of that client's
445
+ * protocol: a client that does not declare it — including every client written
446
+ * before this channel existed — receives no such event, exactly as that frame
447
+ * was dropped before. The `actor` of a `user-message` is not gated: it is an
448
+ * additive field a client that does not read it ignores.
449
+ */
450
+ const CAP_SUBAGENT_THREAD = "subagent.thread.v1";
451
+ /**
452
+ * Capability a client declares in `hello`'s `cap` array to see the host's
453
+ * background jobs and to be told when the set changes.
454
+ *
455
+ * Declaring it is what makes `jobs.list` reachable, and `jobs.list` is the only
456
+ * thing that opens a roster: a connection that declares this capability but
457
+ * never asks for a scope receives no `jobs.changed` at all. A client that does
458
+ * not declare it — including every client written before this channel existed —
459
+ * receives no such event, and its `jobs.list` is refused as an unknown method,
460
+ * exactly as that frame was refused before.
461
+ */
462
+ const CAP_JOBS = "jobs.v1";
463
+ /**
464
+ * Capability a client declares in `hello`'s `cap` array to read the host's
465
+ * Agent presets and to instantiate one as a session.
466
+ *
467
+ * Declaring it is what makes `presets.list` and `session.create` part of that
468
+ * client's protocol at all: a client that does not declare it — including every
469
+ * client written before this channel existed — is refused both as unknown
470
+ * methods, exactly as those frames were refused before. Neither method is
471
+ * called on a connection's behalf either, so a client that never asks sends the
472
+ * host no request.
473
+ */
474
+ const CAP_AGENTS = "agents.v1";
475
+ /**
476
+ * Capability a client declares in `hello`'s `cap` array to be answered with
477
+ * byte-level increments instead of the whole roster or the whole board.
478
+ *
479
+ * Behind it, `session.list` and `board.snapshot` (the latter through the board
480
+ * plugin, §15) accept an opaque `since` token and answer either the whole set
481
+ * (`mode:"reset"`) or only what changed since the set that token names. A
482
+ * client that does not declare it — including every client written before this
483
+ * channel existed — is answered today's body plus the ignorable `mode` and
484
+ * `token` keys, with `mode` always `"reset"`.
485
+ */
486
+ const CAP_DELTA = "delta.v1";
487
+ /**
488
+ * Capability a client declares in `hello`'s `cap` array to be told that an
489
+ * archived session is not in the roster at all.
490
+ *
491
+ * Unlike every capability beside it this one negotiates nothing: the bridge
492
+ * never transfers an archived session, whether or not a client declares it, so
493
+ * an older client simply receives the shorter roster it would have hidden
494
+ * anyway. The name is an announcement of that fact, so a client can stop
495
+ * filtering for itself: behind it, no `session.list` row is a session the
496
+ * host's archive set names, a row that does survive still carries
497
+ * `archived: false` under the same schema, and a live child of an archived
498
+ * parent still crosses with its `parentSessionId` — the parent id, not the
499
+ * parent row.
500
+ */
501
+ const CAP_ROSTER_OMITS_ARCHIVED = "session.list.omit-archived.v1";
502
+ /**
503
+ * Capability a client declares in `hello`'s `cap` array to be answered a
504
+ * compact roster it can page.
505
+ *
506
+ * The declaration alone changes nothing: a listing that carries none of the
507
+ * compact parameters (`cwd`, `maxRows`, `after`) is answered exactly the body
508
+ * protocol v1 always served, so a client can opt into the name before it
509
+ * relies on any of it. Behind the parameters, a row drops its absolute `cwd`
510
+ * unless the request asks for it, drops its `updatedAt` when this connection
511
+ * already sent that id the same value, and a `maxRows`/`after` pair cuts the
512
+ * roster into pages ordered most recent first. The roster is the most repeated
513
+ * large reply on the link, so this is what lets a reconnect pay for the newest
514
+ * screenful plus a cursor instead of the whole list again.
515
+ */
516
+ const CAP_ROSTER_COMPACT = "session.list.compact.v1";
517
+ /**
518
+ * Capability a client declares in `hello`'s `cap` array to be told that this
519
+ * bridge can page a session's durable history down to its oldest entry.
520
+ *
521
+ * The capability is an announcement and nothing more. `session.history.deep` is
522
+ * open to every paired connection, exactly as `session.history` is, because it
523
+ * is a pure read of the session store that costs no other client anything;
524
+ * declaring the capability is how a client learns the method exists, and a
525
+ * client that does not declare it loses only that knowledge.
526
+ */
527
+ const CAP_SESSION_DEEP_HISTORY = "session.deep-history.v1";
528
+ /**
529
+ * Capability a client declares in `hello`'s `cap` array to fork a session.
530
+ *
531
+ * Declaring it is what makes `session.fork` part of that client's protocol at
532
+ * all: a client that does not declare it — including every client written
533
+ * before this channel existed — is refused `unknown-method`, and no fork is
534
+ * asked of the host on its behalf. Behind the name the bridge forwards one
535
+ * `SessionForkRequest` to the host's `session/fork` and hands back the host's
536
+ * own `SessionForkValue`, so what a fork point means stays the host's: an
537
+ * `atSeq` is the source event seq the fork includes, an omitted one is the
538
+ * newest finished turn, and a cut the host opens itself is closed by the host's
539
+ * own synthetic finishing event. Nothing about a fork is modelled or
540
+ * re-derived here.
541
+ */
542
+ const CAP_SESSION_FORK = "session.fork.v1";
543
+ /**
544
+ * Capability a client declares in `hello`'s `cap` array to be sent frames
545
+ * compressed instead of as plain text.
546
+ *
547
+ * Declaring it is what allows the host to compress at all: a frame whose JSON
548
+ * text is at least 1024 UTF-8 bytes crosses as one WebSocket binary frame
549
+ * carrying raw DEFLATE (RFC 1951) of exactly that text, and a frame that does
550
+ * not get smaller still crosses as the text frame it always was. A client that
551
+ * does not declare it — including every client written before this capability
552
+ * existed — receives byte for byte the text frames protocol v1 always wrote.
553
+ *
554
+ * The direction is one way: a client still sends text frames only, and the
555
+ * 10 MiB frame cap stays measured on the text, before inflation.
556
+ */
557
+ const CAP_FRAME_DEFLATE = "frame.deflate.v1";
558
+ /**
559
+ * Methods an unpaired connection may still call: the handshake itself and the
560
+ * two pairing steps. Everything else answers `unpaired` — a caller can pair
561
+ * without a device token, but cannot touch a session without one.
562
+ */
563
+ const UNPAIRED_METHODS = /* @__PURE__ */ new Set([
564
+ METHOD_HELLO,
565
+ METHOD_PAIR_BEGIN,
566
+ METHOD_PAIR_FINISH
567
+ ]);
568
+ /** Every method this protocol version serves. */
569
+ const KNOWN_METHODS = /* @__PURE__ */ new Set([
570
+ METHOD_HELLO,
571
+ METHOD_SESSION_LIST,
572
+ METHOD_SESSION_TITLES,
573
+ METHOD_SESSION_SNAPSHOT,
574
+ METHOD_SESSION_HISTORY,
575
+ METHOD_SESSION_HISTORY_DEEP,
576
+ METHOD_SESSION_PROMPT,
577
+ METHOD_SESSION_INTERRUPT,
578
+ METHOD_SESSION_ATTACHMENT,
579
+ METHOD_SESSION_PERMISSIONS,
580
+ METHOD_SESSION_SET_PERMISSION,
581
+ METHOD_SESSION_MODELS,
582
+ METHOD_SESSION_SET_MODEL,
583
+ METHOD_PAIR_BEGIN,
584
+ METHOD_PAIR_FINISH,
585
+ METHOD_APPROVAL_RESOLVE,
586
+ METHOD_QUESTION_ANSWER,
587
+ METHOD_JOBS_LIST,
588
+ METHOD_PRESETS_LIST,
589
+ METHOD_SESSION_CREATE,
590
+ METHOD_SESSION_FORK
591
+ ]);
592
+ /** Refusal codes the bridge itself raises (DSH failures cross as their own code). */
593
+ const CODE_UNPAIRED = "unpaired";
594
+ const CODE_UNKNOWN_METHOD = "unknown-method";
595
+ const CODE_INVALID_ARGS = "invalid-args";
596
+ const CODE_PROTO_UNSUPPORTED = "proto-unsupported";
597
+ const CODE_TOKEN_INVALID = "token-invalid";
598
+ const CODE_NONCE_INVALID = "nonce-invalid";
599
+ const CODE_APPROVAL_UNKNOWN = "approval-unknown";
600
+ /**
601
+ * The bridge does not hold the named question: it never claimed that call id, it
602
+ * already answered it, or the host no longer holds it as answerable. Host
603
+ * failures crossing this method keep their own codes instead.
604
+ */
605
+ const CODE_QUESTION_UNKNOWN = "question-unknown";
606
+ /**
607
+ * The named session is a delegated child whose durable parent is not a session
608
+ * this connection may read. The bridge follows an addressable child and refuses
609
+ * an unaddressable one, rather than reading it blind.
610
+ */
611
+ const CODE_SESSION_NOT_FOLLOWABLE = "session-not-followable";
612
+ const CODE_SNAPSHOT_UNAVAILABLE = "snapshot-unavailable";
613
+ /**
614
+ * This host composes no job registry, so it has no background jobs to publish.
615
+ * The capability stays advertised — it is a fact about this bridge, not about
616
+ * what a particular host mounts — and only a call that needs the registry fails.
617
+ */
618
+ const CODE_JOBS_UNAVAILABLE = "jobs-unavailable";
619
+ const CODE_SNAPSHOT_TOO_LARGE = "snapshot-too-large";
620
+ const CODE_INTERNAL = "internal";
621
+ /**
622
+ * The capabilities this bridge itself serves, as `hello` advertises them.
623
+ *
624
+ * A capability a mounted plugin adds is not listed here: the bridge cannot know
625
+ * what it is not the author of. A client learns such a capability from the
626
+ * plugin's own documentation, exactly as it did before this list existed.
627
+ */
628
+ const SERVED_CAPABILITIES = [
629
+ CAP_SESSION_SNAPSHOT_TRIM,
630
+ CAP_SESSION_SNAPSHOT_PAGE,
631
+ CAP_QUESTIONS,
632
+ CAP_SUBAGENT_THREAD,
633
+ CAP_JOBS,
634
+ CAP_AGENTS,
635
+ CAP_DELTA,
636
+ CAP_ROSTER_OMITS_ARCHIVED,
637
+ CAP_SESSION_DEEP_HISTORY,
638
+ CAP_FRAME_DEFLATE,
639
+ CAP_ROSTER_COMPACT,
640
+ CAP_SESSION_SNAPSHOT_SINCE,
641
+ CAP_SESSION_FORK
642
+ ];
643
+ /** `server` field of the hello response. */
644
+ const SERVER_ID = "dsh-remote-bridge";
645
+ /** Exact route path of the bridge's WebSocket endpoint. */
646
+ const WS_PATH = "/ios/v1";
647
+ /** Exact route path of the loopback-only bootstrap token endpoint. */
648
+ const PAIR_TOKEN_PATH = "/remote-bridge/pair/token";
649
+ //#endregion
650
+ //#region src/core/extension.ts
651
+ /** Cordis service this seam is published under. */
652
+ const REMOTE_BRIDGE_SERVICE = "remoteBridge";
653
+ /**
654
+ * The methods extensions registered, and the capability each one needs.
655
+ *
656
+ * Every connection consults this registry; nothing else holds extension state,
657
+ * so unmounting one plugin withdraws exactly its own methods.
658
+ */
659
+ var RemoteBridgeRegistry = class {
660
+ #methods = /* @__PURE__ */ new Map();
661
+ /**
662
+ * Register one table of methods, all or nothing: a table naming a protocol
663
+ * method, an empty name or a name already taken is refused before any of its
664
+ * methods becomes callable.
665
+ * @param table - the methods and the capability they require.
666
+ * @returns the disposer withdrawing this table; idempotent.
667
+ */
668
+ registerMethods(table) {
669
+ const entries = [];
670
+ for (const [name, handler] of Object.entries(table.methods)) {
671
+ if (name.trim() === "") throw new Error("a remote bridge method needs a non-empty name");
672
+ if (typeof handler !== "function") throw new Error(`remote bridge method ${name} has no handler`);
673
+ if (KNOWN_METHODS.has(name)) throw new Error(`remote bridge method ${name} is a protocol method`);
674
+ if (this.#methods.has(name)) throw new Error(`remote bridge method ${name} is already registered`);
675
+ entries.push([name, {
676
+ capability: table.capability,
677
+ handler
678
+ }]);
679
+ }
680
+ for (const [name, entry] of entries) this.#methods.set(name, entry);
681
+ return () => {
682
+ for (const [name, entry] of entries) if (this.#methods.get(name) === entry) this.#methods.delete(name);
683
+ };
684
+ }
685
+ /**
686
+ * @param method - the method name a client asked for.
687
+ * @returns whether any plugin registered it, whatever capability it requires.
688
+ */
689
+ has(method) {
690
+ return this.#methods.has(method);
691
+ }
692
+ /**
693
+ * @param method - the method name a client asked for.
694
+ * @param declares - whether the calling connection declared a capability.
695
+ * @returns the handler when the caller may use the method, else undefined.
696
+ */
697
+ handlerFor(method, declares) {
698
+ const entry = this.#methods.get(method);
699
+ if (entry === void 0) return void 0;
700
+ if (entry.capability !== void 0 && !declares(entry.capability)) return void 0;
701
+ return entry.handler;
702
+ }
703
+ };
704
+ /**
705
+ * Compose the published seam over a registry and a fan-out.
706
+ * @param methods - the registry this bridge owns.
707
+ * @param fanout - the hub's broadcast pair.
708
+ * @returns the face a plugin resolves from {@link REMOTE_BRIDGE_SERVICE}.
709
+ */
710
+ function createRemoteBridgeFace(methods, fanout) {
711
+ return {
712
+ registerMethods: (table) => methods.registerMethods(table),
713
+ broadcast: (topic, payload, capability) => capability === void 0 ? fanout.broadcast(topic, payload) : fanout.broadcastTo(capability, topic, payload)
714
+ };
715
+ }
716
+ /** Namespace-qualified and bare spellings of the same failure. */
717
+ function codeIsOneOf(error, bare) {
718
+ const code = error?.code;
719
+ return code === bare || code === `gateway/${bare}`;
720
+ }
721
+ /**
722
+ * Whether a failure means the target service has not finished activating.
723
+ * This is the one failure worth retrying: the same call succeeds moments later.
724
+ */
725
+ function isServiceUnavailable(error) {
726
+ return codeIsOneOf(error, "service-unavailable");
727
+ }
728
+ function delay(ms) {
729
+ return new Promise((resolve) => {
730
+ setTimeout(resolve, ms);
731
+ });
732
+ }
733
+ /** One-line text of a failure, for a decideable reason the phone can show. */
734
+ function failureText(error) {
735
+ const message = error instanceof Error ? error.message : String(error);
736
+ return message.length > 300 ? `${message.slice(0, 297)}...` : message;
737
+ }
738
+ /**
739
+ * The failure's own code, for the response envelope. The gateway's codes cross
740
+ * to the phone unchanged (`gateway/arguments-invalid` and friends) so the client
741
+ * can tell "this deployment cannot" from "this build is wrong"; anything
742
+ * without a string code is `internal`.
743
+ */
744
+ function errorCodeOf(error, fallback) {
745
+ const code = error?.code;
746
+ return typeof code === "string" && code !== "" ? code : fallback;
747
+ }
748
+ /**
749
+ * Run one unary call, retrying only the service-activation window.
750
+ * @param run - the call to attempt.
751
+ * @param options.attempts - total tries (default {@link SERVICE_UNAVAILABLE_ATTEMPTS}).
752
+ * @param options.backoffMs - wait between tries (default {@link SERVICE_UNAVAILABLE_BACKOFF_MS}).
753
+ * @returns the call's own result or failure; the failure is never swallowed.
754
+ */
755
+ async function withServiceUnavailableRetry(run, options = {}) {
756
+ const attempts = options.attempts ?? 5;
757
+ const backoffMs = options.backoffMs ?? 2e3;
758
+ for (let attempt = 1;; attempt += 1) try {
759
+ return await run();
760
+ } catch (error) {
761
+ if (!isServiceUnavailable(error) || attempt >= attempts) throw error;
762
+ await delay(backoffMs);
763
+ }
764
+ }
765
+ /**
766
+ * Project one host job into the protocol's own fields.
767
+ *
768
+ * Explicitly field by field: an unknown key the host adds later must not reach
769
+ * the wire, and a value of the wrong type is dropped rather than coerced — the
770
+ * key is simply absent, which a client already has to handle.
771
+ * @param job - the host's projection.
772
+ * @returns the minimal row, or undefined when the host gave no usable id.
773
+ */
774
+ function projectJob(job) {
775
+ if (typeof job.id !== "string" || job.id === "") return void 0;
776
+ return {
777
+ id: job.id,
778
+ kind: typeof job.kind === "string" ? job.kind : "",
779
+ status: typeof job.status === "string" ? job.status : "",
780
+ ...typeof job.label === "string" && job.label !== "" ? { label: job.label } : {},
781
+ ...typeof job.owner === "string" && job.owner !== "" ? { ownerSessionId: job.owner } : {},
782
+ ...Number.isFinite(job.startedAt) ? { startedAt: job.startedAt } : {},
783
+ ...Number.isFinite(job.finishedAt) ? { finishedAt: job.finishedAt } : {}
784
+ };
785
+ }
786
+ /**
787
+ * Project a whole host roster.
788
+ * @param jobs - the host's projections.
789
+ * @returns the rows, in the host's own order, bounded by {@link JOBS_MAX_ROWS}.
790
+ */
791
+ function projectJobs(jobs) {
792
+ const rows = [];
793
+ for (const job of jobs) {
794
+ const row = projectJob(job);
795
+ if (row !== void 0) rows.push(row);
796
+ if (rows.length >= 200) break;
797
+ }
798
+ return rows;
799
+ }
800
+ /** The key one scope is subscribed and deduplicated under. */
801
+ function scopeKey(sessionId) {
802
+ return sessionId === void 0 ? "unowned" : `session:${sessionId}`;
803
+ }
804
+ /**
805
+ * Whether one job belongs in one scope's visible set.
806
+ *
807
+ * This is the host's own fence, restated for routing events: a session sees its
808
+ * own jobs plus every unowned one, and the unowned scope sees exactly the jobs
809
+ * no session owns.
810
+ * @param owner - the job's owning session, when it has one.
811
+ * @param sessionId - the scope's session; omitted for the unowned scope.
812
+ */
813
+ function inScope(owner, sessionId) {
814
+ if (sessionId === void 0) return owner === void 0;
815
+ return owner === void 0 || owner === sessionId;
816
+ }
817
+ /**
818
+ * The bridge's background-job reads and change notifications.
819
+ *
820
+ * One instance is built per host mount and shared by every connection, because
821
+ * a job is a fact about the host, not about the device that asked. Scopes are
822
+ * reference-counted by their listeners: a scope nobody watches holds no timer,
823
+ * and the registry subscription itself exists only while at least one scope
824
+ * does. That is what makes "a connection that never asked receives nothing"
825
+ * structural rather than a filter someone has to remember to apply.
826
+ */
827
+ var JobRoster = class {
828
+ #options;
829
+ #flushMs;
830
+ #watches = /* @__PURE__ */ new Map();
831
+ #unsubscribe;
832
+ #disposed = false;
833
+ constructor(options) {
834
+ this.#options = options;
835
+ this.#flushMs = options.flushMs ?? 100;
836
+ }
837
+ /** @returns whether this host composes a job registry at all. */
838
+ get available() {
839
+ return this.#face() !== void 0;
840
+ }
841
+ /**
842
+ * Read one scope's visible set.
843
+ *
844
+ * Synchronous, because the host registry projects in memory: no stream is
845
+ * opened and no socket is waited on, which is what makes this cheap enough to
846
+ * answer on request and again after every coalesced burst.
847
+ * @param sessionId - the scope's session; omitted for the unowned scope.
848
+ * @returns the payload, or undefined when this host has no job registry.
849
+ */
850
+ read(sessionId) {
851
+ const face = this.#face();
852
+ if (face === void 0) return void 0;
853
+ try {
854
+ const jobs = face.list(sessionId);
855
+ return {
856
+ ...sessionId === void 0 ? {} : { sessionId },
857
+ scope: sessionId === void 0 ? "unowned" : "session",
858
+ jobs: projectJobs(Array.isArray(jobs) ? jobs : [])
859
+ };
860
+ } catch (error) {
861
+ this.#options.log(`the background job roster could not be read: ${failureText(error)}`);
862
+ return;
863
+ }
864
+ }
865
+ /**
866
+ * Watch one scope, and publish each coalesced change to every watcher of it.
867
+ *
868
+ * Watching is what a `jobs.list` call earns: a scope nobody listed is never
869
+ * read again, so a phone that declared the capability and asked for nothing
870
+ * receives no `jobs.changed` — the requirement that keeps N open sessions
871
+ * from becoming N sets streaming at a phone that asked for none.
872
+ * @param sessionId - the scope's session; omitted for the unowned scope.
873
+ * @param listener - receives one whole-set payload per coalesced change.
874
+ * @returns the disposer, or undefined when this host has no job registry.
875
+ */
876
+ watch(sessionId, listener) {
877
+ if (this.#disposed || this.#face() === void 0) return void 0;
878
+ const key = scopeKey(sessionId);
879
+ let watch = this.#watches.get(key);
880
+ if (watch === void 0) {
881
+ watch = {
882
+ sessionId,
883
+ key,
884
+ listeners: /* @__PURE__ */ new Set(),
885
+ timer: void 0
886
+ };
887
+ this.#watches.set(key, watch);
888
+ }
889
+ watch.listeners.add(listener);
890
+ this.#subscribe();
891
+ return () => {
892
+ this.#unwatch(watch, listener);
893
+ };
894
+ }
895
+ /** Stop every watch and clear every timer. Idempotent. */
896
+ dispose() {
897
+ if (this.#disposed) return;
898
+ this.#disposed = true;
899
+ for (const watch of this.#watches.values()) {
900
+ if (watch.timer !== void 0) clearTimeout(watch.timer);
901
+ watch.timer = void 0;
902
+ }
903
+ this.#watches.clear();
904
+ this.#unsubscribe?.();
905
+ this.#unsubscribe = void 0;
906
+ }
907
+ /** Resolve the host registry now, or undefined when this host mounts none. */
908
+ #face() {
909
+ if (this.#disposed) return void 0;
910
+ try {
911
+ return this.#options.faces().jobs;
912
+ } catch (error) {
913
+ this.#options.log(`the background job registry could not be resolved: ${failureText(error)}`);
914
+ return;
915
+ }
916
+ }
917
+ /** Subscribe to the registry's event stream once, while any scope is watched. */
918
+ #subscribe() {
919
+ if (this.#unsubscribe !== void 0) return;
920
+ const face = this.#face();
921
+ if (face === void 0) return;
922
+ try {
923
+ this.#unsubscribe = face.events.subscribe({ owners: "all" }, (event) => {
924
+ this.#onEvent(event);
925
+ });
926
+ } catch (error) {
927
+ this.#options.log(`the background job event stream could not be subscribed: ${failureText(error)}`);
928
+ }
929
+ }
930
+ /** Route one registry event to the scopes it can change. */
931
+ #onEvent(event) {
932
+ if (event.type === "output") return;
933
+ const owner = event.job?.owner ?? event.owner;
934
+ for (const watch of this.#watches.values()) if (inScope(owner, watch.sessionId)) this.#schedule(watch);
935
+ }
936
+ /** Arm one scope's coalescing window; a burst inside it publishes once. */
937
+ #schedule(watch) {
938
+ if (watch.timer !== void 0) return;
939
+ const timer = setTimeout(() => {
940
+ watch.timer = void 0;
941
+ this.#publish(watch);
942
+ }, this.#flushMs);
943
+ timer.unref?.();
944
+ watch.timer = timer;
945
+ }
946
+ /** Read one scope again and hand its whole set to every watcher. */
947
+ #publish(watch) {
948
+ if (this.#disposed || this.#watches.get(watch.key) !== watch) return;
949
+ const payload = this.read(watch.sessionId);
950
+ if (payload === void 0) return;
951
+ for (const listener of watch.listeners) listener(payload);
952
+ }
953
+ /** Drop one listener, and its scope with it when it was the last. */
954
+ #unwatch(watch, listener) {
955
+ if (this.#watches.get(watch.key) !== watch) return;
956
+ watch.listeners.delete(listener);
957
+ if (watch.listeners.size > 0) return;
958
+ if (watch.timer !== void 0) clearTimeout(watch.timer);
959
+ watch.timer = void 0;
960
+ this.#watches.delete(watch.key);
961
+ if (this.#watches.size > 0) return;
962
+ this.#unsubscribe?.();
963
+ this.#unsubscribe = void 0;
964
+ }
965
+ };
966
+ //#endregion
967
+ //#region src/core/delta.ts
968
+ /**
969
+ * Per-connection delta windows: what a client that already holds a copy of a
970
+ * whole set is sent instead of the whole set again.
971
+ *
972
+ * The difference is computed here, in the bridge, because the bridge is the
973
+ * only place that holds what the host said last — the host itself is asked for
974
+ * its complete answer every time and never learns that a client is caching one.
975
+ * That is the whole point of this module: the saving is bytes on the wire
976
+ * between the bridge and the phone, not a change to any host API.
977
+ *
978
+ * Three rules live in this file and nowhere else, so the roster and the board
979
+ * cannot disagree about them:
980
+ *
981
+ * - a delta is only diffed against the exact set this window last sent, and
982
+ * only for a token this window itself issued; anything else answers a reset,
983
+ * because a wrong base is a wrong answer;
984
+ * - a change is a change of the serialised row, not of a timestamp — the host's
985
+ * `updatedAt` is not a change signal for every field, and a row whose body is
986
+ * byte-identical has not changed;
987
+ * - a delta that is not clearly smaller than the reset body is not worth
988
+ * sending: past {@link DELTA_CHANGED_RATIO} of the rows, the answer is a reset.
989
+ * @module dsh-remote-bridge/core/delta
990
+ */
991
+ /** Largest roster one connection's delta window retains. */
992
+ const ROSTER_DELTA_MAX_ROWS = 5e3;
993
+ /**
994
+ * Identity of this bridge process, minted once at load.
995
+ *
996
+ * Part of every token, so a token minted by an earlier boot can never be
997
+ * replayed into a delta against a set that boot never sent. It is not a secret
998
+ * on its own — the per-window secret beside it is what makes a token
999
+ * unguessable, and the exact comparison below is what actually decides.
1000
+ */
1001
+ const BOOT_ID = randomBytes(8).toString("hex");
1002
+ /**
1003
+ * One connection's view of one set: the rows it last sent, and the token that
1004
+ * set was announced under.
1005
+ *
1006
+ * A window is created lazily by whoever needs it and lives exactly as long as
1007
+ * the connection that owns it (see {@link RemoteBridgeDeltas}), so two
1008
+ * connections never share a base and a dropped connection leaks nothing.
1009
+ */
1010
+ var DeltaWindow = class {
1011
+ #maxRows;
1012
+ /**
1013
+ * This window's own secret: what makes one connection's token useless to
1014
+ * another, and what a client cannot derive from a token it was given.
1015
+ */
1016
+ #secret = randomBytes(8).toString("hex");
1017
+ #sent = /* @__PURE__ */ new Map();
1018
+ #revision = 0;
1019
+ #token;
1020
+ constructor(limits) {
1021
+ this.#maxRows = limits.maxRows;
1022
+ }
1023
+ /**
1024
+ * Answer one call over the current full set.
1025
+ * @param rows - the complete set, exactly as the host answered it this time.
1026
+ * @param since - the opaque token the client sent, if it sent one.
1027
+ * @returns a reset carrying every row, or a delta against the last set sent.
1028
+ */
1029
+ answer(rows, since) {
1030
+ const current = /* @__PURE__ */ new Map();
1031
+ for (const row of rows) current.set(row.id, JSON.stringify(row));
1032
+ if (current.size > this.#maxRows) return this.#forget(rows);
1033
+ if (since === void 0 || this.#token === void 0 || since !== this.#token) return this.#reset(rows, current);
1034
+ const changed = [];
1035
+ for (const row of rows) if (this.#sent.get(row.id) !== current.get(row.id)) changed.push(row);
1036
+ const removed = [];
1037
+ for (const id of this.#sent.keys()) if (!current.has(id)) removed.push(id);
1038
+ if (changed.length > .6 * rows.length) return this.#reset(rows, current);
1039
+ this.#sent.clear();
1040
+ for (const [id, body] of current) this.#sent.set(id, body);
1041
+ return {
1042
+ mode: "delta",
1043
+ token: this.#nextToken(),
1044
+ changed,
1045
+ removed
1046
+ };
1047
+ }
1048
+ /**
1049
+ * Answer the whole set and keep it as the next base.
1050
+ * @param rows - the complete set.
1051
+ * @param current - the set, serialised, to retain.
1052
+ */
1053
+ #reset(rows, current) {
1054
+ this.#sent.clear();
1055
+ for (const [id, body] of current) this.#sent.set(id, body);
1056
+ return {
1057
+ mode: "reset",
1058
+ token: this.#nextToken(),
1059
+ rows
1060
+ };
1061
+ }
1062
+ /**
1063
+ * Answer the whole set and retain nothing.
1064
+ *
1065
+ * The empty token says so: this answer cannot be continued from, because
1066
+ * there is no copy of it here to diff against. A client that sends it back is
1067
+ * answered a reset, which is the truth rather than a wrong delta.
1068
+ * @param rows - the complete set.
1069
+ */
1070
+ #forget(rows) {
1071
+ this.#sent.clear();
1072
+ this.#token = void 0;
1073
+ this.#revision += 1;
1074
+ return {
1075
+ mode: "reset",
1076
+ token: "",
1077
+ rows
1078
+ };
1079
+ }
1080
+ /** @returns the token for the set just retained, bumping the window's revision. */
1081
+ #nextToken() {
1082
+ this.#revision += 1;
1083
+ this.#token = `d1.${BOOT_ID}.${this.#secret}.${this.#revision}`;
1084
+ return this.#token;
1085
+ }
1086
+ };
1087
+ /**
1088
+ * The delta windows one connection owns, by the name its owner keys them with.
1089
+ *
1090
+ * Held on the connection, so the state is released exactly when the connection
1091
+ * is: there is no second registry to expire, and no connection's window can be
1092
+ * read by another.
1093
+ */
1094
+ var RemoteBridgeDeltas = class {
1095
+ #windows = /* @__PURE__ */ new Map();
1096
+ /**
1097
+ * @param key - the window's name within this connection; one set, one key.
1098
+ * @param limits - the cap this window retains.
1099
+ * @returns the window, created on first use.
1100
+ */
1101
+ window(key, limits) {
1102
+ const known = this.#windows.get(key);
1103
+ if (known !== void 0) return known;
1104
+ const created = new DeltaWindow(limits);
1105
+ this.#windows.set(key, created);
1106
+ return created;
1107
+ }
1108
+ /**
1109
+ * @param key - one window's name.
1110
+ *
1111
+ * Drops that window and the set it retained, so its token names nothing and
1112
+ * the next call answers a reset. Used when a connection stops being served
1113
+ * increments at all, which must cost it no memory either.
1114
+ */
1115
+ drop(key) {
1116
+ this.#windows.delete(key);
1117
+ }
1118
+ /** Drop every window: called when the owning connection is torn down. */
1119
+ clear() {
1120
+ this.#windows.clear();
1121
+ }
1122
+ };
338
1123
  /**
339
1124
  * The durable entry types a protocol v1 client renders — `user/message`,
340
- * `assistant/message`, `tool/call` and `tool/result`. Everything else in a
341
- * turn's entries is the harness's own bookkeeping, which the client can only
342
- * count as unknown, so a client that asks for a trimmed baseline is not sent it.
1125
+ * `assistant/message`, `tool/call`, `tool/result` and `subagent/catalog`.
1126
+ * Everything else in a turn's entries is the harness's own bookkeeping, which
1127
+ * the client can only count as unknown, so a client that asks for a trimmed
1128
+ * baseline is not sent it.
1129
+ *
1130
+ * The catalog entry is here because it is the baseline half of the subagent
1131
+ * thread: a phone that opens a session after children were spawned has no other
1132
+ * way to learn that they exist, their labels, their modes or the call that
1133
+ * spawned them. Without it the thread header can only be inferred from agent
1134
+ * messages, and every field the catalog carries is lost.
343
1135
  */
344
1136
  const RENDERED_ENTRY_TYPES = /* @__PURE__ */ new Set([
345
1137
  "user/message",
346
1138
  "assistant/message",
347
1139
  "tool/call",
348
- "tool/result"
1140
+ "tool/result",
1141
+ "subagent/catalog"
349
1142
  ]);
350
1143
  function isRecord$2(value) {
351
1144
  return typeof value === "object" && value !== null && !Array.isArray(value);
@@ -396,14 +1189,168 @@ var MessageIndex = class {
396
1189
  has(id) {
397
1190
  return this.#ids.has(id);
398
1191
  }
399
- /** Remember one message, evicting the oldest entry past {@link USER_MESSAGE_MEMORY}. */
400
- remember(id) {
401
- this.#ids.add(id);
402
- while (this.#ids.size > 512) {
403
- const oldest = this.#ids.values().next();
404
- if (oldest.done === true) break;
405
- this.#ids.delete(oldest.value);
1192
+ /** Remember one message, evicting the oldest entry past {@link USER_MESSAGE_MEMORY}. */
1193
+ remember(id) {
1194
+ this.#ids.add(id);
1195
+ while (this.#ids.size > 512) {
1196
+ const oldest = this.#ids.values().next();
1197
+ if (oldest.done === true) break;
1198
+ this.#ids.delete(oldest.value);
1199
+ }
1200
+ }
1201
+ };
1202
+ /**
1203
+ * The child sessions one `tool/result` payload names as spawned.
1204
+ *
1205
+ * A spawn answers with a handle, and the handle is the only place a durable
1206
+ * record ties a child id to the call that made it: the catalog event names the
1207
+ * child but not the call. Two shapes are written by this harness and both are
1208
+ * read here, verbatim from a real session log —
1209
+ *
1210
+ * - the activation handle the `subagent` tool returns, alone or nested in the
1211
+ * object a `run_code` program returns:
1212
+ * `{"a":{"kind":"activation","subagentId":"b0a3a569-…"}}`;
1213
+ * - the plain notice the same tool prints when it runs without PTC:
1214
+ * `started subagent d605390b-66f6-474b-956d-0824ec2103e0`.
1215
+ *
1216
+ * Nothing else is accepted: a `list_agents` answer that happens to list a child
1217
+ * (`[{"kind":"child","id":"…"}]`) carries neither signature, so it can never
1218
+ * lend its own call id to a thread it did not spawn.
1219
+ * @param data - one durable `tool/result` payload.
1220
+ * @returns the child ids the payload names, in the order it names them.
1221
+ */
1222
+ function spawnedChildIdsOf(data) {
1223
+ const message = isRecord$2(data) ? data.message : void 0;
1224
+ const ids = [];
1225
+ for (const id of spawnIdsIn(textOfBlocks(isRecord$2(message) ? message.content : void 0))) if (!ids.includes(id)) ids.push(id);
1226
+ return ids;
1227
+ }
1228
+ /** The spawn signatures above, as the two patterns that carry a child id. */
1229
+ const SPAWN_HANDLE_IDS = /"subagentId"\s*:\s*"([^"]+)"/g;
1230
+ const SPAWN_NOTICE_IDS = /started subagent\s+([0-9A-Za-z][0-9A-Za-z_.-]{3,})/g;
1231
+ /** @returns every child id one result's text names through a spawn signature. */
1232
+ function spawnIdsIn(text) {
1233
+ const ids = [];
1234
+ for (const pattern of [SPAWN_HANDLE_IDS, SPAWN_NOTICE_IDS]) for (const match of text.matchAll(pattern)) {
1235
+ const id = match[1];
1236
+ if (id !== void 0 && id !== "" && !ids.includes(id)) ids.push(id);
1237
+ }
1238
+ return ids;
1239
+ }
1240
+ /**
1241
+ * The child-to-call evidence one session's records already carry.
1242
+ *
1243
+ * A spawn's result can be projected after the catalog it belongs to, so a
1244
+ * baseline reads the whole record list for this evidence before it resolves any
1245
+ * catalog entry: the snapshot is a session that has already happened, and the
1246
+ * answer it gives a client must not depend on where in the list it stopped
1247
+ * looking. The live subscription feeds the same evidence in as it arrives.
1248
+ * @param records - durable follow records, oldest first.
1249
+ * @returns every child id a `tool/result` names, with the call that produced it.
1250
+ */
1251
+ function spawnCallEvidence(records) {
1252
+ const evidence = /* @__PURE__ */ new Map();
1253
+ for (const record of records) {
1254
+ const event = isRecord$2(record) ? record.event : void 0;
1255
+ if (!isRecord$2(event) || event.type !== "tool/result") continue;
1256
+ const callId = toolResultCallIdOf(event.data);
1257
+ if (callId === void 0) continue;
1258
+ for (const childId of spawnedChildIdsOf(event.data)) evidence.set(childId, callId);
1259
+ }
1260
+ return evidence;
1261
+ }
1262
+ /** @returns the call id one durable `tool/result` payload belongs to. */
1263
+ function toolResultCallIdOf(data) {
1264
+ const callId = stringField(isRecord$2(data) ? data.message : void 0, "toolCallId");
1265
+ return callId === void 0 || callId === "" ? void 0 : callId;
1266
+ }
1267
+ /**
1268
+ * Correlates one `subagent/catalog` event to the tool call that spawned the
1269
+ * child it registers.
1270
+ *
1271
+ * The catalog event names the child but not the call, so the call is read from
1272
+ * two places, in this order:
1273
+ *
1274
+ * 1. the spawn's own `tool/result`, which names the child it started
1275
+ * ({@link spawnedChildIdsOf}). This is the decisive one: it survives a step
1276
+ * that issued several calls, and a step whose one call started a whole team
1277
+ * of children, because the payload says which child it is about.
1278
+ * 2. the nearest preceding `tool/call` of the same turn and step, which is
1279
+ * decidable only while one call is the whole story. A step with several
1280
+ * calls leaves two candidates, and a call that already produced a child
1281
+ * leaves one call behind two children; a guessed id would point a thread at
1282
+ * the wrong card.
1283
+ *
1284
+ * Neither holds: undefined, and the wire carries no call id at all. The same
1285
+ * index answers both paths — a subscription as it watches, and a baseline after
1286
+ * reading the session's records — so the two can never disagree about which rule
1287
+ * decides a given catalog.
1288
+ */
1289
+ var SpawnCallIndex = class {
1290
+ #named;
1291
+ #turn;
1292
+ #step;
1293
+ #calls = [];
1294
+ #correlated = /* @__PURE__ */ new Set();
1295
+ /**
1296
+ * @param evidence - child-to-call pairs already read from the session's
1297
+ * results, for the baseline path; empty for a live subscription.
1298
+ */
1299
+ constructor(evidence = /* @__PURE__ */ new Map()) {
1300
+ this.#named = new Map(evidence);
1301
+ }
1302
+ /**
1303
+ * Read one durable event into the correlation state.
1304
+ *
1305
+ * A turn boundary or a new step is the only reset: a call belongs to the step
1306
+ * that issued it, so a call from an earlier step can never be the nearest
1307
+ * preceding one.
1308
+ */
1309
+ observe(type, data) {
1310
+ if (type === "turn/start") {
1311
+ this.#turn = numberOf(isRecord$2(data) ? data.turn : void 0);
1312
+ this.#step = void 0;
1313
+ this.#calls = [];
1314
+ this.#correlated.clear();
1315
+ return;
1316
+ }
1317
+ if (type === "step/start") {
1318
+ this.#turn = numberOf(isRecord$2(data) ? data.turn : void 0) ?? this.#turn;
1319
+ this.#step = numberOf(isRecord$2(data) ? data.step : void 0);
1320
+ this.#calls = [];
1321
+ this.#correlated.clear();
1322
+ return;
1323
+ }
1324
+ if (type === "tool/result") {
1325
+ const callId = toolResultCallIdOf(data);
1326
+ if (callId === void 0) return;
1327
+ for (const childId of spawnedChildIdsOf(data)) this.#named.set(childId, callId);
1328
+ return;
1329
+ }
1330
+ if (type !== "tool/call") return;
1331
+ const callId = stringField(data, "callId");
1332
+ if (callId === void 0 || callId === "") return;
1333
+ this.#turn = numberOf(isRecord$2(data) ? data.turn : void 0) ?? this.#turn;
1334
+ this.#step = numberOf(isRecord$2(data) ? data.step : void 0) ?? this.#step;
1335
+ this.#calls.push(callId);
1336
+ }
1337
+ /**
1338
+ * The call that spawned the child a catalog event registered.
1339
+ * @param childId - the child that catalog event carries.
1340
+ * @returns its call id, or undefined when nothing on the wire decides it.
1341
+ */
1342
+ spawnCallId(childId) {
1343
+ const named = this.#named.get(childId);
1344
+ if (named !== void 0) {
1345
+ this.#correlated.add(named);
1346
+ return named;
406
1347
  }
1348
+ if (this.#turn === void 0 || this.#step === void 0) return void 0;
1349
+ if (this.#calls.length !== 1) return void 0;
1350
+ const callId = this.#calls[0];
1351
+ if (callId === void 0 || this.#correlated.has(callId)) return void 0;
1352
+ this.#correlated.add(callId);
1353
+ return callId;
407
1354
  }
408
1355
  };
409
1356
  /**
@@ -427,8 +1374,9 @@ function readFollowBaseline(frame) {
427
1374
  * @param frame - one `SessionFollowFrame`.
428
1375
  * @param toolCalls - this connection's tool-call memory.
429
1376
  * @param messages - this connection's published-user-message memory.
1377
+ * @param memory - the stream's own correlation state, and which optional kinds it declared.
430
1378
  */
431
- function deltaOfFollowFrame(frame, toolCalls, messages) {
1379
+ function deltaOfFollowFrame(frame, toolCalls, messages, memory = {}) {
432
1380
  if (!isRecord$2(frame)) return void 0;
433
1381
  if (frame.type === "assistant-stream") return deltaOfAssistantStream(frame.frame, toolCalls);
434
1382
  if (frame.type !== "event") return void 0;
@@ -436,11 +1384,78 @@ function deltaOfFollowFrame(frame, toolCalls, messages) {
436
1384
  if (!isRecord$2(event)) return void 0;
437
1385
  const type = event.type;
438
1386
  const data = event.data;
1387
+ memory.spawnCalls?.observe(typeof type === "string" ? type : "", data);
439
1388
  if (type === "tool/result") return toolResultDelta(data);
440
1389
  if (type === "turn/end") return turnEndDelta(data);
441
1390
  if (type === "tool/call") return assembledToolCallDelta(data, toolCalls);
442
1391
  if (type === "user/message") return userMessageDelta(data, messages);
443
1392
  if (type === "assistant/message") return usageDelta(data);
1393
+ if (type === "subagent/catalog") return memory.subagentThread === true ? subagentDelta(data, memory.spawnCalls) : void 0;
1394
+ }
1395
+ /**
1396
+ * Map one durable `subagent/catalog` to the increment that opens a thread on a
1397
+ * subscribed phone.
1398
+ *
1399
+ * The child id is the only field the host must have written: without it the
1400
+ * event registers nothing this protocol can address, so it publishes nothing
1401
+ * rather than an increment a client could not use.
1402
+ */
1403
+ function subagentDelta(data, spawnCalls) {
1404
+ const childId = stringField(data, "childId");
1405
+ if (childId === void 0 || childId === "") return void 0;
1406
+ const label = textField(data, "label");
1407
+ const mode = textField(data, "mode");
1408
+ const callId = spawnCalls?.spawnCallId(childId);
1409
+ return {
1410
+ kind: "subagent",
1411
+ childId,
1412
+ ...label === void 0 ? {} : { label },
1413
+ ...mode === void 0 ? {} : { mode },
1414
+ ...callId === void 0 ? {} : { callId }
1415
+ };
1416
+ }
1417
+ /**
1418
+ * Where one durable user message came from.
1419
+ *
1420
+ * Absent when the event carries no readable `source.kind`: an event from a log
1421
+ * written before sources existed has no source kind, and inventing one would
1422
+ * report an origin the host never recorded.
1423
+ */
1424
+ function actorOf(data) {
1425
+ return actorOfSource(isRecord$2(data) ? data.source : void 0);
1426
+ }
1427
+ /**
1428
+ * Derive one message's actor from the host's own `source` record, mechanically.
1429
+ * @param source - the `source` member of a durable `user/message`.
1430
+ * @returns the actor, or undefined when the source carries no kind.
1431
+ */
1432
+ function actorOfSource(source) {
1433
+ const sourceKind = stringField(source, "kind");
1434
+ if (sourceKind === void 0 || sourceKind === "") return void 0;
1435
+ const sessionId = stringField(source, "senderSessionId");
1436
+ const label = textField(source, "label");
1437
+ const named = {
1438
+ sourceKind,
1439
+ ...label === void 0 ? {} : { label },
1440
+ ...sessionId === void 0 || sessionId === "" ? {} : { sessionId }
1441
+ };
1442
+ if (sourceKind === "user" || sourceKind === "user-approval") return {
1443
+ kind: "human",
1444
+ ...named
1445
+ };
1446
+ if (sourceKind === "agent-message" || sourceKind === "subagent-settled") return {
1447
+ kind: "agent",
1448
+ ...named
1449
+ };
1450
+ return {
1451
+ kind: "system",
1452
+ ...named
1453
+ };
1454
+ }
1455
+ /** @returns a non-empty string field, or undefined. */
1456
+ function textField(value, key) {
1457
+ const field = stringField(value, key);
1458
+ return field === void 0 || field === "" ? void 0 : field;
444
1459
  }
445
1460
  function deltaOfAssistantStream(frame, toolCalls) {
446
1461
  if (!isRecord$2(frame) || frame.type !== "chunk") return void 0;
@@ -534,11 +1549,13 @@ function userMessageDelta(data, messages) {
534
1549
  messages.remember(messageId);
535
1550
  }
536
1551
  const attachments = imageAttachmentsOf(data.content);
1552
+ const actor = actorOf(data);
537
1553
  return {
538
1554
  kind: "user-message",
539
1555
  text: textOfBlocks(data.content),
540
1556
  ...messageId === void 0 ? {} : { messageId },
541
- ...attachments.length === 0 ? {} : { attachments }
1557
+ ...attachments.length === 0 ? {} : { attachments },
1558
+ ...actor === void 0 ? {} : { actor }
542
1559
  };
543
1560
  }
544
1561
  /**
@@ -611,15 +1628,23 @@ function numberOf(value) {
611
1628
  }
612
1629
  /**
613
1630
  * Project a follow baseline's records into turns.
1631
+ *
1632
+ * A `subagent/catalog` entry leaves here carrying the call that spawned its
1633
+ * child in `data.callId`, decided by the same {@link SpawnCallIndex} a live
1634
+ * subscription uses — so the baseline half and the live half of the thread
1635
+ * cannot answer differently about one catalog.
614
1636
  * @param records - the baseline's durable records, oldest first.
615
1637
  * @returns one turn per `turn/start`, plus a lead-in turn when records precede the first one.
616
1638
  */
617
1639
  function turnsOfRecords(records) {
618
1640
  const turns = [];
1641
+ const spawns = new SpawnCallIndex(spawnCallEvidence(records));
619
1642
  let current;
620
1643
  for (const record of records) {
621
- const entry = snapshotEntryOf(record);
622
- if (entry === void 0) continue;
1644
+ const projected = snapshotEntryOf(record);
1645
+ if (projected === void 0) continue;
1646
+ spawns.observe(projected.type, projected.data);
1647
+ const entry = projected.type === "subagent/catalog" ? catalogEntryWithCall(projected, spawns) : projected;
623
1648
  if (entry.type === "turn/start" && current !== void 0 && current.endSeq === 0) {
624
1649
  turns.push(current);
625
1650
  current = void 0;
@@ -645,6 +1670,31 @@ function turnsOfRecords(records) {
645
1670
  return turns;
646
1671
  }
647
1672
  /**
1673
+ * One `subagent/catalog` entry with the call that spawned its child, when the
1674
+ * session decides it.
1675
+ *
1676
+ * Nothing else about the entry moves: the durable payload is copied as it
1677
+ * arrived and `callId` is added beside it, exactly as the live `subagent`
1678
+ * delta carries the same field under §13.3. A catalog whose spawning call is
1679
+ * undecidable is passed through untouched rather than guessed at.
1680
+ * @param entry - one projected catalog entry.
1681
+ * @param spawns - the index holding this session's spawn evidence.
1682
+ */
1683
+ function catalogEntryWithCall(entry, spawns) {
1684
+ if (!isRecord$2(entry.data)) return entry;
1685
+ const childId = stringField(entry.data, "childId");
1686
+ if (childId === void 0 || childId === "") return entry;
1687
+ const callId = spawns.spawnCallId(childId);
1688
+ if (callId === void 0) return entry;
1689
+ return {
1690
+ ...entry,
1691
+ data: {
1692
+ ...entry.data,
1693
+ callId
1694
+ }
1695
+ };
1696
+ }
1697
+ /**
648
1698
  * Drop the entries of each turn that a protocol v1 client would not render.
649
1699
  *
650
1700
  * Only the inside of a turn changes: which turns survive, their order, their
@@ -730,6 +1780,39 @@ function pageTurns(turns, before, maxBytes, measure) {
730
1780
  start += 1;
731
1781
  }
732
1782
  }
1783
+ /**
1784
+ * Durable seq of a projection's oldest entry, or undefined when it carries none.
1785
+ *
1786
+ * The oldest entry is the first entry of the first turn that has one: a trimmed
1787
+ * turn may keep no entry at all, so the scan skips those rather than reading
1788
+ * `turns[0].entries[0]` and calling an empty-leading view an empty window.
1789
+ * @param turns - the projection to read, in order.
1790
+ */
1791
+ function oldestEntrySeq(turns) {
1792
+ for (const turn of turns) {
1793
+ const first = turn.entries[0];
1794
+ if (first !== void 0) return first.seq;
1795
+ }
1796
+ }
1797
+ /**
1798
+ * Cut a projection at a durable watermark, keeping what is strictly above it.
1799
+ *
1800
+ * This is the forward twin of {@link pageTurns}' own slice: the same
1801
+ * entry-level rule (`seq` is a durable watermark, not an index), the same
1802
+ * turn rebuild, so an incremental snapshot carries turns shaped exactly like
1803
+ * the baseline it continues — a turn whose remaining entries are fewer keeps
1804
+ * its own `seq`, `endSeq`, `reason` and `time`.
1805
+ * @param turns - the projection to cut, in order.
1806
+ * @param watermark - exclusive durable watermark; entries at or below it are dropped.
1807
+ */
1808
+ function turnsAbove(turns, watermark) {
1809
+ const kept = [];
1810
+ for (const turn of turns) for (const entry of turn.entries) if (entry.seq > watermark) kept.push({
1811
+ turn,
1812
+ entry
1813
+ });
1814
+ return groupEntries(kept);
1815
+ }
733
1816
  /** Rebuild the turn list around one contiguous run of entries. */
734
1817
  function groupEntries(items) {
735
1818
  const page = [];
@@ -756,11 +1839,13 @@ function snapshotEntryOf(record) {
756
1839
  const event = isRecord$2(record) ? record.event : void 0;
757
1840
  if (!isRecord$2(event)) return void 0;
758
1841
  if (typeof event.type !== "string" || typeof event.seq !== "number") return void 0;
1842
+ const actor = event.type === "user/message" ? actorOf(event.data) : void 0;
759
1843
  return {
760
1844
  seq: event.seq,
761
1845
  time: typeof event.time === "number" ? event.time : 0,
762
1846
  type: event.type,
763
- data: event.data
1847
+ data: event.data,
1848
+ ...actor === void 0 ? {} : { actor }
764
1849
  };
765
1850
  }
766
1851
  //#endregion
@@ -888,6 +1973,43 @@ function decodeClientFrame(text) {
888
1973
  function encodeFrame(frame) {
889
1974
  return JSON.stringify(frame);
890
1975
  }
1976
+ /**
1977
+ * Decide the wire form of one encoded frame.
1978
+ *
1979
+ * The decision is a byte-level question only, asked after the frame has been
1980
+ * measured against {@link MAX_FRAME_BYTES}: the text is deflated exactly as it
1981
+ * stands, so a peer that inflates gets back the frame the text path would have
1982
+ * written. A frame below {@link FRAME_DEFLATE_MIN_BYTES}, and a frame DEFLATE
1983
+ * does not shrink (zlib's default level), both stay text — a binary frame that
1984
+ * is larger than the text it replaces would pay for itself in neither direction.
1985
+ * @param text - the frame as {@link encodeFrame} produced it.
1986
+ * @param compress - whether the peer declared the capability that permits this.
1987
+ * @param deflate - the compressor: zlib's raw DEFLATE at its default level, unless
1988
+ * a caller injects one. Real deflate shrinks every frame that reaches the
1989
+ * threshold, so an injected compressor is the only way to exercise the no-gain
1990
+ * rule with content that truly cannot be compressed.
1991
+ * @returns the text, or raw DEFLATE of it.
1992
+ */
1993
+ function outboundPayloadOf(text, compress, deflate = deflateRawSync) {
1994
+ if (!compress) return {
1995
+ binary: false,
1996
+ text
1997
+ };
1998
+ const source = Buffer.from(text, "utf8");
1999
+ if (source.length < 1024) return {
2000
+ binary: false,
2001
+ text
2002
+ };
2003
+ const deflated = deflate(source);
2004
+ if (deflated.length >= source.length) return {
2005
+ binary: false,
2006
+ text
2007
+ };
2008
+ return {
2009
+ binary: true,
2010
+ deflated
2011
+ };
2012
+ }
891
2013
  /** One successful response frame. */
892
2014
  function responseFrame(id, result) {
893
2015
  return {
@@ -927,145 +2049,6 @@ var EventSequence = class {
927
2049
  return this.#next;
928
2050
  }
929
2051
  };
930
- /** Namespace-qualified and bare spellings of the same failure. */
931
- function codeIsOneOf(error, bare) {
932
- const code = error?.code;
933
- return code === bare || code === `gateway/${bare}`;
934
- }
935
- /**
936
- * Whether a failure means the target service has not finished activating.
937
- * This is the one failure worth retrying: the same call succeeds moments later.
938
- */
939
- function isServiceUnavailable(error) {
940
- return codeIsOneOf(error, "service-unavailable");
941
- }
942
- function delay(ms) {
943
- return new Promise((resolve) => {
944
- setTimeout(resolve, ms);
945
- });
946
- }
947
- /** One-line text of a failure, for a decideable reason the phone can show. */
948
- function failureText(error) {
949
- const message = error instanceof Error ? error.message : String(error);
950
- return message.length > 300 ? `${message.slice(0, 297)}...` : message;
951
- }
952
- /**
953
- * The failure's own code, for the response envelope. The gateway's codes cross
954
- * to the phone unchanged (`gateway/arguments-invalid` and friends) so the client
955
- * can tell "this deployment cannot" from "this build is wrong"; anything
956
- * without a string code is `internal`.
957
- */
958
- function errorCodeOf(error, fallback) {
959
- const code = error?.code;
960
- return typeof code === "string" && code !== "" ? code : fallback;
961
- }
962
- /**
963
- * Run one unary call, retrying only the service-activation window.
964
- * @param run - the call to attempt.
965
- * @param options.attempts - total tries (default {@link SERVICE_UNAVAILABLE_ATTEMPTS}).
966
- * @param options.backoffMs - wait between tries (default {@link SERVICE_UNAVAILABLE_BACKOFF_MS}).
967
- * @returns the call's own result or failure; the failure is never swallowed.
968
- */
969
- async function withServiceUnavailableRetry(run, options = {}) {
970
- const attempts = options.attempts ?? 5;
971
- const backoffMs = options.backoffMs ?? 2e3;
972
- for (let attempt = 1;; attempt += 1) try {
973
- return await run();
974
- } catch (error) {
975
- if (!isServiceUnavailable(error) || attempt >= attempts) throw error;
976
- await delay(backoffMs);
977
- }
978
- }
979
- //#endregion
980
- //#region src/core/protocol.ts
981
- /**
982
- * The frozen protocol surface: method names, topic names, refusal codes, and
983
- * the one authorization rule the dispatcher enforces before any method runs.
984
- * @module dsh-remote-bridge/core/protocol
985
- */
986
- /** Client-callable methods of protocol v1. */
987
- const METHOD_HELLO = "hello";
988
- const METHOD_SESSION_LIST = "session.list";
989
- const METHOD_SESSION_TITLES = "session.titles";
990
- const METHOD_SESSION_SNAPSHOT = "session.snapshot";
991
- const METHOD_SESSION_HISTORY = "session.history";
992
- const METHOD_SESSION_PROMPT = "session.prompt";
993
- const METHOD_SESSION_INTERRUPT = "session.interrupt";
994
- const METHOD_SESSION_ATTACHMENT = "session.attachment";
995
- const METHOD_SESSION_PERMISSIONS = "session.permissions";
996
- const METHOD_SESSION_SET_PERMISSION = "session.setPermission";
997
- const METHOD_SESSION_MODELS = "session.models";
998
- const METHOD_SESSION_SET_MODEL = "session.setModel";
999
- const METHOD_PAIR_BEGIN = "pair.begin";
1000
- const METHOD_PAIR_FINISH = "pair.finish";
1001
- const METHOD_APPROVAL_RESOLVE = "approval.resolve";
1002
- const METHOD_QUESTION_ANSWER = "question.answer";
1003
- /** Server-pushed topics of protocol v1. */
1004
- const TOPIC_SESSION_DELTA = "session.delta";
1005
- const TOPIC_QUESTION_REQUEST = "question.request";
1006
- /**
1007
- * Capability a client declares in `hello`'s `cap` array to be shown the
1008
- * host's pending user questions and to answer them with `question.answer`.
1009
- *
1010
- * Declaring it is what makes `question.request` reachable and what makes the
1011
- * method part of that client's protocol at all: a client that does not declare
1012
- * it — including every client written before this channel existed — receives no
1013
- * such event, and its `question.answer` is refused as an unknown method,
1014
- * exactly as that frame was refused before.
1015
- */
1016
- const CAP_QUESTIONS = "questions.v1";
1017
- /**
1018
- * Methods an unpaired connection may still call: the handshake itself and the
1019
- * two pairing steps. Everything else answers `unpaired` — a caller can pair
1020
- * without a device token, but cannot touch a session without one.
1021
- */
1022
- const UNPAIRED_METHODS = /* @__PURE__ */ new Set([
1023
- METHOD_HELLO,
1024
- METHOD_PAIR_BEGIN,
1025
- METHOD_PAIR_FINISH
1026
- ]);
1027
- /** Every method this protocol version serves. */
1028
- const KNOWN_METHODS = /* @__PURE__ */ new Set([
1029
- METHOD_HELLO,
1030
- METHOD_SESSION_LIST,
1031
- METHOD_SESSION_TITLES,
1032
- METHOD_SESSION_SNAPSHOT,
1033
- METHOD_SESSION_HISTORY,
1034
- METHOD_SESSION_PROMPT,
1035
- METHOD_SESSION_INTERRUPT,
1036
- METHOD_SESSION_ATTACHMENT,
1037
- METHOD_SESSION_PERMISSIONS,
1038
- METHOD_SESSION_SET_PERMISSION,
1039
- METHOD_SESSION_MODELS,
1040
- METHOD_SESSION_SET_MODEL,
1041
- METHOD_PAIR_BEGIN,
1042
- METHOD_PAIR_FINISH,
1043
- METHOD_APPROVAL_RESOLVE,
1044
- METHOD_QUESTION_ANSWER
1045
- ]);
1046
- /** Refusal codes the bridge itself raises (DSH failures cross as their own code). */
1047
- const CODE_UNPAIRED = "unpaired";
1048
- const CODE_UNKNOWN_METHOD = "unknown-method";
1049
- const CODE_INVALID_ARGS = "invalid-args";
1050
- const CODE_PROTO_UNSUPPORTED = "proto-unsupported";
1051
- const CODE_TOKEN_INVALID = "token-invalid";
1052
- const CODE_NONCE_INVALID = "nonce-invalid";
1053
- const CODE_APPROVAL_UNKNOWN = "approval-unknown";
1054
- /**
1055
- * The bridge does not hold the named question: it never claimed that call id, it
1056
- * already answered it, or the host no longer holds it as answerable. Host
1057
- * failures crossing this method keep their own codes instead.
1058
- */
1059
- const CODE_QUESTION_UNKNOWN = "question-unknown";
1060
- const CODE_SNAPSHOT_UNAVAILABLE = "snapshot-unavailable";
1061
- const CODE_SNAPSHOT_TOO_LARGE = "snapshot-too-large";
1062
- const CODE_INTERNAL = "internal";
1063
- /** `server` field of the hello response. */
1064
- const SERVER_ID = "dsh-remote-bridge";
1065
- /** Exact route path of the bridge's WebSocket endpoint. */
1066
- const WS_PATH = "/ios/v1";
1067
- /** Exact route path of the loopback-only bootstrap token endpoint. */
1068
- const PAIR_TOKEN_PATH = "/remote-bridge/pair/token";
1069
2052
  //#endregion
1070
2053
  //#region src/core/session-meta.ts
1071
2054
  /**
@@ -1228,6 +2211,16 @@ const WIRE_TABLE = [
1228
2211
  method: "list",
1229
2212
  wire: "_request"
1230
2213
  },
2214
+ {
2215
+ namespace: "session",
2216
+ method: "create",
2217
+ wire: "request"
2218
+ },
2219
+ {
2220
+ namespace: "session",
2221
+ method: "fork",
2222
+ wire: "request"
2223
+ },
1231
2224
  {
1232
2225
  namespace: "session",
1233
2226
  method: "page",
@@ -1268,6 +2261,11 @@ const WIRE_TABLE = [
1268
2261
  method: "selectModel",
1269
2262
  wire: "request"
1270
2263
  },
2264
+ {
2265
+ namespace: "agentPresets",
2266
+ method: "list",
2267
+ wire: "none"
2268
+ },
1271
2269
  {
1272
2270
  namespace: "userQuestions",
1273
2271
  method: "answer",
@@ -1277,6 +2275,11 @@ const WIRE_TABLE = [
1277
2275
  "answer"
1278
2276
  ] }
1279
2277
  },
2278
+ {
2279
+ namespace: "userQuestions",
2280
+ method: "attachWait",
2281
+ wire: { names: ["agentId", "callId"] }
2282
+ },
1280
2283
  {
1281
2284
  namespace: "pluginInventory",
1282
2285
  method: "list",
@@ -1293,33 +2296,181 @@ function wireRowFor(namespace, method) {
1293
2296
  return WIRE_TABLE.find((row) => row.namespace === namespace && row.method === method);
1294
2297
  }
1295
2298
  /**
1296
- * Build the `args` object for one endpoint.
2299
+ * Build the `args` object for one endpoint.
2300
+ *
2301
+ * An untabulated endpoint falls back to `{ request }`: that is the layout of
2302
+ * every tabulated endpoint but a few, and a wrong guess fails loudly at the
2303
+ * gateway with `arguments-invalid` rather than silently invoking the wrong
2304
+ * shape. A multi-parameter endpoint carries one key per declared name, and a
2305
+ * name the caller left out stays out — the gateway refuses it by name, which is
2306
+ * the failure a caller should see.
2307
+ * @param namespace - Remote namespace.
2308
+ * @param method - Service method name.
2309
+ * @param request - the endpoint's request payload.
2310
+ * @returns the exact named-argument object.
2311
+ */
2312
+ function wireArgs(namespace, method, request = {}) {
2313
+ const wire = wireRowFor(namespace, method)?.wire ?? "request";
2314
+ if (wire === "none") return {};
2315
+ if (typeof wire === "object") {
2316
+ const named = {};
2317
+ for (const name of wire.names) if (Object.hasOwn(request, name)) named[name] = request[name];
2318
+ return named;
2319
+ }
2320
+ return { [wire]: request };
2321
+ }
2322
+ //#endregion
2323
+ //#region src/core/ws-frames.ts
2324
+ /**
2325
+ * RFC 6455 server-side framing, kept as pure functions so the length, mask and
2326
+ * opcode rules are unit-tested without a socket.
2327
+ *
2328
+ * Only what a server must accept is implemented: client frames are always
2329
+ * masked, one logical message may arrive as a text frame or as a fragmented
2330
+ * sequence, and anything the protocol forbids answers with the close code that
2331
+ * names the violation instead of being ignored.
2332
+ * @module dsh-remote-bridge/core/ws-frames
2333
+ */
2334
+ /** The magic GUID every WebSocket handshake is keyed with. */
2335
+ const WS_GUID = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
2336
+ /** Close code for a protocol violation. */
2337
+ const CLOSE_PROTOCOL_ERROR = 1002;
2338
+ /** Close code for a message this bridge will not carry. */
2339
+ const CLOSE_UNSUPPORTED_DATA = 1003;
2340
+ /** Close code for a message past the size this bridge will carry. */
2341
+ const CLOSE_TOO_LARGE = 1009;
2342
+ /**
2343
+ * Close code for a peer that stopped answering: a liveness ping went out and no
2344
+ * frame at all came back before its deadline.
1297
2345
  *
1298
- * An untabulated endpoint falls back to `{ request }`: that is the layout of
1299
- * every tabulated endpoint but a few, and a wrong guess fails loudly at the
1300
- * gateway with `arguments-invalid` rather than silently invoking the wrong
1301
- * shape. A multi-parameter endpoint carries one key per declared name, and a
1302
- * name the caller left out stays out — the gateway refuses it by name, which is
1303
- * the failure a caller should see.
1304
- * @param namespace - Remote namespace.
1305
- * @param method - Service method name.
1306
- * @param request - the endpoint's request payload.
1307
- * @returns the exact named-argument object.
2346
+ * It is an application-range code (4000-4999), so a client can tell a peer that
2347
+ * went silent from a protocol fault, from a frame this bridge will not carry,
2348
+ * and from the ordinary 1001 teardown of a bridge that is unloading.
1308
2349
  */
1309
- function wireArgs(namespace, method, request = {}) {
1310
- const wire = wireRowFor(namespace, method)?.wire ?? "request";
1311
- if (wire === "none") return {};
1312
- if (typeof wire === "object") {
1313
- const named = {};
1314
- for (const name of wire.names) if (Object.hasOwn(request, name)) named[name] = request[name];
1315
- return named;
2350
+ const CLOSE_LIVENESS_TIMEOUT = 4e3;
2351
+ /** @returns the `Sec-WebSocket-Accept` value for a client's key. */
2352
+ function webSocketAccept(secWebSocketKey) {
2353
+ return createHash("sha1").update(`${secWebSocketKey}${WS_GUID}`).digest("base64");
2354
+ }
2355
+ /**
2356
+ * Decode one frame from the head of a buffer.
2357
+ * @param buffer - the bytes received so far.
2358
+ * @param maxBytes - largest payload this bridge accepts.
2359
+ */
2360
+ function parseClientFrame(buffer, maxBytes) {
2361
+ if (buffer.length < 2) return { status: "incomplete" };
2362
+ const first = buffer[0] ?? 0;
2363
+ const second = buffer[1] ?? 0;
2364
+ const fin = (first & 128) !== 0;
2365
+ if ((first & 112) !== 0) return fault(CLOSE_PROTOCOL_ERROR, "reserved bits set");
2366
+ const opcode = first & 15;
2367
+ if (!((second & 128) !== 0)) return fault(CLOSE_PROTOCOL_ERROR, "client frames must be masked");
2368
+ let length = second & 127;
2369
+ let offset = 2;
2370
+ if (length === 126) {
2371
+ if (buffer.length < offset + 2) return { status: "incomplete" };
2372
+ length = buffer.readUInt16BE(offset);
2373
+ offset += 2;
2374
+ } else if (length === 127) {
2375
+ if (buffer.length < offset + 8) return { status: "incomplete" };
2376
+ const wide = buffer.readBigUInt64BE(offset);
2377
+ if (wide > BigInt(Number.MAX_SAFE_INTEGER)) return fault(CLOSE_TOO_LARGE, "frame length out of range");
2378
+ length = Number(wide);
2379
+ offset += 8;
1316
2380
  }
1317
- return { [wire]: request };
2381
+ if (length > maxBytes) return fault(CLOSE_TOO_LARGE, `frame payload exceeds ${maxBytes} bytes`);
2382
+ if (buffer.length < offset + 4 + length) return { status: "incomplete" };
2383
+ const mask = buffer.subarray(offset, offset + 4);
2384
+ offset += 4;
2385
+ const payload = Buffer.allocUnsafe(length);
2386
+ for (let index = 0; index < length; index += 1) payload[index] = (buffer[offset + index] ?? 0) ^ (mask[index % 4] ?? 0);
2387
+ return {
2388
+ status: "frame",
2389
+ frame: {
2390
+ fin,
2391
+ opcode,
2392
+ payload,
2393
+ consumed: offset + length
2394
+ }
2395
+ };
2396
+ }
2397
+ function fault(closeCode, reason) {
2398
+ return {
2399
+ status: "fault",
2400
+ closeCode,
2401
+ reason
2402
+ };
2403
+ }
2404
+ /**
2405
+ * Encode one server frame. Server frames are never masked.
2406
+ * @param opcode - the frame opcode.
2407
+ * @param payload - already-serialized payload bytes.
2408
+ * @param fin - whether this frame completes the message.
2409
+ */
2410
+ function encodeServerFrame(opcode, payload, fin = true) {
2411
+ const length = payload.length;
2412
+ const header = length < 126 ? Buffer.from([(fin ? 128 : 0) | opcode, length]) : length <= 65535 ? Buffer.from([
2413
+ (fin ? 128 : 0) | opcode,
2414
+ 126,
2415
+ length >> 8,
2416
+ length & 255
2417
+ ]) : (() => {
2418
+ const wide = Buffer.alloc(10);
2419
+ wide[0] = (fin ? 128 : 0) | opcode;
2420
+ wide[1] = 127;
2421
+ wide.writeBigUInt64BE(BigInt(length), 2);
2422
+ return wide;
2423
+ })();
2424
+ return Buffer.concat([header, payload]);
2425
+ }
2426
+ /** Encode one text message. */
2427
+ function encodeTextFrame(text) {
2428
+ return encodeServerFrame(1, Buffer.from(text, "utf8"));
2429
+ }
2430
+ /** Encode one binary message: already-encoded payload bytes, never a text frame. */
2431
+ function encodeBinaryFrame(payload) {
2432
+ return encodeServerFrame(2, payload);
2433
+ }
2434
+ /** Encode one close frame with a code and a short reason. */
2435
+ function encodeCloseFrame(code, reason) {
2436
+ const text = Buffer.from(reason, "utf8").subarray(0, 123);
2437
+ const payload = Buffer.alloc(2 + text.length);
2438
+ payload.writeUInt16BE(code, 0);
2439
+ text.copy(payload, 2);
2440
+ return encodeServerFrame(8, payload);
1318
2441
  }
2442
+ /**
2443
+ * Deadline behind one liveness ping: a peer that sends no frame at all within
2444
+ * this long of the ping is torn down.
2445
+ *
2446
+ * It only ever exists because a ping was sent — a connection the host has not
2447
+ * pinged has no deadline — so a quiet client is never closed for being quiet,
2448
+ * only for failing to answer. The measured one-way path over the relay is about
2449
+ * 410 ms (2026-10-19), so this is more than an order of magnitude of slack.
2450
+ */
2451
+ const LIVENESS_TIMEOUT_MS = 1e4;
1319
2452
  /** How long `session.snapshot` waits for its follow stream's opening frame. */
1320
2453
  const SNAPSHOT_OPEN_TIMEOUT_MS = 1e4;
1321
2454
  /** Default byte budget of one `session.history` page: 512 KiB. */
1322
2455
  const HISTORY_PAGE_BYTES = 512 * 1024;
2456
+ /**
2457
+ * Window one `session.history.deep` read asks DSH for: at least 50 user or
2458
+ * assistant messages across at least 2 turns, and never more than 500 messages.
2459
+ *
2460
+ * It is the window the harness's own Web client pages history with, and it is
2461
+ * deliberately wider than one answer: a byte budget is the caller's, so the
2462
+ * store is asked for a whole span once and the bridge then cuts that span to
2463
+ * `maxBytes` by entry. Nothing in the answer depends on where the store cut:
2464
+ * the host's `hasMore` is folded into the answer's own `hasMore`, and the
2465
+ * cursor is always the oldest entry the answer carries.
2466
+ */
2467
+ const DEEP_HISTORY_WINDOW = {
2468
+ maxMessages: 500,
2469
+ turnWindow: {
2470
+ minMessages: 50,
2471
+ minTurns: 2
2472
+ }
2473
+ };
1323
2474
  /** Largest base64 text one prompt attachment may carry: 6 MiB (protocol §10.2). */
1324
2475
  const PROMPT_ATTACHMENT_MAX_BYTES = 6 * 1024 * 1024;
1325
2476
  function refusal(code, msg) {
@@ -1329,6 +2480,35 @@ function refusal(code, msg) {
1329
2480
  msg
1330
2481
  };
1331
2482
  }
2483
+ /**
2484
+ * The opaque `since` token one request carried.
2485
+ *
2486
+ * Anything that is not a non-empty string is "no usable token", which answers a
2487
+ * reset — the same answer an unknown token gets, because a request that named
2488
+ * no base cannot be diffed against one.
2489
+ * @param payload - the request's `p`.
2490
+ * @returns the token, or undefined.
2491
+ */
2492
+ function sinceOf(payload) {
2493
+ const value = payload.since;
2494
+ return typeof value === "string" && value !== "" ? value : void 0;
2495
+ }
2496
+ /**
2497
+ * Whether a plugin's answer is one of the two shapes the seam defines.
2498
+ *
2499
+ * An extension is ordinary JavaScript calling into this bridge, so a result the
2500
+ * type system never saw still has to leave the client with an answer instead of
2501
+ * a lost frame.
2502
+ * @param value - what the extension method returned.
2503
+ * @returns whether it carries a usable answer or refusal.
2504
+ */
2505
+ function isMethodResult(value) {
2506
+ if (typeof value !== "object" || value === null) return false;
2507
+ const result = value;
2508
+ if (result.ok === true) return true;
2509
+ if (result.ok !== false) return false;
2510
+ return typeof result.code === "string" && result.code !== "" && typeof result.msg === "string";
2511
+ }
1332
2512
  function isRecord(value) {
1333
2513
  return typeof value === "object" && value !== null && !Array.isArray(value);
1334
2514
  }
@@ -1346,6 +2526,13 @@ function pageNumber(value) {
1346
2526
  return typeof value === "number" && Number.isSafeInteger(value) && value >= 0 ? value : void 0;
1347
2527
  }
1348
2528
  /**
2529
+ * @param value - a request's event-seq member, or undefined.
2530
+ * @returns the seq, or undefined when it is not a positive safe integer.
2531
+ */
2532
+ function seqNumber(value) {
2533
+ return typeof value === "number" && Number.isSafeInteger(value) && value >= 1 ? value : void 0;
2534
+ }
2535
+ /**
1349
2536
  * Read one request's page budget.
1350
2537
  *
1351
2538
  * An absent budget is {@link HISTORY_PAGE_BYTES}; a budget an encoded page
@@ -1368,6 +2555,41 @@ function pageBudgetOf(value, method) {
1368
2555
  };
1369
2556
  }
1370
2557
  /**
2558
+ * Read one listing's compact roster parameters.
2559
+ *
2560
+ * The parameters are the switch, not the capability: a listing that names none
2561
+ * of them is answered today's body byte for byte, so declaring
2562
+ * {@link CAP_ROSTER_COMPACT} alone can never change what a client is sent. The
2563
+ * page size reuses {@link pageNumber} and is bounded by the same cap the roster
2564
+ * delta window retains ({@link ROSTER_DELTA_MAX_ROWS}), so no second limit is
2565
+ * invented here. A value that cannot be honoured — a page size of zero,
2566
+ * negative, fractional or past that cap, an `after` that is not an id, a `cwd`
2567
+ * that is not a boolean — is refused rather than clamped, so a caller never
2568
+ * mistakes a silently reduced page for the one it asked for.
2569
+ * @param payload - the request's `p`.
2570
+ * @returns the parameters, or `ok` with no `compact` member when there are none.
2571
+ */
2572
+ function rosterCompactOf(payload) {
2573
+ const { cwd: rawCwd, maxRows: rawRows, after: rawAfter } = payload;
2574
+ if (rawCwd === void 0 && rawRows === void 0 && rawAfter === void 0) return { ok: true };
2575
+ if (rawCwd !== void 0 && typeof rawCwd !== "boolean") return refusal(CODE_INVALID_ARGS, "session.list cwd must be a boolean");
2576
+ let maxRows;
2577
+ if (rawRows !== void 0) {
2578
+ maxRows = pageNumber(rawRows);
2579
+ if (maxRows === void 0 || maxRows < 1 || maxRows > 5e3) return refusal(CODE_INVALID_ARGS, `session.list maxRows must be between 1 and ${ROSTER_DELTA_MAX_ROWS}`);
2580
+ }
2581
+ const after = rawAfter === void 0 ? void 0 : optionalText(rawAfter);
2582
+ if (rawAfter !== void 0 && after === void 0) return refusal(CODE_INVALID_ARGS, "session.list after must be a non-empty session id");
2583
+ return {
2584
+ ok: true,
2585
+ compact: {
2586
+ ...maxRows === void 0 ? {} : { maxRows },
2587
+ ...after === void 0 ? {} : { after },
2588
+ cwd: rawCwd === true
2589
+ }
2590
+ };
2591
+ }
2592
+ /**
1371
2593
  * Read the capability names a `hello` announced.
1372
2594
  *
1373
2595
  * A capability is an announcement, not a negotiation: an unreadable `cap`, an
@@ -1488,7 +2710,14 @@ function promptAttachmentsOf(value) {
1488
2710
  * one frame at a time by the carrier's reader, and the only background work is
1489
2711
  * a subscription's own drain loop.
1490
2712
  */
2713
+ /**
2714
+ * Monotonic source for {@link BridgeConnection.id}. The counter is process-wide
2715
+ * and never reused, so a plugin keying connection-scoped state can trust that a
2716
+ * reclaimed id belongs to no later socket.
2717
+ */
2718
+ let connectionSeq = 0;
1491
2719
  var BridgeConnection = class {
2720
+ #id = `c${connectionSeq += 1}`;
1492
2721
  #options;
1493
2722
  #transport;
1494
2723
  #sequence = new EventSequence();
@@ -1499,10 +2728,41 @@ var BridgeConnection = class {
1499
2728
  #capabilities = /* @__PURE__ */ new Set();
1500
2729
  /** Delegated children this connection has learned the durable parent of, by child id. */
1501
2730
  #lineage = /* @__PURE__ */ new Map();
2731
+ /**
2732
+ * Sessions this connection may read: the ordinary sessions the host's roster
2733
+ * names, plus every session this connection already opened. A delegated child
2734
+ * belongs here only once it has been opened itself, never because the roster
2735
+ * merely names it.
2736
+ */
2737
+ #authorized = /* @__PURE__ */ new Set();
2738
+ /**
2739
+ * The job scopes this connection asked about, by {@link scopeKey}, with the
2740
+ * disposer of each watch. A scope is watched exactly while this connection has
2741
+ * listed it: that is what keeps a declared capability from turning into a
2742
+ * subscription the client never requested.
2743
+ */
2744
+ #jobWatches = /* @__PURE__ */ new Map();
2745
+ /**
2746
+ * The `updatedAt` this connection already sent per session id, for the
2747
+ * compact roster: a row whose value this client holds is answered without it.
2748
+ * Pruned to the roster on every compact answer, so it is bounded by the set it
2749
+ * describes rather than by every id the connection ever listed.
2750
+ */
2751
+ #rosterUpdatedAt = /* @__PURE__ */ new Map();
2752
+ /** The last roster payload this connection received per scope key, for whole-set dedupe. */
2753
+ #jobSeen = /* @__PURE__ */ new Map();
2754
+ /**
2755
+ * This connection's delta windows, one per set it is served incrementally.
2756
+ * Held here so the base is released exactly when the connection is, and so no
2757
+ * two connections can ever diff against each other's set.
2758
+ */
2759
+ #deltas = new RemoteBridgeDeltas();
1502
2760
  #lineageRead = false;
1503
2761
  #deviceId;
1504
2762
  #nonce;
1505
2763
  #heartbeat;
2764
+ /** The deadline armed by the liveness ping currently outstanding, if any. */
2765
+ #liveness;
1506
2766
  #lastSendAt = 0;
1507
2767
  #disposed = false;
1508
2768
  constructor(options, transport, auth) {
@@ -1524,6 +2784,13 @@ var BridgeConnection = class {
1524
2784
  return this.#disposed;
1525
2785
  }
1526
2786
  /**
2787
+ * @returns this connection's identity for the extension seam. Stable for the
2788
+ * life of the socket and never reused by a later one.
2789
+ */
2790
+ get id() {
2791
+ return this.#id;
2792
+ }
2793
+ /**
1527
2794
  * @param capability - one capability name this protocol defines.
1528
2795
  * @returns whether this connection announced it in `hello`.
1529
2796
  */
@@ -1535,10 +2802,12 @@ var BridgeConnection = class {
1535
2802
  if (this.#heartbeat !== void 0) return;
1536
2803
  const period = this.#options.heartbeatMs ?? 2e4;
1537
2804
  this.#heartbeat = setInterval(() => {
1538
- if (this.#options.now() - this.#lastSendAt >= period) this.#send({
2805
+ if (this.#options.now() - this.#lastSendAt < period) return;
2806
+ this.#send({
1539
2807
  t: "ping",
1540
2808
  ts: this.#options.now()
1541
2809
  });
2810
+ this.#armLivenessDeadline();
1542
2811
  }, period);
1543
2812
  this.#heartbeat.unref?.();
1544
2813
  }
@@ -1555,6 +2824,7 @@ var BridgeConnection = class {
1555
2824
  */
1556
2825
  async handleText(text) {
1557
2826
  if (this.#disposed) return;
2827
+ this.#clearLivenessDeadline();
1558
2828
  const outcome = decodeClientFrame(text);
1559
2829
  if (!outcome.ok) {
1560
2830
  this.#send(errorFrame(outcome.id, outcome.code, outcome.msg));
@@ -1586,30 +2856,63 @@ var BridgeConnection = class {
1586
2856
  * Tear the connection down: stop the heartbeat, abort every follow stream it
1587
2857
  * owns, and tell the carrier to go away. Idempotent, and safe to call from a
1588
2858
  * socket error handler — a carrier whose socket already closed ignores it.
2859
+ * @param close - the close frame to send instead of the bridge-unloading one.
2860
+ * Only the liveness deadline passes it, so a client can tell a peer that
2861
+ * stopped answering from an ordinary teardown; every other caller leaves it
2862
+ * out and keeps the same code and reason as before.
1589
2863
  */
1590
- dispose() {
2864
+ dispose(close) {
1591
2865
  if (this.#disposed) return;
1592
2866
  this.#disposed = true;
2867
+ this.#clearLivenessDeadline();
1593
2868
  if (this.#heartbeat !== void 0) {
1594
2869
  clearInterval(this.#heartbeat);
1595
2870
  this.#heartbeat = void 0;
1596
2871
  }
1597
2872
  for (const subscription of this.#subscriptions.values()) subscription.controller.abort();
1598
2873
  this.#subscriptions.clear();
1599
- this.#transport.close(1001, "the bridge is going away");
2874
+ for (const dispose of this.#jobWatches.values()) dispose();
2875
+ this.#jobWatches.clear();
2876
+ this.#jobSeen.clear();
2877
+ this.#deltas.clear();
2878
+ this.#transport.close(close?.code ?? 1001, close?.reason ?? "the bridge is going away");
2879
+ }
2880
+ /** Arm the deadline behind one liveness ping, replacing any earlier one. */
2881
+ #armLivenessDeadline() {
2882
+ this.#clearLivenessDeadline();
2883
+ this.#liveness = setTimeout(() => {
2884
+ this.#options.log(`connection closed on the liveness deadline: no frame within ${LIVENESS_TIMEOUT_MS} ms of a liveness ping`);
2885
+ this.dispose({
2886
+ code: CLOSE_LIVENESS_TIMEOUT,
2887
+ reason: `no frame within ${LIVENESS_TIMEOUT_MS} ms of a liveness ping`
2888
+ });
2889
+ }, LIVENESS_TIMEOUT_MS);
2890
+ this.#liveness.unref?.();
2891
+ }
2892
+ /** Drop the deadline: the peer answered, or the connection is already gone. */
2893
+ #clearLivenessDeadline() {
2894
+ if (this.#liveness === void 0) return;
2895
+ clearTimeout(this.#liveness);
2896
+ this.#liveness = void 0;
1600
2897
  }
1601
2898
  async #dispatch(frame) {
1602
- if (!KNOWN_METHODS.has(frame.m)) return refusal(CODE_UNKNOWN_METHOD, `unknown method ${frame.m}`);
2899
+ const builtIn = KNOWN_METHODS.has(frame.m);
2900
+ if (!builtIn && this.#options.extensions?.has(frame.m) !== true) return refusal(CODE_UNKNOWN_METHOD, `unknown method ${frame.m}`);
1603
2901
  if (frame.m === "question.answer" && !this.declares("questions.v1")) return refusal(CODE_UNKNOWN_METHOD, `unknown method ${frame.m}`);
2902
+ if (frame.m === "jobs.list" && !this.declares("jobs.v1")) return refusal(CODE_UNKNOWN_METHOD, `unknown method ${frame.m}`);
2903
+ if ((frame.m === "presets.list" || frame.m === "session.create") && !this.declares("agents.v1")) return refusal(CODE_UNKNOWN_METHOD, `unknown method ${frame.m}`);
2904
+ if (frame.m === "session.fork" && !this.declares("session.fork.v1")) return refusal(CODE_UNKNOWN_METHOD, `unknown method ${frame.m}`);
1604
2905
  if (!this.paired && !UNPAIRED_METHODS.has(frame.m)) return refusal(CODE_UNPAIRED, "this connection is not paired");
2906
+ if (!builtIn) return await this.#extension(frame);
1605
2907
  switch (frame.m) {
1606
2908
  case METHOD_HELLO: return this.#hello(frame.p);
1607
2909
  case METHOD_PAIR_BEGIN: return this.#pairBegin(frame.p);
1608
2910
  case METHOD_PAIR_FINISH: return await this.#pairFinish(frame.p);
1609
- case METHOD_SESSION_LIST: return await this.#sessionList();
2911
+ case METHOD_SESSION_LIST: return await this.#sessionList(frame.p);
1610
2912
  case METHOD_SESSION_TITLES: return this.#sessionTitles(frame.p);
1611
2913
  case METHOD_SESSION_SNAPSHOT: return await this.#sessionSnapshot(frame.p, frame.id);
1612
2914
  case METHOD_SESSION_HISTORY: return await this.#sessionHistory(frame.p, frame.id);
2915
+ case METHOD_SESSION_HISTORY_DEEP: return await this.#sessionHistoryDeep(frame.p, frame.id);
1613
2916
  case METHOD_SESSION_PROMPT: return await this.#sessionPrompt(frame.p);
1614
2917
  case METHOD_SESSION_INTERRUPT: return await this.#sessionInterrupt(frame.p);
1615
2918
  case METHOD_SESSION_ATTACHMENT: return await this.#sessionAttachment(frame.p, frame.id);
@@ -1619,19 +2922,53 @@ var BridgeConnection = class {
1619
2922
  case METHOD_SESSION_SET_MODEL: return await this.#sessionSetModel(frame.p);
1620
2923
  case METHOD_APPROVAL_RESOLVE: return this.#approvalResolve(frame.p);
1621
2924
  case METHOD_QUESTION_ANSWER: return await this.#questionAnswer(frame.p);
2925
+ case METHOD_JOBS_LIST: return await this.#jobsList(frame.p);
2926
+ case METHOD_PRESETS_LIST: return await this.#presetsList();
2927
+ case METHOD_SESSION_CREATE: return await this.#sessionCreate(frame.p);
2928
+ case METHOD_SESSION_FORK: return await this.#sessionFork(frame.p);
1622
2929
  default: return refusal(CODE_UNKNOWN_METHOD, `unknown method ${frame.m}`);
1623
2930
  }
1624
2931
  }
2932
+ /**
2933
+ * Run one method a plugin registered on the extension seam.
2934
+ *
2935
+ * The plugin decides everything: whether the payload is usable, what an
2936
+ * answer looks like, and which refusal codes exist in its own protocol. This
2937
+ * bridge only forwards — and owns `internal`, because a handler that throws
2938
+ * or answers nothing usable has left the client with no other honest code.
2939
+ * @param frame - the request being served.
2940
+ */
2941
+ async #extension(frame) {
2942
+ const handler = this.#options.extensions?.handlerFor(frame.m, (capability) => this.declares(capability));
2943
+ if (handler === void 0) return refusal(CODE_UNKNOWN_METHOD, `unknown method ${frame.m}`);
2944
+ try {
2945
+ const result = await handler(frame.p, {
2946
+ connectionId: this.#id,
2947
+ declares: (capability) => this.declares(capability),
2948
+ deltas: this.#deltas
2949
+ });
2950
+ if (!isMethodResult(result)) return refusal(CODE_INTERNAL, `${frame.m} answered no result`);
2951
+ return result.ok ? {
2952
+ ok: true,
2953
+ r: result.r
2954
+ } : refusal(result.code, result.msg);
2955
+ } catch (error) {
2956
+ this.#options.log(`${frame.m} failed: ${failureText(error)}`);
2957
+ return refusal(CODE_INTERNAL, failureText(error));
2958
+ }
2959
+ }
1625
2960
  #hello(payload) {
1626
2961
  if (payload.proto !== 1) return refusal(CODE_PROTO_UNSUPPORTED, `this bridge speaks protocol 1`);
1627
2962
  this.#capabilities = capabilitiesOf(payload.cap);
2963
+ this.#transport.frameDeflate?.(this.#capabilities.has(CAP_FRAME_DEFLATE));
1628
2964
  this.#options.onDeclare?.(this);
1629
2965
  return {
1630
2966
  ok: true,
1631
2967
  r: {
1632
2968
  proto: 1,
1633
- minor: 0,
2969
+ minor: 11,
1634
2970
  server: SERVER_ID,
2971
+ capabilities: [...SERVED_CAPABILITIES],
1635
2972
  resume: "snapshot",
1636
2973
  auth: this.paired ? "paired" : "unpaired"
1637
2974
  }
@@ -1675,7 +3012,72 @@ var BridgeConnection = class {
1675
3012
  }
1676
3013
  };
1677
3014
  }
1678
- async #sessionList() {
3015
+ /**
3016
+ * Answer the roster as a whole set, as one compact page, or as the increment
3017
+ * since a token.
3018
+ *
3019
+ * `since` and the two answer modes exist only for a client that declared
3020
+ * {@link CAP_DELTA}: every other client is answered the roster it always was,
3021
+ * with `mode:"reset"` and an empty `token` beside it, and this connection
3022
+ * keeps no copy of a set that client cannot continue from.
3023
+ *
3024
+ * The compact form needs both halves: the capability, and at least one compact
3025
+ * parameter in the request. Either one alone is today's answer, which is what
3026
+ * keeps an older client — and a client that declared the name but asks for
3027
+ * nothing — byte identical to protocol v1.
3028
+ * @param payload - `{since?, cwd?, maxRows?, after?}`.
3029
+ */
3030
+ async #sessionList(payload) {
3031
+ if (this.declares("session.list.compact.v1")) {
3032
+ const requested = rosterCompactOf(payload);
3033
+ if (!requested.ok) return requested;
3034
+ const compact = requested.compact;
3035
+ if (compact !== void 0) {
3036
+ if (sinceOf(payload) !== void 0) return refusal(CODE_INVALID_ARGS, "session.list cannot combine a compact page with a since token");
3037
+ const compactRoster = await this.#readRoster();
3038
+ if (!compactRoster.ok) return compactRoster;
3039
+ return {
3040
+ ok: true,
3041
+ r: this.#compactRoster(compactRoster.rows, compact)
3042
+ };
3043
+ }
3044
+ }
3045
+ const roster = await this.#readRoster();
3046
+ if (!roster.ok) return roster;
3047
+ if (!this.declares("delta.v1")) {
3048
+ this.#deltas.drop("session.list");
3049
+ return {
3050
+ ok: true,
3051
+ r: {
3052
+ mode: "reset",
3053
+ token: "",
3054
+ sessions: roster.rows
3055
+ }
3056
+ };
3057
+ }
3058
+ const answer = this.#deltas.window("session.list", { maxRows: ROSTER_DELTA_MAX_ROWS }).answer(roster.rows, sinceOf(payload));
3059
+ return {
3060
+ ok: true,
3061
+ r: answer.mode === "reset" ? {
3062
+ mode: "reset",
3063
+ token: answer.token,
3064
+ sessions: answer.rows
3065
+ } : {
3066
+ mode: "delta",
3067
+ token: answer.token,
3068
+ changed: answer.changed,
3069
+ removed: answer.removed
3070
+ }
3071
+ };
3072
+ }
3073
+ /**
3074
+ * Read the roster once, as the host answers it.
3075
+ *
3076
+ * Deliberately separate from {@link #sessionList}: lineage and authorization
3077
+ * are learned from the same read, and an internal read must not consume or
3078
+ * advance this connection's incremental base.
3079
+ */
3080
+ async #readRoster() {
1679
3081
  const call = await this.#unary("session", "list");
1680
3082
  if (!call.ok) return call;
1681
3083
  const items = isRecord(call.value) ? call.value.items : void 0;
@@ -1684,6 +3086,7 @@ var BridgeConnection = class {
1684
3086
  const sessions = [];
1685
3087
  for (const item of items) {
1686
3088
  if (!isRecord(item) || typeof item.sessionId !== "string") continue;
3089
+ if (archived?.has(item.sessionId) === true) continue;
1687
3090
  const cwd = optionalText(item.cwd);
1688
3091
  const parentSessionId = optionalText(item.parentSessionId);
1689
3092
  sessions.push({
@@ -1701,7 +3104,60 @@ var BridgeConnection = class {
1701
3104
  this.#rememberLineage(sessions);
1702
3105
  return {
1703
3106
  ok: true,
1704
- r: { sessions }
3107
+ rows: sessions
3108
+ };
3109
+ }
3110
+ /**
3111
+ * Answer one compact roster page out of the roster just read.
3112
+ *
3113
+ * Rows are ordered most recent first, with the id as the tiebreak, because a
3114
+ * cursor is only meaningful over an order that does not depend on the order
3115
+ * the host happened to answer in. `after` is exclusive and names the last row
3116
+ * the previous page carried; a cursor this roster no longer names is an
3117
+ * unknown base and answers a first page again, the way a delta token this
3118
+ * window never issued answers a reset, so the client continues from the page
3119
+ * it is given instead of stalling on an id that no longer exists.
3120
+ *
3121
+ * Three members are what makes the body shorter: `cwd` is present only when
3122
+ * the request asked for it, `updatedAt` only when this connection has not
3123
+ * already sent this id that exact value (a client keeps the one it holds), and
3124
+ * `nextAfter` only while the roster continues past this page. Every other
3125
+ * field of the row is today's, under today's names, so a page is the same
3126
+ * roster cut short rather than a second schema — and `compact:true` says which
3127
+ * schema the rows are in, so a client whose bookkeeping drifted can tell an
3128
+ * omitted `updatedAt` from one this bridge never had.
3129
+ * @param rows - the roster as the host answered it.
3130
+ * @param compact - the parameters this listing carried.
3131
+ */
3132
+ #compactRoster(rows, compact) {
3133
+ const ordered = [...rows].sort((left, right) => right.updatedAt - left.updatedAt || (left.id < right.id ? -1 : left.id > right.id ? 1 : 0));
3134
+ const from = compact.after === void 0 ? 0 : ordered.findIndex((row) => row.id === compact.after) + 1;
3135
+ const end = compact.maxRows === void 0 ? ordered.length : Math.min(ordered.length, from + compact.maxRows);
3136
+ const page = ordered.slice(from, end);
3137
+ const sessions = page.map((row) => {
3138
+ const held = this.#rosterUpdatedAt.get(row.id) === row.updatedAt;
3139
+ this.#rosterUpdatedAt.set(row.id, row.updatedAt);
3140
+ return {
3141
+ id: row.id,
3142
+ title: row.title,
3143
+ ...held ? {} : { updatedAt: row.updatedAt },
3144
+ agentRunning: row.agentRunning,
3145
+ ...compact.cwd && row.cwd !== void 0 ? { cwd: row.cwd } : {},
3146
+ ...row.parentSessionId === void 0 ? {} : { parentSessionId: row.parentSessionId },
3147
+ ...row.origin === void 0 ? {} : { origin: row.origin },
3148
+ blank: row.blank,
3149
+ ...row.archived === void 0 ? {} : { archived: row.archived }
3150
+ };
3151
+ });
3152
+ const current = new Set(rows.map((row) => row.id));
3153
+ for (const id of this.#rosterUpdatedAt.keys()) if (!current.has(id)) this.#rosterUpdatedAt.delete(id);
3154
+ const last = page[page.length - 1]?.id;
3155
+ return {
3156
+ mode: "reset",
3157
+ token: "",
3158
+ compact: true,
3159
+ sessions,
3160
+ ...last === void 0 || end >= ordered.length ? {} : { nextAfter: last }
1705
3161
  };
1706
3162
  }
1707
3163
  /**
@@ -1736,17 +3192,82 @@ var BridgeConnection = class {
1736
3192
  * than a refusal, and `snapshot-too-large` cannot answer such a connection.
1737
3193
  * The oldest entry's own `seq` is the `before` cursor for the next, older
1738
3194
  * page; no second field restates it.
1739
- * @param payload - `{sessionId, maxBytes?}`.
3195
+ *
3196
+ * The budget is measured on the WHOLE answer — `{turns, lastSeq, hasMore}`
3197
+ * encoded as the `res` frame the client receives — and never per turn, so a
3198
+ * turn of many small entries is cut like any other run of entries. What it
3199
+ * does not bound is a single entry: `pageTurns` ends a page at an entry, never
3200
+ * inside one, so when the newest entry alone is past the budget that entry IS
3201
+ * the page and the answer is exactly as large as it is (measured: a 2.2 MB
3202
+ * newest message answers a 2.2 MB page against a 512 KiB budget, while the
3203
+ * same window of ordinary entries answers 513794 bytes). Trimming or splitting
3204
+ * such an entry would hand the client something other than what the session
3205
+ * says, and refusing it would take the session away from the very capability
3206
+ * that exists to open big sessions, so this is a stated bound of the page
3207
+ * budget rather than a defect to be closed by a smaller number elsewhere.
3208
+ * A client that declared {@link CAP_SESSION_SNAPSHOT_SINCE} and named
3209
+ * `sinceSeq` is answered incrementally instead: only the entries above that
3210
+ * durable watermark, in the same turn shape, with `mode:"since"` and
3211
+ * `reset:false`. When the bridge cannot PROVE the chain is unbroken — the
3212
+ * window's oldest entry has scrolled past the watermark — the answer is the
3213
+ * baseline below, carrying `mode:"full"` and `reset:true` so the client knows
3214
+ * to throw its copy away. Nothing else about this method moves: a request
3215
+ * without `sinceSeq`, or from a connection that never declared the capability,
3216
+ * is answered exactly the bytes protocol v1 answered before.
3217
+ * @param payload - `{sessionId, sinceSeq?, maxBytes?}`.
1740
3218
  * @param id - the request id the page budget is measured against.
1741
3219
  */
1742
3220
  async #sessionSnapshot(payload, id) {
1743
3221
  const sessionId = stringArg(payload, "sessionId");
1744
3222
  if (sessionId === void 0) return refusal(CODE_INVALID_ARGS, "session.snapshot requires sessionId");
3223
+ const unfollowable = await this.#unfollowable(sessionId);
3224
+ if (unfollowable !== void 0) return refusal(CODE_SESSION_NOT_FOLLOWABLE, unfollowable);
1745
3225
  const opening = await this.#awaitOpening(this.#ensureSubscription(sessionId));
1746
3226
  if (!opening.ok) return refusal(opening.code, `session ${sessionId} produced no opening frame (${opening.msg})`);
1747
- const projection = this.#projectionOf(opening.baseline.records);
3227
+ const window = turnsOfRecords(opening.baseline.records);
3228
+ const projection = this.#trimmedFor(window);
3229
+ const lastSeq = opening.baseline.cursor;
3230
+ if (payload.sinceSeq !== void 0 && this.#capabilities.has("session.snapshot.since.v1")) {
3231
+ const sinceSeq = pageNumber(payload.sinceSeq);
3232
+ if (sinceSeq === void 0) return refusal(CODE_INVALID_ARGS, "session.snapshot sinceSeq must be a non-negative integer");
3233
+ if (this.#capabilities.has("session.snapshot.page.v1")) {
3234
+ const budget = pageBudgetOf(payload.maxBytes, METHOD_SESSION_SNAPSHOT);
3235
+ if (!budget.ok) return budget;
3236
+ }
3237
+ const incremental = this.#sinceAnswer(projection, window, sinceSeq, lastSeq, id);
3238
+ if (incremental !== void 0) return {
3239
+ ok: true,
3240
+ r: incremental
3241
+ };
3242
+ const baseline = this.#baselineAnswer(sessionId, projection, lastSeq, payload, id);
3243
+ if (!baseline.ok) return baseline;
3244
+ return {
3245
+ ok: true,
3246
+ r: {
3247
+ ...baseline.r,
3248
+ mode: "full",
3249
+ reset: true
3250
+ }
3251
+ };
3252
+ }
3253
+ return this.#baselineAnswer(sessionId, projection, lastSeq, payload, id);
3254
+ }
3255
+ /**
3256
+ * The answer protocol v1 has always served: the whole window, or the newest
3257
+ * page of it for a connection that declared {@link CAP_SESSION_SNAPSHOT_PAGE}.
3258
+ *
3259
+ * One home for that answer, so an incremental request that has to fall back to
3260
+ * a full baseline is sent exactly the bytes it would have been sent without
3261
+ * asking — plus the two fields that say the client must reset.
3262
+ * @param sessionId - the session this baseline is of; the refusal names it.
3263
+ * @param projection - this connection's projection of the opening window.
3264
+ * @param lastSeq - the harness cursor the answer reports.
3265
+ * @param payload - the request, read only for `maxBytes`.
3266
+ * @param id - the request id any page budget is measured against.
3267
+ */
3268
+ #baselineAnswer(sessionId, projection, lastSeq, payload, id) {
1748
3269
  if (!this.#capabilities.has("session.snapshot.page.v1")) {
1749
- const fitted = this.#fitTurns(projection, opening.baseline.cursor, id);
3270
+ const fitted = this.#fitTurns(projection, lastSeq, id);
1750
3271
  if (fitted === void 0) return refusal(CODE_SNAPSHOT_TOO_LARGE, `session ${sessionId} does not fit one ${MAX_FRAME_BYTES} byte frame`);
1751
3272
  return {
1752
3273
  ok: true,
@@ -1758,7 +3279,6 @@ var BridgeConnection = class {
1758
3279
  }
1759
3280
  const budget = pageBudgetOf(payload.maxBytes, METHOD_SESSION_SNAPSHOT);
1760
3281
  if (!budget.ok) return budget;
1761
- const lastSeq = opening.baseline.cursor;
1762
3282
  const page = pageTurns(projection, void 0, budget.maxBytes, (turns, _nextBefore, hasMore) => Buffer.byteLength(JSON.stringify(responseFrame(id, {
1763
3283
  turns,
1764
3284
  lastSeq,
@@ -1774,6 +3294,40 @@ var BridgeConnection = class {
1774
3294
  };
1775
3295
  }
1776
3296
  /**
3297
+ * Answer a snapshot that named a watermark, or hand back undefined when this
3298
+ * request has to be answered with the full baseline instead.
3299
+ *
3300
+ * The continuity proof is the whole contract, and it reads the WINDOW rather
3301
+ * than the trimmed projection: an entry the client never renders is still an
3302
+ * entry the window holds, and continuing past a watermark below it would hand
3303
+ * the client a view it cannot attach to what it already has. Only the window's
3304
+ * own oldest entry can say whether anything between that watermark and this
3305
+ * window is missing, and `oldest <= sinceSeq + 1` is the one case where nothing
3306
+ * is; an empty window proves it trivially, because there is nothing to lose. A
3307
+ * reset is always correct, so an unprovable window takes the safe answer.
3308
+ *
3309
+ * The bound this form still carries is the frame cap: a delta that cannot
3310
+ * cross one frame answers the baseline instead of a refusal, because the
3311
+ * client's recovery from a hole is the `reset` flag, not a failed request.
3312
+ * @param projection - the projection the incremental turns are cut from.
3313
+ * @param window - the same window before trimming, read for its oldest entry.
3314
+ * @param sinceSeq - the durable watermark the client already holds.
3315
+ * @param lastSeq - the harness cursor the answer reports.
3316
+ * @param id - the request id the frame cap is measured against.
3317
+ */
3318
+ #sinceAnswer(projection, window, sinceSeq, lastSeq, id) {
3319
+ const oldest = oldestEntrySeq(window);
3320
+ if (oldest !== void 0 && oldest > sinceSeq + 1) return void 0;
3321
+ const answer = {
3322
+ turns: turnsAbove(projection, sinceSeq),
3323
+ lastSeq,
3324
+ mode: "since",
3325
+ reset: false
3326
+ };
3327
+ if (Buffer.byteLength(JSON.stringify(responseFrame(id, answer)), "utf8") > 10485760) return void 0;
3328
+ return answer;
3329
+ }
3330
+ /**
1777
3331
  * Read one backwards page of a session's history.
1778
3332
  *
1779
3333
  * Pages are cut from the very baseline `session.snapshot` serves, so the two
@@ -1791,6 +3345,8 @@ var BridgeConnection = class {
1791
3345
  if (payload.before !== void 0 && before === void 0) return refusal(CODE_INVALID_ARGS, "session.history before must be a non-negative integer");
1792
3346
  const budget = pageBudgetOf(payload.maxBytes, METHOD_SESSION_HISTORY);
1793
3347
  if (!budget.ok) return budget;
3348
+ const unfollowable = await this.#unfollowable(sessionId);
3349
+ if (unfollowable !== void 0) return refusal(CODE_SESSION_NOT_FOLLOWABLE, unfollowable);
1794
3350
  const opening = await this.#awaitOpening(this.#ensureSubscription(sessionId));
1795
3351
  if (!opening.ok) return refusal(opening.code, `session ${sessionId} produced no opening frame (${opening.msg})`);
1796
3352
  const page = pageTurns(this.#projectionOf(opening.baseline.records), before, budget.maxBytes, (turns, nextBefore, hasMore) => Buffer.byteLength(JSON.stringify(responseFrame(id, {
@@ -1800,17 +3356,133 @@ var BridgeConnection = class {
1800
3356
  })), "utf8"));
1801
3357
  return {
1802
3358
  ok: true,
1803
- r: {
1804
- turns: page.turns,
1805
- ...page.nextBefore === void 0 ? {} : { nextBefore: page.nextBefore },
1806
- hasMore: page.hasMore
1807
- }
3359
+ r: {
3360
+ turns: page.turns,
3361
+ ...page.nextBefore === void 0 ? {} : { nextBefore: page.nextBefore },
3362
+ hasMore: page.hasMore
3363
+ }
3364
+ };
3365
+ }
3366
+ /**
3367
+ * Read one backwards page of a session's DURABLE history.
3368
+ *
3369
+ * `session.history` slices the follow window this connection holds, and that
3370
+ * window is only as wide as the harness was asked to open it (200 messages), so
3371
+ * a client that scrolls past it has no older page to ask for. This method reads
3372
+ * the session store itself: one `session/page` call walked backwards with
3373
+ * `beforeSeq`, with no follow stream and no window involved.
3374
+ *
3375
+ * It is a pure read in the same sense `session.history` is: nothing is
3376
+ * subscribed, remembered, dropped or re-addressed, so the same `before`
3377
+ * answers the same page and reading cannot change what the session is.
3378
+ * @param payload - `{sessionId, before?, maxBytes?}`.
3379
+ * @param id - the request id the page budget is measured against.
3380
+ */
3381
+ async #sessionHistoryDeep(payload, id) {
3382
+ const sessionId = stringArg(payload, "sessionId");
3383
+ if (sessionId === void 0) return refusal(CODE_INVALID_ARGS, "session.history.deep requires sessionId");
3384
+ const before = payload.before === void 0 ? void 0 : pageNumber(payload.before);
3385
+ if (payload.before !== void 0 && before === void 0) return refusal(CODE_INVALID_ARGS, "session.history.deep before must be a non-negative integer");
3386
+ const budget = pageBudgetOf(payload.maxBytes, METHOD_SESSION_HISTORY_DEEP);
3387
+ if (!budget.ok) return budget;
3388
+ const unfollowable = await this.#unfollowable(sessionId);
3389
+ if (unfollowable !== void 0) return refusal(CODE_SESSION_NOT_FOLLOWABLE, unfollowable);
3390
+ const cut = await this.#durableCutOf(sessionId);
3391
+ if (!cut.ok) return cut;
3392
+ const store = await this.#storePageOf(sessionId, cut.cut, before);
3393
+ if (!store.ok) return store;
3394
+ const projection = turnsOfRecords(store.records);
3395
+ const oldestOf = (turns) => turns[0]?.entries[0]?.seq;
3396
+ const page = pageTurns(projection, before, budget.maxBytes, (turns, nextBefore, hasMore) => {
3397
+ const more = hasMore || store.hasMore;
3398
+ const cursor = more ? nextBefore ?? oldestOf(turns) : void 0;
3399
+ return Buffer.byteLength(JSON.stringify(responseFrame(id, {
3400
+ turns,
3401
+ ...cursor === void 0 ? {} : { nextBefore: cursor },
3402
+ hasMore: more
3403
+ })), "utf8");
3404
+ });
3405
+ if (page.turns.length === 0) return {
3406
+ ok: true,
3407
+ r: {
3408
+ turns: [],
3409
+ hasMore: false
3410
+ }
3411
+ };
3412
+ const hasMore = page.hasMore || store.hasMore;
3413
+ const nextBefore = page.nextBefore ?? oldestOf(page.turns);
3414
+ return {
3415
+ ok: true,
3416
+ r: {
3417
+ turns: page.turns,
3418
+ ...hasMore && nextBefore !== void 0 ? { nextBefore } : {},
3419
+ hasMore
3420
+ }
3421
+ };
3422
+ }
3423
+ /**
3424
+ * The inclusive log cut one durable page read names.
3425
+ *
3426
+ * `session/page` takes that cut as `throughSeq` and refuses one the store does
3427
+ * not hold, so a page read has to name a seq the session actually has. The
3428
+ * projection watermark is that seq: the cut every finished projection value has
3429
+ * folded through, read from the non-activating projection service
3430
+ * `session.models` already uses. `-1` is the harness's own name for a log with
3431
+ * no events at all, and the store answers it with an empty page.
3432
+ */
3433
+ async #durableCutOf(sessionId) {
3434
+ const call = await this.#unary("session", "projections", { sessionId });
3435
+ if (!call.ok) return call;
3436
+ const cut = isRecord(call.value) ? call.value.asOfSeq : void 0;
3437
+ if (typeof cut !== "number" || !Number.isSafeInteger(cut) || cut < -1) return refusal(CODE_SNAPSHOT_UNAVAILABLE, `session ${sessionId} reported no durable cut to page from`);
3438
+ return {
3439
+ ok: true,
3440
+ cut
3441
+ };
3442
+ }
3443
+ /**
3444
+ * Read one span of a session's durable history, at the address the harness demands.
3445
+ *
3446
+ * A delegated child is addressable only through its durable parent, and the
3447
+ * harness answers `session/agent-busy` when it is asked as an ordinary session.
3448
+ * That refusal is the one signal that distinguishes it from a real failure, so
3449
+ * it is the only one that triggers the roster lookup and the retry — the same
3450
+ * resolution {@link #openSubscription} performs for the follow stream.
3451
+ */
3452
+ async #storePageOf(sessionId, cut, before) {
3453
+ let call = await this.#pageCall(this.#addressOf(sessionId), cut, before);
3454
+ if (!call.ok && call.code === "session/agent-busy") {
3455
+ const parent = await this.#parentOf(sessionId);
3456
+ if (parent === void 0) return call;
3457
+ this.#lineage.set(sessionId, parent);
3458
+ call = await this.#pageCall(subagentAddress(parent, sessionId), cut, before);
3459
+ }
3460
+ if (!call.ok) return call;
3461
+ const value = call.value;
3462
+ const records = isRecord(value) && Array.isArray(value.records) ? value.records : void 0;
3463
+ if (records === void 0) return refusal(CODE_INTERNAL, "session/page answered no records");
3464
+ return {
3465
+ ok: true,
3466
+ records,
3467
+ hasMore: isRecord(value) && value.hasMore === true
1808
3468
  };
1809
3469
  }
3470
+ /** One `session/page` call at one resolved address. */
3471
+ async #pageCall(address, cut, before) {
3472
+ return await this.#unary("session", "page", {
3473
+ address,
3474
+ throughSeq: cut,
3475
+ ...before === void 0 ? {} : { beforeSeq: before },
3476
+ ...DEEP_HISTORY_WINDOW
3477
+ });
3478
+ }
1810
3479
  /** The projection a baseline is served with: trimmed only for a client that asked for it. */
1811
3480
  #projectionOf(records) {
1812
- const projected = turnsOfRecords(records);
1813
- return this.#capabilities.has("session.snapshot.trim.v1") ? trimUnrenderedEntries(projected) : projected;
3481
+ return this.#trimmedFor(turnsOfRecords(records));
3482
+ }
3483
+ /** Drop the bookkeeping entries only for a client that declared the trim capability. */
3484
+ #trimmedFor(turns) {
3485
+ return this.#capabilities.has("session.snapshot.trim.v1") ? trimUnrenderedEntries(turns) : turns;
1814
3486
  }
1815
3487
  async #sessionPrompt(payload) {
1816
3488
  const sessionId = stringArg(payload, "sessionId");
@@ -1972,6 +3644,67 @@ var BridgeConnection = class {
1972
3644
  }
1973
3645
  };
1974
3646
  }
3647
+ /**
3648
+ * Answer `presets.list`: the host's Agent-preset roster, forwarded verbatim.
3649
+ *
3650
+ * The bridge has no vocabulary of its own for a preset — a row is whatever
3651
+ * `agentPresets/list` publishes, and that endpoint takes no request — so the
3652
+ * answer crosses exactly as the host wrote it, down to the keys a client of
3653
+ * this version does not read.
3654
+ */
3655
+ async #presetsList() {
3656
+ const call = await this.#unary("agentPresets", "list");
3657
+ return call.ok ? {
3658
+ ok: true,
3659
+ r: call.value
3660
+ } : call;
3661
+ }
3662
+ /**
3663
+ * Answer `session.create`: hand the client's request to the host unchanged.
3664
+ *
3665
+ * A preset instantiated as an Agent is a host decision about a body this
3666
+ * bridge does not model — the field names, the defaults and the refusals
3667
+ * belong to `SessionCreateRequest` and to the host that validates it — so the
3668
+ * payload and the answer cross verbatim. Nothing is required here, renamed, or
3669
+ * defaulted: a request the host rejects is rejected with the host's own code
3670
+ * and text.
3671
+ * @param request - the host's `SessionCreateRequest`, exactly as the client wrote it.
3672
+ */
3673
+ async #sessionCreate(request) {
3674
+ const call = await this.#unary("session", "create", request);
3675
+ return call.ok ? {
3676
+ ok: true,
3677
+ r: call.value
3678
+ } : call;
3679
+ }
3680
+ /**
3681
+ * Answer `session.fork`: branch one session into another that inherits it.
3682
+ *
3683
+ * Only the two keys protocol v1 names are read here. `sessionId` is required
3684
+ * and `atSeq` is the host's inclusive source-event cut, so a caller that
3685
+ * omitted it must not have one invented for it: the host reads an absent
3686
+ * `atSeq` as the newest finished turn, and a zero or a fractional number is
3687
+ * not a seq at all, which is refused here rather than forwarded for the host
3688
+ * to reject with a shape this bridge could have caught. Everything else —
3689
+ * whether this host forks at all, what the new session is called, which
3690
+ * synthetic events close an open cut — belongs to `session/fork`, so a host
3691
+ * refusal crosses with its own code and text.
3692
+ * @param payload - `{sessionId, atSeq?}`.
3693
+ */
3694
+ async #sessionFork(payload) {
3695
+ const sessionId = stringArg(payload, "sessionId");
3696
+ if (sessionId === void 0) return refusal(CODE_INVALID_ARGS, "session.fork requires sessionId");
3697
+ const atSeq = payload.atSeq === void 0 ? void 0 : seqNumber(payload.atSeq);
3698
+ if (payload.atSeq !== void 0 && atSeq === void 0) return refusal(CODE_INVALID_ARGS, "session.fork atSeq must be a positive integer");
3699
+ const call = await this.#unary("session", "fork", {
3700
+ sessionId,
3701
+ ...atSeq === void 0 ? {} : { atSeq }
3702
+ });
3703
+ return call.ok ? {
3704
+ ok: true,
3705
+ r: call.value
3706
+ } : call;
3707
+ }
1975
3708
  #approvalResolve(payload) {
1976
3709
  const id = stringArg(payload, "id");
1977
3710
  const decision = payload.decision;
@@ -2003,6 +3736,56 @@ var BridgeConnection = class {
2003
3736
  } : refusal(reply.code, reply.msg);
2004
3737
  }
2005
3738
  /**
3739
+ * Answer one `jobs.list` and start watching that scope.
3740
+ *
3741
+ * The scope is the host registry's own: naming a session reads that session's
3742
+ * fenced set (its own jobs plus every unowned one), naming none reads the
3743
+ * unowned set. Neither is a global list, and this method never assembles one —
3744
+ * a cross-session view would be a second source of truth the host does not
3745
+ * have, and it would have to aggregate N fenced reads to fake it.
3746
+ *
3747
+ * Answering is also what subscribes: every later change of this scope arrives
3748
+ * as `jobs.changed` carrying the same payload, and a scope that was never
3749
+ * listed is never watched.
3750
+ * @param payload - `{}` for the unowned scope, or `{sessionId}` for one session's.
3751
+ */
3752
+ async #jobsList(payload) {
3753
+ const raw = payload.sessionId;
3754
+ if (raw !== void 0 && (typeof raw !== "string" || raw === "")) return refusal(CODE_INVALID_ARGS, "jobs.list sessionId must be a non-empty string when present");
3755
+ const sessionId = raw;
3756
+ if (sessionId !== void 0) {
3757
+ const unfollowable = await this.#unfollowable(sessionId);
3758
+ if (unfollowable !== void 0) return refusal(CODE_SESSION_NOT_FOLLOWABLE, unfollowable);
3759
+ }
3760
+ const roster = this.#options.jobs.read(sessionId);
3761
+ if (roster === void 0) return refusal(CODE_JOBS_UNAVAILABLE, "this host composes no background job registry");
3762
+ this.#watchJobs(sessionId, roster);
3763
+ return {
3764
+ ok: true,
3765
+ r: roster
3766
+ };
3767
+ }
3768
+ /**
3769
+ * Watch one job scope for this connection, once.
3770
+ *
3771
+ * The scope's first payload is the answer the client just received, so it is
3772
+ * seeded as already seen: a change frame only ever carries a set that differs
3773
+ * from the last one this connection was handed.
3774
+ */
3775
+ #watchJobs(sessionId, payload) {
3776
+ const key = scopeKey(sessionId);
3777
+ this.#jobSeen.set(key, JSON.stringify(payload.jobs));
3778
+ if (this.#jobWatches.has(key)) return;
3779
+ const dispose = this.#options.jobs.watch(sessionId, (changed) => {
3780
+ if (!this.declares("jobs.v1")) return;
3781
+ const encoded = JSON.stringify(changed.jobs);
3782
+ if (this.#jobSeen.get(key) === encoded) return;
3783
+ this.#jobSeen.set(key, encoded);
3784
+ this.#emit(TOPIC_JOBS_CHANGED, changed);
3785
+ });
3786
+ if (dispose !== void 0) this.#jobWatches.set(key, dispose);
3787
+ }
3788
+ /**
2006
3789
  * Run one unary Remote call with the activation retry, converting a gateway
2007
3790
  * failure into a refusal that carries the gateway's own code.
2008
3791
  */
@@ -2044,9 +3827,21 @@ var BridgeConnection = class {
2044
3827
  const parent = this.#lineage.get(sessionId);
2045
3828
  return parent === void 0 ? sessionAddress(sessionId) : subagentAddress(parent, sessionId);
2046
3829
  }
2047
- /** Remember the durable parent of every delegated child a roster carried. */
3830
+ /**
3831
+ * Remember the durable parent of every delegated child a roster carried, and
3832
+ * which sessions that same roster authorizes this connection to read.
3833
+ *
3834
+ * A child is not authorized by being named: authorizing it on its own row
3835
+ * would let one refused read teach the connection to follow it on the retry.
3836
+ */
2048
3837
  #rememberLineage(rows) {
2049
- for (const row of rows) if (row.origin === "subagent" && row.parentSessionId !== void 0) this.#lineage.set(row.id, row.parentSessionId);
3838
+ for (const row of rows) {
3839
+ if (row.origin !== "subagent") {
3840
+ this.#authorized.add(row.id);
3841
+ continue;
3842
+ }
3843
+ if (row.parentSessionId !== void 0) this.#lineage.set(row.id, row.parentSessionId);
3844
+ }
2050
3845
  }
2051
3846
  /**
2052
3847
  * The durable parent of a delegated child, or undefined when the roster does
@@ -2059,10 +3854,30 @@ var BridgeConnection = class {
2059
3854
  async #parentOf(sessionId) {
2060
3855
  const known = this.#lineage.get(sessionId);
2061
3856
  if (known !== void 0 || this.#lineageRead) return known;
2062
- if ((await this.#sessionList()).ok) this.#lineageRead = true;
3857
+ if ((await this.#readRoster()).ok) this.#lineageRead = true;
2063
3858
  return this.#lineage.get(sessionId);
2064
3859
  }
2065
3860
  /**
3861
+ * Whether this connection may follow one session at all.
3862
+ *
3863
+ * Following a delegated child is the one case that needs an answer before the
3864
+ * stream is asked for: relaxing the child gate must not become a channel to
3865
+ * any session a caller happens to name. A session this connection already
3866
+ * opened is authorized by that fact, an ordinary session the roster names is
3867
+ * authorized by the host's own roster, and a delegated child is authorized
3868
+ * only when the parent it hangs off is one of those. A session the roster does
3869
+ * not know at all keeps the old path — the harness itself answers for an id
3870
+ * this host does not have.
3871
+ * @returns the refusal to answer with, or undefined when the session may be followed.
3872
+ */
3873
+ async #unfollowable(sessionId) {
3874
+ if (this.#authorized.has(sessionId)) return void 0;
3875
+ const parent = await this.#parentOf(sessionId);
3876
+ if (parent === void 0) return void 0;
3877
+ if (this.#authorized.has(parent)) return void 0;
3878
+ return `session ${sessionId} is a delegated child whose parent ${parent} is not a session this connection may read`;
3879
+ }
3880
+ /**
2066
3881
  * Open one follow stream, resolving the address kind the harness demands.
2067
3882
  *
2068
3883
  * A delegated child is addressable only through its durable parent, and the
@@ -2120,6 +3935,7 @@ var BridgeConnection = class {
2120
3935
  msg: "session/follow returned no opening snapshot frame"
2121
3936
  };
2122
3937
  }
3938
+ this.#authorized.add(subscription.sessionId);
2123
3939
  this.#drain(subscription, iterator);
2124
3940
  return {
2125
3941
  ok: true,
@@ -2135,11 +3951,15 @@ var BridgeConnection = class {
2135
3951
  }
2136
3952
  /** Consume the rest of a follow stream, publishing every increment. */
2137
3953
  async #drain(subscription, iterator) {
3954
+ const memory = {
3955
+ subagentThread: this.declares(CAP_SUBAGENT_THREAD),
3956
+ spawnCalls: new SpawnCallIndex()
3957
+ };
2138
3958
  try {
2139
3959
  for (;;) {
2140
3960
  const next = await iterator.next();
2141
3961
  if (next.done === true) return;
2142
- const delta = deltaOfFollowFrame(next.value, this.#toolCalls, this.#messages);
3962
+ const delta = deltaOfFollowFrame(next.value, this.#toolCalls, this.#messages, memory);
2143
3963
  if (delta === void 0) continue;
2144
3964
  this.#emit(TOPIC_SESSION_DELTA, {
2145
3965
  sessionId: subscription.sessionId,
@@ -2252,11 +4072,29 @@ function approvalSummary(request) {
2252
4072
  return request.displayReason?.zh ?? request.displayReason?.en ?? request.toolName;
2253
4073
  }
2254
4074
  /**
4075
+ * The `approval.request` payload for one claim.
4076
+ *
4077
+ * The first broadcast and the replay of a still-open claim go through this one
4078
+ * function, so the card a phone was originally shown and the same card handed to
4079
+ * it again after a reconnect cannot drift apart.
4080
+ * @param prompt - the claim being published.
4081
+ */
4082
+ function approvalPayload(prompt) {
4083
+ return {
4084
+ sessionId: prompt.sessionId,
4085
+ id: prompt.id,
4086
+ summary: prompt.summary,
4087
+ toolName: prompt.toolName
4088
+ };
4089
+ }
4090
+ /**
2255
4091
  * The `question.request` payload for one claim.
2256
4092
  *
2257
- * No `expiresAt`: the host's foreground deadline is not part of the request the
2258
- * waterfall carries, and a bridge-invented deadline would be a timeout of the
2259
- * bridge's own — the exact thing this channel must not have.
4093
+ * `expiresAt` appears only once the claim learned the host's own deadline from
4094
+ * its wait subscription, and it is the host's deadline unchanged: the bridge
4095
+ * invents none, because a bridge-invented deadline would be a timeout of the
4096
+ * bridge's own — the exact thing this channel must not have. A blocking ask
4097
+ * therefore publishes no such key at all, rather than an empty or null one.
2260
4098
  * @param state - whether the foreground ask still holds the question.
2261
4099
  * @param question - the claim being published.
2262
4100
  */
@@ -2265,7 +4103,8 @@ function questionPayload(state, question) {
2265
4103
  sessionId: question.sessionId,
2266
4104
  callId: question.callId,
2267
4105
  state,
2268
- questions: question.questions
4106
+ questions: question.questions,
4107
+ ...question.expiresAt === void 0 ? {} : { expiresAt: question.expiresAt }
2269
4108
  };
2270
4109
  }
2271
4110
  /** The bridge's live connections plus the answerer it composes onto the approval chain. */
@@ -2291,6 +4130,7 @@ var BridgeHub = class {
2291
4130
  ...this.#options,
2292
4131
  onDeclare: (fresh) => {
2293
4132
  this.replayQuestions(fresh);
4133
+ this.replayApprovals(fresh);
2294
4134
  }
2295
4135
  }, transport, auth);
2296
4136
  this.#connections.add(connection);
@@ -2325,10 +4165,6 @@ var BridgeHub = class {
2325
4165
  return delivered;
2326
4166
  }
2327
4167
  /**
2328
- * Publish one event to every paired device that announced a capability.
2329
- * @returns how many connections actually took the frame.
2330
- */
2331
- /**
2332
4168
  * Hand one freshly declared connection the questions it can now answer.
2333
4169
  *
2334
4170
  * Without this, a question raised while the phone was reconnecting stays on the
@@ -2339,6 +4175,30 @@ var BridgeHub = class {
2339
4175
  if (!connection.paired || !connection.declares("questions.v1")) return;
2340
4176
  for (const claim of this.#options.questions.openClaims()) connection.emit(TOPIC_QUESTION_REQUEST, questionPayload("open", claim));
2341
4177
  }
4178
+ /**
4179
+ * Hand one freshly declared connection the approvals it can now answer.
4180
+ *
4181
+ * The same shape as {@link replayQuestions} and for the same reason: the first
4182
+ * `approval.request` of a question was broadcast to the phones that were
4183
+ * connected at that instant, so a phone that reconnected — or a session screen
4184
+ * opened after the fact — holds no card and has no other way to learn the
4185
+ * question exists. Only unsettled questions are in the registry, so one that
4186
+ * was answered, one the bridge timed out and one withdrawn with the last phone
4187
+ * cannot be replayed.
4188
+ *
4189
+ * The replay emits a frame and nothing else: the claim keeps the deadline it
4190
+ * was opened with, so re-handing a question never lengthens how long the agent
4191
+ * waits for it.
4192
+ * @param connection - the connection that just declared its capabilities.
4193
+ */
4194
+ replayApprovals(connection) {
4195
+ if (!connection.paired || !connection.declares("approvals.v1")) return;
4196
+ for (const prompt of this.#options.approvals.openPrompts()) connection.emit(TOPIC_APPROVAL_REQUEST, approvalPayload(prompt));
4197
+ }
4198
+ /**
4199
+ * Publish one event to every paired device that announced a capability.
4200
+ * @returns how many connections actually took the frame.
4201
+ */
2342
4202
  broadcastTo(capability, topic, payload) {
2343
4203
  let delivered = 0;
2344
4204
  for (const connection of this.#connections) {
@@ -2362,12 +4222,7 @@ var BridgeHub = class {
2362
4222
  summary: approvalSummary(request),
2363
4223
  ...request.signal === void 0 ? {} : { signal: request.signal }
2364
4224
  });
2365
- if (this.broadcast("approval.request", {
2366
- sessionId,
2367
- id: prompt.id,
2368
- summary: prompt.summary,
2369
- toolName: request.toolName
2370
- }) === 0) this.#options.approvals.abandon([prompt.id]);
4225
+ if (this.broadcast("approval.request", approvalPayload(prompt)) === 0) this.#options.approvals.abandon([prompt.id]);
2371
4226
  const answer = await prompt.answer;
2372
4227
  return answer === void 0 ? await next() : answer;
2373
4228
  }
@@ -2380,7 +4235,9 @@ var BridgeHub = class {
2380
4235
  * when the ask is timed, and minted here when it is blocking and the host
2381
4236
  * assigned none — either way the phone answers the id it was shown. A claim
2382
4237
  * nobody received is withdrawn at once instead of holding the agent until the
2383
- * host's deadline.
4238
+ * host's deadline. For a timed ask the host's own remaining wait travels with
4239
+ * the first frame as `expiresAt`, and every later move of that deadline is
4240
+ * re-published under the same call id.
2384
4241
  * @param request - the pending question batch.
2385
4242
  * @param next - the rest of the answerer chain.
2386
4243
  * @returns the phone's answer, the host's own deadline outcome, or whatever the next answerer says.
@@ -2403,10 +4260,18 @@ var BridgeHub = class {
2403
4260
  },
2404
4261
  onContinued: (question) => {
2405
4262
  this.broadcastTo(CAP_QUESTIONS, TOPIC_QUESTION_REQUEST, questionPayload("continued", question));
4263
+ },
4264
+ onDeadline: (question) => {
4265
+ this.broadcastTo(CAP_QUESTIONS, TOPIC_QUESTION_REQUEST, questionPayload("open", question));
2406
4266
  }
2407
4267
  });
2408
4268
  if (claim === void 0) return await next();
2409
- if (this.broadcastTo("questions.v1", "question.request", questionPayload("open", claim)) === 0) this.#options.questions.withdraw([callId]);
4269
+ const expiresAt = await claim.deadline;
4270
+ if (this.#options.questions.stateOf(callId) !== "open") return await claim.answer;
4271
+ if (this.broadcastTo("questions.v1", "question.request", questionPayload("open", expiresAt === void 0 ? claim : {
4272
+ ...claim,
4273
+ expiresAt
4274
+ })) === 0) this.#options.questions.withdraw([callId]);
2410
4275
  return await claim.answer;
2411
4276
  }
2412
4277
  /** Close every connection and withdraw every question. Idempotent. */
@@ -2591,6 +4456,13 @@ var PairingService = class {
2591
4456
  * delegated to `next()`, never answered with a decision the operator did not
2592
4457
  * make.
2593
4458
  *
4459
+ * A timed ask's deadline is read back from the host itself
4460
+ * (`userQuestions/attachWait`) and published as `expiresAt`, so the phone can
4461
+ * count down the wait the host is actually serving. Holding that subscription
4462
+ * parks the host's own deadline timer, so this module also has to let go at the
4463
+ * instant the deadline it learned has passed: only then does the host raise
4464
+ * `ASK_TIMED_OUT` and hand the claim its `continued` state.
4465
+ *
2594
4466
  * The types below mirror `@deepseek-ai/dsh-user-questions` field for field. The
2595
4467
  * package is not a dependency of this one (it is the host's, not the bridge's),
2596
4468
  * so the contract is declared locally instead of imported.
@@ -2612,6 +4484,32 @@ function isTimedOut(reason) {
2612
4484
  return reason?.code === QUESTION_TIMED_OUT_CODE;
2613
4485
  }
2614
4486
  /**
4487
+ * The publishable view of one claim.
4488
+ *
4489
+ * The deadline key is spread in rather than set to undefined: a blocking ask has
4490
+ * no expiry at all, and the phone must see no such field instead of a null one.
4491
+ * @param record - the live claim.
4492
+ * @returns the claim's fields as the hub publishes them.
4493
+ */
4494
+ function viewOf(record) {
4495
+ return {
4496
+ sessionId: record.sessionId,
4497
+ callId: record.callId,
4498
+ questions: record.questions,
4499
+ ...record.expiresAt === void 0 ? {} : { expiresAt: record.expiresAt }
4500
+ };
4501
+ }
4502
+ /**
4503
+ * Read the remaining wait out of one `attachWait` frame.
4504
+ * @param frame - the frame as the gateway delivered it.
4505
+ * @returns the remaining milliseconds, or undefined when the frame is not usable.
4506
+ */
4507
+ function remainingOf(frame) {
4508
+ const remaining = frame?.remainingMs;
4509
+ if (typeof remaining !== "number" || !Number.isFinite(remaining) || remaining < 0) return void 0;
4510
+ return remaining;
4511
+ }
4512
+ /**
2615
4513
  * Project a host question into the contract's own fields.
2616
4514
  *
2617
4515
  * Explicitly field by field: the host's items carry presentation intents this
@@ -2646,12 +4544,14 @@ var QuestionClaims = class {
2646
4544
  #peer;
2647
4545
  #log;
2648
4546
  #random;
4547
+ #now;
2649
4548
  #claims = /* @__PURE__ */ new Map();
2650
4549
  constructor(options) {
2651
4550
  this.#gateway = options.gateway;
2652
4551
  this.#peer = options.peer;
2653
4552
  this.#log = options.log;
2654
4553
  this.#random = options.random ?? randomBase64Url;
4554
+ this.#now = options.now ?? Date.now;
2655
4555
  }
2656
4556
  /** @returns how many questions this bridge currently holds. */
2657
4557
  get size() {
@@ -2694,18 +4594,35 @@ var QuestionClaims = class {
2694
4594
  }
2695
4595
  return nextStarted;
2696
4596
  };
4597
+ const wait = new AbortController();
4598
+ let waitTimer;
4599
+ let stopped = false;
4600
+ const deferred = {};
4601
+ const deadline = new Promise((resolve) => {
4602
+ deferred.resolve = resolve;
4603
+ });
4604
+ const resolveDeadline = (value) => {
4605
+ deferred.resolve?.(value);
4606
+ };
4607
+ const stopWait = () => {
4608
+ if (stopped) return;
4609
+ stopped = true;
4610
+ if (waitTimer !== void 0) {
4611
+ clearTimeout(waitTimer);
4612
+ waitTimer = void 0;
4613
+ }
4614
+ wait.abort();
4615
+ resolveDeadline(void 0);
4616
+ };
2697
4617
  const record = {
2698
4618
  sessionId: input.sessionId,
2699
4619
  callId: input.callId,
2700
4620
  hosted: input.hosted,
2701
4621
  questions: projectQuestions(input.questions),
2702
4622
  state: "open",
4623
+ expiresAt: void 0,
2703
4624
  notifySettled: () => {
2704
- input.onSettled?.({
2705
- sessionId: input.sessionId,
2706
- callId: input.callId,
2707
- questions: projectQuestions(input.questions)
2708
- });
4625
+ input.onSettled?.(viewOf(record));
2709
4626
  },
2710
4627
  settle,
2711
4628
  fail,
@@ -2715,16 +4632,77 @@ var QuestionClaims = class {
2715
4632
  detach: () => {
2716
4633
  signal?.removeEventListener("abort", onAbort);
2717
4634
  },
2718
- onContinued: input.onContinued
4635
+ onContinued: input.onContinued,
4636
+ stopWait
4637
+ };
4638
+ /** Arm the timer that lets go of the wait when the host's own deadline is due. */
4639
+ const armDeadline = (expiresAt) => {
4640
+ if (waitTimer !== void 0) clearTimeout(waitTimer);
4641
+ waitTimer = setTimeout(() => {
4642
+ stopWait();
4643
+ }, Math.max(0, expiresAt - this.#now()));
4644
+ waitTimer.unref?.();
4645
+ };
4646
+ /**
4647
+ * Follow the host's own remaining wait and report it when it moves.
4648
+ *
4649
+ * A failure here is not a verdict on the question: the phone can answer it
4650
+ * without ever knowing the deadline, so every error only ends the
4651
+ * subscription instead of failing the claim.
4652
+ */
4653
+ const trackWait = async () => {
4654
+ if (stopped) return;
4655
+ let frames = 0;
4656
+ let lastBroadcast = 0;
4657
+ try {
4658
+ const iterator = (await this.#gateway.stream({
4659
+ namespace: "userQuestions",
4660
+ method: "attachWait",
4661
+ args: wireArgs("userQuestions", "attachWait", {
4662
+ agentId: input.sessionId,
4663
+ callId: input.callId
4664
+ }),
4665
+ peer: this.#peer,
4666
+ signal: wait.signal
4667
+ }))[Symbol.asyncIterator]();
4668
+ try {
4669
+ for (;;) {
4670
+ const next = await iterator.next();
4671
+ if (next.done === true) return;
4672
+ const remaining = remainingOf(next.value);
4673
+ if (remaining === void 0) continue;
4674
+ const at = this.#now();
4675
+ const expiresAt = at + remaining;
4676
+ record.expiresAt = expiresAt;
4677
+ armDeadline(expiresAt);
4678
+ if (frames === 0) {
4679
+ frames = 1;
4680
+ lastBroadcast = at;
4681
+ resolveDeadline(expiresAt);
4682
+ continue;
4683
+ }
4684
+ if (at - lastBroadcast < 1e3) continue;
4685
+ lastBroadcast = at;
4686
+ input.onDeadline?.(viewOf(record));
4687
+ }
4688
+ } finally {
4689
+ await iterator.return?.();
4690
+ }
4691
+ } catch (error) {
4692
+ if (!stopped) this.#log(`userQuestions/attachWait failed: ${failureText(error)}`);
4693
+ } finally {
4694
+ resolveDeadline(void 0);
4695
+ }
2719
4696
  };
2720
4697
  this.#claims.set(input.callId, record);
2721
4698
  if (signal?.aborted === true) onAbort();
2722
4699
  else signal?.addEventListener("abort", onAbort, { once: true });
4700
+ if (input.hosted) trackWait();
4701
+ else resolveDeadline(void 0);
2723
4702
  return {
2724
- sessionId: record.sessionId,
2725
- callId: record.callId,
2726
- questions: record.questions,
2727
- answer
4703
+ ...viewOf(record),
4704
+ answer,
4705
+ deadline
2728
4706
  };
2729
4707
  }
2730
4708
  /**
@@ -2747,6 +4725,7 @@ var QuestionClaims = class {
2747
4725
  if (record.state === "open") {
2748
4726
  this.#claims.delete(callId);
2749
4727
  record.detach();
4728
+ record.stopWait();
2750
4729
  record.settle({ answers: answer.answers });
2751
4730
  return { ok: true };
2752
4731
  }
@@ -2765,11 +4744,7 @@ var QuestionClaims = class {
2765
4744
  * question sits on the host with an answerable card nowhere.
2766
4745
  */
2767
4746
  openClaims() {
2768
- return [...this.#claims.values()].map((record) => ({
2769
- sessionId: record.sessionId,
2770
- callId: record.callId,
2771
- questions: record.questions
2772
- }));
4747
+ return [...this.#claims.values()].map(viewOf);
2773
4748
  }
2774
4749
  /**
2775
4750
  * Withdraw the named questions, delegating each to the next answerer.
@@ -2782,6 +4757,7 @@ var QuestionClaims = class {
2782
4757
  if (record === void 0) continue;
2783
4758
  this.#claims.delete(callId);
2784
4759
  record.detach();
4760
+ record.stopWait();
2785
4761
  record.notifySettled();
2786
4762
  if (record.state !== "open") continue;
2787
4763
  record.delegate();
@@ -2821,7 +4797,9 @@ var QuestionClaims = class {
2821
4797
  code: CODE_QUESTION_UNKNOWN,
2822
4798
  msg: "the host does not hold this question as answerable yet"
2823
4799
  };
4800
+ const record = this.#claims.get(callId);
2824
4801
  this.#claims.delete(callId);
4802
+ record?.stopWait();
2825
4803
  return { ok: true };
2826
4804
  } catch (error) {
2827
4805
  this.#log(`userQuestions/answer failed: ${failureText(error)}`);
@@ -2843,17 +4821,14 @@ var QuestionClaims = class {
2843
4821
  const record = this.#claims.get(callId);
2844
4822
  if (record === void 0 || record.state !== "open") return;
2845
4823
  record.detach();
4824
+ record.stopWait();
2846
4825
  record.fail(reason);
2847
4826
  if (!record.hosted || !isTimedOut(reason)) {
2848
4827
  this.#claims.delete(callId);
2849
4828
  return;
2850
4829
  }
2851
4830
  record.state = "continued";
2852
- record.onContinued?.({
2853
- sessionId: record.sessionId,
2854
- callId: record.callId,
2855
- questions: record.questions
2856
- });
4831
+ record.onContinued?.(viewOf(record));
2857
4832
  }
2858
4833
  };
2859
4834
  //#endregion
@@ -3080,6 +5055,120 @@ function dshHome() {
3080
5055
  return resolveDshHome();
3081
5056
  }
3082
5057
  //#endregion
5058
+ //#region src/mount-once.ts
5059
+ /**
5060
+ * Host single-instance guard shared by the plugin family. The family bundle
5061
+ * (dsh-web-all / dsh-skins) namespaces every child row id (web-ui-*), so
5062
+ * the loader accepts a standalone install of the same package side by side;
5063
+ * without this guard the second instance would still re-register the same
5064
+ * webserver routes, tools, settings namespaces, and system-prompt sections
5065
+ * and fail the boot. mountOnce makes a mount of an already-mounted package a
5066
+ * no-op for as long as the first instance lives (the browser half is already
5067
+ * deduped by package name in the client module host).
5068
+ *
5069
+ * A no-op is only safe while the holder is ALIVE. The holder can be disposed
5070
+ * long after the refused mount ran its course: the Host reloads a profile by
5071
+ * creating the new loader entries before the old ones are torn down (a
5072
+ * plugin-manager enable/disable/install write, a settings-driven row reload,
5073
+ * HMR), so the new aggregate shell entry mounts its family plugin while the
5074
+ * previous entry still owns the name. Dropping that refused mount lost the
5075
+ * plugin for good - the previous entry then disposed its own mount, releasing
5076
+ * the name with nobody left to take it, and the family row stayed listed as
5077
+ * active while its host routes 404ed (the task-board panel showed
5078
+ * "board.hostError.notMounted", no degraded record appeared, and only a Host
5079
+ * restart recovered it).
5080
+ *
5081
+ * The refused mount is therefore QUEUED, not dropped, and replayed the moment
5082
+ * the holder releases the name - if the waiting fiber is still alive then. The
5083
+ * single-instance guarantee is unchanged: exactly one mount is live per
5084
+ * package name, and the replay re-enters the guard so a later mount still
5085
+ * dedupes against it.
5086
+ *
5087
+ * The registry rides a global symbol so two module instances of the same
5088
+ * package (npm copy vs repository link) still share one verdict. That symbol
5089
+ * is a CROSS-REPOSITORY contract, not this file's private state: the four
5090
+ * satellite packages (dsh-skins / dsh-pet / dsh-presets /
5091
+ * dsh-community-plugins) are separate repositories carrying their own copy of
5092
+ * this guard, rebuilt on their own schedule, so the value under `MOUNTED`
5093
+ * must keep the shape every published copy reads (a `Set` of package names
5094
+ * with `has`/`add`/`delete`). The wait queues this guard added therefore live
5095
+ * under their own additive key, and the registry reads back a `Set` even when
5096
+ * some other build left a different value there. Changing `MOUNTED`'s shape
5097
+ * in place broke that contract once: a satellite's legacy copy created a
5098
+ * `Set`, the family's new copy read it as a `Map`, and every family row
5099
+ * mounted after it failed with "claims.get is not a function".
5100
+ *
5101
+ * cordis `ctx.effect` runs its callback immediately and treats the callback's
5102
+ * return value as the fiber disposer, so the unmarker is returned, not run.
5103
+ */
5104
+ /** Published cross-repository contract: package names currently mounted. */
5105
+ const MOUNTED = Symbol.for("dsh-web.mounted-plugins");
5106
+ /** Additive key this guard owns: refused mounts waiting for the name. */
5107
+ const WAITERS = Symbol.for("dsh-web.mounted-plugins.waiters");
5108
+ /**
5109
+ * The shared name registry, always a `Set` whatever another build stored here:
5110
+ * a foreign value (an interim shape, a hand-written global) must not take every
5111
+ * family plugin down with it.
5112
+ * @returns the process-wide set of mounted package names.
5113
+ */
5114
+ function mountedSet() {
5115
+ const registry = globalThis;
5116
+ const existing = registry[MOUNTED];
5117
+ if (existing instanceof Set) return existing;
5118
+ const created = /* @__PURE__ */ new Set();
5119
+ registry[MOUNTED] = created;
5120
+ return created;
5121
+ }
5122
+ /** Queue per package name for mounts refused while a holder was alive. */
5123
+ function mountWaiters() {
5124
+ const registry = globalThis;
5125
+ return registry[WAITERS] ??= /* @__PURE__ */ new Map();
5126
+ }
5127
+ /**
5128
+ * Wrap a cordis plugin apply so the package runs at most once per process.
5129
+ * The first mount registers normally and releases the name when its fiber
5130
+ * disposes; a mount refused while that name is held waits for the release and
5131
+ * then runs, unless its own fiber disposes first.
5132
+ * @param packageName - npm package identity shared by every install source.
5133
+ * @param fn - the original plugin apply.
5134
+ * @returns an apply of the same shape.
5135
+ */
5136
+ function mountOnce(packageName, fn) {
5137
+ const mount = (...args) => {
5138
+ const mounted = mountedSet();
5139
+ const ctx = args[0];
5140
+ if (mounted.has(packageName)) {
5141
+ const waiters = mountWaiters();
5142
+ const queue = waiters.get(packageName) ?? [];
5143
+ let alive = true;
5144
+ const pending = { run: () => {
5145
+ if (alive) mount(...args);
5146
+ } };
5147
+ ctx?.effect?.(() => () => {
5148
+ alive = false;
5149
+ const index = queue.indexOf(pending);
5150
+ if (index >= 0) queue.splice(index, 1);
5151
+ });
5152
+ queue.push(pending);
5153
+ waiters.set(packageName, queue);
5154
+ return;
5155
+ }
5156
+ mounted.add(packageName);
5157
+ ctx?.effect?.(() => () => {
5158
+ mounted.delete(packageName);
5159
+ const waiters = mountWaiters();
5160
+ const queue = waiters.get(packageName);
5161
+ if (queue === void 0) return;
5162
+ waiters.delete(packageName);
5163
+ for (const waiter of queue.splice(0)) queueMicrotask(() => {
5164
+ waiter.run();
5165
+ });
5166
+ });
5167
+ return fn(...args);
5168
+ };
5169
+ return mount;
5170
+ }
5171
+ //#endregion
3083
5172
  //#region src/core/loopback.ts
3084
5173
  /** Socket addresses that count as "this machine". */
3085
5174
  const LOOPBACK_ADDRESSES = /* @__PURE__ */ new Set([
@@ -3237,113 +5326,6 @@ function makePairTokenRoute(deps) {
3237
5326
  };
3238
5327
  }
3239
5328
  //#endregion
3240
- //#region src/core/ws-frames.ts
3241
- /**
3242
- * RFC 6455 server-side framing, kept as pure functions so the length, mask and
3243
- * opcode rules are unit-tested without a socket.
3244
- *
3245
- * Only what a server must accept is implemented: client frames are always
3246
- * masked, one logical message may arrive as a text frame or as a fragmented
3247
- * sequence, and anything the protocol forbids answers with the close code that
3248
- * names the violation instead of being ignored.
3249
- * @module dsh-remote-bridge/core/ws-frames
3250
- */
3251
- /** The magic GUID every WebSocket handshake is keyed with. */
3252
- const WS_GUID = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
3253
- /** Close code for a protocol violation. */
3254
- const CLOSE_PROTOCOL_ERROR = 1002;
3255
- /** Close code for a message this bridge will not carry. */
3256
- const CLOSE_UNSUPPORTED_DATA = 1003;
3257
- /** Close code for a message past the size this bridge will carry. */
3258
- const CLOSE_TOO_LARGE = 1009;
3259
- /** @returns the `Sec-WebSocket-Accept` value for a client's key. */
3260
- function webSocketAccept(secWebSocketKey) {
3261
- return createHash("sha1").update(`${secWebSocketKey}${WS_GUID}`).digest("base64");
3262
- }
3263
- /**
3264
- * Decode one frame from the head of a buffer.
3265
- * @param buffer - the bytes received so far.
3266
- * @param maxBytes - largest payload this bridge accepts.
3267
- */
3268
- function parseClientFrame(buffer, maxBytes) {
3269
- if (buffer.length < 2) return { status: "incomplete" };
3270
- const first = buffer[0] ?? 0;
3271
- const second = buffer[1] ?? 0;
3272
- const fin = (first & 128) !== 0;
3273
- if ((first & 112) !== 0) return fault(CLOSE_PROTOCOL_ERROR, "reserved bits set");
3274
- const opcode = first & 15;
3275
- if (!((second & 128) !== 0)) return fault(CLOSE_PROTOCOL_ERROR, "client frames must be masked");
3276
- let length = second & 127;
3277
- let offset = 2;
3278
- if (length === 126) {
3279
- if (buffer.length < offset + 2) return { status: "incomplete" };
3280
- length = buffer.readUInt16BE(offset);
3281
- offset += 2;
3282
- } else if (length === 127) {
3283
- if (buffer.length < offset + 8) return { status: "incomplete" };
3284
- const wide = buffer.readBigUInt64BE(offset);
3285
- if (wide > BigInt(Number.MAX_SAFE_INTEGER)) return fault(CLOSE_TOO_LARGE, "frame length out of range");
3286
- length = Number(wide);
3287
- offset += 8;
3288
- }
3289
- if (length > maxBytes) return fault(CLOSE_TOO_LARGE, `frame payload exceeds ${maxBytes} bytes`);
3290
- if (buffer.length < offset + 4 + length) return { status: "incomplete" };
3291
- const mask = buffer.subarray(offset, offset + 4);
3292
- offset += 4;
3293
- const payload = Buffer.allocUnsafe(length);
3294
- for (let index = 0; index < length; index += 1) payload[index] = (buffer[offset + index] ?? 0) ^ (mask[index % 4] ?? 0);
3295
- return {
3296
- status: "frame",
3297
- frame: {
3298
- fin,
3299
- opcode,
3300
- payload,
3301
- consumed: offset + length
3302
- }
3303
- };
3304
- }
3305
- function fault(closeCode, reason) {
3306
- return {
3307
- status: "fault",
3308
- closeCode,
3309
- reason
3310
- };
3311
- }
3312
- /**
3313
- * Encode one server frame. Server frames are never masked.
3314
- * @param opcode - the frame opcode.
3315
- * @param payload - already-serialized payload bytes.
3316
- * @param fin - whether this frame completes the message.
3317
- */
3318
- function encodeServerFrame(opcode, payload, fin = true) {
3319
- const length = payload.length;
3320
- const header = length < 126 ? Buffer.from([(fin ? 128 : 0) | opcode, length]) : length <= 65535 ? Buffer.from([
3321
- (fin ? 128 : 0) | opcode,
3322
- 126,
3323
- length >> 8,
3324
- length & 255
3325
- ]) : (() => {
3326
- const wide = Buffer.alloc(10);
3327
- wide[0] = (fin ? 128 : 0) | opcode;
3328
- wide[1] = 127;
3329
- wide.writeBigUInt64BE(BigInt(length), 2);
3330
- return wide;
3331
- })();
3332
- return Buffer.concat([header, payload]);
3333
- }
3334
- /** Encode one text message. */
3335
- function encodeTextFrame(text) {
3336
- return encodeServerFrame(1, Buffer.from(text, "utf8"));
3337
- }
3338
- /** Encode one close frame with a code and a short reason. */
3339
- function encodeCloseFrame(code, reason) {
3340
- const text = Buffer.from(reason, "utf8").subarray(0, 123);
3341
- const payload = Buffer.alloc(2 + text.length);
3342
- payload.writeUInt16BE(code, 0);
3343
- text.copy(payload, 2);
3344
- return encodeServerFrame(8, payload);
3345
- }
3346
- //#endregion
3347
5329
  //#region src/host/websocket.ts
3348
5330
  /** Close code a well-behaved peer sends when it goes away. */
3349
5331
  const CLOSE_NORMAL = 1e3;
@@ -3404,6 +5386,19 @@ function refuseUpgrade(socket, status, reason) {
3404
5386
  socket.end(`HTTP/1.1 ${status} ${reason}\r\nconnection: close\r\ncontent-length: 0\r\n\r\n`);
3405
5387
  }
3406
5388
  /**
5389
+ * Ask the kernel to write each frame out as it is handed over.
5390
+ *
5391
+ * Every frame on this route is already one whole application message, and a
5392
+ * phone pays a round trip for each answer, so Nagle's coalescing window only
5393
+ * delays bytes that nothing else is waiting to join. It is set on acceptance
5394
+ * because that is the last moment the socket is still ours alone: once the
5395
+ * upgrade has been answered, a peer's frame can already be on the way.
5396
+ */
5397
+ function stopNagleDelay(socket) {
5398
+ const delayable = socket;
5399
+ if (typeof delayable.setNoDelay === "function") delayable.setNoDelay(true);
5400
+ }
5401
+ /**
3407
5402
  * Hand one accepted upgrade to the hub, in the one order that is correct.
3408
5403
  *
3409
5404
  * Every step here is synchronous, which is what makes the carrier's own
@@ -3417,6 +5412,7 @@ function refuseUpgrade(socket, status, reason) {
3417
5412
  */
3418
5413
  function serveUpgrade(handoff) {
3419
5414
  const { socket, secWebSocketKey, head, hub, auth } = handoff;
5415
+ stopNagleDelay(socket);
3420
5416
  const carrier = new WebSocketCarrier(socket);
3421
5417
  carrier.handshake(secWebSocketKey);
3422
5418
  const connection = hub.attach(carrier, auth);
@@ -3448,6 +5444,8 @@ var WebSocketCarrier = class {
3448
5444
  #closed = false;
3449
5445
  #onMessage;
3450
5446
  #onClose;
5447
+ /** Whether the peer declared it can inflate a compressed frame; see {@link frameDeflate}. */
5448
+ #deflate = false;
3451
5449
  /** Messages that arrived before a handler was registered; see {@link deliver}. */
3452
5450
  #pending = [];
3453
5451
  constructor(socket) {
@@ -3502,10 +5500,20 @@ var WebSocketCarrier = class {
3502
5500
  if (!this.#accept(outcome.frame.fin, outcome.frame.opcode, outcome.frame.payload)) return;
3503
5501
  }
3504
5502
  }
3505
- /** Send one text frame. */
5503
+ /**
5504
+ * Record the peer's `frame.deflate.v1` declaration, as `hello` reported it.
5505
+ *
5506
+ * It defaults to off, so a connection that never declares the capability keeps
5507
+ * the text frame this carrier always wrote, byte for byte.
5508
+ */
5509
+ frameDeflate(declared) {
5510
+ this.#deflate = declared;
5511
+ }
5512
+ /** Send one frame: the text itself, or raw DEFLATE of it as a binary frame. */
3506
5513
  send(text) {
3507
5514
  if (this.#closed) return;
3508
- this.#socket.write(encodeTextFrame(text));
5515
+ const payload = outboundPayloadOf(text, this.#deflate);
5516
+ this.#socket.write(payload.binary ? encodeBinaryFrame(payload.deflated) : encodeTextFrame(payload.text));
3509
5517
  }
3510
5518
  /** Send a close frame and end the socket. Idempotent. */
3511
5519
  close(code, reason) {
@@ -3686,10 +5694,31 @@ function permissionFaces(ctx) {
3686
5694
  };
3687
5695
  }
3688
5696
  /**
5697
+ * Resolve the host's job registry, now.
5698
+ *
5699
+ * Read per call, never captured at mount, for the reason the metadata faces
5700
+ * are: `jobs` is not in this plugin's `inject` list, so a host that composes
5701
+ * no job plugin still serves protocol v1 — `jobs.list` answers
5702
+ * `jobs-unavailable` instead of the bridge failing to start. The face is
5703
+ * structural: this package imports no part of the registry's own types.
5704
+ * @param ctx - the plugin's context.
5705
+ * @returns the job faces as they stand right now.
5706
+ */
5707
+ function jobFaces(ctx) {
5708
+ return { jobs: ctx.get("jobs") };
5709
+ }
5710
+ /**
3689
5711
  * Mount the bridge.
5712
+ *
5713
+ * Guarded by the family's single-instance rule: the aggregate row
5714
+ * (`web-ui-remote-bridge`) and a standalone install of this same package can
5715
+ * both be live in one profile, and the second mount would otherwise register
5716
+ * `/ios/v1` and the token route a second time. Whichever source mounts first
5717
+ * owns the package name; the other is queued and replayed when that owner
5718
+ * disposes.
3690
5719
  * @param ctx - the plugin's context, carrying the gateway and web server.
3691
5720
  */
3692
- function apply(ctx) {
5721
+ function applyImpl(ctx) {
3693
5722
  const log = (message) => {
3694
5723
  console.log(`[remote-bridge] ${message}`);
3695
5724
  };
@@ -3705,14 +5734,21 @@ function apply(ctx) {
3705
5734
  peer: ownerPeer,
3706
5735
  log
3707
5736
  });
5737
+ const jobs = new JobRoster({
5738
+ faces: () => jobFaces(ctx),
5739
+ log
5740
+ });
3708
5741
  const sessionMeta = new SessionMeta(() => sessionMetaFaces(ctx), () => Date.now(), log);
3709
5742
  const permissions = new SessionPermissions(() => permissionFaces(ctx), log);
5743
+ const extensions = new RemoteBridgeRegistry();
3710
5744
  const hub = new BridgeHub({
5745
+ extensions,
3711
5746
  gateway: ctx.typertGateway,
3712
5747
  pairing,
3713
5748
  roster,
3714
5749
  approvals,
3715
5750
  questions,
5751
+ jobs,
3716
5752
  sessionMeta,
3717
5753
  permissions,
3718
5754
  ownerPeer,
@@ -3720,6 +5756,7 @@ function apply(ctx) {
3720
5756
  clientTimeZone: localTimeZone,
3721
5757
  log
3722
5758
  });
5759
+ if (typeof ctx.provide === "function") ctx.provide(REMOTE_BRIDGE_SERVICE, createRemoteBridgeFace(extensions, hub));
3723
5760
  ctx.effect(() => {
3724
5761
  roster.load();
3725
5762
  const disposeUpgrade = ctx.webServer.registerUpgrade({
@@ -3735,10 +5772,18 @@ function apply(ctx) {
3735
5772
  disposeUpgrade();
3736
5773
  disposeRoute();
3737
5774
  hub.dispose();
5775
+ jobs.dispose();
3738
5776
  };
3739
5777
  }, "remote-bridge: protocol v1 routes");
3740
5778
  ctx.on("approval/request", (request, next) => hub.approve(request, next));
3741
5779
  ctx.on("user-questions/request", (request, next) => hub.question(request, next), { prepend: true });
3742
5780
  }
5781
+ /**
5782
+ * The plugin's mount point: {@link applyImpl} behind the family's
5783
+ * single-instance guard. The name is the npm package identity, which every
5784
+ * install source of this plugin shares — the aggregate's `web-ui-remote-bridge`
5785
+ * row and the standalone `remote-bridge` row alike.
5786
+ */
5787
+ const apply = mountOnce("@linxin666/dsh-remote-bridge", applyImpl);
3743
5788
  //#endregion
3744
5789
  export { ROSTER_PATH, apply, inject, name };