@northtalk/ts 0.5.1 → 0.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (58) hide show
  1. package/{binary-value-xvJoGg0C.d.ts → binary-value-M8v567iA.d.ts} +1 -1
  2. package/{checker-CUhn2XaM.js → checker-Coml0Tf9.js} +581 -71
  3. package/{core-BuTAYRm-.d.ts → core-D4qYURer.d.ts} +1 -1
  4. package/{debug-DRhMZAxw.d.ts → debug-C_Ob5rkl.d.ts} +137 -12
  5. package/debug.d.ts +1 -1
  6. package/debug.js +1 -1
  7. package/{driver-CHDcuqUy.d.ts → driver-CLi_OmyQ.d.ts} +1 -1
  8. package/driver.d.ts +1 -1
  9. package/driver.js +1 -1
  10. package/encoding-BL2ECJmg.js +338 -0
  11. package/{engine-Cc3yofGM.d.ts → engine-BBNHy4-F.d.ts} +2 -2
  12. package/{engine-CXf5FCwi.js → engine-DhBk0lTt.js} +6 -6
  13. package/{errors-D11zizZg.js → errors-P3ga1I-9.js} +124 -21
  14. package/{group-BflSou2n.js → group-BqccKTWz.js} +406 -75
  15. package/{http-fetch-DFwVIOQg.js → http-fetch-DA-NbFIM.js} +2 -2
  16. package/http.d.ts +1 -1
  17. package/http.js +5 -5
  18. package/index-CBuczWK0.d.ts +9 -0
  19. package/index.d.ts +6 -12
  20. package/index.js +15 -14
  21. package/{inline-grants-XbX9HL_w.js → inline-grants-BT2nnfLA.js} +4 -5
  22. package/{lean-BebPaTMK.js → lean-BJmLobmd.js} +13 -8
  23. package/{lean-CjWVuOrC.d.ts → lean-CFLJ9VrX.d.ts} +155 -6
  24. package/lean.d.ts +5 -6
  25. package/lean.js +15 -14
  26. package/{manifest-CCfpn0kC.js → manifest-37x-HSxH.js} +4 -3
  27. package/message-layer.d.ts +2 -2
  28. package/message-layer.js +2 -2
  29. package/notify.d.ts +1 -1
  30. package/notify.js +1 -1
  31. package/{objects-DmUc0lha.js → objects-DE6kRk0r.js} +1 -1
  32. package/{objects-DC6HjzBY.d.ts → objects-DVlpWsi0.d.ts} +11 -3
  33. package/{operations-DnCcztkZ.js → operations-CGjDlkGU.js} +73 -15
  34. package/package.json +5 -1
  35. package/peer-capability-elnbQy-J.js +149 -0
  36. package/peer.d.ts +173 -0
  37. package/peer.js +542 -0
  38. package/{readers-MmyZ_d0w.d.ts → readers-ChQ0e92c.d.ts} +1 -1
  39. package/{readers-CsvlahLi.js → readers-yMS1eAOp.js} +1 -1
  40. package/{request-pump-binary-oqjWFqZA.js → request-pump-binary-BS1J8DF2.js} +4 -4
  41. package/{router-BZ-aYeXA.js → router-Bm7A2kjt.js} +4 -4
  42. package/{router-D56rSkU8.d.ts → router-D0rf5SkW.d.ts} +2 -2
  43. package/session.d.ts +2 -2
  44. package/session.js +65 -17
  45. package/setup.d.ts +3 -2
  46. package/setup.js +13 -16
  47. package/sqlite.d.ts +2 -2
  48. package/sqlite.js +5 -5
  49. package/{store-DHlo6fP5.js → store-D80OlpyG.js} +2 -2
  50. package/store-capability-DBLlWaNO.js +187 -0
  51. package/store.d.ts +2 -2
  52. package/store.js +2 -2
  53. package/{user-capability-BcRQyyEw.js → user-capability-D6hGa3eF.js} +3 -4
  54. package/wasm.d.ts +16 -7
  55. package/wasm.js +52 -23
  56. package/encoding-RUuES_e4.js +0 -99
  57. package/manifest-DVrx-pT2.d.ts +0 -122
  58. package/store-capability-BrUUAwVS.js +0 -389
@@ -1,12 +1,13 @@
1
1
 
2
- import { A as listValues, Bt as formatInstant, C as functionsBelongTo, E as instantOf$1, F as mapOfLayout, Ft as civilFromFields, H as quantity, K as requireArgs, L as nothing, N as map, P as mapLayout, Q as text, R as num, S as functionValue, U as quantityOf, Vt as isInstant, W as range, a as hostDetail, an as builtins, at as parseUnit, b as displayText, bt as integerOf, cn as libraryExports, d as bytes, f as bytesOf, h as civilOf, i as ScriptError, l as Value, n as LoadError, on as diagnosticCodes, p as canonicalNumber, q as requireValue, r as MailboxFull, s as sendFailed, sn as grammar, t as HostError, u as bool, v as dec, xt as isInteger, y as decimalParts } from "./errors-D11zizZg.js";
3
- import { a as rebindObject, i as propertyChecks, n as makeObject, o as stateOf$1, r as objectKind } from "./objects-DmUc0lha.js";
4
- import { A as negated, B as subjectText, C as isKind, Ct as validMessageSelector, D as matchCaptures, Dt as runTask, E as makeRange, F as search, G as charge, H as waitUs, I as setKey, J as partSize, K as fixedRates, L as smallArithmetic, M as prepareConversion, N as property, O as matchesOf, P as randomBound, Q as arityOf, R as smallOf, S as isEmpty, St as validComputedMessageName, T as makePatternValue, U as wrongKind, V as textForm, W as cacheBuild, X as resetMeasured, Y as rateOf, Z as sizeOf, _ as deleteKey, a as builtin, at as patternSource, b as hasKey, bt as mismatch, c as canConvert, ct as textDisplay, d as chunkSet, dt as errorMessages, et as functionHead, f as chunkThere, ft as languageVersion, g as decodeUtf8, gt as acceptsArgumentCount, h as convert, i as arithmetic, it as numberText, j as outOfRange, k as member, l as chunkDelete, lt as compareText, m as concat, mt as reservedErrorKeys, n as ScriptError$1, nt as opcodes, o as builtinDefaults, ot as quantityText, p as comparison, pt as limitDefaults, q as keysContents, r as appendTo, rt as capturesOf, s as byteOf, st as splicesOf, t as NotImplementedError, tt as instructionSpec, u as chunkGet, ut as costModel, v as equals, w as keyText, x as integerValue, y as getKey, z as splice } from "./operations-DnCcztkZ.js";
5
- import { _ as viewSource, d as operationUses, g as checkDecisionCalls, n as checkSourceForLoad, t as checkSource, u as checkEffectCall } from "./checker-CUhn2XaM.js";
6
- import { a as operationsOf, c as CallMeter, r as grantData, s as invoke, t as canonicalJSON } from "./manifest-CCfpn0kC.js";
2
+ import { A as listValues, C as functionsBelongTo, Ct as integerOf, E as instantOf$1, F as mapOfLayout, H as quantity, K as requireArgs, L as nothing, N as map, P as mapLayout, R as num, Rt as civilFromFields, S as functionValue, U as quantityOf, Ut as formatInstant, W as range, Wt as isInstant, Y as smallCoefficient, Z as smallExponent, a as hostDetail, b as displayText, cn as builtins, ct as parseUnit, d as bytes, dn as libraryExports, et as text, f as bytesOf, h as civilOf, i as ScriptError, l as Value, ln as diagnosticCodes, n as LoadError, p as canonicalNumber, q as requireValue, r as MailboxFull, s as sendFailed, t as HostError, u as bool, un as grammar, v as dec, wt as isInteger, y as decimalParts } from "./errors-P3ga1I-9.js";
3
+ import { a as rebindObject, i as propertyChecks, n as makeObject, o as stateOf$1, r as objectKind } from "./objects-DE6kRk0r.js";
4
+ import { $ as arityOf, A as musicalCount, B as splice, C as isKind, Ct as mismatch, D as matchCaptures, Dt as validComputedMessageName, E as makeRange, Et as shapeDiagnostics, F as randomBound, G as cacheBuild, H as textForm, I as search, J as keysContents, K as charge, L as setKey, M as outOfRange, Mt as runTask, N as prepareConversion, O as matchesOf, Ot as validMessageSelector, P as property, Q as sizeOf, R as smallArithmetic, S as isEmpty, T as makePatternValue, U as waitUs, V as subjectText, W as wrongKind, X as rateOf, Y as partSize, Z as resetMeasured, _ as deleteKey, _t as acceptsArgumentCount, a as builtin, at as numberText, b as hasKey, c as canConvert, ct as splicesOf, d as chunkSet, dt as costModel, f as chunkThere, ft as errorMessages, g as decodeUtf8, h as convert, ht as reservedErrorKeys, i as arithmetic, it as capturesOf, j as negated, k as member, l as chunkDelete, lt as textDisplay, m as concat, mt as limitDefaults, n as ScriptError$1, nt as instructionSpec, o as builtinDefaults, ot as patternSource, p as comparison, pt as languageVersion, q as fixedRates, r as appendTo, rt as opcodes, s as byteOf, st as quantityText, t as NotImplementedError, tt as functionHead, u as chunkGet, ut as compareText, v as equals, vt as decodeShape, w as keyText, x as integerValue, xt as diagnosticRecord, y as getKey, z as smallCoefficientOf } from "./operations-CGjDlkGU.js";
5
+ import { _ as viewSource, d as operationUses, g as checkDecisionCalls, n as checkSourceForLoad, t as checkSource, u as checkEffectCall } from "./checker-Coml0Tf9.js";
6
+ import { a as operationsOf, c as CallMeter, r as grantData, s as invoke, t as canonicalJSON } from "./manifest-37x-HSxH.js";
7
7
  import { n as trackOperation } from "./operation-promises-ClA1BTaS.js";
8
- import { c as readDisplay } from "./readers-CsvlahLi.js";
9
- import { i as standardChecks } from "./encoding-RUuES_e4.js";
8
+ import { c as readDisplay } from "./readers-yMS1eAOp.js";
9
+ import { l as isMusicalClock, p as standardChecks, r as MUSICAL_CLOCK } from "./encoding-BL2ECJmg.js";
10
+ import { r as PEER_POST, t as PEER_CALL } from "./peer-capability-elnbQy-J.js";
10
11
  import { n as sha256, r as sha256Bytes, t as Sha256 } from "./sha256-9CGf5BS_.js";
11
12
  //#region src/stdlib-registry.ts
12
13
  /** The seven stdlib Library names, which a Host may not register. */
@@ -466,6 +467,10 @@ var UnitLowering = class {
466
467
  for (const body of this.bodies) {
467
468
  body.start = code.length;
468
469
  if (body.acceptedAt !== void 0) body.acceptedAt += body.start;
470
+ if (body.tests) {
471
+ body.tests.guardAt += body.start;
472
+ for (const shape of body.tests.shapes) shape.at += body.start;
473
+ }
469
474
  for (const ins of this.code.get(body.index) ?? []) {
470
475
  const opcode = opcodes.get(ins.op);
471
476
  if (opcode === void 0) throw new Error(`\`${ins.op}\` isn't an instruction`);
@@ -617,6 +622,21 @@ var BodyLowering = class BodyLowering {
617
622
  if (this.isIt(binding)) return this.whoseIt.at(-1) ?? 0;
618
623
  return this.overrides.get(binding) ?? this.slots.get(binding);
619
624
  }
625
+ namedShape(name) {
626
+ const binding = this.u.scopes[0].bindings.find((b) => b.name === name && b.shape);
627
+ return binding ? {
628
+ kind: "name",
629
+ role: "value",
630
+ text: name,
631
+ binding,
632
+ span: binding.span ?? {
633
+ line: 0,
634
+ col: 0,
635
+ start: 0,
636
+ end: 0
637
+ }
638
+ } : void 0;
639
+ }
620
640
  load(name, at) {
621
641
  const binding = name.binding;
622
642
  const slot = this.slotOf(binding);
@@ -683,7 +703,7 @@ var BodyLowering = class BodyLowering {
683
703
  const args = this.layout(params, [], this.scopeLocals());
684
704
  if (decl.during?.binding) this.body.duringSlot = this.slots.get(decl.during.binding);
685
705
  const failed = this.label();
686
- yield this.guarded(failed, this.parameters(params, args, decl.guard, failed));
706
+ yield this.guarded(failed, this.parameters(params, args, decl.guard, failed, decl.shapes));
687
707
  this.body.acceptedAt = this.code.length;
688
708
  yield decl.finally ? this.tryStatement({
689
709
  k: "try",
@@ -698,8 +718,29 @@ var BodyLowering = class BodyLowering {
698
718
  this.emit(decl.end, "clause-fail");
699
719
  this.finish();
700
720
  }
701
- *parameters(params, args, guard, failed) {
721
+ *parameters(params, args, guard, failed, shapes = []) {
702
722
  for (const [i, p] of params.entries()) if (p.k !== "bind") yield this.pattern(p, args[i], failed, null, false);
723
+ const tests = {
724
+ guardAt: 0,
725
+ shapes: []
726
+ };
727
+ for (const [i, s] of shapes.entries()) if (s) {
728
+ const shape = this.namedShape(s.kind);
729
+ const definition = shape && this.u.definitionOf.get(shape.binding);
730
+ tests.shapes.push({
731
+ arg: i,
732
+ at: this.code.length,
733
+ ...shape ? definition === void 0 ? {} : { definition } : { kind: s.kind }
734
+ });
735
+ this.emit(s.pos, "load", args[i]);
736
+ if (shape) {
737
+ this.load(shape, s.pos);
738
+ this.emit(s.pos, "call-builtin", "conforms", 2);
739
+ } else this.emit(s.pos, "is-kind", s.kind);
740
+ this.emit(s.pos, "branch-false", failed);
741
+ }
742
+ tests.guardAt = this.code.length;
743
+ if (this.body.kind === "handler" || this.body.kind === "fallback") this.body.tests = tests;
703
744
  if (guard) yield this.guard(guard, failed);
704
745
  }
705
746
  *guard(guard, failed) {
@@ -1791,7 +1832,10 @@ var BodyLowering = class BodyLowering {
1791
1832
  case "is-kind":
1792
1833
  case "is-empty":
1793
1834
  yield this.expr(e.l);
1794
- if (e.k === "is-kind") this.emit(at, "is-kind", e.kind);
1835
+ if (e.k === "is-kind" && this.namedShape(e.kind)) {
1836
+ this.load(this.namedShape(e.kind), at);
1837
+ this.emit(at, "call-builtin", "conforms", 2);
1838
+ } else if (e.k === "is-kind") this.emit(at, "is-kind", e.kind);
1795
1839
  else this.emit(at, "is-empty");
1796
1840
  e.neg && this.emit(at, "not");
1797
1841
  return;
@@ -2100,7 +2144,10 @@ const exportsOf = (tree) => {
2100
2144
  else out[decl.k === "handler" ? decl.name : decl.name.text] = decl.k === "handler" ? {
2101
2145
  kind: decl.k,
2102
2146
  maySuspend: tree.maySuspend?.includes(decl.name) ?? false
2103
- } : { kind: decl.k };
2147
+ } : {
2148
+ kind: decl.k,
2149
+ ...decl.shape ? { shape: true } : {}
2150
+ };
2104
2151
  }
2105
2152
  return out;
2106
2153
  };
@@ -2528,15 +2575,11 @@ var Waits = class {
2528
2575
  }
2529
2576
  /** Waits on a call or reply, as a Run's own Wait or a Join Member's. */
2530
2577
  add(id, s, running, timer, join) {
2531
- this.pending.set(id, join ? {
2532
- s,
2533
- running,
2534
- timer,
2535
- join
2536
- } : {
2578
+ this.pending.set(id, {
2537
2579
  s,
2538
2580
  running,
2539
- timer
2581
+ ...timer ? { timer } : {},
2582
+ ...join ? { join } : {}
2540
2583
  });
2541
2584
  }
2542
2585
  has(id) {
@@ -2553,7 +2596,8 @@ var Waits = class {
2553
2596
  cut(members, reason) {
2554
2597
  const cut = this.pendingMembers(members);
2555
2598
  for (const m of cut) {
2556
- this.pending.get(m.id).timer.live = false;
2599
+ const t = this.pending.get(m.id).timer;
2600
+ if (t) t.live = false;
2557
2601
  this.pending.delete(m.id);
2558
2602
  abandon(m.abort, reason);
2559
2603
  }
@@ -2571,7 +2615,7 @@ var Waits = class {
2571
2615
  return { k: "late" };
2572
2616
  }
2573
2617
  this.pending.delete(id);
2574
- p.timer.live = false;
2618
+ if (p.timer) p.timer.live = false;
2575
2619
  const { s, running } = p;
2576
2620
  if (!p.join) return {
2577
2621
  k: "ready",
@@ -3089,7 +3133,7 @@ const iteratorOver = (v) => {
3089
3133
  };
3090
3134
  const isValue = (item) => Value.isValue(item);
3091
3135
  const isBoolean = (item) => isValue(item) && item.kind === "boolean";
3092
- const smallAt = (item) => isValue(item) ? smallOf(item) : NaN;
3136
+ const decimalAt = (item) => isValue(item) ? item.asDecimal() : void 0;
3093
3137
  const drop = (stack, n) => {
3094
3138
  for (let i = 0; i < n; i++) stack.pop();
3095
3139
  };
@@ -3109,7 +3153,7 @@ const fixedCharges = fixedRates();
3109
3153
  const compareCharges = [];
3110
3154
  const numberCharges = [];
3111
3155
  const numberCharge = (rate, result) => {
3112
- const n = Math.abs(smallOf(result));
3156
+ const n = Math.abs(smallCoefficientOf(result));
3113
3157
  let digits = 1;
3114
3158
  for (let ten = 10; n >= ten; ten *= 10) digits++;
3115
3159
  return (numberCharges[rate] ??= [])[digits] ??= charge(rate, { result });
@@ -3327,6 +3371,15 @@ var Run = class Run {
3327
3371
  clause = 0;
3328
3372
  /** Its entry dispatch reached the Fallback Handler's clauses (ADR 0064). */
3329
3373
  viaFallback = false;
3374
+ /**
3375
+ * Why dispatch skipped each named clause of the entry Delivery, for the
3376
+ * Trace's `mismatches` (ADR 0172). Tooling-only, never saved or charged.
3377
+ */
3378
+ mismatches = [];
3379
+ stepFrame = null;
3380
+ stepPc = -1;
3381
+ priorFrame = null;
3382
+ priorPc = -1;
3330
3383
  during = nothing;
3331
3384
  /** Its Fuel when its cancellation cleanup began, if it has been cancelled. */
3332
3385
  cleanupFrom = null;
@@ -4001,7 +4054,12 @@ var Run = class Run {
4001
4054
  for (;;) {
4002
4055
  while (d.next < d.clauses.length) {
4003
4056
  const body = d.clauses[d.next++];
4004
- if (body.params.length === d.args.length) {
4057
+ if (body.params.length !== d.args.length) {
4058
+ if (!this.frames.length && !this.viaFallback) this.mismatches.push({
4059
+ clause: body.clause ?? 0,
4060
+ reason: "arity"
4061
+ });
4062
+ } else {
4005
4063
  if (!this.frames.length) this.clause = body.clause ?? 0;
4006
4064
  this.push(d.code, body, d.args, d);
4007
4065
  return true;
@@ -4016,6 +4074,29 @@ var Run = class Run {
4016
4074
  this.viaFallback = true;
4017
4075
  }
4018
4076
  }
4077
+ mismatchOf(frame) {
4078
+ const clause = frame.body.clause ?? 0;
4079
+ const tests = frame.body.tests;
4080
+ const pc = this.priorFrame === frame ? this.priorPc : null;
4081
+ if (!tests || pc === null || pc >= tests.guardAt) return {
4082
+ clause,
4083
+ reason: "guard"
4084
+ };
4085
+ let shape;
4086
+ for (const s of tests.shapes) if (s.at <= pc) shape = s;
4087
+ if (!shape) return {
4088
+ clause,
4089
+ reason: "pattern"
4090
+ };
4091
+ const definition = shape.definition === void 0 ? void 0 : frame.code.definitions[shape.definition];
4092
+ return {
4093
+ clause,
4094
+ reason: "shape",
4095
+ argument: shape.arg + 1,
4096
+ value: frame.dispatch.args[shape.arg],
4097
+ shape: shape.kind !== void 0 ? text(shape.kind) : definition && homeConstant(definition, this.script.home ?? this.script)
4098
+ };
4099
+ }
4019
4100
  /** Whether a dispatch has a clause left to try after the current one. */
4020
4101
  static more(d) {
4021
4102
  return !!d && (!!d.fallback?.clauses.length || d.clauses.slice(d.next).some((b) => b.params.length === d.args.length));
@@ -4135,6 +4216,10 @@ var Run = class Run {
4135
4216
  const frame = this.frame;
4136
4217
  const ins = frame.code.unit.code[frame.pc];
4137
4218
  const rate = ins.rate;
4219
+ this.priorFrame = this.stepFrame;
4220
+ this.priorPc = this.stepPc;
4221
+ this.stepFrame = frame;
4222
+ this.stepPc = frame.pc;
4138
4223
  const m = this.m;
4139
4224
  resetMeasured(m);
4140
4225
  const resumption = this.resumption;
@@ -4200,7 +4285,9 @@ var Run = class Run {
4200
4285
  fastSteps(room) {
4201
4286
  if (!fastPath.enabled || !this.charging || this.cancelling || this.resumption || this.entryError || this.suspended || this.outcome || !this.frames.length) return;
4202
4287
  let frame = this.frame;
4203
- if (frame.restricted || frame.clauseCharge) return;
4288
+ if (frame.restricted || frame.clauseCharge && frame === this.frames[0]) return;
4289
+ const clauseFuel = fixedCharges[CLAUSE].fuel;
4290
+ let clause = frame.clauseCharge ? clauseFuel : 0;
4204
4291
  let { locals, stack, code } = frame;
4205
4292
  let instructions = code.unit.code;
4206
4293
  const m = this.m;
@@ -4239,9 +4326,12 @@ var Run = class Run {
4239
4326
  case 34:
4240
4327
  case 29:
4241
4328
  case 30: {
4242
- const x = smallAt(stack.at(-2));
4243
- const y = smallAt(stack.at(-1));
4244
- if (Number.isNaN(x) || Number.isNaN(y)) break;
4329
+ const left = decimalAt(stack.at(-2));
4330
+ const right = decimalAt(stack.at(-1));
4331
+ if (!left || !right) break;
4332
+ const x = smallCoefficient(left);
4333
+ const y = smallCoefficient(right);
4334
+ if (Number.isNaN(x) || Number.isNaN(y) || smallExponent(left) !== smallExponent(right)) break;
4245
4335
  cost = compareCharges[ins.rate] ??= charge(ins.rate, {
4246
4336
  result: bool(true),
4247
4337
  scanned: 0
@@ -4249,7 +4339,7 @@ var Run = class Run {
4249
4339
  const holds = ordered(opcode, x, y);
4250
4340
  const following = instructions[pc + 1];
4251
4341
  const branch = fixedCharges[following.rate];
4252
- if ((following.opcode === 15 || following.opcode === 16) && branch && fuel + cost.fuel < end && fuel + cost.fuel + branch.fuel <= fuelLimit && alloc + cost.alloc + branch.alloc <= allocLimit) {
4342
+ if ((following.opcode === 15 || following.opcode === 16) && branch && clause === 0 && fuel + cost.fuel < end && fuel + cost.fuel + branch.fuel <= fuelLimit && alloc + cost.alloc + branch.alloc <= allocLimit) {
4253
4343
  fuel += cost.fuel + branch.fuel;
4254
4344
  alloc += cost.alloc + branch.alloc;
4255
4345
  drop(stack, 2);
@@ -4279,6 +4369,12 @@ var Run = class Run {
4279
4369
  if (isValue(receiver) && receiver.kind === "map") cost = fixedCharges[ins.rate];
4280
4370
  break;
4281
4371
  }
4372
+ case 63:
4373
+ cost = this.fastSetKeyCharge(ins, stack);
4374
+ break;
4375
+ case 91:
4376
+ cost = this.fastCallHandlerCharge(ins, code);
4377
+ break;
4282
4378
  case 67: {
4283
4379
  const current = stack.at(-2);
4284
4380
  const input = stack.at(-1);
@@ -4299,11 +4395,20 @@ var Run = class Run {
4299
4395
  break;
4300
4396
  case 19:
4301
4397
  case 20:
4302
- case 21:
4303
- result = smallArithmetic(ins.op, smallAt(stack.at(-2)), smallAt(stack.at(-1)));
4398
+ case 21: {
4399
+ const left = decimalAt(stack.at(-2));
4400
+ const right = decimalAt(stack.at(-1));
4401
+ result = left && right ? smallArithmetic(ins.op, smallCoefficient(left), smallExponent(left), smallCoefficient(right), smallExponent(right)) : void 0;
4304
4402
  if (result) cost = numberCharge(ins.rate, result);
4403
+ break;
4404
+ }
4405
+ }
4406
+ if (!cost || fuel + clause + cost.fuel > fuelLimit || alloc + cost.alloc > allocLimit) break;
4407
+ if (clause !== 0) {
4408
+ frame.clauseCharge = false;
4409
+ fuel += clause;
4410
+ clause = 0;
4305
4411
  }
4306
- if (!cost || fuel + cost.fuel > fuelLimit || alloc + cost.alloc > allocLimit) break;
4307
4412
  fuel += cost.fuel;
4308
4413
  alloc += cost.alloc;
4309
4414
  const [a, b] = ins.operands;
@@ -4349,10 +4454,16 @@ var Run = class Run {
4349
4454
  case 44:
4350
4455
  stack[stack.length - 1] = stack.at(-1).get(a);
4351
4456
  break;
4457
+ case 63:
4458
+ stack.pop();
4459
+ stack[stack.length - 1] = this.m.result;
4460
+ break;
4352
4461
  case 89:
4462
+ case 91:
4353
4463
  case 97:
4354
4464
  frame.pc = pc;
4355
- if (opcode === 89) {
4465
+ if (opcode === 91) this.fastCallHandler(code, a, b);
4466
+ else if (opcode === 89) {
4356
4467
  const body = code.unit.bodies[a];
4357
4468
  const args = stack.slice(stack.length - b);
4358
4469
  this.push(code, body, this.fillDefaults(code, body, args), null);
@@ -4368,6 +4479,7 @@ var Run = class Run {
4368
4479
  ({locals, stack, code} = frame);
4369
4480
  instructions = code.unit.code;
4370
4481
  pc = frame.pc;
4482
+ clause = frame.clauseCharge ? clauseFuel : 0;
4371
4483
  continue;
4372
4484
  default:
4373
4485
  stack.pop();
@@ -4380,6 +4492,39 @@ var Run = class Run {
4380
4492
  this.alloc = alloc;
4381
4493
  }
4382
4494
  /**
4495
+ * `fastSteps`' charge for writing a key its Map already has, with the new
4496
+ * Map version left as the measured result; or nothing, for `step`. The
4497
+ * entry count doesn't change, so the result's charge is the Map's.
4498
+ */
4499
+ fastSetKeyCharge(ins, stack) {
4500
+ const receiver = stack.at(-2);
4501
+ const input = stack.at(-1);
4502
+ const key = ins.operands[0];
4503
+ if (!isValue(receiver) || !isValue(input) || receiver.kind !== "map" || !receiver.hasKey(key)) return;
4504
+ const m = this.m;
4505
+ resetMeasured(m);
4506
+ m.input = input;
4507
+ m.result = receiver;
4508
+ const cost = charge(ins.rate, m, this.instructionCharge);
4509
+ m.result = setKey(receiver, key, input);
4510
+ return cost;
4511
+ }
4512
+ /** `fastSteps`' charge for calling the unit's own Handler, whose first clause takes the arguments. */
4513
+ fastCallHandlerCharge(ins, code) {
4514
+ return code.clauses.get(ins.operands[0])?.[0]?.params.length === ins.operands[1] && !this.callWouldExceedDepth() ? fixedCharges[CALL] : void 0;
4515
+ }
4516
+ fastCallHandler(code, name, n) {
4517
+ const stack = this.frame.stack;
4518
+ const args = stack.slice(stack.length - n);
4519
+ drop(stack, n);
4520
+ this.dispatch({
4521
+ clauses: code.clauses.get(name),
4522
+ code,
4523
+ next: 0,
4524
+ args
4525
+ });
4526
+ }
4527
+ /**
4383
4528
  * Run instructions, fast and general, while they spend less than `room`
4384
4529
  * Fuel and the Group has nothing to do between them: none writes a record
4385
4530
  * or ends, suspends or cancels the Run. Returns whether any took the
@@ -4531,7 +4676,7 @@ var Run = class Run {
4531
4676
  this.abandoning = own === void 0 ? [] : [own];
4532
4677
  }
4533
4678
  const value = this.settled(s.k === "ask" ? s.call : null, r);
4534
- if (s.k !== "wait") frame.stack.push(value);
4679
+ if (s.k !== "wait" && frame.code.unit.code[frame.pc].opcode !== 136) frame.stack.push(value);
4535
4680
  frame.pc++;
4536
4681
  }
4537
4682
  settled(call, r) {
@@ -5527,6 +5672,21 @@ var Run = class Run {
5527
5672
  return this.frame.stack.slice(this.frame.stack.length - n);
5528
5673
  }
5529
5674
  /**
5675
+ * `wait q` in a Musical Unit (chapter 5): `wait 0 bars` goes straight on;
5676
+ * any other count calls the Group's musical clock with `q`, as an
5677
+ * `ask … and wait` would, or raises `no musical time` without one.
5678
+ */
5679
+ musicalWait(count, rate, frame) {
5680
+ if (count === 0n) {
5681
+ this.pay(rate);
5682
+ this.pop();
5683
+ next(frame);
5684
+ return;
5685
+ }
5686
+ if (!this.host?.grants.has("musical-clock") || this.host.isUnbound?.("musical-clock")) throw new ScriptError$1("no musical time");
5687
+ this.capability(MUSICAL_CLOCK, "wait", [this.peek()], CAPABILITY);
5688
+ }
5689
+ /**
5530
5690
  * A Capability call (chapter 9): the arguments checked against their
5531
5691
  * Shapes, uncharged; the declared cost; the Host function, which may
5532
5692
  * `Charge` more while it starts; then an immediate call's result checked
@@ -5697,8 +5857,9 @@ var Run = class Run {
5697
5857
  charged
5698
5858
  });
5699
5859
  callSites.get(ctx).charged = charged;
5700
- const ms = op.maxPendingMs ?? this.limits.maxWaitMs;
5860
+ const ms = grantName === "musical-clock" ? null : op.maxPendingMs ?? this.limits.maxWaitMs;
5701
5861
  if (member) {
5862
+ const memberMs = ms ?? this.limits.maxWaitMs;
5702
5863
  const m = {
5703
5864
  site: {
5704
5865
  frame: this.frame,
@@ -5707,8 +5868,8 @@ var Run = class Run {
5707
5868
  id,
5708
5869
  call: ctx,
5709
5870
  abort,
5710
- ms,
5711
- at: this.host.now + BigInt(ms) * 1000n
5871
+ ms: memberMs,
5872
+ at: this.host.now + BigInt(memberMs) * 1000n
5712
5873
  };
5713
5874
  waitOrders.set(m, this.host.waitOrder?.() ?? 0);
5714
5875
  m.order = this.host.timerOrder?.();
@@ -5853,7 +6014,9 @@ var Run = class Run {
5853
6014
  case 49:
5854
6015
  case 50: return true;
5855
6016
  case 44:
5856
- case 45: return this.peek().kind === "object" && (ins.opcode === 44 ? ins.operands[0] !== "id" : this.peek(1).asText() !== "id");
6017
+ case 45:
6018
+ case 46:
6019
+ case 47: return this.peek().kind === "object" && (ins.opcode === 44 || ins.opcode === 46 ? ins.operands[0] !== "id" : this.peek(1).asText() !== "id");
5857
6020
  default: return false;
5858
6021
  }
5859
6022
  }
@@ -5993,6 +6156,12 @@ var Run = class Run {
5993
6156
  const computed = ins.opcode === 47;
5994
6157
  const key = computed ? keyText(this.peek(1)) : a;
5995
6158
  const receiver = this.peek();
6159
+ if (receiver.kind === "object") {
6160
+ m.result = this.getProperty(receiver, key, rate);
6161
+ drop(frame.stack, computed ? 2 : 1);
6162
+ frame.stack.push(m.result);
6163
+ return next(frame);
6164
+ }
5996
6165
  m.result = receiver.kind === "nothing" ? receiver : getKey(receiver, key);
5997
6166
  return this.replace(computed ? 2 : 1, rate);
5998
6167
  }
@@ -6360,6 +6529,8 @@ var Run = class Run {
6360
6529
  return next(frame);
6361
6530
  }
6362
6531
  case 136: {
6532
+ const count = musicalCount(this.peek());
6533
+ if (count !== void 0) return this.musicalWait(count, rate, frame);
6363
6534
  const us = waitUs(this.peek());
6364
6535
  this.checkDeadline();
6365
6536
  this.checkScopeBoundary();
@@ -6404,6 +6575,7 @@ var Run = class Run {
6404
6575
  const x = items[i++];
6405
6576
  if (isValue(x)) {
6406
6577
  if (x.kind !== "object") throw wrongKind("object", x);
6578
+ if (x.asObjectRef()?.kind === "peer") throw new ScriptError$1("out of domain", [["function", text("wait for")], ["value", x]]);
6407
6579
  from = x;
6408
6580
  } else if (x.k === "receiver") from = x.name;
6409
6581
  else throw new Error("A from expression must produce a receiver or Value");
@@ -6495,6 +6667,24 @@ var Run = class Run {
6495
6667
  target = o;
6496
6668
  }
6497
6669
  const args = spread ?? this.frame.stack.slice(this.frame.stack.length - n - (up ? 0 : 1), up ? void 0 : -1);
6670
+ const waitsHere = ins.opcode !== 128 && ins.opcode !== 130 && ins.opcode !== 132 && ins.opcode !== 134;
6671
+ if (typeof target === "object" && target?.handle.kind.name === "peer") {
6672
+ const peer = target.handle.value;
6673
+ const opName = waitsHere ? PEER_CALL : PEER_POST;
6674
+ const grantName = [...this.host.grants].find(([, g]) => g.capability.name === "peer")?.[0];
6675
+ if (grantName === void 0 || !this.host.grants.get(grantName).ops.has(opName)) throw new ScriptError$1("out of domain", [["function", text("send")], ["value", peer]]);
6676
+ const opArgs = [
6677
+ peer,
6678
+ text(message),
6679
+ listValues(args)
6680
+ ];
6681
+ drop(frame.stack, spread ? 3 : n + 1 + (named ? 1 : 0));
6682
+ frame.stack.push(...opArgs);
6683
+ this.capability(grantName, opName, opArgs, CAPABILITY, join);
6684
+ if (waitsHere && !join) return;
6685
+ drop(frame.stack, opArgs.length);
6686
+ return next(frame);
6687
+ }
6498
6688
  m.inputSize = partSize("message", 0, args.reduce((sum, v) => sum + sizeOf(v), 0));
6499
6689
  const waits = ins.opcode !== 128 && ins.opcode !== 130 && ins.opcode !== 132 && ins.opcode !== 134;
6500
6690
  if (waits) {
@@ -6511,7 +6701,8 @@ var Run = class Run {
6511
6701
  kind: "unhandled",
6512
6702
  message,
6513
6703
  args,
6514
- target: object ? object.handle.value : null
6704
+ target: object ? object.handle.value : null,
6705
+ ...up ? { up: true } : {}
6515
6706
  });
6516
6707
  if (waits) throw new ScriptError$1("send failed", [["reason", text("unhandled")]], true);
6517
6708
  return next(frame);
@@ -6701,6 +6892,7 @@ var Run = class Run {
6701
6892
  case 98: {
6702
6893
  if (this.frames.length === 1 && !Run.more(frame.dispatch)) this.checkState();
6703
6894
  this.pay(rate);
6895
+ if (this.frames.length === 1 && !this.viaFallback) this.mismatches.push(this.mismatchOf(frame));
6704
6896
  const d = this.frames.pop().dispatch;
6705
6897
  if (this.dispatch(d)) return;
6706
6898
  if (!this.frames.length) {
@@ -7055,7 +7247,9 @@ const loadOrReject = (name, load) => {
7055
7247
  /**
7056
7248
  * Compile a Library, once per process for each code identity. `imports` holds
7057
7249
  * every Library its `use` lines name, other than the stdlib's, which are
7058
- * always there. Throws LoadError.
7250
+ * always there. `declarations` holds the Operations of every Capability its
7251
+ * code calls, built with `operationDeclarations`; without them each `ask` or
7252
+ * `tell` fails with `unknown operation`. Throws LoadError.
7059
7253
  */
7060
7254
  const compileLibrary = (src, imports = [], declarations = {}, options = {}) => build(src, imports, false, declarations, options.atCaller);
7061
7255
  const stdlib = /* @__PURE__ */ new Map();
@@ -9802,7 +9996,7 @@ var RunWriter = class {
9802
9996
  let after = 0n;
9803
9997
  let branch = 0;
9804
9998
  if (block) after = microsOf(s.deadline.after);
9805
- else if (s.k === "ask") after = BigInt(s.ms) * 1000n;
9999
+ else if (s.k === "ask") after = BigInt(s.ms ?? 0) * 1000n;
9806
10000
  else if (s.k === "send" || s.k === "call-value") after = BigInt(r.limits.maxWaitMs) * 1000n;
9807
10001
  else if (s.k === "wait-for" && earliest?.action.k === "event") branch = earliest.action.branch;
9808
10002
  const fields = this.waitFields(running, s);
@@ -10377,10 +10571,17 @@ const runFromRecord = (rec, ctx) => {
10377
10571
  deadline: block
10378
10572
  } : x;
10379
10573
  switch (at) {
10380
- case "wait": return withBlock({
10381
- k: "wait",
10382
- us: 0n
10383
- });
10574
+ case "wait":
10575
+ if (w.grant === "musical-clock" && w.call !== void 0) return withBlock({
10576
+ k: "ask",
10577
+ call: ctx.call(w.call),
10578
+ abort: new AbortController(),
10579
+ ms: null
10580
+ });
10581
+ return withBlock({
10582
+ k: "wait",
10583
+ us: 0n
10584
+ });
10384
10585
  case "ask-wait": {
10385
10586
  const call = w.call === void 0 ? ctx.invalid() : ctx.call(w.call);
10386
10587
  return withBlock({
@@ -10768,6 +10969,7 @@ const inputRecord = (action, delivery, ref) => {
10768
10969
  delivery: deliveryNumber(action.id)
10769
10970
  };
10770
10971
  case "refusal": throw new Error("A save never holds a queued refusal");
10972
+ case "record": throw new Error("A save never holds a queued record");
10771
10973
  }
10772
10974
  };
10773
10975
  const markOf = (r) => r.veto ? {
@@ -10892,6 +11094,7 @@ const nextRandom = (state, n) => {
10892
11094
  };
10893
11095
  //#endregion
10894
11096
  //#region src/group.ts
11097
+ const CAPABILITY_RATE = rateOf("capability");
10895
11098
  const compiledScripts = /* @__PURE__ */ new Map();
10896
11099
  const faultNames = {
10897
11100
  cleanupBudget: "cleanup",
@@ -10914,7 +11117,7 @@ const overridable = /* @__PURE__ */ new Set([
10914
11117
  "maxJoin"
10915
11118
  ]);
10916
11119
  const sameClause = (a, b) => a.run.fallback === b.run.fallback && (a.run.fallback || a.delivery.message === b.delivery.message) && a.run.clauseNumber === b.run.clauseNumber;
10917
- const declarationsOf = (grants) => Object.fromEntries([...grants].map(([name, grant]) => [name, Object.fromEntries([...grant.ops].map((op) => {
11120
+ const declarationsOf = (grants) => Object.fromEntries([...grants].filter(([name]) => name !== MUSICAL_CLOCK).map(([name, grant]) => [name, Object.fromEntries([...grant.ops].map((op) => {
10918
11121
  const decl = grant.capability.operations.get(op);
10919
11122
  return [op, {
10920
11123
  mode: decl.mode,
@@ -10932,6 +11135,10 @@ const keepOperations = (grant, names) => {
10932
11135
  kept.add(op.scope.abandon);
10933
11136
  }
10934
11137
  }
11138
+ if (grant.capability.name === "peer") {
11139
+ const also = [...kept.has("reach") || kept.has("expose") ? ["post", "call"] : [], ...kept.has("expose") ? ["caller"] : []];
11140
+ for (const name of also) if (grant.ops.has(name)) kept.add(name);
11141
+ }
10935
11142
  return {
10936
11143
  ...grant,
10937
11144
  ops: kept
@@ -11065,6 +11272,8 @@ var TsGroup = class TsGroup {
11065
11272
  saves = 0;
11066
11273
  lastClock = null;
11067
11274
  randomState = seedState(0n);
11275
+ /** The musical clock's Grant, which every Script holds (chapter 9). */
11276
+ musicalClock;
11068
11277
  pumping = false;
11069
11278
  combining = false;
11070
11279
  combinedAdmission = false;
@@ -11395,6 +11604,7 @@ var TsGroup = class TsGroup {
11395
11604
  const group = new TsGroup({
11396
11605
  name: o.name,
11397
11606
  onReady: o.onReady,
11607
+ ...o.musicalClock ? { musicalClock: o.musicalClock } : {},
11398
11608
  trace: o.trace ? (line) => {
11399
11609
  if (emitting) o.trace?.(line);
11400
11610
  } : void 0
@@ -11438,12 +11648,13 @@ var TsGroup = class TsGroup {
11438
11648
  const grants = Object.create(null);
11439
11649
  const revoked = /* @__PURE__ */ new Set();
11440
11650
  const grantNames = /* @__PURE__ */ new Set();
11651
+ let musicalClock;
11441
11652
  for (const grant of script.grants) {
11442
11653
  if (grantNames.has(grant.name)) invalidSave();
11443
11654
  grantNames.add(grant.name);
11444
11655
  const declared = operationsOf(grant.declarations);
11445
11656
  if (declared.capability !== grant.capability || grant.operations.some((op) => !declared.operations.has(op.name))) invalidSave();
11446
- const offered = o.grants(script.name, grant.name);
11657
+ const offered = grant.name === "musical-clock" ? group.musicalClock : o.grants(script.name, grant.name);
11447
11658
  const rebound = offered ? keepOperations(offered, new Set(grant.operations.map((op) => op.name))) : void 0;
11448
11659
  const placeholder = {
11449
11660
  binding: void 0,
@@ -11460,7 +11671,8 @@ var TsGroup = class TsGroup {
11460
11671
  revoked.add(grant.name);
11461
11672
  unbound.push(`${script.name}.${grant.name}`);
11462
11673
  } else if (canonicalJSON(grantData(rebound)) !== grant.declarations) wholeGroup = true;
11463
- grants[grant.name] = rebound ?? placeholder;
11674
+ if (grant.name === "musical-clock") musicalClock = rebound ?? placeholder;
11675
+ else grants[grant.name] = rebound ?? placeholder;
11464
11676
  }
11465
11677
  if (loadFailure) continue;
11466
11678
  try {
@@ -11473,6 +11685,7 @@ var TsGroup = class TsGroup {
11473
11685
  objects: Object.fromEntries(script.objects.map((x) => [x.name, (x.object === void 0 ? invalidSave() : objects[x.object]).handle]))
11474
11686
  });
11475
11687
  const state = group.scripts.at(-1);
11688
+ if (musicalClock) state.grants = new Map(state.grants).set(MUSICAL_CLOCK, musicalClock);
11476
11689
  for (const source of sources.slice(1)) group.applyExtension(state, source, void 0, false);
11477
11690
  if (state.units.length !== identities.length || state.units.some((unit, i) => unit.identity !== identities[i])) changed.add(script.name);
11478
11691
  state.revoked = revoked;
@@ -11777,11 +11990,10 @@ var TsGroup = class TsGroup {
11777
11990
  const operation = operations.get(i) ?? invalidSave();
11778
11991
  if (c.script !== s.name) invalidSave();
11779
11992
  const op = (s.grants.get(c.grant) ?? invalidSave()).capability.operations.get(operation) ?? invalidSave();
11780
- const ins = ([...s.loaded.units].find((u) => u.name === c.atUnit) ?? this.libraryCode(s, c.atUnit))?.unit.code[c.atPc];
11781
11993
  ctx = {
11782
11994
  id: c.id,
11783
11995
  op,
11784
- rate: ins?.rate ?? -1,
11996
+ rate: CAPABILITY_RATE,
11785
11997
  named: [["capability", text(c.grant)], ["operation", text(operation)]],
11786
11998
  declared: op.cost.fuel,
11787
11999
  opName: `${c.grant}.${operation}`,
@@ -12081,10 +12293,15 @@ var TsGroup = class TsGroup {
12081
12293
  else {
12082
12294
  const id = x.pendingId ?? invalidSave();
12083
12295
  const ms = sus.k === "ask" ? sus.ms : running.run.limits.maxWaitMs;
12296
+ if (ms === null && !p.block) {
12297
+ if (p.deadline !== void 0) invalidSave();
12298
+ this.waits.add(id, s, running);
12299
+ continue;
12300
+ }
12084
12301
  const timer = this.waits.timer(p.deadline ?? invalidSave(), {
12085
12302
  k: "call",
12086
12303
  id,
12087
- ms,
12304
+ ms: ms ?? 0,
12088
12305
  ...sus.k === "ask" ? { abort: sus.abort } : {},
12089
12306
  ...p.block ? { deadline: sus.deadline?.after ?? msOf(p.after) } : {}
12090
12307
  }, running);
@@ -12269,10 +12486,6 @@ var TsGroup = class TsGroup {
12269
12486
  }
12270
12487
  return known;
12271
12488
  }
12272
- /** A Library's code a Script imports, by its unit name. */
12273
- libraryCode(s, name) {
12274
- for (const code of this.knownCode()) if (code.name === name && s.loaded.units.length >= 0) return code;
12275
- }
12276
12489
  discardedDecisions = [];
12277
12490
  unsettled = /* @__PURE__ */ new Set();
12278
12491
  restored = false;
@@ -12566,12 +12779,13 @@ var TsGroup = class TsGroup {
12566
12779
  }
12567
12780
  applyInput(action) {
12568
12781
  switch (action.k) {
12782
+ case "record": break;
12569
12783
  case "refusal":
12570
12784
  this.trace?.(recordLine("refused", [], [["code", JSON.stringify(action.code)]]));
12571
12785
  break;
12572
12786
  case "revoke": {
12573
12787
  const s = this.scripts.find((s) => s.name === action.name);
12574
- if (s.grants.has(action.grant) && !s.revoked.has(action.grant)) {
12788
+ if (action.grant !== "musical-clock" && s.grants.has(action.grant) && !s.revoked.has(action.grant)) {
12575
12789
  s.revoked.add(action.grant);
12576
12790
  this.releaseGrant(s, action.grant, "revoke");
12577
12791
  }
@@ -12882,6 +13096,10 @@ var TsGroup = class TsGroup {
12882
13096
  if (options.seed < 0n || options.seed > 18446744073709551615n) throw new HostError("invalid value", "A seed is a whole number 0 to 2^64 - 1");
12883
13097
  this.randomState = seedState(options.seed);
12884
13098
  }
13099
+ if (options.musicalClock !== void 0) {
13100
+ if (!isMusicalClock(options.musicalClock)) throw new HostError("invalid value", "A musical clock comes from musicalClockCapability");
13101
+ this.musicalClock = options.musicalClock.grant("all", void 0);
13102
+ }
12885
13103
  this.trace = options.trace ? (line) => {
12886
13104
  if (this.drainingTrace) this.drainingTrace.push(line);
12887
13105
  else options.trace(line);
@@ -12953,7 +13171,7 @@ var TsGroup = class TsGroup {
12953
13171
  }
12954
13172
  scriptGrants(name) {
12955
13173
  this.worker();
12956
- return Object.fromEntries([...this.scripts.find((s) => s.name === name).grants].sort(([a], [b]) => compareText(a, b)).map(([name, grant]) => [name, [...grant.ops].sort(compareText)]));
13174
+ return Object.fromEntries([...this.scripts.find((s) => s.name === name).grants].filter(([name]) => name !== MUSICAL_CLOCK).sort(([a], [b]) => compareText(a, b)).map(([name, grant]) => [name, [...grant.ops].sort(compareText)]));
12957
13175
  }
12958
13176
  /** Worker. Compiles, checks and loads a Script, or throws LoadError. */
12959
13177
  load(o) {
@@ -12964,6 +13182,8 @@ var TsGroup = class TsGroup {
12964
13182
  if (owner?.owner) throw new HostError("invalid value", `${owner.handle.value} already has an Owning Script, ${owner.owner}`);
12965
13183
  for (const object of Object.values(o.objects ?? {})) this.held(object);
12966
13184
  const grants = new Map(Object.entries(o.grants ?? {}));
13185
+ if (grants.has("musical-clock")) throw new HostError("invalid value", `${MUSICAL_CLOCK} is the Group's own Grant name`);
13186
+ if ([...grants.values()].filter((g) => g.capability.name === "peer").length > 1) throw new HostError("invalid value", `Script ${o.name} has more than one peer Grant`);
12967
13187
  const p = prepare("script", o.name, o.source, this.libraries, objects, declarationsOf(grants), void 0, propertyChecks(o.objects ?? {}, o.owner));
12968
13188
  this.trace?.(recordLine("load", [o.name], [["identity", p.identity]], true));
12969
13189
  const limits = {
@@ -12976,6 +13196,7 @@ var TsGroup = class TsGroup {
12976
13196
  const bound = keepOperations(grant, used?.get(name) ?? (used ? /* @__PURE__ */ new Set() : grant.ops));
12977
13197
  return used && bound.ops.size === 0 ? [] : [[name, bound]];
12978
13198
  }));
13199
+ if (this.musicalClock) kept.set(MUSICAL_CLOCK, this.musicalClock);
12979
13200
  const handle = new TsScript(this.channel, o.name);
12980
13201
  if (owner) owner.owner = o.name;
12981
13202
  this.scripts.push({
@@ -13106,6 +13327,7 @@ var TsGroup = class TsGroup {
13106
13327
  const current = {
13107
13328
  kind: binding.kind,
13108
13329
  contract: binding.contract,
13330
+ ...binding.shape ? { shape: true } : {},
13109
13331
  importedFrom: binding.kind === "script variable" ? void 0 : binding.importedFrom ?? {
13110
13332
  library: key,
13111
13333
  name: binding.name
@@ -13246,11 +13468,13 @@ var TsGroup = class TsGroup {
13246
13468
  this.libraries.set(l.name, l);
13247
13469
  }
13248
13470
  /** Worker. Prepare every dependent before changing the Group. */
13249
- replaceLibrary(l, carry) {
13471
+ replaceLibrary(l, carry, o) {
13472
+ const keepMailbox = !!o?.keepMailbox;
13250
13473
  this.worker();
13251
13474
  this.requireKnownEffects();
13252
13475
  this.trace?.(recordLine("replace-library", [l.name], [
13253
13476
  ["carry", carry === "carry variables" ? "yes" : "no"],
13477
+ ["mailbox", keepMailbox ? "keep" : null],
13254
13478
  ["source", displayText(l.source)],
13255
13479
  ["identity", identityOf(l)]
13256
13480
  ], true));
@@ -13275,12 +13499,12 @@ var TsGroup = class TsGroup {
13275
13499
  affected.add(l.name);
13276
13500
  const replacements = this.scripts.filter((s) => s.units.some((u) => u.imports.some((i) => affected.has(i.name)))).map((s) => ({
13277
13501
  s,
13278
- ...this.replacement(s, s.units[0].source, carry, libraries, s.units.slice(1).map((u) => u.source))
13502
+ ...this.replacement(s, s.units[0].source, carry, libraries, s.units.slice(1).map((u) => u.source), keepMailbox)
13279
13503
  }));
13280
13504
  this.discardReason = "library replacement";
13281
13505
  let reports;
13282
13506
  try {
13283
- reports = this.replaceScripts(replacements);
13507
+ reports = this.replaceScripts(replacements, keepMailbox);
13284
13508
  } finally {
13285
13509
  this.discardReason = "stop";
13286
13510
  }
@@ -13361,7 +13585,10 @@ var TsGroup = class TsGroup {
13361
13585
  at: named.owner
13362
13586
  };
13363
13587
  })() : this.route(to);
13364
- if (!r) return null;
13588
+ if (!r) {
13589
+ this.unhandledSend(message, args, to);
13590
+ return null;
13591
+ }
13365
13592
  this.enqueue(r.s, to, {
13366
13593
  id: null,
13367
13594
  from: reply ?? run.id,
@@ -13381,7 +13608,10 @@ var TsGroup = class TsGroup {
13381
13608
  },
13382
13609
  sendUp: (message, args, reply) => {
13383
13610
  const r = this.route(s.owner?.parent ?? null);
13384
- if (!r) return null;
13611
+ if (!r) {
13612
+ this.unhandledSend(message, args, s.owner);
13613
+ return null;
13614
+ }
13385
13615
  this.enqueue(r.s, r.s.name, {
13386
13616
  id: null,
13387
13617
  from: reply ?? run.id,
@@ -13514,7 +13744,7 @@ var TsGroup = class TsGroup {
13514
13744
  */
13515
13745
  markWait(running, sus, now) {
13516
13746
  const last = lastWaits.get(running);
13517
- const suspendedAt = sus.k === "wait-for" && sus.any ? "wait-for-any" : suspendReasons[sus.k];
13747
+ const suspendedAt = suspendReason(sus);
13518
13748
  const block = sus.deadline;
13519
13749
  if (sus.k === "join") {
13520
13750
  if (block) waitOrders.set(running, ++this.waitOrder);
@@ -13533,7 +13763,7 @@ var TsGroup = class TsGroup {
13533
13763
  return;
13534
13764
  }
13535
13765
  waitOrders.set(running, ++this.waitOrder);
13536
- const own = sus.k === "ask" ? BigInt(sus.ms) * 1000n : sus.k === "send" || sus.k === "call-value" ? BigInt(running.run.limits.maxWaitMs) * 1000n : null;
13766
+ const own = sus.k === "ask" ? sus.ms === null ? null : BigInt(sus.ms) * 1000n : sus.k === "send" || sus.k === "call-value" ? BigInt(running.run.limits.maxWaitMs) * 1000n : null;
13537
13767
  const bounded = !!block && (sus.k === "wait" ? block.at <= now + sus.us : sus.k === "wait-for" ? true : own !== null && block.at <= now + own);
13538
13768
  const [grant, operation] = sus.k === "ask" ? sus.call.opName.split(".") : ["", ""];
13539
13769
  lastWaits.set(running, {
@@ -13609,12 +13839,16 @@ var TsGroup = class TsGroup {
13609
13839
  }
13610
13840
  const id = sus.k === "ask" ? sus.call.id : sus.id;
13611
13841
  const ms = sus.k === "ask" ? sus.ms : running.run.limits.maxWaitMs;
13612
- const own = now + BigInt(ms) * 1000n;
13842
+ const own = ms === null ? null : now + BigInt(ms) * 1000n;
13613
13843
  const bounded = ends(own);
13844
+ if (own === null && !bounded) {
13845
+ this.waits.add(id, s, running);
13846
+ return null;
13847
+ }
13614
13848
  const timer = this.waits.timer(bounded ? block.at : own, {
13615
13849
  k: "call",
13616
13850
  id,
13617
- ms,
13851
+ ms: ms ?? 0,
13618
13852
  ...sus.k === "ask" ? { abort: sus.abort } : {},
13619
13853
  ...bounded ? { deadline: block.after } : {}
13620
13854
  }, running);
@@ -13941,11 +14175,23 @@ var TsGroup = class TsGroup {
13941
14175
  };
13942
14176
  }
13943
14177
  /** Makes a handle for a Host-owned thing, the first time it crosses in. */
13944
- object(kind, id, native) {
14178
+ object(kind, id, native, o) {
13945
14179
  const key = `${kind.name}\u0000${id}`;
13946
14180
  if (this.objects.has(key)) throw new HostError("duplicate object id", `The Group already has a ${kind.name} ${id}`);
14181
+ const up = o?.parent ? this.held(o.parent) : null;
14182
+ if (up?.disposed) throw new HostError("invalid value", `${up.handle.value} is disposed`);
13947
14183
  const state = makeObject(kind, id, native);
14184
+ state.parent = up;
13948
14185
  this.objects.set(key, state);
14186
+ if (up && this.trace) {
14187
+ const line = recordLine("object", [], [["object", traceValue(state.handle.value)], ["parent", traceValue(up.handle.value)]]);
14188
+ if (this.pumping) this.inputs.push({
14189
+ line,
14190
+ urgent: true,
14191
+ action: { k: "record" }
14192
+ });
14193
+ else this.trace(line);
14194
+ }
13949
14195
  return state.handle;
13950
14196
  }
13951
14197
  /** The handle with this Object Kind name and id, disposed or not, such as one Restore made. */
@@ -14006,6 +14252,16 @@ var TsGroup = class TsGroup {
14006
14252
  }
14007
14253
  return null;
14008
14254
  }
14255
+ unhandledSend(message, args, target) {
14256
+ this.drainReports.push({
14257
+ kind: "unhandled",
14258
+ message: {
14259
+ name: message,
14260
+ args
14261
+ },
14262
+ ...target ? { target: target.handle } : {}
14263
+ });
14264
+ }
14009
14265
  unhandled(delivery, reports, run) {
14010
14266
  this.trace?.(recordLine("unhandled", [delivery.id], [
14011
14267
  ["message", delivery.message],
@@ -14018,9 +14274,9 @@ var TsGroup = class TsGroup {
14018
14274
  message: delivery.message,
14019
14275
  args: delivery.args
14020
14276
  });
14021
- if (delivery.id) reports.push({
14277
+ reports.push({
14022
14278
  kind: "unhandled",
14023
- delivery: delivery.id,
14279
+ ...delivery.id ? { delivery: delivery.id } : {},
14024
14280
  message: {
14025
14281
  name: delivery.message,
14026
14282
  args: delivery.args
@@ -14042,7 +14298,7 @@ var TsGroup = class TsGroup {
14042
14298
  });
14043
14299
  if (delivery.request) {
14044
14300
  if (outcome.kind === "completed") delivery.request.resolve(outcome.result);
14045
- else delivery.request.reject(sendFailed(outcome.kind));
14301
+ else delivery.request.reject(sendFailed(outcome.kind, outcome.kind === "errored" ? outcome.error : null));
14046
14302
  }
14047
14303
  }
14048
14304
  deliveryLine(record, id, to, m, fn) {
@@ -14393,10 +14649,10 @@ var TsGroup = class TsGroup {
14393
14649
  ...start,
14394
14650
  ...stretch,
14395
14651
  ["state", String(this.persistentState(s))],
14396
- ["end", suspension.k === "wait-for" && suspension.any ? "wait-for-any" : suspendReasons[suspension.k]],
14652
+ ["end", suspendReason(suspension)],
14397
14653
  ["until", deadline === null || !isInstant(deadline) ? null : formatInstant(deadline)]
14398
14654
  ]));
14399
- observe(suspension.k === "wait-for" && suspension.any ? "wait-for-any" : suspendReasons[suspension.k], deadline ?? void 0);
14655
+ observe(suspendReason(suspension), deadline ?? void 0);
14400
14656
  this.seal(running.delivery, { verdict: "allowed" });
14401
14657
  run.openVerdict = false;
14402
14658
  return;
@@ -14533,10 +14789,11 @@ var TsGroup = class TsGroup {
14533
14789
  continue;
14534
14790
  }
14535
14791
  if (rec.kind === "unhandled") {
14792
+ const target = rec.up ? this.scripts.find((s) => s.name === run.script.name)?.owner?.handle.value ?? null : rec.target;
14536
14793
  this.trace?.(recordLine("unhandled", [], [
14537
14794
  ["message", rec.message ?? null],
14538
14795
  ["args", rec.args.length ? traceValue(listValues(rec.args)) : null],
14539
- ["target", rec.target ? traceValue(rec.target) : null]
14796
+ ["target", target ? traceValue(target) : null]
14540
14797
  ]));
14541
14798
  this.session?.runs({
14542
14799
  k: "unhandled",
@@ -14644,6 +14901,7 @@ var TsGroup = class TsGroup {
14644
14901
  ["status", text(outcome.effect.status)],
14645
14902
  ...outcome.effect.scope ? [["scope", text(outcome.effect.scope)]] : []
14646
14903
  ])) : null],
14904
+ ["mismatches", (outcome.kind === "unhandled" || fallback) && run.mismatches.length ? traceValue(mismatchesValue(run.mismatches)) : null],
14647
14905
  ["fuel", String(run.fuel)],
14648
14906
  ["alloc", String(run.alloc)]
14649
14907
  ]));
@@ -14760,7 +15018,7 @@ var TsGroup = class TsGroup {
14760
15018
  const until = this.waits.until(running, !!sus.deadline && sus.k !== "join");
14761
15019
  const calls = sus.k === "ask" ? [sus.call.id] : sus.k === "send" || sus.k === "call-value" ? [sus.id] : sus.k === "join" ? this.waits.pendingMembers(sus.members).map((m) => m.id) : [];
14762
15020
  return {
14763
- wait: sus.k === "wait-for" && sus.any ? "wait-for-any" : suspendReasons[sus.k],
15021
+ wait: suspendReason(sus),
14764
15022
  ...until === void 0 || !isInstant(until) ? {} : { until },
14765
15023
  ...calls.length ? { calls } : {}
14766
15024
  };
@@ -14850,6 +15108,7 @@ const suspendReasons = {
14850
15108
  join: "join-end",
14851
15109
  "wait-for": "wait-for"
14852
15110
  };
15111
+ const suspendReason = (s) => s.k === "wait-for" && s.any ? "wait-for-any" : s.k === "ask" && s.ms === null ? "wait" : suspendReasons[s.k];
14853
15112
  const hostError = (error) => {
14854
15113
  const message = error.get("message");
14855
15114
  const textMessage = message.kind === "text";
@@ -14986,8 +15245,80 @@ const messageFields = (m) => {
14986
15245
  ["limits", limits.length ? `{${limits.map(([k, v]) => `${k}: ${v}`).join(", ")}}` : null]
14987
15246
  ];
14988
15247
  };
14989
- const newGroup = (o) => new TsGroup(o);
15248
+ const fastStepsPrimer = `function weigh v
15249
+ if v > 2 then return v * 2
15250
+ return v
15251
+ end weigh
15252
+
15253
+ on tick state
15254
+ if state's x < 100 then
15255
+ put state's x + 1 into state's x
15256
+ end if
15257
+ return state
15258
+ end tick
15259
+
15260
+ on run n
15261
+ put {x: 0} into state
15262
+ put [] into items
15263
+ put "" into word
15264
+ put 0 into j
15265
+ repeat for each i in 1..n
15266
+ put tick(state) into state
15267
+ put i after items
15268
+ put "x" after word
15269
+ put weigh(i) into state's y
15270
+ put i - 1 into j
15271
+ put i = 2 into flag
15272
+ if flag then add 1 to j
15273
+ end repeat
15274
+ repeat for each v in items
15275
+ add weigh(v) * 3 to j
15276
+ end repeat
15277
+ add 0.5 to j
15278
+ put 9007199254740990 * 9007199254740990 into big
15279
+ return [state, word, j, big]
15280
+ end run`;
15281
+ let fastStepsPrimed = false;
15282
+ const onJavaScriptCore = typeof globalThis.process?.versions?.bun === "string" || typeof navigator === "object" && /AppleWebKit/.test(navigator.userAgent) && !/Chrome|Chromium|Edg\//.test(navigator.userAgent);
15283
+ const primeFastSteps = () => {
15284
+ if (fastStepsPrimed || !onJavaScriptCore) return;
15285
+ fastStepsPrimed = true;
15286
+ const group = new TsGroup({ name: "fast-steps-primer" });
15287
+ group.load({
15288
+ name: "primer",
15289
+ source: fastStepsPrimer
15290
+ });
15291
+ group.script("primer").deliver({
15292
+ args: [num(4)],
15293
+ name: "run"
15294
+ });
15295
+ for (let i = 0; i < 100 && group.pump(0n, {}).state !== "idle"; i++);
15296
+ };
15297
+ const newGroup = (o) => {
15298
+ primeFastSteps();
15299
+ return new TsGroup(o);
15300
+ };
14990
15301
  const messageSize = (d) => partSize("message", 0, d.args.reduce((sum, v) => sum + sizeOf(v), 0) + (d.fn ? sizeOf(d.fn) : 0));
14991
- const restore = (bytes, options) => TsGroup.restore(bytes, options);
15302
+ const restore = (bytes, options) => {
15303
+ primeFastSteps();
15304
+ return TsGroup.restore(bytes, options);
15305
+ };
15306
+ /**
15307
+ * A Run's `mismatches`, built only for the Trace and charged to no one
15308
+ * (ADR 0172): each skipped named clause's reason, and for a Clause Shape,
15309
+ * what `explain` gives for its argument.
15310
+ */
15311
+ const mismatchesValue = (mismatches) => listValues(mismatches.map((m) => {
15312
+ const entries = [["clause", num(m.clause)], ["reason", text(m.reason)]];
15313
+ if (m.reason === "shape") {
15314
+ entries.push(["argument", num(m.argument)]);
15315
+ const shape = m.shape && decodeShape(m.shape).shape;
15316
+ if (shape) {
15317
+ const { diags } = shapeDiagnostics(m.value, shape, false, 0);
15318
+ entries.push(["mismatches", listValues(diags.map(diagnosticRecord))]);
15319
+ }
15320
+ }
15321
+ return map(entries);
15322
+ }));
14992
15323
  //#endregion
14993
15324
  export { registeredStdlib as C, registerStdlib as S, stdlibSource as T, loadScript as _, recordLine as a, exportsOf as b, codeIdentity as c, Run as d, Script as f, deliver as g, defaultLimits as h, restore as i, compileLibrary as l, callFunction as m, TsScript as n, traceValue as o, UnitLoadError as p, newGroup as r, stateFingerprint$1 as s, TsGroup as t, replacementLibraries as u, LoweringError as v, stdlibNames as w, lowerTree as x, compileSource as y };