@ai-matrx/alchemy 0.8.60 → 0.10.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.
- package/CHANGELOG.md +60 -0
- package/README.md +3 -0
- package/dist/actions.cjs +1 -1
- package/dist/actions.cjs.map +1 -1
- package/dist/actions.d.cts +465 -4
- package/dist/actions.d.ts +465 -4
- package/dist/actions.js +1 -1
- package/dist/actions.js.map +1 -1
- package/dist/checks.cjs +1 -1
- package/dist/checks.cjs.map +1 -1
- package/dist/checks.d.cts +22 -1
- package/dist/checks.d.ts +22 -1
- package/dist/checks.js +2 -2
- package/dist/checks.js.map +1 -1
- package/dist/core.cjs +1 -1
- package/dist/core.cjs.map +1 -1
- package/dist/core.d.cts +283 -39
- package/dist/core.d.ts +283 -39
- package/dist/core.js +2 -2
- package/dist/core.js.map +1 -1
- package/dist/declare.cjs +1 -1
- package/dist/declare.cjs.map +1 -1
- package/dist/declare.d.cts +12 -4
- package/dist/declare.d.ts +12 -4
- package/dist/declare.js +1 -1
- package/dist/declare.js.map +1 -1
- package/dist/index.cjs +1 -1
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +283 -39
- package/dist/index.d.ts +283 -39
- package/dist/index.js +2 -2
- package/dist/index.js.map +1 -1
- package/dist/menu.cjs +1 -1
- package/dist/menu.cjs.map +1 -1
- package/dist/menu.d.cts +262 -3
- package/dist/menu.d.ts +262 -3
- package/dist/menu.js +1 -1
- package/dist/menu.js.map +1 -1
- package/dist/operate-server.d.cts +11 -1
- package/dist/operate-server.d.ts +11 -1
- package/dist/operate.cjs +1 -1
- package/dist/operate.cjs.map +1 -1
- package/dist/operate.d.cts +283 -39
- package/dist/operate.d.ts +283 -39
- package/dist/operate.js +2 -2
- package/dist/operate.js.map +1 -1
- package/dist/ports.cjs.map +1 -1
- package/dist/ports.d.cts +269 -2
- package/dist/ports.d.ts +269 -2
- package/dist/react-bar.cjs +1 -1
- package/dist/react-bar.cjs.map +1 -1
- package/dist/react-bar.d.cts +4 -2
- package/dist/react-bar.d.ts +4 -2
- package/dist/react-bar.js +1 -1
- package/dist/react-bar.js.map +1 -1
- package/dist/react-host.d.cts +262 -3
- package/dist/react-host.d.ts +262 -3
- package/dist/react-menu.cjs +1 -1
- package/dist/react-menu.cjs.map +1 -1
- package/dist/react-menu.d.cts +4 -2
- package/dist/react-menu.d.ts +4 -2
- package/dist/react-menu.js +1 -1
- package/dist/react-menu.js.map +1 -1
- package/dist/react-overflow.cjs +1 -1
- package/dist/react-overflow.cjs.map +1 -1
- package/dist/react-overflow.d.cts +262 -3
- package/dist/react-overflow.d.ts +262 -3
- package/dist/react-overflow.js +1 -1
- package/dist/react-overflow.js.map +1 -1
- package/dist/react-palette.cjs +1 -1
- package/dist/react-palette.cjs.map +1 -1
- package/dist/react-palette.d.cts +4 -2
- package/dist/react-palette.d.ts +4 -2
- package/dist/react-palette.js +1 -1
- package/dist/react-palette.js.map +1 -1
- package/dist/react-selection.cjs +1 -1
- package/dist/react-selection.cjs.map +1 -1
- package/dist/react-selection.d.cts +4 -2
- package/dist/react-selection.d.ts +4 -2
- package/dist/react-selection.js +1 -1
- package/dist/react-selection.js.map +1 -1
- package/dist/react-sheet.cjs +1 -1
- package/dist/react-sheet.cjs.map +1 -1
- package/dist/react-sheet.d.cts +4 -2
- package/dist/react-sheet.d.ts +4 -2
- package/dist/react-sheet.js +1 -1
- package/dist/react-sheet.js.map +1 -1
- package/package.json +1 -1
package/dist/actions.d.ts
CHANGED
|
@@ -250,6 +250,308 @@ interface ClickTarget {
|
|
|
250
250
|
host?: unknown;
|
|
251
251
|
}
|
|
252
252
|
|
|
253
|
+
/**
|
|
254
|
+
* Operate — the format and delivery contract (Matrx Alchemy CONTRACT §2.3, ALC-16).
|
|
255
|
+
*
|
|
256
|
+
* A format is an ADAPTER: `supports` is synchronous and loads nothing; `load` dynamically
|
|
257
|
+
* imports the engine the first time the format is chosen (print for rich-html/html/pdf/docx/
|
|
258
|
+
* epub, SheetJS for xlsx). Delivery accepts only a SEALED artifact, so the bytes previewed are
|
|
259
|
+
* the bytes copied, downloaded or sent.
|
|
260
|
+
*/
|
|
261
|
+
|
|
262
|
+
/** A reference to a declared write target (resolved by the one write door, ALC-17). */
|
|
263
|
+
interface WriteTargetRef {
|
|
264
|
+
surfaceName?: string;
|
|
265
|
+
target: string;
|
|
266
|
+
item?: {
|
|
267
|
+
itemType: string;
|
|
268
|
+
identity: Record<string, string>;
|
|
269
|
+
};
|
|
270
|
+
}
|
|
271
|
+
/**
|
|
272
|
+
* Every write returns one (CONTRACT §2.3; the door is `createWriteDoor`, ALC-17). An applied
|
|
273
|
+
* receipt may carry a `warning` with its `fix` (rule 10: a person's kind mismatch warns, never refuses).
|
|
274
|
+
* A refusal's `reason` is a `WriteRefusalReason` (`./door`).
|
|
275
|
+
*/
|
|
276
|
+
type Receipt = {
|
|
277
|
+
status: "applied";
|
|
278
|
+
to: WriteTargetRef;
|
|
279
|
+
sentence: string;
|
|
280
|
+
warning?: string;
|
|
281
|
+
fix?: string;
|
|
282
|
+
} | {
|
|
283
|
+
status: "queued";
|
|
284
|
+
to: WriteTargetRef;
|
|
285
|
+
sentence: string;
|
|
286
|
+
remedy: string;
|
|
287
|
+
} | {
|
|
288
|
+
status: "refused";
|
|
289
|
+
to: WriteTargetRef;
|
|
290
|
+
reason: string;
|
|
291
|
+
sentence: string;
|
|
292
|
+
remedy: string;
|
|
293
|
+
};
|
|
294
|
+
|
|
295
|
+
/**
|
|
296
|
+
* THE ONE WRITE DOOR (Matrx Alchemy ALC-17; Applets CONTRACTS §6 "receipts through the one write door").
|
|
297
|
+
*
|
|
298
|
+
* Every write — a person's edit, a menu row, a destination send, an agent, an applet, an automation,
|
|
299
|
+
* an Action projected from a write target — lands through `door.write`. The door:
|
|
300
|
+
*
|
|
301
|
+
* 1. resolves the DECLARED write target (the surface's own, then its ancestors'); an undeclared
|
|
302
|
+
* target is refused by name;
|
|
303
|
+
* 2. enforces the mode: `stream` takes ops from the target's `streamOps`; ops on any other target
|
|
304
|
+
* need `patchable` (+ `updatesValue`); a value on a `stream` target is refused;
|
|
305
|
+
* 3. checks the kind (rule 10): a person's mismatch WARNS (the receipt is still applied, with a
|
|
306
|
+
* `warning` and a `fix`); an agent's, applet's or automation's malformed write is REFUSED;
|
|
307
|
+
* 4. applies the policy: manual → a person only; ask → a person's own act is the approval, anyone
|
|
308
|
+
* else asks through `approvals`; queued → filed through `review`; auto → applies;
|
|
309
|
+
* 5. applies through the handler: the mounted page's LIVE handler wins over the HEADLESS one;
|
|
310
|
+
* neither → refused `unapplicable` ("open <surface> to apply it");
|
|
311
|
+
* 6. turns stale / missing record / broken protected span into "cannot apply" with a one-click
|
|
312
|
+
* remedy (rule 11).
|
|
313
|
+
*
|
|
314
|
+
* Every outcome is a `Receipt` carrying the system's own sentence. `write` never throws.
|
|
315
|
+
*
|
|
316
|
+
* Who counts as a person: `person`, `menu` and `destination` (a destination send is a person's own
|
|
317
|
+
* click on "Send to …"). `agent`, `applet` and `automation` are not.
|
|
318
|
+
*
|
|
319
|
+
* Open-risk ruling — stream ops into an entity target: an entity write is ONE atomic save. Ops reach
|
|
320
|
+
* an entity target only when it is declared `patchable` (the ops are handed to the handler in one
|
|
321
|
+
* call and commit as one save); a non-patchable entity target refuses ops with the remedy "stream
|
|
322
|
+
* into the editor, then save". Op-by-op persistence into a record does not exist.
|
|
323
|
+
*/
|
|
324
|
+
|
|
325
|
+
/** Who is writing. `menu` and `destination` are a person's own act. */
|
|
326
|
+
type WriteCaller = "person" | "agent" | "applet" | "automation" | "destination" | "menu";
|
|
327
|
+
/** One text op for a `stream` (or `patchable`) target — the WidgetHandle op set. */
|
|
328
|
+
interface WriteOp {
|
|
329
|
+
op: StreamOp;
|
|
330
|
+
/** The text the op inserts or replaces with. */
|
|
331
|
+
text?: string;
|
|
332
|
+
/** What `replace` / `insert_before` / `insert_after` / `patch` anchor on. */
|
|
333
|
+
find?: string;
|
|
334
|
+
}
|
|
335
|
+
interface WriteRequest {
|
|
336
|
+
surfaceName: string;
|
|
337
|
+
/** A write target name; `"<itemType>.<name>"` names an item's target. */
|
|
338
|
+
target: string;
|
|
339
|
+
itemType?: string;
|
|
340
|
+
/** Which item, by its declared identity values. Required for an item target. */
|
|
341
|
+
itemIdentity?: Record<string, string>;
|
|
342
|
+
/** A whole value. Exactly one of `value` / `ops`. */
|
|
343
|
+
value?: unknown;
|
|
344
|
+
/** Text ops (stream / patchable targets). */
|
|
345
|
+
ops?: readonly WriteOp[];
|
|
346
|
+
by: WriteCaller;
|
|
347
|
+
runId?: string;
|
|
348
|
+
}
|
|
349
|
+
/** What a handler receives: the request plus the declared target it resolved to. */
|
|
350
|
+
interface WriteApplyRequest {
|
|
351
|
+
surfaceName: string;
|
|
352
|
+
/** The surface that declares the target (an ancestor when inherited). */
|
|
353
|
+
declaredOn: string;
|
|
354
|
+
target: WriteTarget;
|
|
355
|
+
item?: {
|
|
356
|
+
itemType: string;
|
|
357
|
+
identity: Record<string, string>;
|
|
358
|
+
};
|
|
359
|
+
value?: unknown;
|
|
360
|
+
ops?: readonly WriteOp[];
|
|
361
|
+
by: WriteCaller;
|
|
362
|
+
runId?: string;
|
|
363
|
+
}
|
|
364
|
+
/** Rule 11: the three "cannot apply" signals. */
|
|
365
|
+
type CannotApply = "stale" | "missing-record" | "broken-span";
|
|
366
|
+
/**
|
|
367
|
+
* A handler applies the write. Return nothing (or `{ status: "applied" }`) when it landed, or a
|
|
368
|
+
* `cannotApply` signal; THROWING an error whose `code` is a `CannotApply` signal means the same.
|
|
369
|
+
*/
|
|
370
|
+
type WriteHandlerResult = void | {
|
|
371
|
+
status: "applied";
|
|
372
|
+
sentence?: string;
|
|
373
|
+
} | {
|
|
374
|
+
status: "cannot-apply";
|
|
375
|
+
cannotApply: CannotApply;
|
|
376
|
+
sentence?: string;
|
|
377
|
+
remedy?: string;
|
|
378
|
+
};
|
|
379
|
+
type WriteHandler = (request: WriteApplyRequest, signal: AbortSignal) => WriteHandlerResult | Promise<WriteHandlerResult>;
|
|
380
|
+
/** Files a `queued` write for an organization's review. */
|
|
381
|
+
interface WriteReviewPort {
|
|
382
|
+
file(request: WriteApplyRequest): Promise<{
|
|
383
|
+
sentence?: string;
|
|
384
|
+
remedy?: string;
|
|
385
|
+
} | void>;
|
|
386
|
+
}
|
|
387
|
+
interface WriteDoor {
|
|
388
|
+
write(request: WriteRequest, signal?: AbortSignal): Promise<Receipt>;
|
|
389
|
+
/** A feature's write handler that works with no page mounted. Refuses a second one for the same target. */
|
|
390
|
+
registerHeadless(surfaceName: string, targetName: string, handler: WriteHandler): () => void;
|
|
391
|
+
/** A mounted page's handler; wins over the headless one while registered. Returns unregister. */
|
|
392
|
+
registerLive(surfaceName: string, targetName: string, handler: WriteHandler): () => void;
|
|
393
|
+
}
|
|
394
|
+
|
|
395
|
+
/**
|
|
396
|
+
* Surface Actions — the shapes (Applets CONTRACTS §6, FROZEN; exported here as a superset).
|
|
397
|
+
*
|
|
398
|
+
* An Action is one thing a surface can have done to it, by a person, an agent,
|
|
399
|
+
* an applet or an automation: a write target, a client tool, a Kind Action or a
|
|
400
|
+
* row in `ui.ui_surface_action`. All of them project onto `ActionDeclaration`
|
|
401
|
+
* (`./declarations.ts`) and run through ONE runner (`./surface-run.ts`). There is
|
|
402
|
+
* never a second registry: `name` IS the alchemy action id, and `category`
|
|
403
|
+
* defaults to "applet" in alchemy's closed `ActionCategory` union.
|
|
404
|
+
*
|
|
405
|
+
* Types only — no runtime code, no React, no `@ai-matrx/agents`. `/ports`
|
|
406
|
+
* imports from here, so this file imports nothing but local types.
|
|
407
|
+
*/
|
|
408
|
+
|
|
409
|
+
/** Who started a run. */
|
|
410
|
+
type ActionCaller = "person" | "agent" | "applet" | "automation";
|
|
411
|
+
/** Where a run goes: the page's own handler, an aidream server action, a mandate, or a route. */
|
|
412
|
+
type ActionRuns = "page" | "server" | "mandate" | "navigate";
|
|
413
|
+
/** Who may run it without a click: "manual" = only a person; "ask" = proposed first; "auto" = runs. */
|
|
414
|
+
type ActionPolicy = "ask" | "auto" | "manual";
|
|
415
|
+
/** A registered kind slug (`KindRef`, content-ir) or an inline JSON Schema. */
|
|
416
|
+
type ActionInput = string | {
|
|
417
|
+
jsonSchema: object;
|
|
418
|
+
};
|
|
419
|
+
/** Who authored the row (`ui.ui_surface*.declared_by`). Code sync touches only "code". */
|
|
420
|
+
type ActionDeclaredBy = "code" | "database";
|
|
421
|
+
/** The write-target modes (WriteMode), kept losslessly. CONTRACTS §6 names three; "stream" is the superset. */
|
|
422
|
+
type ActionWriteMode = "ui" | "draft" | "entity" | "stream";
|
|
423
|
+
/** Where the Action came from — superset field so a projection loses nothing. */
|
|
424
|
+
interface ActionOrigin {
|
|
425
|
+
source: "write-target" | "client-tool" | "surface-action";
|
|
426
|
+
surfaceName?: string;
|
|
427
|
+
surfaceId?: string;
|
|
428
|
+
/** The source row's id, when it came from a row. */
|
|
429
|
+
id?: string;
|
|
430
|
+
declaredBy?: ActionDeclaredBy;
|
|
431
|
+
/** `ui.ui_surface_action.code_ref`: the code item a database Action names. */
|
|
432
|
+
codeRef?: string;
|
|
433
|
+
}
|
|
434
|
+
interface ActionDeclaration {
|
|
435
|
+
/** The Action's unique id within its chain (alchemy's `Action.id`). */
|
|
436
|
+
name: string;
|
|
437
|
+
/** Defaults to "applet". A value of alchemy's `ActionCategory` union. */
|
|
438
|
+
category?: string;
|
|
439
|
+
label: string;
|
|
440
|
+
description: string;
|
|
441
|
+
input?: ActionInput;
|
|
442
|
+
/** KindRef of what the run returns. */
|
|
443
|
+
output?: string;
|
|
444
|
+
runs: ActionRuns;
|
|
445
|
+
/** Server action name | mandate alias | route. `{param}` placeholders are filled from the input. */
|
|
446
|
+
target?: string;
|
|
447
|
+
triggeredBy: ActionCaller[];
|
|
448
|
+
policy: ActionPolicy;
|
|
449
|
+
updatesValue?: string;
|
|
450
|
+
mode?: ActionWriteMode;
|
|
451
|
+
patchable?: boolean;
|
|
452
|
+
approvalComparison?: string;
|
|
453
|
+
streamOps?: string[];
|
|
454
|
+
/** CONTRACTS §6 types it `string`; a write target's is a boolean flag. */
|
|
455
|
+
destination?: string | boolean;
|
|
456
|
+
groupKey?: string;
|
|
457
|
+
itemType?: string;
|
|
458
|
+
/** The write target's own apply policy, kept when it differs from `policy` ("queued" → policy "ask"). */
|
|
459
|
+
applyPolicy?: "manual" | "ask" | "auto" | "queued";
|
|
460
|
+
valueType?: string;
|
|
461
|
+
valueKind?: string;
|
|
462
|
+
sortOrder?: number;
|
|
463
|
+
origin?: ActionOrigin;
|
|
464
|
+
}
|
|
465
|
+
/** JSON only: what a lister (an agent, the menu, an applet) sees. */
|
|
466
|
+
interface ActionInfo {
|
|
467
|
+
name: string;
|
|
468
|
+
category: string;
|
|
469
|
+
label: string;
|
|
470
|
+
description: string;
|
|
471
|
+
runs: ActionRuns;
|
|
472
|
+
policy: ActionPolicy;
|
|
473
|
+
triggeredBy: ActionCaller[];
|
|
474
|
+
input?: ActionInput;
|
|
475
|
+
output?: string;
|
|
476
|
+
/** The surface that declared it (a child's override names the child). */
|
|
477
|
+
declaredOn: string;
|
|
478
|
+
target?: string;
|
|
479
|
+
updatesValue?: string;
|
|
480
|
+
itemType?: string;
|
|
481
|
+
/** Where it came from. "write-target" Actions go through the write door when one is bound (ALC-17). */
|
|
482
|
+
source?: ActionOrigin["source"];
|
|
483
|
+
}
|
|
484
|
+
interface ActionContext {
|
|
485
|
+
runId: string;
|
|
486
|
+
by: ActionCaller;
|
|
487
|
+
viewerId: string | null;
|
|
488
|
+
surfaceName?: string;
|
|
489
|
+
policy?: ActionPolicy;
|
|
490
|
+
}
|
|
491
|
+
/** The system's own sentence, never thrown into a UI. Superset of RecordsError (CONTRACTS §0 `AppletError`). */
|
|
492
|
+
interface ActionError {
|
|
493
|
+
code: string;
|
|
494
|
+
message: string;
|
|
495
|
+
retryable: boolean;
|
|
496
|
+
diagnostic?: string;
|
|
497
|
+
/** Superset: the one-click remedy a write door refusal names. */
|
|
498
|
+
remedy?: string;
|
|
499
|
+
}
|
|
500
|
+
/** CONTRACTS §0 `Result<T>`. */
|
|
501
|
+
type ActionResult<T = unknown> = {
|
|
502
|
+
ok: true;
|
|
503
|
+
data: T;
|
|
504
|
+
} | {
|
|
505
|
+
ok: false;
|
|
506
|
+
error: ActionError;
|
|
507
|
+
};
|
|
508
|
+
/** `POST /actions/run` (aidream) — the request. */
|
|
509
|
+
interface ServerActionRunRequest {
|
|
510
|
+
name: string;
|
|
511
|
+
input: Json$1;
|
|
512
|
+
by: ActionCaller;
|
|
513
|
+
surface_name?: string;
|
|
514
|
+
policy?: ActionPolicy;
|
|
515
|
+
}
|
|
516
|
+
/** `POST /actions/run` (aidream) — the response. */
|
|
517
|
+
interface ServerActionRunResponse {
|
|
518
|
+
status: "applied" | "proposed" | "refused";
|
|
519
|
+
message: string;
|
|
520
|
+
receipts: Json$1[];
|
|
521
|
+
proposal?: Json$1;
|
|
522
|
+
}
|
|
523
|
+
/** A mandate run request: by alias (an Action's `target`) or by key. */
|
|
524
|
+
type MandateRunRequest = ({
|
|
525
|
+
alias: string;
|
|
526
|
+
key?: never;
|
|
527
|
+
} | {
|
|
528
|
+
key: string;
|
|
529
|
+
alias?: never;
|
|
530
|
+
}) & {
|
|
531
|
+
variables: Record<string, Json$1>;
|
|
532
|
+
userInput?: string;
|
|
533
|
+
by: ActionCaller;
|
|
534
|
+
policy: ActionPolicy;
|
|
535
|
+
};
|
|
536
|
+
/**
|
|
537
|
+
* CONTRACTS §6 `SurfacePort` — the surface runtime as the frame sees it. Types
|
|
538
|
+
* only here; the in-page host is AP-0's.
|
|
539
|
+
*/
|
|
540
|
+
interface SurfacePort {
|
|
541
|
+
/** Joins the runtime chain. */
|
|
542
|
+
mount(name: string, parent: string | null): Promise<ActionResult<{
|
|
543
|
+
mountId: string;
|
|
544
|
+
}>>;
|
|
545
|
+
unmount(mountId: string): Promise<void>;
|
|
546
|
+
getValue(name: string): Promise<unknown>;
|
|
547
|
+
setValue(name: string, v: unknown): Promise<void>;
|
|
548
|
+
/** This mount's own Actions plus inherited ones. */
|
|
549
|
+
listActions(): Promise<ActionInfo[]>;
|
|
550
|
+
runAction(name: string, input: unknown, by: ActionCaller): Promise<ActionResult<unknown>>;
|
|
551
|
+
/** A "page" Action is routed to the frame as `{ action, input, runId }`; the frame answers here. */
|
|
552
|
+
completeAction(runId: string, result: ActionResult<unknown>): Promise<void>;
|
|
553
|
+
}
|
|
554
|
+
|
|
253
555
|
/**
|
|
254
556
|
* `@ai-matrx/alchemy/ports` — the host ports (Matrx Alchemy CONTRACT §2.2).
|
|
255
557
|
*
|
|
@@ -268,7 +570,7 @@ interface ClickTarget {
|
|
|
268
570
|
* PP-01a `window` (host-rendered windows for a live preparation session)
|
|
269
571
|
* PP-13a `transferKnobs` (organization default recipes)
|
|
270
572
|
*
|
|
271
|
-
*
|
|
573
|
+
* ALC-17 `door` (the one write door), `review` (queued writes)
|
|
272
574
|
*
|
|
273
575
|
* ── Absent-port semantics ───────────────────────────────────────────────────
|
|
274
576
|
*
|
|
@@ -298,6 +600,16 @@ interface ClickTarget {
|
|
|
298
600
|
* to an overlay carrying the session as data)
|
|
299
601
|
* transferKnobs absent → no organization default recipe; a person's own
|
|
300
602
|
* default (persistence) or the package's Full applies
|
|
603
|
+
* serverActions absent → `runs: "server"` Actions refuse with "not available here"
|
|
604
|
+
* mandates absent → `runs: "mandate"` Actions refuse the same way
|
|
605
|
+
* pageActions absent → `runs: "page"` Actions refuse the same way
|
|
606
|
+
* approvals absent → a policy "ask" Action started by an agent, applet or automation is refused
|
|
607
|
+
* ("needs a person's approval"); a person's own click is the approval
|
|
608
|
+
* (`runs: "navigate"` goes through `overlay.navigate`; overlay absent → refused)
|
|
609
|
+
* door absent → write-target Actions dispatch to `pageActions` as before, and
|
|
610
|
+
* `Delivery.send` is refused with a remedy; bound → every such write goes
|
|
611
|
+
* through it and returns its receipt
|
|
612
|
+
* review absent → a write to a `queued` target is refused ("review isn't available here")
|
|
301
613
|
*
|
|
302
614
|
* Types only: this entry has no runtime code.
|
|
303
615
|
*/
|
|
@@ -443,6 +755,40 @@ interface AlchemyHostPorts {
|
|
|
443
755
|
window?: WindowPort;
|
|
444
756
|
/** Organization default recipes, resolved by the host's Feature Knob ladder (platform → organization). */
|
|
445
757
|
transferKnobs?: TransferKnobsPort;
|
|
758
|
+
/** aidream `POST /actions/run`: a registered server action by name, as the caller, under the apply-policy cascade. */
|
|
759
|
+
serverActions?: ServerActionPort;
|
|
760
|
+
/** Runs a mandate by alias or key (the host binds `@ai-matrx/agents`; alchemy never imports it). */
|
|
761
|
+
mandates?: MandatePort;
|
|
762
|
+
/** The page's own handlers for `runs: "page"` Actions (in an applet frame: routed as `{ action, input, runId }`). */
|
|
763
|
+
pageActions?: PageActionPort;
|
|
764
|
+
/** Asks a person, in place, to approve an `ask` Action that an agent, applet or automation started. */
|
|
765
|
+
approvals?: ApprovalPort;
|
|
766
|
+
/** `createWriteDoor(...)`: every write to a declared target lands here and returns a receipt. */
|
|
767
|
+
door?: WriteDoor;
|
|
768
|
+
/** Files a write to a `queued` target for an organization's review. */
|
|
769
|
+
review?: WriteReviewPort;
|
|
770
|
+
}
|
|
771
|
+
interface ServerActionPort {
|
|
772
|
+
run(request: ServerActionRunRequest): Promise<ServerActionRunResponse>;
|
|
773
|
+
}
|
|
774
|
+
interface MandatePort {
|
|
775
|
+
/** Resolves with the run's result (a kind envelope or JSON); rejects with the system's sentence. */
|
|
776
|
+
run(request: MandateRunRequest): Promise<unknown>;
|
|
777
|
+
}
|
|
778
|
+
interface ApprovalRequest {
|
|
779
|
+
action: string;
|
|
780
|
+
label: string;
|
|
781
|
+
description: string;
|
|
782
|
+
input: Json;
|
|
783
|
+
by: "agent" | "applet" | "automation";
|
|
784
|
+
surfaceName: string;
|
|
785
|
+
}
|
|
786
|
+
interface ApprovalPort {
|
|
787
|
+
/** Resolves true when the person approves; false when they decline or dismiss. */
|
|
788
|
+
ask(request: ApprovalRequest): Promise<boolean>;
|
|
789
|
+
}
|
|
790
|
+
interface PageActionPort {
|
|
791
|
+
dispatch(name: string, input: unknown, context: ActionContext): Promise<ActionResult<unknown>>;
|
|
446
792
|
}
|
|
447
793
|
/**
|
|
448
794
|
* Why a port and not `OverlayHostPort`: an overlay's `data` is `Json`, and a live preparation
|
|
@@ -596,8 +942,10 @@ type Eligibility = {
|
|
|
596
942
|
status: "unavailable";
|
|
597
943
|
sentence: string;
|
|
598
944
|
};
|
|
599
|
-
/** rich-document's ActionCategory, unchanged, plus the three the context menu groups by. */
|
|
600
|
-
type ActionCategory = "feedback" | "copy" | "export" | "save" | "edit" | "share" | "creator" | "app" | "listen" | "study" | "ask" | "ai" | "admin" | "clipboard" | "history" | "surface-info"
|
|
945
|
+
/** rich-document's ActionCategory, unchanged, plus the three the context menu groups by, plus "applet" (surface Actions). */
|
|
946
|
+
type ActionCategory = "feedback" | "copy" | "export" | "save" | "edit" | "share" | "creator" | "app" | "listen" | "study" | "ask" | "ai" | "admin" | "clipboard" | "history" | "surface-info"
|
|
947
|
+
/** Surface Actions (Applets CONTRACTS §6): the default category of an `ActionDeclaration`. */
|
|
948
|
+
| "applet";
|
|
601
949
|
declare const ACTION_CATEGORIES: readonly ActionCategory[];
|
|
602
950
|
/**
|
|
603
951
|
* An optional named section inside the action's group (a grid's cell / row /
|
|
@@ -871,4 +1219,117 @@ type RunResult = {
|
|
|
871
1219
|
};
|
|
872
1220
|
declare function runAction(action: Action, target: ClickTarget, options: RunActionOptions): Promise<RunResult>;
|
|
873
1221
|
|
|
874
|
-
|
|
1222
|
+
/** Default `category` of an Action that names none. */
|
|
1223
|
+
declare const APPLET_CATEGORY = "applet";
|
|
1224
|
+
/** The DB default of `ui.ui_surface_action.triggered_by`, used where a source carries no list. */
|
|
1225
|
+
declare const DEFAULT_TRIGGERED_BY: readonly ActionCaller[];
|
|
1226
|
+
declare const ACTION_CALLERS: readonly ActionCaller[];
|
|
1227
|
+
declare const ACTION_RUNS: readonly ActionRuns[];
|
|
1228
|
+
declare const ACTION_POLICIES: readonly ActionPolicy[];
|
|
1229
|
+
/** A `ui.ui_surface_client_tool` row (live columns that carry meaning). */
|
|
1230
|
+
interface ClientToolRow {
|
|
1231
|
+
id?: string;
|
|
1232
|
+
surface_name: string;
|
|
1233
|
+
name: string;
|
|
1234
|
+
label: string;
|
|
1235
|
+
description: string;
|
|
1236
|
+
input_schema: Json$1;
|
|
1237
|
+
/** Live values: "ui" (applied directly) | "draft" (proposed for review). */
|
|
1238
|
+
mode: "ui" | "draft";
|
|
1239
|
+
declared_by?: ActionDeclaredBy;
|
|
1240
|
+
}
|
|
1241
|
+
/** A `ui.ui_surface_action` row. */
|
|
1242
|
+
interface SurfaceActionRow {
|
|
1243
|
+
id?: string;
|
|
1244
|
+
surface_id: string;
|
|
1245
|
+
surface_name: string;
|
|
1246
|
+
/** '' = the screen itself. */
|
|
1247
|
+
item_type: string;
|
|
1248
|
+
name: string;
|
|
1249
|
+
category: string;
|
|
1250
|
+
label: string;
|
|
1251
|
+
description: string;
|
|
1252
|
+
input: ActionInput | null;
|
|
1253
|
+
output: string | null;
|
|
1254
|
+
runs: ActionRuns;
|
|
1255
|
+
target: string | null;
|
|
1256
|
+
triggered_by: ActionCaller[];
|
|
1257
|
+
policy: ActionPolicy;
|
|
1258
|
+
updates_value: string | null;
|
|
1259
|
+
code_ref: string | null;
|
|
1260
|
+
declared_by: ActionDeclaredBy;
|
|
1261
|
+
sort_order: number;
|
|
1262
|
+
}
|
|
1263
|
+
/** A declared write target → an Action that runs on the page. */
|
|
1264
|
+
declare function writeTargetToAction(target: WriteTarget): ActionDeclaration;
|
|
1265
|
+
/** A client tool row → an Action an agent runs on the page ("draft" tools are proposed first). */
|
|
1266
|
+
declare function clientToolToAction(row: ClientToolRow): ActionDeclaration;
|
|
1267
|
+
/** A `ui.ui_surface_action` row → its Action. */
|
|
1268
|
+
declare function surfaceActionRowToAction(row: SurfaceActionRow): ActionDeclaration;
|
|
1269
|
+
/** JSON-only view of an Action as declared on `declaredOn`. */
|
|
1270
|
+
declare function toActionInfo(declaration: ActionDeclaration, declaredOn: string): ActionInfo;
|
|
1271
|
+
interface ActionChainLink {
|
|
1272
|
+
surfaceName: string;
|
|
1273
|
+
actions: readonly ActionDeclaration[];
|
|
1274
|
+
}
|
|
1275
|
+
/**
|
|
1276
|
+
* The Actions a mount sees: its own plus every ancestor's, a child winning by
|
|
1277
|
+
* name. `chain` runs MOST GENERAL FIRST (root parent … the mounted surface),
|
|
1278
|
+
* as `DeclarationRegistry` resolves inheritance. Guards are loud, like the
|
|
1279
|
+
* declaration registry's: a surface twice in the chain is a cycle, more
|
|
1280
|
+
* ancestors than `maxDepth` throws, and one surface naming an Action twice throws.
|
|
1281
|
+
*/
|
|
1282
|
+
declare function resolveActionChain(chain: readonly ActionChainLink[], options?: {
|
|
1283
|
+
maxDepth?: number;
|
|
1284
|
+
}): ActionInfo[];
|
|
1285
|
+
|
|
1286
|
+
/**
|
|
1287
|
+
* THE ONE RUNNER for surface Actions (Applets CONTRACTS §6). Every caller — a
|
|
1288
|
+
* person's click, an agent, an applet, an automation — runs an Action through
|
|
1289
|
+
* here, so policy and caller rules live once.
|
|
1290
|
+
*
|
|
1291
|
+
* Policy "ask": a person's own click is the approval. Started by an agent, applet or automation,
|
|
1292
|
+
* a "server" run carries the policy to aidream (which answers with a proposal); every other run
|
|
1293
|
+
* asks the person through `ports.approvals` first, and is refused by name without that port.
|
|
1294
|
+
*
|
|
1295
|
+
* Dispatch by `runs`:
|
|
1296
|
+
* "server" → `ports.serverActions.run({ name: target, input, by, surface_name, policy })`
|
|
1297
|
+
* "mandate" → `ports.mandates.run({ alias: target, variables, by, policy })`
|
|
1298
|
+
* "navigate" → `ports.overlay.navigate(target)` with `{param}` filled from the input
|
|
1299
|
+
* "page" → `ports.pageActions.dispatch(name, input, context)`
|
|
1300
|
+
* A port the host did not bind means that capability is ABSENT: the run is
|
|
1301
|
+
* refused with a sentence, never stubbed (ports rule).
|
|
1302
|
+
*
|
|
1303
|
+
* Write targets (ALC-17): an Action projected from a declared write target (`source: "write-target"`)
|
|
1304
|
+
* goes through `ports.door.write` when a door is bound — the door applies the target's own policy
|
|
1305
|
+
* (manual / ask / queued / auto) and its receipt becomes the result (`applied` / `queued` → ok with
|
|
1306
|
+
* the receipt; refused → an error whose code is the refusal reason and whose `remedy` is the door's).
|
|
1307
|
+
* Without a door it dispatches to `pageActions` as before.
|
|
1308
|
+
*
|
|
1309
|
+
* Never throws: every outcome is a `Result` whose error message is the
|
|
1310
|
+
* system's own sentence.
|
|
1311
|
+
*/
|
|
1312
|
+
|
|
1313
|
+
type SurfaceActionPorts = Pick<AlchemyHostPorts, "diagnostics" | "serverActions" | "mandates" | "pageActions" | "overlay" | "approvals" | "door">;
|
|
1314
|
+
interface RunSurfaceActionOptions {
|
|
1315
|
+
runId?: string;
|
|
1316
|
+
viewerId?: string | null;
|
|
1317
|
+
signal?: AbortSignal;
|
|
1318
|
+
/** Which item a write-target Action writes into (by its declared identity values). */
|
|
1319
|
+
itemIdentity?: Record<string, string>;
|
|
1320
|
+
/** Text edits for a stream or patchable write target, instead of the input as the whole value. */
|
|
1321
|
+
ops?: readonly WriteOp[];
|
|
1322
|
+
}
|
|
1323
|
+
/** Fill `{param}` placeholders from the input object. Returns the names it could not fill. */
|
|
1324
|
+
declare function fillActionTarget(template: string, input: unknown): {
|
|
1325
|
+
value: string;
|
|
1326
|
+
missing: string[];
|
|
1327
|
+
};
|
|
1328
|
+
/**
|
|
1329
|
+
* Who may run this Action, under its policy. Returns the refusal, or null.
|
|
1330
|
+
* "manual" = a person only. `triggeredBy` lists every caller allowed at all.
|
|
1331
|
+
*/
|
|
1332
|
+
declare function refuseCaller(info: Pick<ActionInfo, "name" | "label" | "policy" | "triggeredBy">, by: ActionCaller): ActionError | null;
|
|
1333
|
+
declare function runSurfaceAction(info: ActionInfo, input: unknown, by: ActionCaller, ports: SurfaceActionPorts, options?: RunSurfaceActionOptions): Promise<ActionResult<unknown>>;
|
|
1334
|
+
|
|
1335
|
+
export { ACTION_CALLERS, ACTION_CATEGORIES, ACTION_POLICIES, ACTION_RUNS, APPLET_CATEGORY, type Action, type ActionCaller, type ActionCategory, type ActionChainLink, type ActionContext, type ActionDeclaration, type ActionDeclaredBy, type ActionError, type ActionInfo, type ActionInput, type ActionOrigin, type ActionPolicy, type ActionProvider, type ActionRegistry, type ActionRegistryOptions, type ActionResult, type ActionRunContext, type ActionRuns, type ActionSection, type ActionWriteMode, type ClickTarget, type ClickTargetInput, type ClientToolRow, DEFAULT_TRIGGERED_BY, DuplicateActionError, DuplicateProviderError, type Eligibility, type MandateRunRequest, type ProjectedReads, type ProjectionSource, type ReadOmission, type ResolveRestriction, type ResolvedAction, type RunActionOptions, type RunResult, type RunSurfaceActionOptions, type ServerActionRunRequest, type ServerActionRunResponse, type SurfaceActionPorts, type SurfaceActionRow, type SurfacePort, UNIVERSAL_VERBS, type UniversalVerb, alwaysEligible, clientToolToAction, computeEligibility, createActionRegistry, createClickTarget, createProjectedReads, fillActionTarget, projectValues, refuseCaller, resolveActionChain, runAction, runSurfaceAction, staticActionProvider, surfaceActionRowToAction, toActionInfo, writeTargetToAction };
|
package/dist/actions.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
var UNIVERSAL_VERBS=["copy","cut","paste","undo","redo","find"];var ACTION_CATEGORIES=["feedback","copy","export","save","edit","share","creator","app","listen","study","ask","ai","admin","clipboard","history","surface-info"];var DuplicateActionError=class extends Error{actionId;providers;constructor(actionId,first,second){super(first===second?`Action "${actionId}" is yielded twice by provider "${first}". Ids are unique; the second was refused.`:`Action "${actionId}" is registered by provider "${first}" and again by "${second}". Ids are unique; "${second}"'s copy was refused.`),this.name="DuplicateActionError",this.actionId=actionId,this.providers=[first,second]}},DuplicateProviderError=class extends Error{providerId;constructor(providerId){super(`Action provider "${providerId}" is already registered. Unregister it first; nothing was overwritten.`),this.name="DuplicateProviderError",this.providerId=providerId}},VERBS=new Set(UNIVERSAL_VERBS);function capture(ports,error,detail){try{ports.diagnostics.capture(error,{area:"actions",detail})}catch{}}function computeEligibility(action,target,options){let restrict=options.restrict;if(target.excludedActionIds.has(action.id))return{status:"absent"};if(restrict?.exclude?.includes(action.id))return{status:"absent"};if(restrict?.categories&&!restrict.categories.includes(action.category))return{status:"absent"};if(action.writes&&action.writes.length>0){if(target.readOnly)return{status:"absent"};let writable=new Set(target.writable.map(w=>w.name));if(!action.writes.some(name=>writable.has(name)))return{status:"absent"}}if(action.requiresAuth&&!target.auth.authenticated&&!options.authResumable)return{status:"absent"};let own=action.eligible(target);return own.status==="unavailable"?own.sentence.trim()?own:{status:"absent"}:own.status!=="unavailable-verb"?own:action.category!=="clipboard"||!VERBS.has(own.verb)?{status:"contract-break",reason:`Action "${action.id}" answered unavailable-verb but only the six universal verbs (category "clipboard") may grey; it is absent instead.`}:own.sentence.trim()?own:{status:"contract-break",reason:`Universal verb "${action.id}" greyed without a sentence; a greyed verb must say why.`}}function createActionRegistry(options){let ports=options.ports,entries=new Map,listeners=new Set,notify=()=>{for(let l of[...listeners])l()};return{register(provider){if(entries.has(provider.id))throw new DuplicateProviderError(provider.id);let declared=provider.declaredIds?.()??[],own=new Set;for(let id of declared){if(own.has(id))throw new DuplicateActionError(id,provider.id,provider.id);own.add(id);for(let[otherId,other]of entries)if(other.declared.includes(id))throw new DuplicateActionError(id,otherId,provider.id)}let entry={provider,declared};return entries.set(provider.id,entry),notify(),()=>{entries.get(provider.id)===entry&&(entries.delete(provider.id),notify())}},async resolve(target,restrict){let authResumable=!!ports.auth,seen=new Map,out=[];for(let[providerId,{provider}]of[...entries]){let actions;try{actions=await provider.actions(target)}catch(error){capture(ports,error,{providerId,stage:"actions"});continue}for(let raw of actions){let first=seen.get(raw.id);if(first!==void 0){capture(ports,new DuplicateActionError(raw.id,first,providerId),{actionId:raw.id});continue}seen.set(raw.id,providerId);let action=raw.provider===providerId?raw:{...raw,provider:providerId},eligibility;try{eligibility=computeEligibility(action,target,{restrict:restrict??{},authResumable})}catch(error){capture(ports,error,{actionId:action.id,stage:"eligible"});continue}if(eligibility.status==="contract-break"){capture(ports,new Error(eligibility.reason),{actionId:action.id,stage:"eligible"});continue}eligibility.status!=="absent"&&out.push({action,eligibility})}}return out},providers(){return[...entries.keys()]},subscribe(listener){return listeners.add(listener),()=>{listeners.delete(listener)}}}}function staticActionProvider(id,actions,tier="T0"){let list=actions.map(a=>a.provider===id?a:{...a,provider:id});return{id,tier,declaredIds:()=>list.map(a=>a.id),actions:()=>list}}var alwaysEligible=()=>({status:"available"});var DEFAULT_SENSITIVITY=Object.freeze({exportable:!0,classification:"ordinary",includedByDefault:!0});function resolveSensitivity(value){return{exportable:value.sensitivity?.exportable??DEFAULT_SENSITIVITY.exportable,classification:value.sensitivity?.classification??DEFAULT_SENSITIVITY.classification,includedByDefault:value.sensitivity?.includedByDefault??DEFAULT_SENSITIVITY.includedByDefault}}function toJson(value){if(!(value===void 0||typeof value=="function"||typeof value=="symbol")){if(value===null||typeof value=="string"||typeof value=="boolean")return value;if(typeof value=="number")return Number.isFinite(value)?value:null;if(typeof value=="bigint")return value.toString();if(value instanceof Date)return value.toISOString();if(Array.isArray(value))return value.map(v=>toJson(v)??null);if(typeof value=="object"){let out={};for(let[k,v]of Object.entries(value)){let j=toJson(v);j!==void 0&&(out[k]=j)}return out}}}function projectValues(raw,declared,pathPrefix=""){let byName=new Map(declared.map(d=>[d.name,d])),values={},omissions=[];for(let[name,value]of Object.entries(raw)){let path=pathPrefix?`${pathPrefix}.${name}`:name,decl=byName.get(name);if(!decl){omissions.push({path,reason:"filtered"});continue}let sensitivity=resolveSensitivity(decl);if(sensitivity.classification!=="ordinary"){omissions.push({path,reason:"excluded",classification:sensitivity.classification});continue}if(!sensitivity.exportable){omissions.push({path,reason:"excluded"});continue}let json=toJson(value);json!==void 0&&(values[name]=json)}return{values,omissions}}function createProjectedReads(source){return{async values(signal){if(!source.surface||!source.declaration)return{values:{},omissions:[]};let raw=await source.surface.readValues(signal),screenValues=source.declaration.values;return projectValues(raw,screenValues)},async item(signal){let item=source.item;if(!item||!source.declaration)return null;let type=source.declaration.itemTypes?.find(t=>t.name===item.itemType);if(!type)return{values:{},omissions:[{path:item.itemType,reason:"filtered"}]};let raw=await item.readValues(signal);return projectValues(raw,type.values,item.itemType)},async live(signal){return source.surface?.readLive?source.surface.readLive(signal):{}}}}function qualifyValueKey(itemType,name){return itemType?`${itemType}.${name}`:name}function domainOf(surfaceName){let slash=surfaceName.indexOf("/");return slash>0?surfaceName.slice(0,slash):surfaceName}function createClickTarget(input={}){let declaration=input.declaration??null,item=input.item??null,valueKeys=new Set,restricted=!1,writable=[];if(declaration){for(let value of declaration.values){valueKeys.add(value.name);let s=resolveSensitivity(value);(s.classification!=="ordinary"||!s.exportable)&&(restricted=!0)}let itemType=item?declaration.itemTypes?.find(t=>t.name===item.itemType):void 0;if(itemType){for(let value of itemType.values){valueKeys.add(qualifyValueKey(itemType.name,value.name));let s=resolveSensitivity(value);(s.classification!=="ordinary"||!s.exportable)&&(restricted=!0)}for(let t of itemType.writeTargets??[])writable.push(t)}for(let t of declaration.writeTargets??[])(!t.itemType||t.itemType===item?.itemType)&&writable.push(t)}let readOnly=input.readOnly??item?.readOnly??!1,surfaceName=input.surface?.surfaceName??declaration?.surfaceName??null,scopeChain=input.scopeChain??(surfaceName?["global",domainOf(surfaceName),surfaceName]:["global"]);return{surface:input.surface??null,declaration,valueKeys,scopeChain,excludedActionIds:new Set(input.excludedActionIds??[]),item,level:input.level??item?.level??null,selection:input.selection??null,payloadKinds:input.payloadKinds??[],writable:readOnly?[]:input.writable??writable,readOnly,restricted,organizationId:input.organizationId??null,auth:{authenticated:input.auth?.authenticated??!1,admin:input.auth?.admin??!1,creator:input.auth?.creator??!1},host:input.host}}async function runAction(action,target,options){let{ports}=options;if(action.requiresAuth&&!target.auth.authenticated)return ports.auth?(ports.auth.signInThenResume({actionId:action.id,contentFingerprint:options.contentFingerprint??action.id}),{status:"auth-pending"}):(ports.diagnostics.capture(new Error(`requiresAuth action "${action.id}" ran signed out with no auth port`),{area:"actions",detail:{actionId:action.id}}),{status:"failed",error:new Error("sign-in unavailable")});let reads=createProjectedReads(options.source??{surface:null,declaration:target.declaration,item:null}),signal=options.signal??new AbortController().signal;try{return{status:"ran",outcome:await action.run(target,{reads,ports,signal})}}catch(error){ports.diagnostics.capture(error,{area:"actions",detail:{actionId:action.id,stage:"run"}});let label=typeof action.label=="string"?action.label:action.id;return ports.notify?.error(`${label} did not finish.`,"Try again; if it keeps failing, report it from the feedback button."),{status:"failed",error}}}export{ACTION_CATEGORIES,DuplicateActionError,DuplicateProviderError,UNIVERSAL_VERBS,alwaysEligible,computeEligibility,createActionRegistry,createClickTarget,createProjectedReads,projectValues,runAction,staticActionProvider};
|
|
1
|
+
var UNIVERSAL_VERBS=["copy","cut","paste","undo","redo","find"];var ACTION_CATEGORIES=["feedback","copy","export","save","edit","share","creator","app","listen","study","ask","ai","admin","clipboard","history","surface-info","applet"];var DuplicateActionError=class extends Error{actionId;providers;constructor(actionId,first,second){super(first===second?`Action "${actionId}" is yielded twice by provider "${first}". Ids are unique; the second was refused.`:`Action "${actionId}" is registered by provider "${first}" and again by "${second}". Ids are unique; "${second}"'s copy was refused.`),this.name="DuplicateActionError",this.actionId=actionId,this.providers=[first,second]}},DuplicateProviderError=class extends Error{providerId;constructor(providerId){super(`Action provider "${providerId}" is already registered. Unregister it first; nothing was overwritten.`),this.name="DuplicateProviderError",this.providerId=providerId}},VERBS=new Set(UNIVERSAL_VERBS);function capture(ports,error,detail){try{ports.diagnostics.capture(error,{area:"actions",detail})}catch{}}function computeEligibility(action,target,options){let restrict=options.restrict;if(target.excludedActionIds.has(action.id))return{status:"absent"};if(restrict?.exclude?.includes(action.id))return{status:"absent"};if(restrict?.categories&&!restrict.categories.includes(action.category))return{status:"absent"};if(action.writes&&action.writes.length>0){if(target.readOnly)return{status:"absent"};let writable=new Set(target.writable.map(w=>w.name));if(!action.writes.some(name=>writable.has(name)))return{status:"absent"}}if(action.requiresAuth&&!target.auth.authenticated&&!options.authResumable)return{status:"absent"};let own=action.eligible(target);return own.status==="unavailable"?own.sentence.trim()?own:{status:"absent"}:own.status!=="unavailable-verb"?own:action.category!=="clipboard"||!VERBS.has(own.verb)?{status:"contract-break",reason:`Action "${action.id}" answered unavailable-verb but only the six universal verbs (category "clipboard") may grey; it is absent instead.`}:own.sentence.trim()?own:{status:"contract-break",reason:`Universal verb "${action.id}" greyed without a sentence; a greyed verb must say why.`}}function createActionRegistry(options){let ports=options.ports,entries=new Map,listeners=new Set,notify=()=>{for(let l of[...listeners])l()};return{register(provider){if(entries.has(provider.id))throw new DuplicateProviderError(provider.id);let declared=provider.declaredIds?.()??[],own=new Set;for(let id of declared){if(own.has(id))throw new DuplicateActionError(id,provider.id,provider.id);own.add(id);for(let[otherId,other]of entries)if(other.declared.includes(id))throw new DuplicateActionError(id,otherId,provider.id)}let entry={provider,declared};return entries.set(provider.id,entry),notify(),()=>{entries.get(provider.id)===entry&&(entries.delete(provider.id),notify())}},async resolve(target,restrict){let authResumable=!!ports.auth,seen=new Map,out=[];for(let[providerId,{provider}]of[...entries]){let actions;try{actions=await provider.actions(target)}catch(error){capture(ports,error,{providerId,stage:"actions"});continue}for(let raw of actions){let first=seen.get(raw.id);if(first!==void 0){capture(ports,new DuplicateActionError(raw.id,first,providerId),{actionId:raw.id});continue}seen.set(raw.id,providerId);let action=raw.provider===providerId?raw:{...raw,provider:providerId},eligibility;try{eligibility=computeEligibility(action,target,{restrict:restrict??{},authResumable})}catch(error){capture(ports,error,{actionId:action.id,stage:"eligible"});continue}if(eligibility.status==="contract-break"){capture(ports,new Error(eligibility.reason),{actionId:action.id,stage:"eligible"});continue}eligibility.status!=="absent"&&out.push({action,eligibility})}}return out},providers(){return[...entries.keys()]},subscribe(listener){return listeners.add(listener),()=>{listeners.delete(listener)}}}}function staticActionProvider(id,actions,tier="T0"){let list=actions.map(a=>a.provider===id?a:{...a,provider:id});return{id,tier,declaredIds:()=>list.map(a=>a.id),actions:()=>list}}var alwaysEligible=()=>({status:"available"});var DEFAULT_SENSITIVITY=Object.freeze({exportable:!0,classification:"ordinary",includedByDefault:!0});function resolveSensitivity(value){return{exportable:value.sensitivity?.exportable??DEFAULT_SENSITIVITY.exportable,classification:value.sensitivity?.classification??DEFAULT_SENSITIVITY.classification,includedByDefault:value.sensitivity?.includedByDefault??DEFAULT_SENSITIVITY.includedByDefault}}function toJson(value){if(!(value===void 0||typeof value=="function"||typeof value=="symbol")){if(value===null||typeof value=="string"||typeof value=="boolean")return value;if(typeof value=="number")return Number.isFinite(value)?value:null;if(typeof value=="bigint")return value.toString();if(value instanceof Date)return value.toISOString();if(Array.isArray(value))return value.map(v=>toJson(v)??null);if(typeof value=="object"){let out={};for(let[k,v]of Object.entries(value)){let j=toJson(v);j!==void 0&&(out[k]=j)}return out}}}function projectValues(raw,declared,pathPrefix=""){let byName=new Map(declared.map(d=>[d.name,d])),values={},omissions=[];for(let[name,value]of Object.entries(raw)){let path=pathPrefix?`${pathPrefix}.${name}`:name,decl=byName.get(name);if(!decl){omissions.push({path,reason:"filtered"});continue}let sensitivity=resolveSensitivity(decl);if(sensitivity.classification!=="ordinary"){omissions.push({path,reason:"excluded",classification:sensitivity.classification});continue}if(!sensitivity.exportable){omissions.push({path,reason:"excluded"});continue}let json=toJson(value);json!==void 0&&(values[name]=json)}return{values,omissions}}function createProjectedReads(source){return{async values(signal){if(!source.surface||!source.declaration)return{values:{},omissions:[]};let raw=await source.surface.readValues(signal),screenValues=source.declaration.values;return projectValues(raw,screenValues)},async item(signal){let item=source.item;if(!item||!source.declaration)return null;let type=source.declaration.itemTypes?.find(t=>t.name===item.itemType);if(!type)return{values:{},omissions:[{path:item.itemType,reason:"filtered"}]};let raw=await item.readValues(signal);return projectValues(raw,type.values,item.itemType)},async live(signal){return source.surface?.readLive?source.surface.readLive(signal):{}}}}function qualifyValueKey(itemType,name){return itemType?`${itemType}.${name}`:name}function domainOf(surfaceName){let slash=surfaceName.indexOf("/");return slash>0?surfaceName.slice(0,slash):surfaceName}function createClickTarget(input={}){let declaration=input.declaration??null,item=input.item??null,valueKeys=new Set,restricted=!1,writable=[];if(declaration){for(let value of declaration.values){valueKeys.add(value.name);let s=resolveSensitivity(value);(s.classification!=="ordinary"||!s.exportable)&&(restricted=!0)}let itemType=item?declaration.itemTypes?.find(t=>t.name===item.itemType):void 0;if(itemType){for(let value of itemType.values){valueKeys.add(qualifyValueKey(itemType.name,value.name));let s=resolveSensitivity(value);(s.classification!=="ordinary"||!s.exportable)&&(restricted=!0)}for(let t of itemType.writeTargets??[])writable.push(t)}for(let t of declaration.writeTargets??[])(!t.itemType||t.itemType===item?.itemType)&&writable.push(t)}let readOnly=input.readOnly??item?.readOnly??!1,surfaceName=input.surface?.surfaceName??declaration?.surfaceName??null,scopeChain=input.scopeChain??(surfaceName?["global",domainOf(surfaceName),surfaceName]:["global"]);return{surface:input.surface??null,declaration,valueKeys,scopeChain,excludedActionIds:new Set(input.excludedActionIds??[]),item,level:input.level??item?.level??null,selection:input.selection??null,payloadKinds:input.payloadKinds??[],writable:readOnly?[]:input.writable??writable,readOnly,restricted,organizationId:input.organizationId??null,auth:{authenticated:input.auth?.authenticated??!1,admin:input.auth?.admin??!1,creator:input.auth?.creator??!1},host:input.host}}async function runAction(action,target,options){let{ports}=options;if(action.requiresAuth&&!target.auth.authenticated)return ports.auth?(ports.auth.signInThenResume({actionId:action.id,contentFingerprint:options.contentFingerprint??action.id}),{status:"auth-pending"}):(ports.diagnostics.capture(new Error(`requiresAuth action "${action.id}" ran signed out with no auth port`),{area:"actions",detail:{actionId:action.id}}),{status:"failed",error:new Error("sign-in unavailable")});let reads=createProjectedReads(options.source??{surface:null,declaration:target.declaration,item:null}),signal=options.signal??new AbortController().signal;try{return{status:"ran",outcome:await action.run(target,{reads,ports,signal})}}catch(error){ports.diagnostics.capture(error,{area:"actions",detail:{actionId:action.id,stage:"run"}});let label=typeof action.label=="string"?action.label:action.id;return ports.notify?.error(`${label} did not finish.`,"Try again; if it keeps failing, report it from the feedback button."),{status:"failed",error}}}var DEFAULT_MAX_INHERITANCE_DEPTH=3;var APPLET_CATEGORY="applet",DEFAULT_TRIGGERED_BY=["person","agent","applet"],ACTION_CALLERS=["person","agent","applet","automation"],ACTION_RUNS=["page","server","mandate","navigate"],ACTION_POLICIES=["ask","auto","manual"];function compact(value){return Object.fromEntries(Object.entries(value).filter(([,v])=>v!==void 0))}var POLICY_OF_APPLY={manual:"manual",ask:"ask",auto:"auto",queued:"ask"};function writeTargetToAction(target){let applyPolicy=target.applyPolicy??"manual";return compact({name:target.name,label:target.label,description:target.description,input:target.valueKind??{jsonSchema:target.valueType==="document"?{}:{type:target.valueType}},runs:"page",triggeredBy:[...DEFAULT_TRIGGERED_BY],policy:POLICY_OF_APPLY[applyPolicy],updatesValue:target.updatesValue,mode:target.mode,patchable:target.patchable,approvalComparison:target.approvalComparison,streamOps:target.streamOps?[...target.streamOps]:void 0,destination:target.destination,groupKey:target.group,itemType:target.itemType,applyPolicy:target.applyPolicy,valueType:target.valueType,valueKind:target.valueKind,sortOrder:target.sortOrder,origin:{source:"write-target",declaredBy:"code"}})}function clientToolToAction(row){return compact({name:row.name,label:row.label,description:row.description,input:{jsonSchema:row.input_schema??{}},runs:"page",triggeredBy:["agent"],policy:row.mode==="draft"?"ask":"auto",mode:row.mode,origin:compact({source:"client-tool",surfaceName:row.surface_name,id:row.id,declaredBy:row.declared_by})})}function surfaceActionRowToAction(row){return compact({name:row.name,category:row.category,label:row.label,description:row.description,input:row.input??void 0,output:row.output??void 0,runs:row.runs,target:row.target??void 0,triggeredBy:[...row.triggered_by],policy:row.policy,updatesValue:row.updates_value??void 0,itemType:row.item_type||void 0,sortOrder:row.sort_order,origin:compact({source:"surface-action",surfaceName:row.surface_name,surfaceId:row.surface_id,id:row.id,declaredBy:row.declared_by,codeRef:row.code_ref??void 0})})}function toActionInfo(declaration,declaredOn){return compact({name:declaration.name,category:declaration.category??APPLET_CATEGORY,label:declaration.label,description:declaration.description,runs:declaration.runs,policy:declaration.policy,triggeredBy:[...declaration.triggeredBy],input:declaration.input,output:declaration.output,declaredOn,target:declaration.target,updatesValue:declaration.updatesValue,itemType:declaration.itemType,source:declaration.origin?.source})}function resolveActionChain(chain,options={}){let maxDepth=options.maxDepth??DEFAULT_MAX_INHERITANCE_DEPTH,names=chain.map(link=>link.surfaceName),seen=new Set;for(let name of names){if(seen.has(name))throw new Error(`[actions] inheritance CYCLE detected at "${name}". Fix the surface chain: ${names.join(" \u2192 ")}`);seen.add(name)}if(chain.length-1>maxDepth)throw new Error(`[actions] inheritance chain for "${names[names.length-1]}" exceeds depth ${maxDepth}: ${names.join(" \u2192 ")}`);let byName=new Map;for(let link of chain){let own=new Set;for(let action of link.actions){if(own.has(action.name))throw new Error(`[actions] surface "${link.surfaceName}" declares Action "${action.name}" twice. Names are unique; nothing was overwritten.`);own.add(action.name),byName.set(action.name,toActionInfo(action,link.surfaceName))}}return[...byName.values()]}function fail(code,message,retryable=!1,diagnostic){return{ok:!1,error:diagnostic?{code,message,retryable,diagnostic}:{code,message,retryable}}}function messageOf(error){return error instanceof Error&&error.message.trim()?error.message:typeof error=="string"&&error.trim()?error:"The run failed without saying why."}function newRunId(){let c=globalThis.crypto;return c?.randomUUID?c.randomUUID():`run-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,10)}`}function fillActionTarget(template,input){let source=input&&typeof input=="object"&&!Array.isArray(input)?input:{},missing=[];return{value:template.replace(/\{([A-Za-z_][A-Za-z0-9_]*)\}/g,(_,key)=>{let v=source[key];return v==null||v===""||typeof v=="object"?(missing.push(key),""):encodeURIComponent(String(v))}),missing}}function fillName(template,input){let filled=fillActionTarget(template,input);return{value:decodeURIComponent(filled.value),missing:filled.missing}}function toJson2(value){return value===void 0?null:JSON.parse(JSON.stringify(value))}function refuseCaller(info,by){return info.triggeredBy.includes(by)?info.policy==="manual"&&by!=="person"?{code:"manual_only",message:`"${info.label}" (${info.name}) runs only when a person starts it.`,retryable:!1}:null:{code:"caller_not_allowed",message:`"${info.label}" (${info.name}) can't be started by ${CALLER_WORDS[by]}; it allows ${info.triggeredBy.join(", ")||"no one"}.`,retryable:!1}}var CALLER_WORDS={person:"a person",agent:"an agent",applet:"an applet",automation:"an automation"};function absent(info,capability){return fail("capability_absent",`"${info.label}" can't run here: ${capability} isn't available on this page.`)}async function runSurfaceAction(info,input,by,ports,options={}){let refusal=refuseCaller(info,by);if(refusal)return{ok:!1,error:refusal};let context={runId:options.runId??newRunId(),by,viewerId:options.viewerId??null,surfaceName:info.declaredOn,policy:info.policy},capture2=(error,stage)=>{try{ports.diagnostics.capture(error,{area:"actions",detail:{action:info.name,runs:info.runs,stage,runId:context.runId}})}catch{}};try{if(info.source==="write-target"&&ports.door){let receipt=await ports.door.write({surfaceName:info.declaredOn,target:info.name,...info.itemType?{itemType:info.itemType}:{},...options.itemIdentity?{itemIdentity:options.itemIdentity}:{},...options.ops?{ops:options.ops}:{value:input},by,runId:context.runId},options.signal);return receipt.status==="refused"?{ok:!1,error:{code:receipt.reason,message:receipt.sentence,retryable:receipt.reason==="failed",remedy:receipt.remedy}}:{ok:!0,data:receipt}}if(info.policy==="ask"&&by!=="person"&&info.runs!=="server"){if(!ports.approvals)return fail("needs_approval",`"${info.label}" needs a person's approval, and there is no one to ask here.`);if(!await ports.approvals.ask({action:info.name,label:info.label,description:info.description,input:toJson2(input),by,surfaceName:info.declaredOn}))return fail("declined",`"${info.label}" was not approved, so it did not run.`)}switch(info.runs){case"server":{if(!ports.serverActions)return absent(info,"server actions");let filled=fillName(info.target??info.name,input);if(filled.missing.length)return fail("input_missing",`"${info.label}" needs ${filled.missing.join(", ")}.`);let response=await ports.serverActions.run({name:filled.value,input:toJson2(input),by,surface_name:info.declaredOn,policy:info.policy});return response.status==="refused"?fail("refused",response.message):{ok:!0,data:response}}case"mandate":{if(!ports.mandates)return absent(info,"running a job");if(!info.target)return fail("target_missing",`"${info.label}" names no job to run.`);let filled=fillName(info.target,input);if(filled.missing.length)return fail("input_missing",`"${info.label}" needs ${filled.missing.join(", ")}.`);let record=input&&typeof input=="object"&&!Array.isArray(input)?input:{},variables=/\{[A-Za-z_]/.test(info.target)?record.variables&&typeof record.variables=="object"?toJson2(record.variables):{}:toJson2(record),userInput=typeof record.userInput=="string"?record.userInput:void 0;return{ok:!0,data:await ports.mandates.run({alias:filled.value,variables,...userInput!==void 0?{userInput}:{},by,policy:info.policy})}}case"navigate":{if(!ports.overlay)return absent(info,"navigation");let filled=fillActionTarget(info.target??"",input);if(filled.missing.length)return fail("input_missing",`"${info.label}" needs ${filled.missing.join(", ")}.`);let to=info.target&&/^\{[A-Za-z_][A-Za-z0-9_]*\}$/.test(info.target)?decodeURIComponent(filled.value):filled.value;return to?(ports.overlay.navigate(to),{ok:!0,data:{to}}):fail("target_missing",`"${info.label}" names no page to open.`)}case"page":return ports.pageActions?await ports.pageActions.dispatch(info.name,input,context):absent(info,"this page's actions");default:{let runs=info.runs;return fail("runs_unknown",`"${info.label}" runs as "${String(runs)}", which nothing here knows how to run.`)}}}catch(error){return capture2(error,"run"),fail("run_failed",messageOf(error),!0)}}export{ACTION_CALLERS,ACTION_CATEGORIES,ACTION_POLICIES,ACTION_RUNS,APPLET_CATEGORY,DEFAULT_TRIGGERED_BY,DuplicateActionError,DuplicateProviderError,UNIVERSAL_VERBS,alwaysEligible,clientToolToAction,computeEligibility,createActionRegistry,createClickTarget,createProjectedReads,fillActionTarget,projectValues,refuseCaller,resolveActionChain,runAction,runSurfaceAction,staticActionProvider,surfaceActionRowToAction,toActionInfo,writeTargetToAction};
|
|
2
2
|
//# sourceMappingURL=actions.js.map
|