@composable-os/sdk 0.0.0-stage → 0.1.0-beta.8

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 (72) hide show
  1. package/LICENSE +109 -0
  2. package/dist/automation-check.d.ts +38 -0
  3. package/dist/automation-check.js +454 -0
  4. package/dist/automation.d.ts +767 -0
  5. package/dist/automation.js +303 -0
  6. package/dist/behaviour.d.ts +3 -0
  7. package/dist/behaviour.js +153 -0
  8. package/dist/capacity.d.ts +51 -0
  9. package/dist/capacity.js +68 -0
  10. package/dist/contract.d.ts +706 -0
  11. package/dist/contract.js +42 -0
  12. package/dist/document.d.ts +165 -0
  13. package/dist/document.js +636 -0
  14. package/dist/field-types.d.ts +11 -0
  15. package/dist/field-types.js +93 -0
  16. package/dist/formula/ast.d.ts +67 -0
  17. package/dist/formula/ast.js +22 -0
  18. package/dist/formula/compile.d.ts +37 -0
  19. package/dist/formula/compile.js +379 -0
  20. package/dist/formula/index.d.ts +3 -0
  21. package/dist/formula/index.js +4 -0
  22. package/dist/formula/parser.d.ts +13 -0
  23. package/dist/formula/parser.js +365 -0
  24. package/dist/index.d.ts +17 -0
  25. package/dist/index.js +21 -0
  26. package/dist/manifest.d.ts +1131 -0
  27. package/dist/manifest.js +1229 -0
  28. package/dist/media.d.ts +9 -0
  29. package/dist/media.js +43 -0
  30. package/dist/permissions.d.ts +17 -0
  31. package/dist/permissions.js +44 -0
  32. package/dist/renamed.d.ts +16 -0
  33. package/dist/renamed.js +59 -0
  34. package/dist/rich-text-fixture.d.ts +121 -0
  35. package/dist/rich-text-fixture.js +67 -0
  36. package/dist/rich-text.d.ts +34 -0
  37. package/dist/rich-text.js +138 -0
  38. package/dist/runtime.d.ts +95 -0
  39. package/dist/runtime.js +312 -0
  40. package/dist/sellable.d.ts +103 -0
  41. package/dist/sellable.js +258 -0
  42. package/dist/slug.d.ts +11 -0
  43. package/dist/slug.js +23 -0
  44. package/dist/states.d.ts +64 -0
  45. package/dist/states.js +101 -0
  46. package/dist/testing.d.ts +151 -0
  47. package/dist/testing.js +670 -0
  48. package/package.json +34 -4
  49. package/src/automation-check.ts +534 -0
  50. package/src/automation.ts +743 -0
  51. package/src/behaviour.ts +215 -0
  52. package/src/capacity.ts +112 -0
  53. package/src/contract.ts +766 -0
  54. package/src/document.ts +788 -0
  55. package/src/field-types.ts +106 -0
  56. package/src/formula/ast.ts +72 -0
  57. package/src/formula/compile.ts +454 -0
  58. package/src/formula/index.ts +4 -0
  59. package/src/formula/parser.ts +417 -0
  60. package/src/index.ts +33 -0
  61. package/src/manifest.ts +1484 -0
  62. package/src/media.ts +46 -0
  63. package/src/permissions.ts +60 -0
  64. package/src/renamed.ts +63 -0
  65. package/src/rich-text-fixture.ts +68 -0
  66. package/src/rich-text.ts +173 -0
  67. package/src/runtime.ts +410 -0
  68. package/src/sellable.ts +396 -0
  69. package/src/slug.ts +25 -0
  70. package/src/states.ts +162 -0
  71. package/src/testing.ts +836 -0
  72. package/README.md +0 -3
package/dist/slug.js ADDED
@@ -0,0 +1,23 @@
1
+ // The `slug` field type (stage 28, ADR 0442): a record's address in its object, such as
2
+ // `summer-launch` in `/blog/summer-launch`. Lowercase letters and digits in words joined by single
3
+ // hyphens. The host keeps it unique among the object's live records and makes one from the title
4
+ // when a record is created without one.
5
+ /** What a slug may be. */
6
+ export const SLUG_RE = /^[a-z0-9]+(?:-[a-z0-9]+)*$/;
7
+ /** The longest a slug may be. */
8
+ export const SLUG_MAX = 120;
9
+ /** The longest slug made from a title, leaving room for a `-<n>` that tells two apart. */
10
+ export const SLUG_FROM_TITLE_MAX = 80;
11
+ /**
12
+ * A slug made from a title: accents dropped, every run of anything that is not a letter or digit
13
+ * a hyphen, at most SLUG_FROM_TITLE_MAX characters. Empty when nothing is left.
14
+ */
15
+ export function slugify(title) {
16
+ const plain = title
17
+ .normalize("NFKD")
18
+ .replace(/[̀-ͯ]/g, "")
19
+ .toLowerCase()
20
+ .replace(/[^a-z0-9]+/g, "-")
21
+ .replace(/^-+|-+$/g, "");
22
+ return plain.slice(0, SLUG_FROM_TITLE_MAX).replace(/-+$/g, "");
23
+ }
@@ -0,0 +1,64 @@
1
+ import { z } from "zod";
2
+ import type { ExtensionManifest, ObjectManifest } from "./manifest.ts";
3
+ /**
4
+ * Who may make a move. `staff`: anyone working for the organisation (people, their assistants,
5
+ * MCP clients, automations and extensions acting for them). `customer`: a signed-in customer, on
6
+ * their own record. `host`: platform code only (a payment confirmation, an expiry); no caller of
7
+ * an operation can make it.
8
+ */
9
+ export declare const MOVERS: readonly ["staff", "customer", "host"];
10
+ export type Mover = (typeof MOVERS)[number];
11
+ /** One allowed move of a state machine. */
12
+ export interface StateMove {
13
+ /** The state, or states, the record moves from. */
14
+ from: string | readonly string[];
15
+ /** The state it moves to. */
16
+ to: string;
17
+ /** Who may make it. */
18
+ by: readonly Mover[];
19
+ /** Fields that must have a value to make the move, and cannot be emptied while in `to`. */
20
+ requires?: readonly string[];
21
+ /** The move ends the lifecycle: nothing moves out of `to`. */
22
+ final?: boolean;
23
+ }
24
+ /**
25
+ * A state machine (ADR 0425). The host enforces it in the record operations and the record CSV
26
+ * import, for every actor, and in the approval queue's dry run:
27
+ *
28
+ * - A record is created in `initial`. Creating it in another state is judged as the move from
29
+ * `initial` to that state.
30
+ * - A move that is not declared is refused, with details naming the rule, the state and the
31
+ * field to fix. So is a declared move made by someone its `by` does not list, and a move while
32
+ * one of its `requires` fields is empty.
33
+ * - Every move is recorded in state history (entered and left times, who) in the same batch as
34
+ * the write and, when the state field is tracked, posted on the timeline as "Moved to <state>".
35
+ */
36
+ export interface StatesSpec {
37
+ /** This object's select field holding the state. Its options are the states. */
38
+ field: string;
39
+ /** The state a new record starts in. */
40
+ initial: string;
41
+ moves: readonly StateMove[];
42
+ }
43
+ export declare const statesManifestSchema: z.ZodObject<{
44
+ field: z.ZodString;
45
+ initial: z.ZodString;
46
+ moves: z.ZodArray<z.ZodObject<{
47
+ from: z.ZodUnion<readonly [z.ZodString, z.ZodArray<z.ZodString>]>;
48
+ to: z.ZodString;
49
+ by: z.ZodArray<z.ZodEnum<{
50
+ staff: "staff";
51
+ customer: "customer";
52
+ host: "host";
53
+ }>>;
54
+ requires: z.ZodOptional<z.ZodArray<z.ZodString>>;
55
+ final: z.ZodOptional<z.ZodBoolean>;
56
+ }, z.core.$strip>>;
57
+ }, z.core.$strip>;
58
+ export type StatesManifest = z.infer<typeof statesManifestSchema>;
59
+ /** The states a move leaves, as a list. */
60
+ export declare function moveOrigins(move: {
61
+ from: string | readonly string[];
62
+ }): readonly string[];
63
+ /** Reports problems with `objects.<name>.states` through `contract`. */
64
+ export declare function checkObjectStates(_m: ExtensionManifest, name: string, object: ObjectManifest, contract: (path: string, message: string) => void): void;
package/dist/states.js ADDED
@@ -0,0 +1,101 @@
1
+ // The `states` behaviour (ADR 0425): an object declares a small, fixed state machine and the host
2
+ // holds every write to it. Its declaration, its manifest schema and its contract checks live
3
+ // here; the host's side is packages/core/src/records/states.ts, on the transition engine it
4
+ // shares with `stages`.
5
+ import { z } from "zod";
6
+ /**
7
+ * Who may make a move. `staff`: anyone working for the organisation (people, their assistants,
8
+ * MCP clients, automations and extensions acting for them). `customer`: a signed-in customer, on
9
+ * their own record. `host`: platform code only (a payment confirmation, an expiry); no caller of
10
+ * an operation can make it.
11
+ */
12
+ export const MOVERS = ["staff", "customer", "host"];
13
+ const fieldName = z.string().max(40);
14
+ const stateValue = z.string().min(1).max(100);
15
+ export const statesManifestSchema = z.object({
16
+ field: fieldName,
17
+ initial: stateValue,
18
+ moves: z
19
+ .array(z.object({
20
+ from: z.union([stateValue, z.array(stateValue).min(1).max(50)]),
21
+ to: stateValue,
22
+ by: z.array(z.enum(MOVERS)).min(1).max(MOVERS.length),
23
+ requires: z.array(fieldName).max(50).optional(),
24
+ final: z.boolean().optional(),
25
+ }))
26
+ .max(200),
27
+ });
28
+ /** The states a move leaves, as a list. */
29
+ export function moveOrigins(move) {
30
+ return typeof move.from === "string" ? [move.from] : move.from;
31
+ }
32
+ /** Reports problems with `objects.<name>.states` through `contract`. */
33
+ export function checkObjectStates(_m, name, object, contract) {
34
+ const states = object.states;
35
+ if (!states)
36
+ return;
37
+ const sp = `objects.${name}.states`;
38
+ if (object.stages) {
39
+ contract(sp, "An object has one lifecycle: declare stages or states, not both");
40
+ }
41
+ const fieldOf = (local) => Object.hasOwn(object.fields, local) ? object.fields[local] : undefined;
42
+ const field = fieldOf(states.field);
43
+ if (field?.type !== "select") {
44
+ contract(`${sp}.field`, `"${states.field}" must be a select field of ${name}`);
45
+ return;
46
+ }
47
+ if (field.readOnly) {
48
+ contract(`${sp}.field`, "The state field cannot be read-only: the moves say who may change it");
49
+ }
50
+ if (field.editableOptions) {
51
+ contract(`${sp}.field`, "The state field cannot have editableOptions: states are fixed in the declaration");
52
+ }
53
+ const values = new Set((field.options ?? []).map((o) => o.value));
54
+ const isState = (value) => values.has(value);
55
+ if (!isState(states.initial)) {
56
+ contract(`${sp}.initial`, `"${states.initial}" is not an option of ${states.field}`);
57
+ }
58
+ if (field.default !== undefined && field.default !== states.initial) {
59
+ contract(`${sp}.initial`, `${states.field}'s default must be the initial state "${states.initial}", or be left out`);
60
+ }
61
+ const seen = new Set();
62
+ const finals = new Set(states.moves.filter((move) => move.final).map((move) => move.to));
63
+ states.moves.forEach((move, i) => {
64
+ const mp = `${sp}.moves.${i}`;
65
+ if (!isState(move.to))
66
+ contract(`${mp}.to`, `"${move.to}" is not an option of ${states.field}`);
67
+ if (new Set(move.by).size !== move.by.length)
68
+ contract(`${mp}.by`, "List each mover once");
69
+ if (finals.has(move.to) && !move.final) {
70
+ contract(`${mp}.final`, `Another move into "${move.to}" is final; every move into a state must agree`);
71
+ }
72
+ if (move.final && move.to === states.initial) {
73
+ contract(`${mp}.final`, "The initial state cannot be final");
74
+ }
75
+ for (const from of moveOrigins(move)) {
76
+ if (!isState(from)) {
77
+ contract(`${mp}.from`, `"${from}" is not an option of ${states.field}`);
78
+ }
79
+ if (from === move.to)
80
+ contract(`${mp}.from`, `A move cannot go from "${from}" to itself`);
81
+ if (finals.has(from)) {
82
+ contract(`${mp}.from`, `"${from}" is final: nothing moves out of it`);
83
+ }
84
+ const key = JSON.stringify([from, move.to]);
85
+ if (seen.has(key)) {
86
+ contract(mp, `The move from "${from}" to "${move.to}" is declared twice`);
87
+ }
88
+ seen.add(key);
89
+ }
90
+ for (const local of move.requires ?? []) {
91
+ const required = fieldOf(local);
92
+ if (!required || required.type === "formula" || local === states.field) {
93
+ contract(`${mp}.requires`, `"${local}" must be a field of ${name} other than a formula or the state field`);
94
+ }
95
+ else if (required.readOnly && move.by.some((mover) => mover !== "host")) {
96
+ // Only the host writes a read-only field, so only a host move can fill it.
97
+ contract(`${mp}.requires`, `"${local}" is read-only, so only a move made by the host alone can require it`);
98
+ }
99
+ }
100
+ });
101
+ }
@@ -0,0 +1,151 @@
1
+ import { type AutomationEvent, type AutomationTestStep, type NotificationSendInput } from "./automation.ts";
2
+ import { type AiModule, type Extension, type StartedBy } from "./contract.ts";
3
+ import type { ExtensionManifest, ManifestIssue, ValidateOptions } from "./manifest.ts";
4
+ type Values = Record<string, unknown> & {
5
+ id: string;
6
+ };
7
+ type OperationFake = (input: Record<string, unknown>) => unknown;
8
+ export interface TestHostOptions {
9
+ /** Seed records by object name (`organisation`, `example.project`). */
10
+ records?: Record<string, Values[]>;
11
+ /** Fakes for operations the harness does not implement, by name. */
12
+ operations?: Record<string, OperationFake>;
13
+ /** Fakes for the AI module. Default: deterministic stand-ins. */
14
+ ai?: Partial<AiModule>;
15
+ /** Passed to validateManifest. */
16
+ validate?: ValidateOptions;
17
+ /**
18
+ * Users `notification.send` resolves (`{ role: "admin" }`, `managerOf`). Default one admin,
19
+ * `usr_admin`.
20
+ */
21
+ users?: {
22
+ id: string;
23
+ role: "admin" | "member" | "viewer";
24
+ }[];
25
+ /**
26
+ * Fakes for the gatekeepers the extension declares in `permissions.modules`, by name: what a
27
+ * session method returns for `call(connectionId, resource, method, ...args)`. Every call is
28
+ * recorded in `gatekeeperCalls`. A declared gatekeeper with no fake answers `{ status: "pending" }`
29
+ * (a person would approve it), with one connection per declared automation connection.
30
+ */
31
+ gatekeepers?: Record<string, (call: {
32
+ connectionId: string;
33
+ resource: string;
34
+ method: string;
35
+ args: unknown[];
36
+ }) => unknown>;
37
+ }
38
+ /** A call a tool or automation made through `ctx.gatekeeper(name).call(...)`. */
39
+ export interface GatekeeperCall {
40
+ gatekeeper: string;
41
+ connectionId: string;
42
+ resource: string;
43
+ method: string;
44
+ args: unknown[];
45
+ /** The step it was made in (null: outside a step, or a tool). */
46
+ step: string | null;
47
+ }
48
+ /** A notification the in-memory `notification.send` delivered. */
49
+ export interface SentNotification extends Omit<NotificationSendInput, "type" | "dedupeKey"> {
50
+ type: string;
51
+ dedupeKey: string | null;
52
+ /** Resolved, deduplicated recipients. */
53
+ userIds: string[];
54
+ notes: string[];
55
+ /** The step that sent it (null: outside a step). */
56
+ step: string | null;
57
+ }
58
+ export interface AutomationRunOptions {
59
+ /** The trigger record, from the seeded `records`. */
60
+ record?: {
61
+ object: string;
62
+ id: string;
63
+ };
64
+ change?: AutomationEvent["change"];
65
+ period?: string;
66
+ manual?: AutomationEvent["manual"];
67
+ approval?: AutomationEvent["approval"];
68
+ /** waitForEvent payloads by step name. Default null (the wait timed out). */
69
+ events?: Record<string, unknown>;
70
+ runId?: string;
71
+ /** `event.test`. Default false: the run writes to the in-memory store. */
72
+ test?: boolean;
73
+ }
74
+ export interface AutomationRunResult {
75
+ /** False when the declared conditions did not match the trigger record (nothing ran). */
76
+ matched: boolean;
77
+ /** What `run` returned. */
78
+ value: unknown;
79
+ /** Set when `run` threw (a step failed, or an undeclared step name). */
80
+ error: {
81
+ code: string;
82
+ message: string;
83
+ } | null;
84
+ /** Every step in the order it ran; waits carry `skippedMs`. */
85
+ steps: (AutomationTestStep & {
86
+ calls: TestHost["calls"];
87
+ })[];
88
+ /** Record writes the run made (operation, object, the created or changed id). */
89
+ writes: {
90
+ step: string | null;
91
+ operation: string;
92
+ object: string | null;
93
+ id: string | null;
94
+ }[];
95
+ notifications: SentNotification[];
96
+ /** Effects no declaration covers, e.g. "step notifyOwner wrote task (not in its writes)". */
97
+ undeclared: string[];
98
+ }
99
+ /** Thrown into `run` when it uses a step name it did not declare (the host refuses it too). */
100
+ export declare class AutomationStepError extends Error {
101
+ name: string;
102
+ readonly code = "undeclared_step";
103
+ }
104
+ export declare class ExtensionToolError extends Error {
105
+ readonly code: string;
106
+ readonly details?: unknown | undefined;
107
+ name: string;
108
+ constructor(code: string, message: string, details?: unknown | undefined);
109
+ }
110
+ export interface TestHost {
111
+ manifest: ExtensionManifest;
112
+ /** Contract and formula issues (`extension.check` minus typecheck and dry-run reconcile). */
113
+ issues: ManifestIssue[];
114
+ /**
115
+ * Runs a tool like the host does: input and output validated, ctx from in-memory modules.
116
+ * `caller` is who started it (`ctx.caller`, ADR 0436); default the staff user `usr_admin`.
117
+ */
118
+ runTool<T = unknown>(tool: string, input: unknown, options?: {
119
+ caller?: StartedBy;
120
+ }): Promise<T>;
121
+ /** Every codemode:ops call, in order (allowed or refused). */
122
+ calls: {
123
+ operation: string;
124
+ input: unknown;
125
+ allowed: boolean;
126
+ }[];
127
+ logs: {
128
+ level: string;
129
+ message: string;
130
+ data: unknown;
131
+ }[];
132
+ storage: Map<string, unknown>;
133
+ records: Map<string, Map<string, Values>>;
134
+ /** Every notification sent through the in-memory `notification.send`. */
135
+ notifications: SentNotification[];
136
+ /** Every call through a gatekeeper module, in order. */
137
+ gatekeeperCalls: GatekeeperCall[];
138
+ /**
139
+ * Runs automation `name` in memory, start to finish: conditions checked on the trigger
140
+ * record, waits skipped (and recorded), steps held to the declarations.
141
+ */
142
+ runAutomation(name: string, options?: AutomationRunOptions): Promise<AutomationRunResult>;
143
+ /**
144
+ * Publishes a record of a publishable object as a person would (`record.publish`, which no
145
+ * tool may call): its content fields become the next version, which `record.version` reads.
146
+ * Returns the version's number.
147
+ */
148
+ publish(object: string, id: string): number;
149
+ }
150
+ export declare function createTestHost(extension: Extension, options?: TestHostOptions): TestHost;
151
+ export {};