@fungi.computer/oyster 0.33.0 → 0.34.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.
@@ -1,2 +1,2 @@
1
- /** The sandbox every installed App frame runs in, shell-mounted or not. */
2
- export declare const appSandbox = "allow-scripts allow-modals allow-popups allow-forms";
1
+ /** Apps stay opaque; external tabs need their own origin for preview cookies. */
2
+ export declare const appSandbox = "allow-scripts allow-modals allow-popups allow-popups-to-escape-sandbox allow-forms";
@@ -1,2 +1,2 @@
1
- /** The sandbox every installed App frame runs in, shell-mounted or not. */
2
- export const appSandbox = "allow-scripts allow-modals allow-popups allow-forms";
1
+ /** Apps stay opaque; external tabs need their own origin for preview cookies. */
2
+ export const appSandbox = "allow-scripts allow-modals allow-popups allow-popups-to-escape-sandbox allow-forms";
@@ -0,0 +1,2 @@
1
+ /** Pin a finite deadline before RPC so delayed delivery cannot renew a call. */
2
+ export declare function oysterApprovalDeadlineAt(deadlineAt: number | null): number;
@@ -0,0 +1,7 @@
1
+ // Mycelium's execute admission caps the live invocation at fifteen minutes.
2
+ const maximumCallMs = 900_000;
3
+ /** Pin a finite deadline before RPC so delayed delivery cannot renew a call. */
4
+ export function oysterApprovalDeadlineAt(deadlineAt) {
5
+ const maximum = Date.now() + maximumCallMs;
6
+ return Math.min(deadlineAt ?? maximum, maximum);
7
+ }
@@ -1,5 +1,5 @@
1
1
  import { z } from "zod";
2
- import { ApprovalLedger, type Approvals, type PendingApproval, type ApprovalApplyResult } from "@fungi.computer/approvals";
2
+ import { ApprovalLedger, type Approvals, type ApprovalApplyResult } from "@fungi.computer/approvals";
3
3
  import type { WatchdogSqliteOwner } from "@fungi.computer/watchdog";
4
4
  import type { OysterHost } from "./host.js";
5
5
  import type { HostActor } from "@fungi.computer/puffball/app";
@@ -25,13 +25,31 @@ declare const callSchema: z.ZodObject<{
25
25
  authorityFence: z.ZodString;
26
26
  idempotencyKey: z.ZodString;
27
27
  input: z.ZodJSONSchema;
28
+ deadlineAt: z.ZodNumber;
28
29
  }, z.core.$strict>;
29
30
  /** Host-generated App call metadata; the operation's input contains no actor or approval choice. */
30
31
  export type OysterApprovalCall = z.output<typeof callSchema>;
32
+ /** The originating call receives the output or this terminal decision, never a pending notice. */
33
+ export type OysterApprovalResult = Exclude<ApprovalApplyResult, {
34
+ kind: "refused";
35
+ }> | Readonly<{
36
+ kind: "denied";
37
+ by: string;
38
+ note?: string;
39
+ message: string;
40
+ }> | Readonly<{
41
+ kind: "refused";
42
+ reason: Exclude<Extract<ApprovalApplyResult, {
43
+ kind: "refused";
44
+ }>["reason"], "expired"> | "approval_expired" | "cancelled";
45
+ denialNote?: string;
46
+ }>;
31
47
  /** The registry's durable App effect home. Mycelium still owns operation/schema invocation. */
32
48
  export declare class OysterApprovalHome {
33
49
  private readonly host;
34
50
  readonly ledger: ApprovalLedger;
51
+ private readonly active;
52
+ private readonly waiting;
35
53
  private surfaces;
36
54
  constructor(host: Readonly<{
37
55
  owner: WatchdogSqliteOwner;
@@ -41,10 +59,15 @@ export declare class OysterApprovalHome {
41
59
  commit: <T>(write: () => Promise<T>, nextWakeAt: () => number | null) => Promise<T>;
42
60
  }>);
43
61
  private createLedger;
44
- submit(raw: OysterApprovalCall): Promise<PendingApproval | ApprovalApplyResult>;
62
+ submit(raw: OysterApprovalCall): Promise<OysterApprovalResult>;
63
+ /** Trusted host cancellation, pinned to the same caller and operation identity. */
64
+ cancel(raw: OysterApprovalCall): Promise<void>;
65
+ private pruneCancellations;
66
+ private nextWakeAt;
67
+ private run;
45
68
  /** Bind each read/decision to current membership, not the renderer's actor bytes. */
46
69
  capability(rawActor: HostActor): Approvals;
47
- /** One native alarm quantum; apply owns the fresh grant/fence check and single claim. */
70
+ /** Alarms expire records only. They never execute a former call's effect. */
48
71
  reconcile(): Promise<number | null>;
49
72
  private resolve;
50
73
  private execution;
@@ -5,6 +5,7 @@ import { ApprovalLedger, } from "@fungi.computer/approvals";
5
5
  import { invokeModuleOperation } from "@fungi.computer/mycelium/remote";
6
6
  import { keyAppAccess, oysterPrincipalIsOwner } from "./authorization.js";
7
7
  import { sha256 } from "./release.js";
8
+ const cancellationPruneLimit = 128;
8
9
  const identity = z.string().min(1).max(256);
9
10
  const targetSchema = z.strictObject({
10
11
  actor: hostActorSchema,
@@ -17,24 +18,54 @@ const callSchema = targetSchema.extend({
17
18
  authorityFence: identity,
18
19
  idempotencyKey: identity,
19
20
  input: z.json(),
21
+ deadlineAt: z.number().int().nonnegative(),
20
22
  });
23
+ /** Ledger lifecycle names stay internal; every tool uses the same expiry code. */
24
+ function callOutcome(result) {
25
+ return result.kind === "refused"
26
+ ? {
27
+ ...result,
28
+ reason: result.reason === "expired" ? "approval_expired" : result.reason,
29
+ }
30
+ : result;
31
+ }
32
+ function callKey(call) {
33
+ return JSON.stringify([
34
+ call.actor,
35
+ call.installationId,
36
+ call.sessionId,
37
+ call.operation,
38
+ call.idempotencyKey,
39
+ ]);
40
+ }
21
41
  const decodeJson = Schema.decodeUnknownSync(Schema.fromJsonString(Schema.Json));
22
42
  const intentRow = Schema.decodeUnknownSync(Schema.Struct({ target_json: Schema.String }));
43
+ const wakeRow = Schema.decodeUnknownSync(Schema.Struct({ at: Schema.NullOr(Schema.Number) }));
23
44
  /** The registry's durable App effect home. Mycelium still owns operation/schema invocation. */
24
45
  export class OysterApprovalHome {
25
46
  host;
26
47
  ledger;
48
+ active = new Map();
49
+ waiting = new Map();
27
50
  // The home's artifact store and capability configuration are fixed, unlike
28
51
  // the authority read fresh from current() for every recheck and dispatch.
29
52
  surfaces;
30
53
  constructor(host) {
31
54
  this.host = host;
32
55
  host.owner.sql.exec("CREATE TABLE IF NOT EXISTS oyster_approval_targets (record_id TEXT PRIMARY KEY, target_json TEXT NOT NULL) STRICT");
56
+ // A cancellation is terminal intent for this call identity, even if its
57
+ // submit RPC arrives later or this home restarts before it arrives.
58
+ host.owner.sql.exec("CREATE TABLE IF NOT EXISTS oyster_approval_cancellations (call_key TEXT PRIMARY KEY, expires_at INTEGER NOT NULL) STRICT");
59
+ host.owner.sql.exec("CREATE INDEX IF NOT EXISTS oyster_approval_cancellations_expiry ON oyster_approval_cancellations (expires_at)");
60
+ this.pruneCancellations();
33
61
  this.ledger = this.createLedger();
34
62
  // A new native home represents boot, before any live call can claim work.
35
63
  while (this.ledger.recoverClaims().length > 0) {
36
64
  // Each bounded batch settles part of the finite orphan set.
37
65
  }
66
+ while (this.ledger.withdrawWaiting() > 0) {
67
+ // No waiting call survived this native home's restart.
68
+ }
38
69
  }
39
70
  createLedger(persistIntent) {
40
71
  const home = { kind: "oyster", id: this.host.scope.tenantId };
@@ -46,6 +77,56 @@ export class OysterApprovalHome {
46
77
  async submit(raw) {
47
78
  // Maintained decoder snapshots the host's serialized call before any await.
48
79
  const call = callSchema.parse(raw);
80
+ // This check survives deletion of the marker: an expired envelope can
81
+ // never register fresh work, including an automatically approved write.
82
+ if (call.deadlineAt <= Date.now())
83
+ return { kind: "refused", reason: "approval_expired" };
84
+ const key = callKey(call);
85
+ if (this.host.owner.sql
86
+ .exec("SELECT call_key FROM oyster_approval_cancellations WHERE call_key = ?", key)
87
+ .toArray().length > 0)
88
+ return { kind: "refused", reason: "cancelled" };
89
+ if (this.active.has(key))
90
+ return { kind: "refused", reason: "in-flight" };
91
+ const controller = new AbortController();
92
+ this.active.set(key, controller);
93
+ try {
94
+ return await this.run(call, controller.signal);
95
+ }
96
+ finally {
97
+ this.active.delete(key);
98
+ }
99
+ }
100
+ /** Trusted host cancellation, pinned to the same caller and operation identity. */
101
+ async cancel(raw) {
102
+ const call = callSchema.parse(raw);
103
+ const key = callKey(call);
104
+ await this.host.commit(() => {
105
+ this.pruneCancellations();
106
+ this.host.owner.sql.exec("INSERT OR IGNORE INTO oyster_approval_cancellations (call_key, expires_at) VALUES (?, ?)", key, call.deadlineAt);
107
+ this.active.get(key)?.abort();
108
+ return Promise.resolve();
109
+ }, () => this.nextWakeAt());
110
+ }
111
+ pruneCancellations() {
112
+ this.host.owner.sql.exec("DELETE FROM oyster_approval_cancellations WHERE call_key IN (SELECT call_key FROM oyster_approval_cancellations WHERE expires_at <= ? ORDER BY expires_at LIMIT ?)", Date.now(), cancellationPruneLimit);
113
+ }
114
+ nextWakeAt() {
115
+ const cancellation = wakeRow(this.host.owner.sql
116
+ .exec("SELECT MIN(expires_at) AS at FROM oyster_approval_cancellations")
117
+ .toArray()[0]).at;
118
+ const approval = this.ledger.nextWakeAt();
119
+ if (cancellation === null)
120
+ return approval;
121
+ return approval === null ? cancellation : Math.min(approval, cancellation);
122
+ }
123
+ async run(call, signal) {
124
+ const cancelled = () => signal.aborted;
125
+ const expiresAt = Math.min(Date.now() + 5 * 60_000, call.deadlineAt - 30_000);
126
+ if (cancelled())
127
+ return { kind: "refused", reason: "cancelled" };
128
+ if (call.deadlineAt <= Date.now())
129
+ return { kind: "refused", reason: "approval_expired" };
49
130
  const actor = call.actor;
50
131
  const target = targetSchema.parse({
51
132
  actor: call.actor,
@@ -74,15 +155,56 @@ export class OysterApprovalHome {
74
155
  authorityFence: call.authorityFence,
75
156
  idempotencyKey: call.idempotencyKey,
76
157
  inputJson: JSON.stringify(call.input),
77
- }), () => ledger.nextWakeAt());
158
+ expiresAt,
159
+ }), () => this.nextWakeAt());
78
160
  if (staged.kind === "refused")
79
- return staged;
80
- // Only this call's own policy approval applies inline; a retry reports
81
- // status and leaves every other approved record to the home's work loop.
82
- if (!staged.created || staged.record.state !== "approved")
83
- return ledger.outcome(staged.record);
84
- // The native commit is complete before any external effect can run.
85
- return ledger.applyInline(staged.record.recordId, this.execution());
161
+ return callOutcome(staged);
162
+ const recordId = staged.record.recordId;
163
+ try {
164
+ if (ledger.get(recordId)?.state === "pending" && !cancelled())
165
+ await new Promise((resolve) => {
166
+ const finish = () => {
167
+ clearTimeout(timer);
168
+ signal.removeEventListener("abort", finish);
169
+ this.waiting.delete(recordId);
170
+ resolve();
171
+ };
172
+ const timer = setTimeout(finish, Math.max(0, expiresAt - Date.now()));
173
+ this.waiting.set(recordId, finish);
174
+ signal.addEventListener("abort", finish, { once: true });
175
+ // The answer may have arrived while the native commit was finishing.
176
+ if (cancelled() || ledger.get(recordId)?.state !== "pending")
177
+ finish();
178
+ });
179
+ if (cancelled())
180
+ return { kind: "refused", reason: "cancelled" };
181
+ const record = ledger.get(recordId);
182
+ if (record?.state === "denied" &&
183
+ record.reason === "declined" &&
184
+ record.by?.kind === "human") {
185
+ const by = record.by.memberId;
186
+ const denied = {
187
+ kind: "denied",
188
+ by,
189
+ message: `Denied by ${by}.${record.denialNote === undefined ? "" : ` User-provided note: ${JSON.stringify(record.denialNote)}`}`,
190
+ };
191
+ return record.denialNote === undefined
192
+ ? denied
193
+ : { ...denied, note: record.denialNote };
194
+ }
195
+ if (record?.state === "pending" || record?.state === "expired")
196
+ return { kind: "refused", reason: "approval_expired" };
197
+ if (record?.state === "approved" &&
198
+ record.by?.kind !== "policy" &&
199
+ Date.now() >= expiresAt)
200
+ return { kind: "refused", reason: "approval_expired" };
201
+ // Native commit completed before the waiting caller claims the effect.
202
+ const deadlineAt = Math.min(call.deadlineAt, Date.now() + 30_000);
203
+ return callOutcome(await ledger.apply(recordId, this.execution(signal, deadlineAt)));
204
+ }
205
+ finally {
206
+ ledger.withdraw(recordId);
207
+ }
86
208
  }
87
209
  /** Bind each read/decision to current membership, not the renderer's actor bytes. */
88
210
  capability(rawActor) {
@@ -108,17 +230,20 @@ export class OysterApprovalHome {
108
230
  (await this.resolve(record, actor)).kind === "authorized",
109
231
  };
110
232
  },
111
- decision: async (recordId) => {
112
- await this.ledger.apply(recordId, this.execution());
233
+ decision: (recordId) => {
234
+ this.waiting.get(recordId)?.();
235
+ return Promise.resolve();
113
236
  },
114
237
  });
115
238
  }
116
- /** One native alarm quantum; apply owns the fresh grant/fence check and single claim. */
117
- async reconcile() {
239
+ /** Alarms expire records only. They never execute a former call's effect. */
240
+ reconcile() {
241
+ this.pruneCancellations();
118
242
  this.ledger.expirePending();
119
- for (const recordId of this.ledger.pendingApplications())
120
- await this.ledger.apply(recordId, this.execution());
121
- return this.ledger.nextWakeAt();
243
+ for (const [recordId, finish] of this.waiting)
244
+ if (this.ledger.get(recordId)?.state !== "pending")
245
+ finish();
246
+ return Promise.resolve(this.nextWakeAt());
122
247
  }
123
248
  async resolve(record, answerer) {
124
249
  const raw = this.host.owner.sql
@@ -200,10 +325,16 @@ export class OysterApprovalHome {
200
325
  };
201
326
  return { kind: "authorized", module, fence };
202
327
  }
203
- execution() {
328
+ execution(callerSignal, deadlineAt) {
329
+ const signal = AbortSignal.any([
330
+ callerSignal,
331
+ AbortSignal.timeout(Math.max(0, deadlineAt - Date.now())),
332
+ ]);
204
333
  return {
205
334
  recheck: async (record) => {
335
+ signal.throwIfAborted();
206
336
  const current = await this.resolve(record);
337
+ signal.throwIfAborted();
207
338
  return current.kind === "refused"
208
339
  ? current
209
340
  : { kind: "authorized", authorityFence: current.fence };
@@ -211,12 +342,11 @@ export class OysterApprovalHome {
211
342
  dispatch: async ({ record, input }) => {
212
343
  // Reconstruct again at dispatch; never widen a captured operation or fence.
213
344
  const current = await this.resolve(record);
345
+ signal.throwIfAborted();
214
346
  if (current.kind === "refused")
215
347
  return current;
216
348
  if (current.fence !== record.authorityFence)
217
349
  return { kind: "refused", reason: "not-granted" };
218
- const deadlineAt = Date.now() + 30_000;
219
- const signal = AbortSignal.timeout(30_000);
220
350
  const output = await invokeModuleOperation(current.module, record.operation, input, {
221
351
  executionId: "approval:" + record.recordId,
222
352
  toolCallId: "approval:" + record.recordId,
@@ -1,6 +1,6 @@
1
1
  /** Installation records and pure admission rules; tenant state and commits stay host-owned. */
2
2
  export { applyGrantCommand, appAuthoritySchema, grantCommandSchema, type AppAuthority, type GrantCommand, type GrantContext, type GrantRefusal, applyInstallationCommand, approvedGrantSchema, declaredOperationsSchema, installationCommandSchema, installationIdSchema, installationRefusalSchema, installationSchema, type Approval, type ApprovedGrant, type CapabilityOperationDescriptor, type DeclaredOperations, grantChangeSchema, type GrantChange, type Installation, type InstallationCommand, type InstallationContext, type InstallationReader, type InstallationRefusal, type InstallationUpdate, type ResourceRef, unstampedFingerprint, } from "./installation.js";
3
- export { permissionPinsSchema, permissionSaveSchema, type PermissionPins, appPermissionsWireSchema, appPermissionPageSchema, permissionScreen, draftOf, editPermissions, planGrantChange, rebaseDraft, type PermissionDraft, type PermissionEdit, type PermissionScreen, type AppPermissionsWire, type AppPermissionsPort, type AppPermissionsViewData, grantRequestFor, pendingCapabilities, type GrantRequestDecision, type ResourceOption, } from "./permissions.js";
3
+ export { permissionPinsSchema, permissionSaveSchema, type PermissionPins, appPermissionsWireSchema, appPermissionPageSchema, permissionScreen, draftOf, editPermissions, planGrantChange, rebaseDraft, type PermissionDraft, type PermissionEdit, type PermissionScreen, type AppPermissionsWire, type AppPermissionsPort, type AppPermissionsViewData, grantRequestFor, pendingCapabilities, type GrantRequestDecision, appCallTargetName, type ResourceOption, } from "./permissions.js";
4
4
  export { admits, admitMethodMetadata, appInvocationCeiling, approvedBindingGrants, scopedBindings, grantsFor, gateRefusalSchema, gateRequestSchema, invocationGrantsSchema, type AppMethodDeclaration, type AppMethodMetadataDecision, type GateDecision, type GateFacts, type GateRequest, type HostPrincipal, type InvocationGrants, } from "./gate.js";
5
5
  export { deriveDeclaredOperations, appCallOperation } from "./operations.js";
6
6
  export { appToolPolicySchema, type AppToolAccess, type AppToolEntry, type AppToolPolicy, } from "./tools.js";
@@ -1,6 +1,6 @@
1
1
  /** Installation records and pure admission rules; tenant state and commits stay host-owned. */
2
2
  export { applyGrantCommand, appAuthoritySchema, grantCommandSchema, applyInstallationCommand, approvedGrantSchema, declaredOperationsSchema, installationCommandSchema, installationIdSchema, installationRefusalSchema, installationSchema, grantChangeSchema, unstampedFingerprint, } from "./installation.js";
3
- export { permissionPinsSchema, permissionSaveSchema, appPermissionsWireSchema, appPermissionPageSchema, permissionScreen, draftOf, editPermissions, planGrantChange, rebaseDraft, grantRequestFor, pendingCapabilities, } from "./permissions.js";
3
+ export { permissionPinsSchema, permissionSaveSchema, appPermissionsWireSchema, appPermissionPageSchema, permissionScreen, draftOf, editPermissions, planGrantChange, rebaseDraft, grantRequestFor, pendingCapabilities, appCallTargetName, } from "./permissions.js";
4
4
  export { admits, admitMethodMetadata, appInvocationCeiling, approvedBindingGrants, scopedBindings, grantsFor, gateRefusalSchema, gateRequestSchema, invocationGrantsSchema, } from "./gate.js";
5
5
  export { deriveDeclaredOperations, appCallOperation } from "./operations.js";
6
6
  export { appToolPolicySchema, } from "./tools.js";