@northtalk/ts 0.6.0 → 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-C4ZiXVjv.d.ts → binary-value-M8v567iA.d.ts} +1 -1
  2. package/{checker-CUhn2XaM.js → checker-Coml0Tf9.js} +581 -71
  3. package/{core-egHbNmve.d.ts → core-D4qYURer.d.ts} +1 -1
  4. package/{debug--Of4MSLw.d.ts → debug-C_Ob5rkl.d.ts} +126 -9
  5. package/debug.d.ts +1 -1
  6. package/debug.js +1 -1
  7. package/{driver-BIm1mL77.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-DbDcopGM.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-BpzTo0k4.js → group-BqccKTWz.js} +367 -68
  15. package/{http-fetch-DFwVIOQg.js → http-fetch-DA-NbFIM.js} +2 -2
  16. package/http.d.ts +1 -1
  17. package/http.js +4 -4
  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-aCvN6y52.js → lean-BJmLobmd.js} +13 -8
  23. package/{lean-DiS9rUcn.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-DYq_YvaQ.d.ts → objects-DVlpWsi0.d.ts} +7 -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-8WCimMop.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-BQsO8aPV.d.ts → router-D0rf5SkW.d.ts} +2 -2
  43. package/session.d.ts +2 -2
  44. package/session.js +64 -16
  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 +13 -6
  55. package/wasm.js +45 -19
  56. package/encoding-RUuES_e4.js +0 -99
  57. package/manifest-mpivREn-.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) {
@@ -6702,6 +6892,7 @@ var Run = class Run {
6702
6892
  case 98: {
6703
6893
  if (this.frames.length === 1 && !Run.more(frame.dispatch)) this.checkState();
6704
6894
  this.pay(rate);
6895
+ if (this.frames.length === 1 && !this.viaFallback) this.mismatches.push(this.mismatchOf(frame));
6705
6896
  const d = this.frames.pop().dispatch;
6706
6897
  if (this.dispatch(d)) return;
6707
6898
  if (!this.frames.length) {
@@ -7056,7 +7247,9 @@ const loadOrReject = (name, load) => {
7056
7247
  /**
7057
7248
  * Compile a Library, once per process for each code identity. `imports` holds
7058
7249
  * every Library its `use` lines name, other than the stdlib's, which are
7059
- * 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.
7060
7253
  */
7061
7254
  const compileLibrary = (src, imports = [], declarations = {}, options = {}) => build(src, imports, false, declarations, options.atCaller);
7062
7255
  const stdlib = /* @__PURE__ */ new Map();
@@ -9803,7 +9996,7 @@ var RunWriter = class {
9803
9996
  let after = 0n;
9804
9997
  let branch = 0;
9805
9998
  if (block) after = microsOf(s.deadline.after);
9806
- else if (s.k === "ask") after = BigInt(s.ms) * 1000n;
9999
+ else if (s.k === "ask") after = BigInt(s.ms ?? 0) * 1000n;
9807
10000
  else if (s.k === "send" || s.k === "call-value") after = BigInt(r.limits.maxWaitMs) * 1000n;
9808
10001
  else if (s.k === "wait-for" && earliest?.action.k === "event") branch = earliest.action.branch;
9809
10002
  const fields = this.waitFields(running, s);
@@ -10378,10 +10571,17 @@ const runFromRecord = (rec, ctx) => {
10378
10571
  deadline: block
10379
10572
  } : x;
10380
10573
  switch (at) {
10381
- case "wait": return withBlock({
10382
- k: "wait",
10383
- us: 0n
10384
- });
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
+ });
10385
10585
  case "ask-wait": {
10386
10586
  const call = w.call === void 0 ? ctx.invalid() : ctx.call(w.call);
10387
10587
  return withBlock({
@@ -10894,6 +11094,7 @@ const nextRandom = (state, n) => {
10894
11094
  };
10895
11095
  //#endregion
10896
11096
  //#region src/group.ts
11097
+ const CAPABILITY_RATE = rateOf("capability");
10897
11098
  const compiledScripts = /* @__PURE__ */ new Map();
10898
11099
  const faultNames = {
10899
11100
  cleanupBudget: "cleanup",
@@ -10916,7 +11117,7 @@ const overridable = /* @__PURE__ */ new Set([
10916
11117
  "maxJoin"
10917
11118
  ]);
10918
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;
10919
- 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) => {
10920
11121
  const decl = grant.capability.operations.get(op);
10921
11122
  return [op, {
10922
11123
  mode: decl.mode,
@@ -10934,6 +11135,10 @@ const keepOperations = (grant, names) => {
10934
11135
  kept.add(op.scope.abandon);
10935
11136
  }
10936
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
+ }
10937
11142
  return {
10938
11143
  ...grant,
10939
11144
  ops: kept
@@ -11067,6 +11272,8 @@ var TsGroup = class TsGroup {
11067
11272
  saves = 0;
11068
11273
  lastClock = null;
11069
11274
  randomState = seedState(0n);
11275
+ /** The musical clock's Grant, which every Script holds (chapter 9). */
11276
+ musicalClock;
11070
11277
  pumping = false;
11071
11278
  combining = false;
11072
11279
  combinedAdmission = false;
@@ -11397,6 +11604,7 @@ var TsGroup = class TsGroup {
11397
11604
  const group = new TsGroup({
11398
11605
  name: o.name,
11399
11606
  onReady: o.onReady,
11607
+ ...o.musicalClock ? { musicalClock: o.musicalClock } : {},
11400
11608
  trace: o.trace ? (line) => {
11401
11609
  if (emitting) o.trace?.(line);
11402
11610
  } : void 0
@@ -11440,12 +11648,13 @@ var TsGroup = class TsGroup {
11440
11648
  const grants = Object.create(null);
11441
11649
  const revoked = /* @__PURE__ */ new Set();
11442
11650
  const grantNames = /* @__PURE__ */ new Set();
11651
+ let musicalClock;
11443
11652
  for (const grant of script.grants) {
11444
11653
  if (grantNames.has(grant.name)) invalidSave();
11445
11654
  grantNames.add(grant.name);
11446
11655
  const declared = operationsOf(grant.declarations);
11447
11656
  if (declared.capability !== grant.capability || grant.operations.some((op) => !declared.operations.has(op.name))) invalidSave();
11448
- const offered = o.grants(script.name, grant.name);
11657
+ const offered = grant.name === "musical-clock" ? group.musicalClock : o.grants(script.name, grant.name);
11449
11658
  const rebound = offered ? keepOperations(offered, new Set(grant.operations.map((op) => op.name))) : void 0;
11450
11659
  const placeholder = {
11451
11660
  binding: void 0,
@@ -11462,7 +11671,8 @@ var TsGroup = class TsGroup {
11462
11671
  revoked.add(grant.name);
11463
11672
  unbound.push(`${script.name}.${grant.name}`);
11464
11673
  } else if (canonicalJSON(grantData(rebound)) !== grant.declarations) wholeGroup = true;
11465
- grants[grant.name] = rebound ?? placeholder;
11674
+ if (grant.name === "musical-clock") musicalClock = rebound ?? placeholder;
11675
+ else grants[grant.name] = rebound ?? placeholder;
11466
11676
  }
11467
11677
  if (loadFailure) continue;
11468
11678
  try {
@@ -11475,6 +11685,7 @@ var TsGroup = class TsGroup {
11475
11685
  objects: Object.fromEntries(script.objects.map((x) => [x.name, (x.object === void 0 ? invalidSave() : objects[x.object]).handle]))
11476
11686
  });
11477
11687
  const state = group.scripts.at(-1);
11688
+ if (musicalClock) state.grants = new Map(state.grants).set(MUSICAL_CLOCK, musicalClock);
11478
11689
  for (const source of sources.slice(1)) group.applyExtension(state, source, void 0, false);
11479
11690
  if (state.units.length !== identities.length || state.units.some((unit, i) => unit.identity !== identities[i])) changed.add(script.name);
11480
11691
  state.revoked = revoked;
@@ -11779,11 +11990,10 @@ var TsGroup = class TsGroup {
11779
11990
  const operation = operations.get(i) ?? invalidSave();
11780
11991
  if (c.script !== s.name) invalidSave();
11781
11992
  const op = (s.grants.get(c.grant) ?? invalidSave()).capability.operations.get(operation) ?? invalidSave();
11782
- const ins = ([...s.loaded.units].find((u) => u.name === c.atUnit) ?? this.libraryCode(s, c.atUnit))?.unit.code[c.atPc];
11783
11993
  ctx = {
11784
11994
  id: c.id,
11785
11995
  op,
11786
- rate: ins?.rate ?? -1,
11996
+ rate: CAPABILITY_RATE,
11787
11997
  named: [["capability", text(c.grant)], ["operation", text(operation)]],
11788
11998
  declared: op.cost.fuel,
11789
11999
  opName: `${c.grant}.${operation}`,
@@ -12083,10 +12293,15 @@ var TsGroup = class TsGroup {
12083
12293
  else {
12084
12294
  const id = x.pendingId ?? invalidSave();
12085
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
+ }
12086
12301
  const timer = this.waits.timer(p.deadline ?? invalidSave(), {
12087
12302
  k: "call",
12088
12303
  id,
12089
- ms,
12304
+ ms: ms ?? 0,
12090
12305
  ...sus.k === "ask" ? { abort: sus.abort } : {},
12091
12306
  ...p.block ? { deadline: sus.deadline?.after ?? msOf(p.after) } : {}
12092
12307
  }, running);
@@ -12271,10 +12486,6 @@ var TsGroup = class TsGroup {
12271
12486
  }
12272
12487
  return known;
12273
12488
  }
12274
- /** A Library's code a Script imports, by its unit name. */
12275
- libraryCode(s, name) {
12276
- for (const code of this.knownCode()) if (code.name === name && s.loaded.units.length >= 0) return code;
12277
- }
12278
12489
  discardedDecisions = [];
12279
12490
  unsettled = /* @__PURE__ */ new Set();
12280
12491
  restored = false;
@@ -12574,7 +12785,7 @@ var TsGroup = class TsGroup {
12574
12785
  break;
12575
12786
  case "revoke": {
12576
12787
  const s = this.scripts.find((s) => s.name === action.name);
12577
- 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)) {
12578
12789
  s.revoked.add(action.grant);
12579
12790
  this.releaseGrant(s, action.grant, "revoke");
12580
12791
  }
@@ -12885,6 +13096,10 @@ var TsGroup = class TsGroup {
12885
13096
  if (options.seed < 0n || options.seed > 18446744073709551615n) throw new HostError("invalid value", "A seed is a whole number 0 to 2^64 - 1");
12886
13097
  this.randomState = seedState(options.seed);
12887
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
+ }
12888
13103
  this.trace = options.trace ? (line) => {
12889
13104
  if (this.drainingTrace) this.drainingTrace.push(line);
12890
13105
  else options.trace(line);
@@ -12956,7 +13171,7 @@ var TsGroup = class TsGroup {
12956
13171
  }
12957
13172
  scriptGrants(name) {
12958
13173
  this.worker();
12959
- 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)]));
12960
13175
  }
12961
13176
  /** Worker. Compiles, checks and loads a Script, or throws LoadError. */
12962
13177
  load(o) {
@@ -12967,6 +13182,8 @@ var TsGroup = class TsGroup {
12967
13182
  if (owner?.owner) throw new HostError("invalid value", `${owner.handle.value} already has an Owning Script, ${owner.owner}`);
12968
13183
  for (const object of Object.values(o.objects ?? {})) this.held(object);
12969
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`);
12970
13187
  const p = prepare("script", o.name, o.source, this.libraries, objects, declarationsOf(grants), void 0, propertyChecks(o.objects ?? {}, o.owner));
12971
13188
  this.trace?.(recordLine("load", [o.name], [["identity", p.identity]], true));
12972
13189
  const limits = {
@@ -12979,6 +13196,7 @@ var TsGroup = class TsGroup {
12979
13196
  const bound = keepOperations(grant, used?.get(name) ?? (used ? /* @__PURE__ */ new Set() : grant.ops));
12980
13197
  return used && bound.ops.size === 0 ? [] : [[name, bound]];
12981
13198
  }));
13199
+ if (this.musicalClock) kept.set(MUSICAL_CLOCK, this.musicalClock);
12982
13200
  const handle = new TsScript(this.channel, o.name);
12983
13201
  if (owner) owner.owner = o.name;
12984
13202
  this.scripts.push({
@@ -13109,6 +13327,7 @@ var TsGroup = class TsGroup {
13109
13327
  const current = {
13110
13328
  kind: binding.kind,
13111
13329
  contract: binding.contract,
13330
+ ...binding.shape ? { shape: true } : {},
13112
13331
  importedFrom: binding.kind === "script variable" ? void 0 : binding.importedFrom ?? {
13113
13332
  library: key,
13114
13333
  name: binding.name
@@ -13249,11 +13468,13 @@ var TsGroup = class TsGroup {
13249
13468
  this.libraries.set(l.name, l);
13250
13469
  }
13251
13470
  /** Worker. Prepare every dependent before changing the Group. */
13252
- replaceLibrary(l, carry) {
13471
+ replaceLibrary(l, carry, o) {
13472
+ const keepMailbox = !!o?.keepMailbox;
13253
13473
  this.worker();
13254
13474
  this.requireKnownEffects();
13255
13475
  this.trace?.(recordLine("replace-library", [l.name], [
13256
13476
  ["carry", carry === "carry variables" ? "yes" : "no"],
13477
+ ["mailbox", keepMailbox ? "keep" : null],
13257
13478
  ["source", displayText(l.source)],
13258
13479
  ["identity", identityOf(l)]
13259
13480
  ], true));
@@ -13278,12 +13499,12 @@ var TsGroup = class TsGroup {
13278
13499
  affected.add(l.name);
13279
13500
  const replacements = this.scripts.filter((s) => s.units.some((u) => u.imports.some((i) => affected.has(i.name)))).map((s) => ({
13280
13501
  s,
13281
- ...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)
13282
13503
  }));
13283
13504
  this.discardReason = "library replacement";
13284
13505
  let reports;
13285
13506
  try {
13286
- reports = this.replaceScripts(replacements);
13507
+ reports = this.replaceScripts(replacements, keepMailbox);
13287
13508
  } finally {
13288
13509
  this.discardReason = "stop";
13289
13510
  }
@@ -13523,7 +13744,7 @@ var TsGroup = class TsGroup {
13523
13744
  */
13524
13745
  markWait(running, sus, now) {
13525
13746
  const last = lastWaits.get(running);
13526
- const suspendedAt = sus.k === "wait-for" && sus.any ? "wait-for-any" : suspendReasons[sus.k];
13747
+ const suspendedAt = suspendReason(sus);
13527
13748
  const block = sus.deadline;
13528
13749
  if (sus.k === "join") {
13529
13750
  if (block) waitOrders.set(running, ++this.waitOrder);
@@ -13542,7 +13763,7 @@ var TsGroup = class TsGroup {
13542
13763
  return;
13543
13764
  }
13544
13765
  waitOrders.set(running, ++this.waitOrder);
13545
- 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;
13546
13767
  const bounded = !!block && (sus.k === "wait" ? block.at <= now + sus.us : sus.k === "wait-for" ? true : own !== null && block.at <= now + own);
13547
13768
  const [grant, operation] = sus.k === "ask" ? sus.call.opName.split(".") : ["", ""];
13548
13769
  lastWaits.set(running, {
@@ -13618,12 +13839,16 @@ var TsGroup = class TsGroup {
13618
13839
  }
13619
13840
  const id = sus.k === "ask" ? sus.call.id : sus.id;
13620
13841
  const ms = sus.k === "ask" ? sus.ms : running.run.limits.maxWaitMs;
13621
- const own = now + BigInt(ms) * 1000n;
13842
+ const own = ms === null ? null : now + BigInt(ms) * 1000n;
13622
13843
  const bounded = ends(own);
13844
+ if (own === null && !bounded) {
13845
+ this.waits.add(id, s, running);
13846
+ return null;
13847
+ }
13623
13848
  const timer = this.waits.timer(bounded ? block.at : own, {
13624
13849
  k: "call",
13625
13850
  id,
13626
- ms,
13851
+ ms: ms ?? 0,
13627
13852
  ...sus.k === "ask" ? { abort: sus.abort } : {},
13628
13853
  ...bounded ? { deadline: block.after } : {}
13629
13854
  }, running);
@@ -14073,7 +14298,7 @@ var TsGroup = class TsGroup {
14073
14298
  });
14074
14299
  if (delivery.request) {
14075
14300
  if (outcome.kind === "completed") delivery.request.resolve(outcome.result);
14076
- else delivery.request.reject(sendFailed(outcome.kind));
14301
+ else delivery.request.reject(sendFailed(outcome.kind, outcome.kind === "errored" ? outcome.error : null));
14077
14302
  }
14078
14303
  }
14079
14304
  deliveryLine(record, id, to, m, fn) {
@@ -14424,10 +14649,10 @@ var TsGroup = class TsGroup {
14424
14649
  ...start,
14425
14650
  ...stretch,
14426
14651
  ["state", String(this.persistentState(s))],
14427
- ["end", suspension.k === "wait-for" && suspension.any ? "wait-for-any" : suspendReasons[suspension.k]],
14652
+ ["end", suspendReason(suspension)],
14428
14653
  ["until", deadline === null || !isInstant(deadline) ? null : formatInstant(deadline)]
14429
14654
  ]));
14430
- observe(suspension.k === "wait-for" && suspension.any ? "wait-for-any" : suspendReasons[suspension.k], deadline ?? void 0);
14655
+ observe(suspendReason(suspension), deadline ?? void 0);
14431
14656
  this.seal(running.delivery, { verdict: "allowed" });
14432
14657
  run.openVerdict = false;
14433
14658
  return;
@@ -14676,6 +14901,7 @@ var TsGroup = class TsGroup {
14676
14901
  ["status", text(outcome.effect.status)],
14677
14902
  ...outcome.effect.scope ? [["scope", text(outcome.effect.scope)]] : []
14678
14903
  ])) : null],
14904
+ ["mismatches", (outcome.kind === "unhandled" || fallback) && run.mismatches.length ? traceValue(mismatchesValue(run.mismatches)) : null],
14679
14905
  ["fuel", String(run.fuel)],
14680
14906
  ["alloc", String(run.alloc)]
14681
14907
  ]));
@@ -14792,7 +15018,7 @@ var TsGroup = class TsGroup {
14792
15018
  const until = this.waits.until(running, !!sus.deadline && sus.k !== "join");
14793
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) : [];
14794
15020
  return {
14795
- wait: sus.k === "wait-for" && sus.any ? "wait-for-any" : suspendReasons[sus.k],
15021
+ wait: suspendReason(sus),
14796
15022
  ...until === void 0 || !isInstant(until) ? {} : { until },
14797
15023
  ...calls.length ? { calls } : {}
14798
15024
  };
@@ -14882,6 +15108,7 @@ const suspendReasons = {
14882
15108
  join: "join-end",
14883
15109
  "wait-for": "wait-for"
14884
15110
  };
15111
+ const suspendReason = (s) => s.k === "wait-for" && s.any ? "wait-for-any" : s.k === "ask" && s.ms === null ? "wait" : suspendReasons[s.k];
14885
15112
  const hostError = (error) => {
14886
15113
  const message = error.get("message");
14887
15114
  const textMessage = message.kind === "text";
@@ -15018,8 +15245,80 @@ const messageFields = (m) => {
15018
15245
  ["limits", limits.length ? `{${limits.map(([k, v]) => `${k}: ${v}`).join(", ")}}` : null]
15019
15246
  ];
15020
15247
  };
15021
- 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
+ };
15022
15301
  const messageSize = (d) => partSize("message", 0, d.args.reduce((sum, v) => sum + sizeOf(v), 0) + (d.fn ? sizeOf(d.fn) : 0));
15023
- 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
+ }));
15024
15323
  //#endregion
15025
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 };