@sema-agent/core 7.65.0 → 7.66.1

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 (129) hide show
  1. package/CHANGELOG.md +269 -0
  2. package/dist/agents/delegation-registry-seat.d.ts +15 -0
  3. package/dist/agents/delegation-registry-seat.js +13 -0
  4. package/dist/agents/org-delivery-gate.d.ts +8 -1
  5. package/dist/agents/org-delivery-gate.js +9 -3
  6. package/dist/agents/peer-session-drain.d.ts +51 -12
  7. package/dist/agents/peer-session-drain.js +44 -31
  8. package/dist/agents/read-inbox-tool.d.ts +6 -2
  9. package/dist/agents/read-inbox-tool.js +18 -5
  10. package/dist/agents/subagent.d.ts +3 -1
  11. package/dist/agents/subagent.js +79 -75
  12. package/dist/brain/reasoning.d.ts +2 -0
  13. package/dist/brain/reasoning.js +1 -0
  14. package/dist/core/allow-entry.d.ts +9 -0
  15. package/dist/core/allow-entry.js +7 -1
  16. package/dist/core/ask-origin.d.ts +23 -3
  17. package/dist/core/ask-origin.js +11 -1
  18. package/dist/core/engine-notice.d.ts +3 -3
  19. package/dist/core/governance-codes.js +1 -0
  20. package/dist/core/human-input-projection.d.ts +9 -0
  21. package/dist/core/human-input-projection.js +13 -0
  22. package/dist/core/input-author.d.ts +66 -6
  23. package/dist/core/input-author.js +21 -3
  24. package/dist/core/memory-engine/consolidation.d.ts +23 -9
  25. package/dist/core/memory-engine/consolidation.js +30 -5
  26. package/dist/core/memory-engine/control-plane-adoption.d.ts +11 -10
  27. package/dist/core/memory-engine/control-plane-adoption.js +54 -29
  28. package/dist/core/memory-engine/delegation-settlement.d.ts +18 -12
  29. package/dist/core/memory-engine/delegation-settlement.js +36 -26
  30. package/dist/core/memory-engine/engine.d.ts +17 -6
  31. package/dist/core/memory-engine/engine.js +78 -35
  32. package/dist/core/memory-engine/file-backend.d.ts +4 -1
  33. package/dist/core/memory-engine/file-backend.js +5 -1
  34. package/dist/core/memory-engine/index.d.ts +2 -2
  35. package/dist/core/memory-engine/index.js +2 -2
  36. package/dist/core/memory-engine/layout.d.ts +57 -36
  37. package/dist/core/memory-engine/layout.js +109 -134
  38. package/dist/core/memory-engine/memory-backend-contract.js +7 -7
  39. package/dist/core/memory-engine/memory-deployment.d.ts +3 -2
  40. package/dist/core/memory-engine/memory-deployment.js +6 -3
  41. package/dist/core/memory-engine/origin-clearance.d.ts +43 -15
  42. package/dist/core/memory-engine/origin-clearance.js +143 -55
  43. package/dist/core/model-receipt.d.ts +2 -1
  44. package/dist/core/model-receipt.js +5 -0
  45. package/dist/core/mods/dollar.d.ts +12 -0
  46. package/dist/core/mods/kernel/dispatch.d.ts +3 -1
  47. package/dist/core/mods/kernel/dispatch.js +5 -2
  48. package/dist/core/mods/kernel/events.d.ts +3 -1
  49. package/dist/core/mods/kernel/events.js +2 -2
  50. package/dist/core/mods/prompt-submit.d.ts +4 -0
  51. package/dist/core/mods/prompt-submit.js +24 -0
  52. package/dist/core/mods/stations.d.ts +23 -4
  53. package/dist/core/mods/stations.js +14 -7
  54. package/dist/core/retired-host-table-account.d.ts +19 -0
  55. package/dist/core/retired-host-table-account.js +28 -0
  56. package/dist/core/retired-tool-name-account.d.ts +60 -0
  57. package/dist/core/retired-tool-name-account.js +32 -0
  58. package/dist/core/roles.d.ts +3 -1
  59. package/dist/core/roles.js +5 -2
  60. package/dist/core/runner/compact-session.js +2 -1
  61. package/dist/core/runner/contracts.d.ts +1 -1
  62. package/dist/core/runner/gate-exit.js +9 -2
  63. package/dist/core/runner/memory-consolidation-driver.js +2 -2
  64. package/dist/core/runner/prepare-config-doors.js +1 -1
  65. package/dist/core/runner/prepare-delegation-surface.d.ts +1 -1
  66. package/dist/core/runner/prepare-delegation-surface.js +5 -3
  67. package/dist/core/runner/prepare-inherited-gate.js +2 -0
  68. package/dist/core/runner/prepare-memory.js +26 -5
  69. package/dist/core/runner/prepare-park-ask.d.ts +2 -0
  70. package/dist/core/runner/prepare-park-ask.js +3 -1
  71. package/dist/core/runner/prepare-policy-chain.js +2 -1
  72. package/dist/core/runner/prepare-project-context.js +2 -2
  73. package/dist/core/runner/prepare-question-face.d.ts +2 -2
  74. package/dist/core/runner/prepare-task.d.ts +5 -1
  75. package/dist/core/runner/prepare-task.js +5 -4
  76. package/dist/core/runner/prepare-wiring-manifest.js +5 -4
  77. package/dist/core/runner/prompt-suggestions.js +1 -1
  78. package/dist/core/runner/run-identity-wiring.js +2 -2
  79. package/dist/core/runner/run-leg.js +3 -3
  80. package/dist/core/runner/run-notification-lane.d.ts +3 -0
  81. package/dist/core/runner/run-notification-lane.js +2 -2
  82. package/dist/core/runner/runtask.js +6 -3
  83. package/dist/core/runner/steer-admission.d.ts +11 -2
  84. package/dist/core/runner/stream-steer-verb.d.ts +5 -2
  85. package/dist/core/runner/stream-steer-verb.js +67 -14
  86. package/dist/core/runner/sub-agent-deny-lists.d.ts +8 -27
  87. package/dist/core/runner/sub-agent-deny-lists.js +22 -33
  88. package/dist/core/runner-deps.d.ts +4 -4
  89. package/dist/core/shell-run-candidates.js +3 -3
  90. package/dist/core/side-query.js +1 -1
  91. package/dist/core/skill-grant.d.ts +7 -0
  92. package/dist/core/skill-grant.js +14 -5
  93. package/dist/core/task-event.d.ts +14 -0
  94. package/dist/core/tool-policy.js +2 -3
  95. package/dist/core/tool-spec.d.ts +13 -3
  96. package/dist/core/user-attachment.d.ts +5 -1
  97. package/dist/core/user-attachment.js +11 -5
  98. package/dist/engine/harness/agent-harness.d.ts +19 -11
  99. package/dist/engine/harness/agent-harness.js +7 -4
  100. package/dist/engine/llm/types.d.ts +22 -10
  101. package/dist/index.d.ts +4 -2
  102. package/dist/index.js +3 -1
  103. package/dist/shell/lex.d.ts +50 -15
  104. package/dist/shell/lex.js +43 -9
  105. package/dist/tools/fs/fs-bash.js +3 -3
  106. package/dist/tools/fs/removal-targets.d.ts +8 -2
  107. package/dist/tools/fs/removal-targets.js +31 -4
  108. package/dist/tools/fs/shell-read-argv.js +7 -1
  109. package/dist/tools/fs/shell-read-bindings.d.ts +21 -5
  110. package/dist/tools/fs/shell-read-bindings.js +130 -44
  111. package/dist/tools/fs/shell-read-plan.js +95 -29
  112. package/dist/tools/fs/shell-read-sourced.d.ts +25 -0
  113. package/dist/tools/fs/shell-read-sourced.js +119 -0
  114. package/dist/tools/fs/shell-read-word.d.ts +2 -2
  115. package/dist/tools/fs/shell-read-word.js +4 -5
  116. package/dist/tools/fs/shell-read-workdir.d.ts +19 -3
  117. package/dist/tools/fs/shell-read-workdir.js +60 -15
  118. package/dist/tools/fs/shell-reentry-text.d.ts +10 -2
  119. package/dist/tools/fs/shell-reentry-text.js +11 -4
  120. package/package.json +2 -2
  121. package/test/export-surface.snapshot.json +13 -7
  122. package/wire-changes/core-stores-sql@7.66.0.json +30 -0
  123. package/wire-changes/core-stores-sql@7.66.1.json +30 -0
  124. package/wire-changes/core@7.66.0.json +1218 -0
  125. package/wire-changes/core@7.66.1.json +46 -0
  126. package/wire-changes/mods-kernel@7.66.0.json +65 -0
  127. package/wire-changes/mods-kernel@7.66.1.json +30 -0
  128. package/wire-changes/primitives@7.66.0.json +30 -0
  129. package/wire-changes/primitives@7.66.1.json +30 -0
@@ -805,7 +805,7 @@ export async function memoryBackendContract(hooks) {
805
805
  await b.applyPatches([{ op: "add", id: e.id, entry: e }]);
806
806
  const att = await erase.call(b, { requestId: "req-contract-1", select: { ids: [e.id, "id-ghost-8888"] } });
807
807
  assert.strictEqual(att.v, 2, "the attestation rides the v:2 envelope");
808
- for (const cls of ["projection", "shadow", "indexLine", "quarantineCopy", "planArchive", "planWorkbook", "evidenceBinding", "backendDerived"]) {
808
+ for (const cls of ["projection", "shadow", "indexLine", "quarantineCopy", "clearanceCustody", "planArchive", "planWorkbook", "evidenceBinding", "backendDerived"]) {
809
809
  const answer = att.residuals.carriers[cls];
810
810
  assert.ok(answer !== undefined && (answer.unverified === true || (typeof answer.removed === "number" && typeof answer.remaining === "number")), `carrier class ${cls} is answered (removed/remaining counts, or unverified)`);
811
811
  }
@@ -1284,7 +1284,7 @@ export async function memoryGovernanceStoreContract(hooks) {
1284
1284
  rmSync(replica, { recursive: true, force: true });
1285
1285
  }
1286
1286
  };
1287
- defer("adoption: what the store lacks is written, what it holds the same converges, and the replica keeps its records beside a receipt", async () => {
1287
+ defer("adoption: what the store lacks is written, what it holds the same converges, and a pass that refused nothing removes the replica's copies beside a body-less receipt", async () => {
1288
1288
  const s = await hooks.make();
1289
1289
  await withReplica(async (replica, file) => {
1290
1290
  await file.updateDoc("holds", judgeDoc, () => ({ next: { v: 1, owner: "replica", n: 1 }, result: undefined }));
@@ -1296,7 +1296,7 @@ export async function memoryGovernanceStoreContract(hooks) {
1296
1296
  assert.deepStrictEqual(report.adopted.map((r) => `${r.record}:${r.outcome}`).sort(), ["doc:holds:written", "hold/cap.md:written", "pollution/s1.json:converged"]);
1297
1297
  assert.deepStrictEqual(await s.readDoc("holds"), { v: 1, owner: "replica", n: 1 });
1298
1298
  assert.ok(same(await s.getObject("hold", "cap.md"), enc("captured")));
1299
- assert.deepStrictEqual(replicaControlPlaneStrays(replica), { docs: ["holds"], objects: { hold: 1, pollution: 1 } }, "adoption copies: the replica's records stay where the engine's readers read them");
1299
+ assert.deepStrictEqual(replicaControlPlaneStrays(replica), { docs: [], objects: {} }, "the engine's readers read these records in the store: the replica's copies are removed (#3484)");
1300
1300
  assert.deepStrictEqual(readControlPlaneAdoptionReceipt(replica).map((r) => r.record).sort(), ["doc:holds", "hold/cap.md", "pollution/s1.json"]);
1301
1301
  });
1302
1302
  });
@@ -1319,10 +1319,10 @@ export async function memoryGovernanceStoreContract(hooks) {
1319
1319
  assert.deepStrictEqual(again.adopted.map((r) => `${r.record}:${r.outcome}`).sort(), ["doc:holds:written", "quarantine/q.md:written"]);
1320
1320
  assert.deepStrictEqual(again.refused.map((r) => r.record), ["doc:lineage"]);
1321
1321
  assert.deepStrictEqual(await s.readDoc("lineage"), { v: 1, owner: "carrier", n: 7 }, "no merge is invented");
1322
- assert.deepStrictEqual(replicaControlPlaneStrays(replica), { docs: ["lineage", "holds"], objects: { quarantine: 1 } }, "adoption copies: nothing leaves the replica");
1322
+ assert.deepStrictEqual(replicaControlPlaneStrays(replica), { docs: ["lineage", "holds"], objects: { quarantine: 1 } }, "a pass with a refusal removes nothing from the replica");
1323
1323
  });
1324
1324
  });
1325
- defer("adoption: a re-run converges — an interrupted handover converges, a finished one converges again and writes no second receipt row", async () => {
1325
+ defer("adoption: a re-run converges — an interrupted handover converges and empties the replica, and a re-run over the emptied replica hands over nothing and writes no second receipt row", async () => {
1326
1326
  const s = await hooks.make();
1327
1327
  await withReplica(async (replica, file) => {
1328
1328
  await file.putObject("capture", "s2.json", enc("opted out"));
@@ -1331,9 +1331,9 @@ export async function memoryGovernanceStoreContract(hooks) {
1331
1331
  const first = await adoptReplicaControlPlane(replica, s);
1332
1332
  assert.deepStrictEqual(first.refused, []);
1333
1333
  assert.deepStrictEqual(first.adopted.map((r) => `${r.record}:${r.outcome}`).sort(), ["capture/s2.json:converged", "doc:challenges:written"]);
1334
+ assert.deepStrictEqual(replicaControlPlaneStrays(replica), { docs: [], objects: {} }, "the finished handover leaves the replica empty");
1334
1335
  const again = await adoptReplicaControlPlane(replica, s);
1335
- assert.deepStrictEqual(again.refused, []);
1336
- assert.deepStrictEqual(again.adopted.map((r) => `${r.record}:${r.outcome}`).sort(), ["capture/s2.json:converged", "doc:challenges:converged"], "a finished adoption converges again");
1336
+ assert.deepStrictEqual(again, { adopted: [], refused: [] }, "a finished adoption has nothing left to hand over");
1337
1337
  assert.deepStrictEqual(readControlPlaneAdoptionReceipt(replica).map((r) => r.record).sort(), ["capture/s2.json", "doc:challenges"], "one receipt row per record");
1338
1338
  assert.deepStrictEqual(await s.readDoc("challenges"), { v: 1, owner: "replica", n: 2 });
1339
1339
  });
@@ -11,7 +11,7 @@ export interface MemoryDeploymentInput {
11
11
  * there, and a backend without one keeps them in per-project control planes no deployment-wide reading can name —
12
12
  * refused (`config.memory_scope_key`). This is the deployment's own question, not consolidation's
13
13
  * (`memoryGovernanceDurability`). A backend that carries only `governance` stays refused here: its session accounts
14
- * ride its store, its scope registry and capture records do not. */
14
+ * and capture records ride its store (#3484), its scope registry does not. */
15
15
  backend: MemoryBackend;
16
16
  /** The value given as `RunnerDeps.memoryEngineDir` — a required key, judged as `resolveMemoryScopeStore`
17
17
  * judges it (`undefined` written out reads the Runner's same fallback). */
@@ -76,7 +76,8 @@ export interface MemoryDeployment {
76
76
  * absence), counts as holding one, and so does an anchor, a scope registry or a registry journal that stands there
77
77
  * damaged (a link, no regular file, unreadable, not JSON or out of shape). Opening, reading and a refused request
78
78
  * add no store, and every deployment object over one engine root answers the same. A store in the set that cannot be
79
- * opened is not a store of the list: the call throws `ControlPlaneCorruptError` (a bare system error is carried by one
79
+ * opened — the damaged anchor, scope registry or registry journal that put it there is one such cause: the census and the
80
+ * open read the same fault — is not a store of the list: the call throws `ControlPlaneCorruptError` (a bare system error is carried by one
80
81
  * that names its errno, the original as its `cause`), and the session status answers that plane
81
82
  * `optOutSource: "fault"`.
82
83
  */
@@ -1,7 +1,7 @@
1
1
  import { join } from "node:path";
2
2
  import { MemoryEngine } from "./engine.js";
3
3
  import { derivePersonalControlDir, derivePersonalMemoryDir, directoryPinOf, judgeMemoryStoreSeat, memoryPlaneStore, memoryScopePlaneOf, mergeErasureAttestations, refuseMemoryStoreInput } from "./dual-root.js";
4
- import { acquireStoreTxnLock, assertStoreTxnLockOwnership, ControlPlaneCorruptError, renewStoreTxnLock, resolveMemoryEngineRoot, storeHoldsRecord, TXN_LOCK_STALE_MS } from "./layout.js";
4
+ import { acquireStoreTxnLock, assertStoreTxnLockOwnership, ControlPlaneCorruptError, renewStoreTxnLock, resolveMemoryEngineRoot, storeHoldsRecord, storeOpenArtifactFault, TXN_LOCK_STALE_MS } from "./layout.js";
5
5
  import { captureErasureInput, erasureRequestInvalid, erasureSelectHash } from "./file-backend.js";
6
6
  import { canonicalExpectedScopes } from "./export-bundle.js";
7
7
  import { thrownLabel, thrownText } from "../thrown-value.js";
@@ -62,9 +62,12 @@ export function createMemoryDeployment(input) {
62
62
  const project = seatOf("project", backend);
63
63
  let personal;
64
64
  const personalStore = () => {
65
- if (personal !== undefined)
66
- return personal;
67
65
  try {
66
+ const fault = storeOpenArtifactFault(derivePersonalMemoryDir(engineRoot), derivePersonalControlDir(engineRoot));
67
+ if (fault !== undefined)
68
+ throw fault;
69
+ if (personal !== undefined)
70
+ return personal;
68
71
  personal = seatOf("personal", memoryPlaneStore("personal", backend, engineRoot, onIncident));
69
72
  }
70
73
  catch (err) {
@@ -1,5 +1,6 @@
1
- import type { MemoryEntryOrigin } from "./types.js";
2
- export declare const ORIGIN_CLEARANCES_FILE: string;
1
+ import type { MemoryEntryOrigin, MemoryGovernanceDocs, MemoryGovernanceObjects } from "./types.js";
2
+ /** The part of a governance store the account is kept through: its document and its custody objects. */
3
+ export type OriginClearanceStore = MemoryGovernanceDocs & Pick<MemoryGovernanceObjects, "putObject" | "getObject" | "deleteObject">;
3
4
  /** The custody object a clearance's cleared-entry text is kept as (kind `clearance-custody`): named by the row, so the
4
5
  * row alone finds it again. */
5
6
  export declare function clearanceCustodyName(clearanceId: string): string;
@@ -34,8 +35,13 @@ export interface OriginClearanceRow {
34
35
  * the re-record batch leaves this as the only copy — the pending row is the loud recovery seat
35
36
  * (a later clearEntryOrigin call for the same entry resumes from it). Kept as the row's custody
36
37
  * object ({@link clearanceCustodyName}), never inside the account: the stored row carries the
37
- * text's sha-256 (`custodyDigest`) and every read answers the text, checked against it. */
38
+ * text's sha-256 (`custodyDigest`) and every read answers the text, checked against it. `""` on a row whose
39
+ * custody was erased with its entry (`custodyErased`). */
38
40
  entryText: string;
41
+ /** Present (`true`) ⇔ an erasure of the entry erased this clearance's custody (#3463): the text is gone from the
42
+ * store, `entryText` answers `""`, and the row no longer resumes (`memory.origin_clear_unknown`). The row itself —
43
+ * who cleared, why, when, its events — stays. ADDITIVE: absent on every row whose custody stands. */
44
+ custodyErased?: true;
39
45
  /** Set the moment THIS clearance's tombstone commits ({@link markOriginClearanceTombstoned}) —
40
46
  * the resume arm's arbiter for an absent entry: with it, absence is the known crash window
41
47
  * (tombstone landed, re-record owed — replay from custody); without it, the absence is an
@@ -73,18 +79,19 @@ export interface OriginClearanceShadow {
73
79
  requestId: string;
74
80
  settledAt: number;
75
81
  }
76
- /** Move every custody text the account still carries inline out into its custody object, under the account's lock;
77
- * writes nothing when there is none. */
78
- export declare function moveOriginClearanceCustodyOut(controlDir: string): void;
79
- /** Lock-free strict read of the whole account (host audit face; journal-aware, corrupt = throw). Each row answers its
80
- * custody text, wherever the account keeps it. */
81
- export declare function readOriginClearances(controlDir: string): OriginClearanceRow[];
82
+ /** Move every custody text the account still carries inline out into its custody object (each object before the
83
+ * update that drops its text); writes nothing when there is none. */
84
+ export declare function moveOriginClearanceCustodyOut(store: OriginClearanceStore): Promise<void>;
85
+ /** Strict read of the whole account (host audit face; corrupt = throw). Each row answers its custody text, wherever the
86
+ * account keeps it (`""` once an erasure took it, `custodyErased`). */
87
+ export declare function readOriginClearances(store: Pick<MemoryGovernanceDocs, "readDoc"> & Pick<MemoryGovernanceObjects, "getObject">): Promise<OriginClearanceRow[]>;
82
88
  /**
83
89
  * WRITE-AHEAD open: append the pending row (custody included) before any store mutation. Refuses a
84
90
  * second OPEN while a pending row for the same entry stands — the pending row is a resume seat,
85
- * not a queue (the caller resumes it instead).
91
+ * not a queue (the caller resumes it instead). The custody text lands as its object before the update
92
+ * that appends the row naming it; a refused open removes the object it wrote (no row names it).
86
93
  */
87
- export declare function openOriginClearance(controlDir: string, row: Omit<OriginClearanceRow, "status" | "events">): void;
94
+ export declare function openOriginClearance(store: OriginClearanceStore, row: Omit<OriginClearanceRow, "status" | "events" | "custodyErased">): Promise<void>;
88
95
  /**
89
96
  * Record that THIS clearance's tombstone leg committed (called between the delete's success and
90
97
  * the re-record attempt). The record is what lets a later resume read an ABSENT entry as "the
@@ -93,10 +100,10 @@ export declare function openOriginClearance(controlDir: string, row: Omit<Origin
93
100
  * the identical committed state). Idempotent (first write wins); non-pending rows are a no-op
94
101
  * (a settled row's history never rewrites).
95
102
  */
96
- export declare function markOriginClearanceTombstoned(controlDir: string, input: {
103
+ export declare function markOriginClearanceTombstoned(store: OriginClearanceStore, input: {
97
104
  clearanceId: string;
98
105
  now: () => number;
99
- }): void;
106
+ }): Promise<void>;
100
107
  /**
101
108
  * Terminal event append + status flip. Unknown clearanceId is a corrupt-caller refusal.
102
109
  *
@@ -111,7 +118,7 @@ export declare function markOriginClearanceTombstoned(controlDir: string, input:
111
118
  * bytes, so the row must stay resumable (a `failed` flip would strand them: the resume arm only
112
119
  * completes pending rows).
113
120
  */
114
- export declare function settleOriginClearance(controlDir: string, input: {
121
+ export declare function settleOriginClearance(store: OriginClearanceStore, input: {
115
122
  clearanceId: string;
116
123
  to: "done" | "failed";
117
124
  requestId: string;
@@ -119,4 +126,25 @@ export declare function settleOriginClearance(controlDir: string, input: {
119
126
  now: () => number;
120
127
  detail?: string;
121
128
  keepPending?: boolean;
122
- }): void;
129
+ }): Promise<void>;
130
+ /** Whether an erasure has taken this clearance's custody (a row that is not there reads as taken: nothing stands to
131
+ * resume from). The re-record legs ask it right before they add the entry back from the custody they read earlier. */
132
+ export declare function clearanceCustodyErased(store: Pick<MemoryGovernanceDocs, "readDoc">, clearanceId: string): Promise<boolean>;
133
+ /** What one erasure did to the clearances' custody (the attestation's `clearanceCustody` carrier class): `removed` — the
134
+ * custody texts of the erased entries this call took out of the store: each row this call marked (an inline text dropped
135
+ * from its row; a kept text whose object is gone after this call's delete — deleted by it, or already by an update of the
136
+ * account that read the mark first, {@link clearanceUpdate}), and each object a replay found still standing under a row
137
+ * marked before and deleted; `remaining` — the ones it could not delete. */
138
+ export interface ClearanceCustodyErasure {
139
+ removed: number;
140
+ remaining: number;
141
+ }
142
+ /**
143
+ * #3463 — erase the custody of every clearance of an erased entry (`entryIds`). The rows go first: one update marks each
144
+ * of them `custodyErased` at `at` (`custodyErasedAt`; an inline text and the digest are dropped with it), so from then on no read answers the text
145
+ * and no resume acts on it; then each one's custody object is deleted. A row already marked is left as it is (a replay
146
+ * converges: its object is deleted again when one still stands, and a row is never rewritten twice). The row itself —
147
+ * who cleared, why, when, its events, its status — stays. A failed delete is counted in `remaining`, never swallowed; a
148
+ * document that cannot be read or updated throws (the lane that called decides what its attestation says about that).
149
+ */
150
+ export declare function eraseOriginClearanceCustody(store: OriginClearanceStore, entryIds: ReadonlySet<string>, at: number): Promise<ClearanceCustodyErasure>;
@@ -1,52 +1,75 @@
1
1
  import { createHash } from "node:crypto";
2
- import { ControlPlaneCorruptError, fileGovernanceDocOf, lockedStrictUpdate, readStrictSidecar } from "./layout.js";
3
- import { getFileControlObject, putFileControlObject } from "./control-objects.js";
2
+ import { ControlPlaneCorruptError } from "./layout.js";
4
3
  import { MEMORY_ORIGIN_CAUSES } from "./types.js";
5
- const CLEARANCES = fileGovernanceDocOf("origin-clearances");
6
- export const ORIGIN_CLEARANCES_FILE = CLEARANCES.file;
7
4
  export function clearanceCustodyName(clearanceId) {
8
5
  return `${clearanceId}.md`;
9
6
  }
10
7
  function sha256Hex(bytes) {
11
8
  return createHash("sha256").update(bytes).digest("hex");
12
9
  }
13
- function custodyTextOf(controlDir, row) {
10
+ async function readClearanceRecord(store) {
11
+ return coerceClearances(await store.readDoc("origin-clearances"));
12
+ }
13
+ async function custodyTextOf(store, row) {
14
+ if (row.custodyErased === true)
15
+ return "";
14
16
  if (row.entryText !== undefined)
15
17
  return row.entryText;
16
18
  const name = clearanceCustodyName(row.clearanceId);
17
- const bytes = getFileControlObject(controlDir, "clearance-custody", name);
19
+ const bytes = await store.getObject("clearance-custody", name);
18
20
  if (bytes === undefined)
19
21
  throw new ControlPlaneCorruptError(`memory origin-clearance ledger: clearance ${JSON.stringify(row.clearanceId)} names custody ${JSON.stringify(name)} that is not there (fail-closed)`);
20
22
  if (sha256Hex(bytes) !== row.custodyDigest)
21
23
  throw new ControlPlaneCorruptError(`memory origin-clearance ledger: clearance ${JSON.stringify(row.clearanceId)}'s custody does not match the digest its row records (fail-closed)`);
22
24
  return new TextDecoder("utf-8", { fatal: true }).decode(bytes);
23
25
  }
24
- function keepCustody(controlDir, clearanceId, text) {
26
+ async function keepCustody(store, clearanceId, text) {
25
27
  const bytes = new TextEncoder().encode(text);
26
- const digest = sha256Hex(bytes);
27
- const name = clearanceCustodyName(clearanceId);
28
- putFileControlObject(controlDir, "clearance-custody", name, bytes);
29
- return digest;
30
- }
31
- function moveInlineCustody(controlDir, rec) {
32
- let moved = false;
33
- for (const row of rec.rows) {
34
- if (row.entryText === undefined)
35
- continue;
36
- const custodyDigest = keepCustody(controlDir, row.clearanceId, row.entryText);
37
- const r = row;
38
- delete r.entryText;
39
- r.custodyDigest = custodyDigest;
40
- moved = true;
41
- }
42
- return moved;
28
+ await store.putObject("clearance-custody", clearanceCustodyName(clearanceId), bytes);
29
+ return sha256Hex(bytes);
43
30
  }
44
- function lockedClearanceUpdate(controlDir, fn) {
45
- lockedStrictUpdate(controlDir, CLEARANCES.file, CLEARANCES.what, coerceClearances, (rec) => {
46
- const moved = moveInlineCustody(controlDir, rec);
47
- const out = fn(rec);
48
- return out.next === undefined && moved ? { next: rec, result: out.result } : out;
49
- });
31
+ async function clearanceUpdate(store, fn) {
32
+ const kept = new Map();
33
+ let seen;
34
+ try {
35
+ for (const row of (await readClearanceRecord(store)).rows) {
36
+ if (row.entryText !== undefined)
37
+ kept.set(row.clearanceId, await keepCustody(store, row.clearanceId, row.entryText));
38
+ }
39
+ return await store.updateDoc("origin-clearances", coerceClearances, (rec) => {
40
+ seen = [...rec.rows];
41
+ let moved = false;
42
+ for (const row of rec.rows) {
43
+ if (row.entryText === undefined)
44
+ continue;
45
+ const digest = kept.get(row.clearanceId);
46
+ if (digest === undefined || digest !== sha256Hex(new TextEncoder().encode(row.entryText)))
47
+ continue;
48
+ const r = row;
49
+ delete r.entryText;
50
+ r.custodyDigest = digest;
51
+ moved = true;
52
+ }
53
+ const out = fn(rec);
54
+ return out.next === undefined && moved ? { next: rec, result: out.result } : out;
55
+ });
56
+ }
57
+ finally {
58
+ const rows = seen ?? (await readClearanceRecord(store).then((rec) => rec.rows, () => undefined));
59
+ const deleteFailures = [];
60
+ for (const row of rows ?? []) {
61
+ if (row.custodyErased !== true)
62
+ continue;
63
+ try {
64
+ await store.deleteObject("clearance-custody", clearanceCustodyName(row.clearanceId));
65
+ }
66
+ catch (err) {
67
+ deleteFailures.push(err);
68
+ }
69
+ }
70
+ if (deleteFailures.length > 0)
71
+ throw deleteFailures[0];
72
+ }
50
73
  }
51
74
  function reqStr(v) {
52
75
  return typeof v === "string" && v.length > 0;
@@ -71,8 +94,10 @@ function coerceClearances(raw) {
71
94
  if (rec.version !== 1)
72
95
  throw new ControlPlaneCorruptError(`memory origin-clearance ledger has an unrecognized version (${String(rec.version)}) — refusing (fail-closed)`);
73
96
  for (const r of rec.rows) {
74
- const custodyInline = typeof r?.entryText === "string" && r.entryText.length > 0 && r.custodyDigest === undefined;
75
- const custodyKept = r?.entryText === undefined && typeof r?.custodyDigest === "string" && /^[0-9a-f]{64}$/.test(r.custodyDigest);
97
+ const notErased = r?.custodyErased === undefined && r?.custodyErasedAt === undefined;
98
+ const custodyInline = typeof r?.entryText === "string" && r.entryText.length > 0 && r.custodyDigest === undefined && notErased;
99
+ const custodyKept = r?.entryText === undefined && typeof r?.custodyDigest === "string" && /^[0-9a-f]{64}$/.test(r.custodyDigest) && notErased;
100
+ const custodyGone = r?.custodyErased === true && typeof r.custodyErasedAt === "number" && Number.isFinite(r.custodyErasedAt) && r.entryText === undefined && r.custodyDigest === undefined;
76
101
  if (typeof r !== "object" ||
77
102
  r === null ||
78
103
  !reqStr(r.clearanceId) ||
@@ -84,7 +109,7 @@ function coerceClearances(raw) {
84
109
  !reqStr(r.reason) ||
85
110
  typeof r.at !== "number" ||
86
111
  !Number.isFinite(r.at) ||
87
- !(custodyInline || custodyKept) ||
112
+ !(custodyInline || custodyKept || custodyGone) ||
88
113
  (r.tombstonedAt !== undefined && (typeof r.tombstonedAt !== "number" || !Number.isFinite(r.tombstonedAt))) ||
89
114
  (r.status !== "pending" && r.status !== "done" && r.status !== "failed") ||
90
115
  !Array.isArray(r.events)) {
@@ -99,29 +124,47 @@ function coerceClearances(raw) {
99
124
  }
100
125
  return rec;
101
126
  }
102
- export function moveOriginClearanceCustodyOut(controlDir) {
103
- lockedClearanceUpdate(controlDir, () => ({ result: undefined }));
127
+ export async function moveOriginClearanceCustodyOut(store) {
128
+ await clearanceUpdate(store, () => ({ result: undefined }));
104
129
  }
105
- export function readOriginClearances(controlDir) {
106
- return coerceClearances(readStrictSidecar(controlDir, CLEARANCES.file, CLEARANCES.what)).rows.map((r) => {
107
- const { custodyDigest: _digest, entryText: _inline, ...row } = r;
108
- return { ...row, entryText: custodyTextOf(controlDir, r), events: [...r.events] };
109
- });
130
+ export async function readOriginClearances(store) {
131
+ const out = [];
132
+ for (const r of (await readClearanceRecord(store)).rows) {
133
+ const { custodyDigest: _digest, entryText: _inline, custodyErased: _erased, custodyErasedAt: _erasedAt, ...row } = r;
134
+ out.push({ ...row, entryText: await custodyTextOf(store, r), ...(r.custodyErased === true ? { custodyErased: true } : {}), events: [...r.events] });
135
+ }
136
+ return out;
110
137
  }
111
- export function openOriginClearance(controlDir, row) {
112
- lockedClearanceUpdate(controlDir, (rec) => {
113
- if (rec.rows.some((r) => r.entryId === row.entryId && r.status === "pending")) {
114
- const e = new Error(`origin clearance for entry ${JSON.stringify(row.entryId)} is already pending — resume it (call clearEntryOrigin again) instead of opening a second row.`);
115
- e.code = "memory.origin_clear_pending";
116
- throw e;
117
- }
118
- const { entryText, ...rest } = row;
119
- rec.rows.push({ ...rest, custodyDigest: keepCustody(controlDir, row.clearanceId, entryText), status: "pending", events: [] });
120
- return { next: rec, result: undefined };
121
- });
138
+ function pendingClearanceRefusal(entryId) {
139
+ const e = new Error(`origin clearance for entry ${JSON.stringify(entryId)} is already pending — resume it (call clearEntryOrigin again) instead of opening a second row.`);
140
+ e.code = "memory.origin_clear_pending";
141
+ return e;
122
142
  }
123
- export function markOriginClearanceTombstoned(controlDir, input) {
124
- lockedClearanceUpdate(controlDir, (rec) => {
143
+ export async function openOriginClearance(store, row) {
144
+ const pendingFor = (rec) => rec.rows.some((r) => r.entryId === row.entryId && r.status === "pending");
145
+ if (pendingFor(await readClearanceRecord(store)))
146
+ throw pendingClearanceRefusal(row.entryId);
147
+ const { entryText, ...rest } = row;
148
+ const custodyDigest = await keepCustody(store, row.clearanceId, entryText);
149
+ let refusedAsPending = false;
150
+ try {
151
+ await clearanceUpdate(store, (rec) => {
152
+ if (pendingFor(rec)) {
153
+ refusedAsPending = true;
154
+ throw pendingClearanceRefusal(row.entryId);
155
+ }
156
+ rec.rows.push({ ...rest, custodyDigest, status: "pending", events: [] });
157
+ return { next: rec, result: undefined };
158
+ });
159
+ }
160
+ catch (err) {
161
+ if (refusedAsPending)
162
+ await Promise.resolve(store.deleteObject("clearance-custody", clearanceCustodyName(row.clearanceId))).catch(() => undefined);
163
+ throw err;
164
+ }
165
+ }
166
+ export async function markOriginClearanceTombstoned(store, input) {
167
+ await clearanceUpdate(store, (rec) => {
125
168
  const r = rec.rows.find((x) => x.clearanceId === input.clearanceId);
126
169
  if (r === undefined || r.status !== "pending" || r.tombstonedAt !== undefined)
127
170
  return { result: undefined };
@@ -129,8 +172,8 @@ export function markOriginClearanceTombstoned(controlDir, input) {
129
172
  return { next: rec, result: undefined };
130
173
  });
131
174
  }
132
- export function settleOriginClearance(controlDir, input) {
133
- lockedClearanceUpdate(controlDir, (rec) => {
175
+ export async function settleOriginClearance(store, input) {
176
+ await clearanceUpdate(store, (rec) => {
134
177
  const r = rec.rows.find((x) => x.clearanceId === input.clearanceId);
135
178
  if (r === undefined) {
136
179
  const e = new Error(`origin clearance ${JSON.stringify(input.clearanceId)} is unknown`);
@@ -147,3 +190,48 @@ export function settleOriginClearance(controlDir, input) {
147
190
  return { next: rec, result: undefined };
148
191
  });
149
192
  }
193
+ export async function clearanceCustodyErased(store, clearanceId) {
194
+ const row = (await readClearanceRecord(store)).rows.find((r) => r.clearanceId === clearanceId);
195
+ return row === undefined || row.custodyErased === true;
196
+ }
197
+ export async function eraseOriginClearanceCustody(store, entryIds, at) {
198
+ if (entryIds.size === 0 || !(await readClearanceRecord(store)).rows.some((r) => entryIds.has(r.entryId)))
199
+ return { removed: 0, remaining: 0 };
200
+ const marked = await store.updateDoc("origin-clearances", coerceClearances, (rec) => {
201
+ const objects = [];
202
+ let inline = 0;
203
+ let changed = false;
204
+ for (const row of rec.rows) {
205
+ if (!entryIds.has(row.entryId))
206
+ continue;
207
+ if (row.custodyErased === true) {
208
+ objects.push({ clearanceId: row.clearanceId, take: "leftover" });
209
+ continue;
210
+ }
211
+ if (row.entryText !== undefined)
212
+ inline++;
213
+ objects.push({ clearanceId: row.clearanceId, take: row.entryText !== undefined ? "inline" : "kept" });
214
+ const r = row;
215
+ delete r.entryText;
216
+ delete r.custodyDigest;
217
+ r.custodyErased = true;
218
+ r.custodyErasedAt = at;
219
+ changed = true;
220
+ }
221
+ return changed ? { next: rec, result: { objects, inline } } : { result: { objects, inline } };
222
+ });
223
+ const out = { removed: marked.inline, remaining: 0 };
224
+ for (const { clearanceId, take } of marked.objects) {
225
+ try {
226
+ const deleted = await store.deleteObject("clearance-custody", clearanceCustodyName(clearanceId));
227
+ if (deleted !== true && deleted !== false)
228
+ out.remaining++;
229
+ else if (take === "kept" || (take === "leftover" && deleted === true))
230
+ out.removed++;
231
+ }
232
+ catch {
233
+ out.remaining++;
234
+ }
235
+ }
236
+ return out;
237
+ }
@@ -34,6 +34,7 @@ export declare function modelOriginOf(model: Model): Model;
34
34
  * holds a member the receipt cannot copy (a getter that threw, a function, another prototype) — `config.unknown_role` /
35
35
  * `not_a_model_ref`; a retired member — `config.deps_retired_key` (its own sentence); a member outside the contract — `not_a_model_ref`
36
36
  * (a provider's own parameters belong in `Model.params`); an `id` that is not a non-empty string or an `api` that is not a string —
37
- * `not_a_model_ref`, naming the member.
37
+ * `not_a_model_ref`, naming the member; a `defaultThinking` that is present but not one of the seven tiers — `not_a_model_ref`, naming
38
+ * the member.
38
39
  */
39
40
  export declare function receiveModel(value: unknown, seat: string, what?: string, note?: string): Model;
@@ -1,4 +1,5 @@
1
1
  import { types } from "node:util";
2
+ import { isThinkingLevel, THINKING_LEVELS } from "../brain/reasoning.js";
2
3
  import { describeFault, receive } from "./mods/kernel/receive.js";
3
4
  import { DECLARATION_RECEIPT_MODE } from "./own-property-receipt.js";
4
5
  import { assertNoRetiredKeys, RETIRED_MODEL_KEYS } from "./retired-keys.js";
@@ -99,6 +100,10 @@ function judgeModelCopy(copy, seat, what, note) {
99
100
  throw modelBindingRefusal(seat, "not_a_model_ref", `${seat} is ${what} carrying ${bindingShown(key)}, which is not a member of Model — a provider's own parameters belong in \`Model.params\`.${note}`);
100
101
  }
101
102
  }
103
+ const defaultThinking = copy["defaultThinking"];
104
+ if (defaultThinking !== undefined && !isThinkingLevel(defaultThinking)) {
105
+ throw modelBindingRefusal(seat, "not_a_model_ref", `${seat} is ${what} whose \`defaultThinking\` is ${bindingShown(defaultThinking)} — a model's default thinking level is one of ${THINKING_LEVELS.join(", ")} ("off" spells thinking off), or absent for no default.${note}`);
106
+ }
102
107
  }
103
108
  function sameData(a, b, top = false, compared = new Map()) {
104
109
  if (Object.is(a, b))
@@ -147,6 +147,12 @@ export interface EngineDollar extends ModDollarBase {
147
147
  readonly instructions?: string;
148
148
  }): Promise<SessionCompactAnswer>;
149
149
  };
150
+ readonly prompt: {
151
+ /** `$.prompt.submit({ text })`: an extension's prompt entering this leg in the person's place (`prompt-submit.ts`). */
152
+ submit(args: {
153
+ readonly text: string;
154
+ }): Promise<PromptSubmitAnswer>;
155
+ };
150
156
  readonly clock: {
151
157
  now(): Promise<number>;
152
158
  sleep(args: {
@@ -207,6 +213,12 @@ export type SessionSendAnswer = {
207
213
  readonly isDelivered: false;
208
214
  readonly reason: string;
209
215
  };
216
+ /** What `$.prompt.submit` answers when the input is taken: the text that entered, or why it did not (returned, not thrown). */
217
+ export type PromptSubmitAnswer = {
218
+ readonly text: string;
219
+ } | {
220
+ readonly drop: string;
221
+ };
210
222
  /** What `$.session.compact` answers: the in-place pass's outcome (a call it refuses throws, its reason on the report sink too). */
211
223
  export interface SessionCompactAnswer {
212
224
  readonly outcome: CompactOutcome;
@@ -1,7 +1,8 @@
1
1
  import { type ModBusSide, type ModEventName, type ModSeat } from "./events.js";
2
2
  import { type ModAdmissionRecord, type ModDollarBase, type ModOrigin, type ModSeats } from "./registration.js";
3
3
  import { type ModAnswerCheck, type ModAnswerer, type ModAnswerRanks, type ModEventPayload, type ModFailureCause, type ModMatcher, type ModSkip, type ProxyProbe } from "./site-rules.js";
4
- /** A frame on the dispatch stack: a registration's own `$` call, or one of its handlers running. */
4
+ /** A frame on the dispatch stack: a registration's own `$` call, or one of its handlers running — on `event` (a handler may hang
5
+ * on several events; the frame says which one it is running on, every frame from its mint, {@link handlerFrame}). */
5
6
  export type ModFrame = {
6
7
  readonly kind: "dollar";
7
8
  readonly plugin: string;
@@ -9,6 +10,7 @@ export type ModFrame = {
9
10
  readonly kind: "handler";
10
11
  readonly plugin: string;
11
12
  readonly handler: number;
13
+ readonly event: ModEventName;
12
14
  };
13
15
  /** What a chain bottom (the core of an event) receives besides `e`. */
14
16
  export interface ModBottomContext {
@@ -2,6 +2,9 @@ import { CATCH_BUDGET_MS, createSelfBudget, POST_ABORT_GRACE_MS, RUNAWAY_AFTER_M
2
2
  import { expandOnSide, failureRefuses, isModEventName, MOD_SEATS, nextToRefusal, stationOn } from "./events.js";
3
3
  import { ENGINE_ORIGIN, modsInvalid, screenModSeats, } from "./registration.js";
4
4
  import { answerUpward, answerViolation, detachedCopy, engineObjectsOnce, handedOn, handOnViolation, matcherMatches, matcherViolation, methodAnswerViolation, NEXT_IN_FLIGHT, receiveAnswer, receiveEvent, receivePayload, sealedObjects, } from "./site-rules.js";
5
+ function handlerFrame(below, plugin, handler, event) {
6
+ return Object.freeze([...below, Object.freeze({ kind: "handler", plugin, handler, event })]);
7
+ }
5
8
  const TIER_RANK = { prepend: 0, user: 1, append: 2, builtin: 3, core: 4 };
6
9
  const bypassed = (floors, tier) => floors.some((f) => TIER_RANK[f.from] < TIER_RANK[tier] && TIER_RANK[tier] < TIER_RANK[f.to]);
7
10
  export async function admitMods(input) {
@@ -501,7 +504,7 @@ function createBus(side, mounted, bottoms, entries, report, records, describe, i
501
504
  live.add(ac);
502
505
  const budgetMs = ownMs(h.reg.budgetMs);
503
506
  const budget = createSelfBudget(budgetMs, () => ac.abort(new Error(`${name} ran past its ${budgetMs}ms budget`)));
504
- const myFrames = Object.freeze([...fr, Object.freeze({ kind: "handler", plugin: name, handler: h.index })]);
507
+ const myFrames = handlerFrame(fr, name, h.index, event);
505
508
  const state = {
506
509
  pending: 0,
507
510
  called: false,
@@ -672,7 +675,7 @@ function createBus(side, mounted, bottoms, entries, report, records, describe, i
672
675
  live.add(ac);
673
676
  const budgetMs = ownMs(h.reg.budgetMs);
674
677
  const budget = createSelfBudget(budgetMs, () => ac.abort(new Error(`${name} ran past its ${budgetMs}ms budget`)));
675
- const myFrames = Object.freeze([...fr, Object.freeze({ kind: "handler", plugin: name, handler: h.index })]);
678
+ const myFrames = handlerFrame(fr, name, h.index, event);
676
679
  const refuse = () => Promise.reject(new Error(`${name}: an observe handler is not in the chain; next() is unavailable`));
677
680
  const next = makeNext({ budget, signal: ac.signal, trace: () => Object.freeze([]) }, refuse, refuse);
678
681
  const verdict = (r) => {
@@ -38,8 +38,10 @@
38
38
  * `prompt.submit` (a person's input entering the leg — rewritable, droppable, refused on a failure), `classic.SessionStart` and
39
39
  * `classic.SessionEnd` have stations, the two classic ones raised in the bottoms of `session.start` and `session.end`; the
40
40
  * methods `session.turns`, `session.usage` and `session.version` have bottoms, and `session.messages` takes `{ agentId }`.
41
+ * 9: `prompt.submit` has a `call` column — a `$` call reaches the host's entry, an extension's input entering the leg under the
42
+ * author `extension` — and pins `author` and `extension`; a handler's frame names the event it runs on (`ModFrame.event`).
41
43
  */
42
- export declare const KERNEL_CONTRACT_VERSION = 8;
44
+ export declare const KERNEL_CONTRACT_VERSION = 9;
43
45
  /** The five tiers in run order (CC names). `builtin` and `core` are the engine's own. */
44
46
  export declare const MOD_TIERS: readonly ["prepend", "user", "append", "builtin", "core"];
45
47
  export type ModTier = (typeof MOD_TIERS)[number];
@@ -1,4 +1,4 @@
1
- export const KERNEL_CONTRACT_VERSION = 8;
1
+ export const KERNEL_CONTRACT_VERSION = 9;
2
2
  export const MOD_TIERS = Object.freeze(["prepend", "user", "append", "builtin", "core"]);
3
3
  export const MOD_SEATS = Object.freeze(["deployment", "task"]);
4
4
  export const MOD_EVENT_SIDES = Object.freeze(["engine", "surface", "both"]);
@@ -94,7 +94,7 @@ export const MOD_EVENT_TABLE = Object.freeze({
94
94
  "ui.focus": surface(station("skip", "grace", ["component", "requestId", "plugin", "origin", "element"], { call: true })),
95
95
  "agent.offer": engine(station("skip", "grace", ["agent", "provider"])),
96
96
  "agent.spawn": engine(station("refuse_until_run", "immediate", AGENT_SPAWN_PINNED, { call: true })),
97
- "prompt.submit": engine(station("refuse", "immediate", ["source", "inputId", "actor"])),
97
+ "prompt.submit": engine(station("refuse", "immediate", ["source", "inputId", "actor", "author", "extension"], { call: true })),
98
98
  "prompt.fill": surface(station("skip", "grace", ["origin", "mode"], { call: true })),
99
99
  "prompt.suggest": surface(station("skip", "grace", ["origin"], { call: true })),
100
100
  "prompt.edit": surface(station("skip", "grace", ["origin", "key"], { budgetMs: PROMPT_EDIT_BUDGET_MS })),
@@ -0,0 +1,4 @@
1
+ import type { PromptSubmitRef } from "../input-author.js";
2
+ import type { ModCallEntry } from "./kernel/index.js";
3
+ /** `$.prompt.submit`'s host entry over the stream's binding (read at call time: unfilled ⇒ the call is dropped). */
4
+ export declare function createPromptSubmitEntry(ref: PromptSubmitRef | undefined): ModCallEntry;
@@ -0,0 +1,24 @@
1
+ import { PROMPT_SCREEN_STATIONS } from "./stations.js";
2
+ import { extensionWords } from "../untrusted-egress.js";
3
+ const ARGUMENT = "text";
4
+ export function createPromptSubmitEntry(ref) {
5
+ return async (args, ctx) => {
6
+ const by = ctx.origin.plugin;
7
+ const refused = (why) => `${by}: $.prompt.submit: refused: ${why}`;
8
+ const extra = Object.keys(args).find((k) => k !== ARGUMENT);
9
+ if (extra !== undefined)
10
+ throw new TypeError(refused(`takes { text }; "${extensionWords(extra, 40)}" is not one`));
11
+ const text = args[ARGUMENT];
12
+ if (typeof text !== "string" || text.trim() === "")
13
+ throw new TypeError(refused("no { text } (a non-empty string)"));
14
+ const seat = ref?.seat;
15
+ const handlers = ctx.frames.filter((f) => f.kind === "handler");
16
+ const waitedOn = handlers.some((f) => PROMPT_SCREEN_STATIONS.includes(f.event)) || (handlers.length > 0 && seat?.inputWindow() === "before");
17
+ if (waitedOn)
18
+ throw new Error(refused("called from a handler the leg is waiting on before it can take this input; answer { text } instead, or submit from a later event (turn.start / turn.complete)"));
19
+ if (seat === undefined)
20
+ return Object.freeze({ drop: "no running leg takes a prompt here" });
21
+ const answer = await seat.relay("extension", text, { frames: ctx.frames, origin: ctx.origin, extension: by, priority: "later", signal: ctx.signal });
22
+ return "entered" in answer ? Object.freeze({ text: answer.entered }) : Object.freeze({ drop: answer.drop });
23
+ };
24
+ }