@byollm/relay 0.1.4 → 0.1.5-beta.2

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.
@@ -1,4 +1,4 @@
1
- import { PublicIdentity, CapabilityMatrix, WithheldKind, JobStub, SealedEnvelope, ClaimedStub } from '@byollm/protocol';
1
+ import { PublicIdentity, SealedEnvelope, CapabilityMatrix, WithheldKind, JobStub, ClaimedStub } from '@byollm/protocol';
2
2
 
3
3
  /**
4
4
  * The relay's routing state — byollm_009 §7, reachable at last.
@@ -198,6 +198,82 @@ interface RoutedJob {
198
198
  * decision, not a security property.
199
199
  */
200
200
  disposition?: "ok" | "error" | "canceled";
201
+ /**
202
+ * How many tool calls this job may make — byollm_012 §8, the relay's
203
+ * counter.
204
+ *
205
+ * The site's number, sent beside the stub at enqueue for `llm.tools` only:
206
+ * the lower of the payload's `maxToolCalls` and the purpose's. The relay
207
+ * cannot read the payload, so it takes the site's word, and that is safe in
208
+ * the one direction this counter exists for: it protects the site's tools
209
+ * from a modified daemon, and a site that overstates its own budget spends
210
+ * only its own. Absent, the protocol ceiling applies.
211
+ */
212
+ maxToolCalls?: number;
213
+ /**
214
+ * Tool calls this job has made, under any grant.
215
+ *
216
+ * Monotonic and never reset, so it is not a tally that a missed decrement
217
+ * can corrupt. It survives `#requeue` on purpose: a budget that restarted
218
+ * with every grant would let a modified daemon release, re-claim and spend
219
+ * the site's tools again — the counter exists to stop exactly that. The
220
+ * cost is that a job reclaimed after a lapse runs on what is left, and a
221
+ * second device's own count starts at 0: its first call past what is left
222
+ * is refused as `budget`, which an honest daemon reads as the job's tools
223
+ * being spent — a tool error to the model and the closing turn, `ok` with
224
+ * `stop: "tool-budget"` (byollm_012 §8, `TOOLS_SPENT_MESSAGE`).
225
+ */
226
+ toolCallsMade?: number;
227
+ /**
228
+ * The calls in flight under the CURRENT grant — byollm_012 §5.2.
229
+ *
230
+ * Short-lived: cleared when the grant ends (`#requeue`), when the job
231
+ * finishes, and with the job. So a result can only ever be bound to a call
232
+ * made under the lease that is running now, and a late answer for a grant
233
+ * that ended has nothing to land on.
234
+ */
235
+ toolCalls?: ToolCallRow[];
236
+ }
237
+ /** One tool call the relay is carrying. Ciphertext and ids, nothing else. */
238
+ interface ToolCallRow {
239
+ readonly callId: string;
240
+ /** The grant it was made under, which is the one it can be answered for. */
241
+ readonly leaseId: string;
242
+ /** Sealed to the site by the device. Opaque here. */
243
+ readonly envelope: SealedEnvelope;
244
+ /** When the relay stops holding it open: `TOOL_LIMITS.callTimeoutMs` on. */
245
+ readonly expiresAt: number;
246
+ /** Sealed to the device by the site, once answered. Opaque here. */
247
+ result?: SealedEnvelope;
248
+ }
249
+ /**
250
+ * The sub-state of a running job — byollm_012 §5.3.
251
+ *
252
+ * A job waiting on a tool result is still `running` and still holds its
253
+ * lease. `waiting-on-site` says why nothing is moving, so that a reader
254
+ * asking "is anything running this?" (`NO_RUNNER_SIGNAL`) can tell a device
255
+ * at work from a site that has not answered. Derived rather than stored: it
256
+ * is true exactly while a call made under the current grant is unanswered
257
+ * and inside its timeout, and a stored flag would be a second answer to that.
258
+ */
259
+ type RunningSubState = "waiting-on-site";
260
+ declare function subStateOf(job: RoutedJob, now: number): RunningSubState | undefined;
261
+ /** Why a tool call was refused, beyond the holder refusals. */
262
+ type ToolCallRefusal = HolderRefusal
263
+ /** The job is not `llm.tools`, so it has no tools to call. */
264
+ | "not-tools"
265
+ /** The call past the job's budget — byollm_012 §8. */
266
+ | "budget"
267
+ /** A call id this grant already used, for a different envelope. */
268
+ | "call-conflict";
269
+ /** A call waiting on a site, with the device the answer is sealed to. */
270
+ interface OutstandingToolCall {
271
+ readonly jobId: string;
272
+ readonly leaseId: string;
273
+ readonly callId: string;
274
+ readonly envelope: SealedEnvelope;
275
+ readonly device: PublicIdentity;
276
+ readonly expiresAt: number;
201
277
  }
202
278
  /** A device the relay has seen recently. */
203
279
  interface Presence {
@@ -412,6 +488,7 @@ declare class RelayState implements RoutingStore {
412
488
  id: string;
413
489
  siteId: string;
414
490
  stub: JobStub;
491
+ maxToolCalls?: number;
415
492
  }): Promise<RoutedJob>;
416
493
  job(siteId: string, jobId: string): Promise<RoutedJob | undefined>;
417
494
  jobs(): Promise<RoutedJob[]>;
@@ -516,6 +593,78 @@ declare class RelayState implements RoutingStore {
516
593
  }[];
517
594
  lost: Grant[];
518
595
  }>;
596
+ /**
597
+ * {@link RoutingStore.recordToolCall} — one sealed call, counted and kept.
598
+ *
599
+ * The holder checks are `takePayload`'s, in the same order, because a
600
+ * tool call is the same claim ("this grant, held by me") made mid-job.
601
+ * Then the two only this endpoint has: the job must be `llm.tools`, and
602
+ * the call must fit the budget. Counted **before** it is written, so the
603
+ * call that would exceed the budget is the one refused (`TOOLS_BUDGETED`).
604
+ */
605
+ recordToolCall(input: {
606
+ jobId: string;
607
+ runnerId: string;
608
+ leaseId: string;
609
+ callId: string;
610
+ envelope: SealedEnvelope;
611
+ }): Promise<{
612
+ callId: string;
613
+ expiresAt: number;
614
+ duplicate?: true;
615
+ } | {
616
+ refused: ToolCallRefusal;
617
+ }>;
618
+ /**
619
+ * {@link RoutingStore.toolCalls} — what is waiting on this site.
620
+ *
621
+ * Outstanding only: the current grant's, unanswered, inside the timeout.
622
+ * A call that timed out is gone from here because the daemon has already
623
+ * told the model the site did not answer, and running the tool now would
624
+ * spend the site's tools on an answer nobody will read.
625
+ */
626
+ toolCalls(siteId: string): Promise<OutstandingToolCall[]>;
627
+ /**
628
+ * {@link RoutingStore.answerToolCall} — a site's sealed answer, bound to
629
+ * its call (`TOOL_ENVELOPES_BOUND`, the relay's half).
630
+ *
631
+ * Found by **(site, job, call)**, so a result posted for job A can only
632
+ * ever land on a call of job A: another job's call id is not found here,
633
+ * and so is a call of A's that belonged to a grant that has ended. The
634
+ * daemon holds the other half — it opens the envelope and checks the job
635
+ * and the call inside the signature.
636
+ */
637
+ answerToolCall(input: {
638
+ siteId: string;
639
+ jobId: string;
640
+ callId: string;
641
+ envelope: SealedEnvelope;
642
+ }): Promise<{
643
+ accepted: true;
644
+ } | {
645
+ refused: "not-found" | "too-late";
646
+ }>;
647
+ /**
648
+ * {@link RoutingStore.toolResults} — answers, to the holder that asked.
649
+ *
650
+ * Each named call is looked up through the caller's grant, exactly as
651
+ * `takePayload` looks up a job: the lease must be current and held by this
652
+ * runner, and the call must have been made under it. Anything else is
653
+ * absent rather than refused, so a poll tells a stranger nothing.
654
+ */
655
+ toolResults(input: {
656
+ runnerId: string;
657
+ calls: readonly {
658
+ jobId: string;
659
+ leaseId: string;
660
+ callId: string;
661
+ }[];
662
+ }): Promise<{
663
+ jobId: string;
664
+ leaseId: string;
665
+ callId: string;
666
+ envelope: SealedEnvelope;
667
+ }[]>;
519
668
  seen(presence: Omit<Presence, "lastSeenAt">): Promise<Presence>;
520
669
  presence(runnerId: string): Promise<Presence | undefined>;
521
670
  /**
@@ -619,6 +768,11 @@ interface RoutingStore {
619
768
  id: string;
620
769
  siteId: string;
621
770
  stub: JobStub;
771
+ /**
772
+ * The job's tool-call budget, from the site, for `llm.tools` only —
773
+ * byollm_012 §8. Kept with the job; absent means the protocol ceiling.
774
+ */
775
+ maxToolCalls?: number;
622
776
  }): Promise<RoutedJob>;
623
777
  /**
624
778
  * One job, named by the site that published it — cloud_009 §3.
@@ -760,6 +914,73 @@ interface RoutingStore {
760
914
  * result nobody would accept, on somebody's own machine, at their expense.
761
915
  */
762
916
  cancelRequests(runnerId: string): Promise<Grant[]>;
917
+ /**
918
+ * Keep one sealed call from the lease's holder, counted against the job.
919
+ *
920
+ * MUST refuse, in this order: an unknown grant (`not-found`), another
921
+ * runner's (`not-holder`), a finished or withdrawn job (`terminal`), a grant
922
+ * that ended (`stale-lease`), a job whose payload was not collected
923
+ * (`not-ready`), a job that is not `llm.tools` (`not-tools`), and the call
924
+ * past the job's budget (`budget`) — counted before the write, over every
925
+ * grant the job has had. A call id already recorded under this grant
926
+ * returns that call with `duplicate` if the envelope is the same, and is
927
+ * refused (`call-conflict`) if it is not; neither is counted again.
928
+ */
929
+ recordToolCall(input: {
930
+ jobId: string;
931
+ runnerId: string;
932
+ leaseId: string;
933
+ callId: string;
934
+ envelope: SealedEnvelope;
935
+ }): Promise<{
936
+ callId: string;
937
+ expiresAt: number;
938
+ duplicate?: true;
939
+ } | {
940
+ refused: ToolCallRefusal;
941
+ }>;
942
+ /**
943
+ * This site's outstanding calls: made under a job's current grant, not
944
+ * answered, and not past `TOOL_LIMITS.callTimeoutMs` on this store's clock.
945
+ */
946
+ toolCalls(siteId: string): Promise<OutstandingToolCall[]>;
947
+ /**
948
+ * Keep a site's sealed answer — only for an outstanding call of the same
949
+ * job (`TOOL_ENVELOPES_BOUND`, the upstream's half).
950
+ *
951
+ * `not-found` for a call this job never made, made under a grant that has
952
+ * ended, or of a job that has; `too-late` for one that timed out or was
953
+ * already answered differently. The same answer twice is accepted twice
954
+ * and written once.
955
+ */
956
+ answerToolCall(input: {
957
+ siteId: string;
958
+ jobId: string;
959
+ callId: string;
960
+ envelope: SealedEnvelope;
961
+ }): Promise<{
962
+ accepted: true;
963
+ } | {
964
+ refused: "not-found" | "too-late";
965
+ }>;
966
+ /**
967
+ * The answered calls among those named, for the runner holding each one's
968
+ * current grant. A call not answered, not this runner's, or under a grant
969
+ * that ended is left out rather than refused.
970
+ */
971
+ toolResults(input: {
972
+ runnerId: string;
973
+ calls: readonly {
974
+ jobId: string;
975
+ leaseId: string;
976
+ callId: string;
977
+ }[];
978
+ }): Promise<{
979
+ jobId: string;
980
+ leaseId: string;
981
+ callId: string;
982
+ envelope: SealedEnvelope;
983
+ }[]>;
763
984
  /** Record a device as present. The store stamps when. */
764
985
  seen(presence: Omit<Presence, "lastSeenAt">): Promise<Presence>;
765
986
  presence(runnerId: string): Promise<Presence | undefined>;
@@ -768,4 +989,4 @@ interface RoutingStore {
768
989
  sweep(): Promise<RoutedJob[]>;
769
990
  }
770
991
 
771
- export { AWAITING_PAYLOAD_MS as A, CHURN_EXPIRIES as C, type Grant as G, type HolderRefusal as H, type Presence as P, type RoutingStore as R, SEAL_ATTEMPTS_BEFORE_EVICTION as S, type UnsealedChurn as U, CHURN_QUIET_MS as a, CHURN_WINDOW_MS as b, type ClaimInput as c, RelayState as d, type ReleaseReason as e, type RoutedJob as f, type RoutedState as g, UNSEALED_PER_PAIR as h, routeKey as r };
992
+ export { AWAITING_PAYLOAD_MS as A, CHURN_EXPIRIES as C, type Grant as G, type HolderRefusal as H, type OutstandingToolCall as O, type Presence as P, type RoutingStore as R, SEAL_ATTEMPTS_BEFORE_EVICTION as S, type ToolCallRefusal as T, type UnsealedChurn as U, CHURN_QUIET_MS as a, CHURN_WINDOW_MS as b, type ClaimInput as c, RelayState as d, type ReleaseReason as e, type RoutedJob as f, type RoutedState as g, type RunningSubState as h, type ToolCallRow as i, UNSEALED_PER_PAIR as j, routeKey as r, subStateOf as s };
@@ -1,4 +1,4 @@
1
- import { R as RoutingStore } from './store-BNhCedHZ.js';
1
+ import { R as RoutingStore } from './store-BesaBmxr.js';
2
2
  import '@byollm/protocol';
3
3
 
4
4
  /**
@@ -1,10 +1,14 @@
1
1
  import {
2
2
  AWAITING_PAYLOAD_MS,
3
3
  routeKey
4
- } from "./chunk-4ISUXCIO.js";
4
+ } from "./chunk-YRJDRZ6G.js";
5
5
 
6
6
  // src/store-contract.ts
7
- import { generateKeys, publicIdentityOf } from "@byollm/protocol";
7
+ import {
8
+ TOOL_LIMITS,
9
+ generateKeys,
10
+ publicIdentityOf
11
+ } from "@byollm/protocol";
8
12
  import { describe, expect, it } from "vitest";
9
13
  var CONTRACT_SITE = "site_store";
10
14
  var SITE_KEY_ID = "BYOLLM-TEST-SITE-KEY-ID";
@@ -34,6 +38,10 @@ var ENVELOPE = {
34
38
  direction: "payload",
35
39
  deadlineAt: 41024448e5
36
40
  };
41
+ var toolsStub = (id) => ({ ...stub(id), kind: "llm.tools" });
42
+ var callId = (n) => `call_${String(n).padStart(12, "0")}`;
43
+ var CALL = { ...ENVELOPE, direction: "tool-call" };
44
+ var ANSWER = { ...ENVELOPE, direction: "tool-result" };
37
45
  var claimArgs = (over = {}) => {
38
46
  const { owners = ["alice"], sites = [SITE], ...rest } = over;
39
47
  return {
@@ -703,6 +711,218 @@ function describeStoreContract(name, options) {
703
711
  expect(granted.lease.expiresAt).toBeLessThanOrEqual(after + 45e3);
704
712
  await done();
705
713
  });
714
+ const runningTools = async (store, id, maxToolCalls) => {
715
+ await store.enqueue({
716
+ id,
717
+ siteId: SITE,
718
+ stub: toolsStub(id),
719
+ ...maxToolCalls === void 0 ? {} : { maxToolCalls }
720
+ });
721
+ const granted = await store.claim(
722
+ claimArgs({ kinds: /* @__PURE__ */ new Set(["llm.tools"]) })
723
+ );
724
+ const leaseId = granted.find((job) => job.id === id)?.lease.id;
725
+ if (leaseId === void 0) throw new Error(`${id} was not claimed`);
726
+ await store.seal({ jobId: id, siteId: SITE, envelope: ENVELOPE });
727
+ await store.takePayload({ jobId: id, runnerId: "runner_1", leaseId });
728
+ return { jobId: id, leaseId };
729
+ };
730
+ it("carries a tool call from the holder to the site and its answer back", async () => {
731
+ const { store, done } = await make();
732
+ const job = await runningTools(store, "t");
733
+ const recorded = await store.recordToolCall({
734
+ ...job,
735
+ runnerId: "runner_1",
736
+ callId: callId(1),
737
+ envelope: CALL
738
+ });
739
+ expect(recorded).toMatchObject({ callId: callId(1) });
740
+ const [waiting] = await store.toolCalls(SITE);
741
+ expect(waiting).toMatchObject({ ...job, callId: callId(1) });
742
+ expect(
743
+ await store.answerToolCall({
744
+ siteId: SITE,
745
+ jobId: "t",
746
+ callId: callId(1),
747
+ envelope: ANSWER
748
+ })
749
+ ).toEqual({ accepted: true });
750
+ expect(await store.toolCalls(SITE)).toEqual([]);
751
+ expect(
752
+ await store.toolResults({
753
+ runnerId: "runner_1",
754
+ calls: [{ ...job, callId: callId(1) }]
755
+ })
756
+ ).toEqual([{ ...job, callId: callId(1), envelope: ANSWER }]);
757
+ await done();
758
+ });
759
+ it("binds an answer to its own job's call, and to no other", async () => {
760
+ const { store, done } = await make();
761
+ const a = await runningTools(store, "ta");
762
+ const b = await runningTools(store, "tb");
763
+ await store.recordToolCall({
764
+ ...b,
765
+ runnerId: "runner_1",
766
+ callId: callId(2),
767
+ envelope: CALL
768
+ });
769
+ expect(
770
+ await store.answerToolCall({
771
+ siteId: SITE,
772
+ jobId: "ta",
773
+ callId: callId(2),
774
+ envelope: ANSWER
775
+ })
776
+ ).toEqual({ refused: "not-found" });
777
+ expect(
778
+ await store.answerToolCall({
779
+ siteId: "site_other",
780
+ jobId: "tb",
781
+ callId: callId(2),
782
+ envelope: ANSWER
783
+ })
784
+ ).toEqual({ refused: "not-found" });
785
+ expect(
786
+ await store.toolResults({
787
+ runnerId: "runner_1",
788
+ calls: [{ ...a, callId: callId(2) }]
789
+ })
790
+ ).toEqual([]);
791
+ await done();
792
+ });
793
+ it("refuses the call past a job's budget, counted across grants", async () => {
794
+ const { store, done } = await make();
795
+ const job = await runningTools(store, "tbudget", 1);
796
+ expect(
797
+ await store.recordToolCall({
798
+ ...job,
799
+ runnerId: "runner_1",
800
+ callId: callId(3),
801
+ envelope: CALL
802
+ })
803
+ ).not.toHaveProperty("refused");
804
+ expect(
805
+ await store.recordToolCall({
806
+ ...job,
807
+ runnerId: "runner_1",
808
+ callId: callId(4),
809
+ envelope: CALL
810
+ })
811
+ ).toEqual({ refused: "budget" });
812
+ await store.releaseLeases({ runnerId: "runner_1", leases: [job] });
813
+ const again = await runningTools(store, "tbudget");
814
+ expect(
815
+ await store.recordToolCall({
816
+ ...again,
817
+ runnerId: "runner_1",
818
+ callId: callId(5),
819
+ envelope: CALL
820
+ })
821
+ ).toEqual({ refused: "budget" });
822
+ await done();
823
+ });
824
+ it("defaults a job's budget to the protocol ceiling", async () => {
825
+ const { store, done } = await make();
826
+ const job = await runningTools(store, "tceiling");
827
+ for (let n = 1; n <= TOOL_LIMITS.maxToolCalls; n += 1) {
828
+ const recorded = await store.recordToolCall({
829
+ ...job,
830
+ runnerId: "runner_1",
831
+ callId: callId(100 + n),
832
+ envelope: CALL
833
+ });
834
+ expect(recorded).not.toHaveProperty("refused");
835
+ }
836
+ expect(
837
+ await store.recordToolCall({
838
+ ...job,
839
+ runnerId: "runner_1",
840
+ callId: callId(199),
841
+ envelope: CALL
842
+ })
843
+ ).toEqual({ refused: "budget" });
844
+ await done();
845
+ });
846
+ it("refuses a call on a job without tools, or before its payload was taken", async () => {
847
+ const { store, done } = await make();
848
+ await store.enqueue({ id: "plain", siteId: SITE, stub: stub("plain") });
849
+ const [granted] = await store.claim(claimArgs());
850
+ const lease = { jobId: "plain", leaseId: granted.lease.id };
851
+ expect(
852
+ await store.recordToolCall({
853
+ ...lease,
854
+ runnerId: "runner_1",
855
+ callId: callId(6),
856
+ envelope: CALL
857
+ })
858
+ ).toEqual({ refused: "not-ready" });
859
+ await store.seal({ jobId: "plain", siteId: SITE, envelope: ENVELOPE });
860
+ await store.takePayload({ ...lease, runnerId: "runner_1" });
861
+ expect(
862
+ await store.recordToolCall({
863
+ ...lease,
864
+ runnerId: "runner_1",
865
+ callId: callId(6),
866
+ envelope: CALL
867
+ })
868
+ ).toEqual({ refused: "not-tools" });
869
+ await done();
870
+ });
871
+ it("ends a job's calls with the job", async () => {
872
+ const { store, done } = await make();
873
+ const job = await runningTools(store, "tend");
874
+ await store.recordToolCall({
875
+ ...job,
876
+ runnerId: "runner_1",
877
+ callId: callId(7),
878
+ envelope: CALL
879
+ });
880
+ await store.complete({
881
+ ...job,
882
+ runnerId: "runner_1",
883
+ envelope: ENVELOPE,
884
+ disposition: "ok"
885
+ });
886
+ expect(await store.toolCalls(SITE)).toEqual([]);
887
+ expect(
888
+ await store.answerToolCall({
889
+ siteId: SITE,
890
+ jobId: "tend",
891
+ callId: callId(7),
892
+ envelope: ANSWER
893
+ })
894
+ ).toEqual({ refused: "not-found" });
895
+ await done();
896
+ });
897
+ it.skipIf(advance === void 0)(
898
+ "stops holding a call open at the call timeout",
899
+ async () => {
900
+ const { store, done } = await make();
901
+ const job = await runningTools(store, "tlate");
902
+ await store.recordToolCall({
903
+ ...job,
904
+ runnerId: "runner_1",
905
+ callId: callId(8),
906
+ envelope: CALL
907
+ });
908
+ await advance(store, TOOL_LIMITS.callTimeoutMs + 1);
909
+ await store.renewLeases({
910
+ runnerId: "runner_1",
911
+ leases: [job],
912
+ leaseMs: 6e4
913
+ });
914
+ expect(await store.toolCalls(SITE)).toEqual([]);
915
+ expect(
916
+ await store.answerToolCall({
917
+ siteId: SITE,
918
+ jobId: "tlate",
919
+ callId: callId(8),
920
+ envelope: ANSWER
921
+ })
922
+ ).toEqual({ refused: "too-late" });
923
+ await done();
924
+ }
925
+ );
706
926
  });
707
927
  }
708
928
  export {