@clegra/sdk 0.0.0-stage → 0.1.0-next.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (81) hide show
  1. package/CHANGELOG.md +158 -0
  2. package/LICENSE +21 -0
  3. package/NOTICE.md +25 -0
  4. package/README.md +258 -2
  5. package/dist/spec/kinds.json +211 -0
  6. package/dist/spec/schema/clegra.schema.json +1249 -0
  7. package/dist/spec/src/cli.d.ts +2 -0
  8. package/dist/spec/src/cli.js +21 -0
  9. package/dist/spec/src/cli.js.map +1 -0
  10. package/dist/spec/src/conformance.d.ts +34 -0
  11. package/dist/spec/src/conformance.js +704 -0
  12. package/dist/spec/src/conformance.js.map +1 -0
  13. package/dist/spec/src/init/index.d.ts +31 -0
  14. package/dist/spec/src/init/index.js +151 -0
  15. package/dist/spec/src/init/index.js.map +1 -0
  16. package/dist/spec/src/init/next-config.d.ts +19 -0
  17. package/dist/spec/src/init/next-config.js +77 -0
  18. package/dist/spec/src/init/next-config.js.map +1 -0
  19. package/dist/spec/src/init/project.d.ts +44 -0
  20. package/dist/spec/src/init/project.js +141 -0
  21. package/dist/spec/src/init/project.js.map +1 -0
  22. package/dist/spec/src/init/templates.d.ts +20 -0
  23. package/dist/spec/src/init/templates.js +166 -0
  24. package/dist/spec/src/init/templates.js.map +1 -0
  25. package/dist/spec/src/init/ui.d.ts +30 -0
  26. package/dist/spec/src/init/ui.js +82 -0
  27. package/dist/spec/src/init/ui.js.map +1 -0
  28. package/dist/spec/src/kinds.d.ts +89 -0
  29. package/dist/spec/src/kinds.js +319 -0
  30. package/dist/spec/src/kinds.js.map +1 -0
  31. package/dist/spec/src/protocol.d.ts +50 -0
  32. package/dist/spec/src/protocol.js +52 -0
  33. package/dist/spec/src/protocol.js.map +1 -0
  34. package/dist/spec/src/rules.d.ts +132 -0
  35. package/dist/spec/src/rules.js +282 -0
  36. package/dist/spec/src/rules.js.map +1 -0
  37. package/dist/src/auth.d.ts +371 -0
  38. package/dist/src/auth.js +964 -0
  39. package/dist/src/auth.js.map +1 -0
  40. package/dist/src/define.d.ts +249 -0
  41. package/dist/src/define.js +83 -0
  42. package/dist/src/define.js.map +1 -0
  43. package/dist/src/embed.d.ts +98 -0
  44. package/dist/src/embed.js +256 -0
  45. package/dist/src/embed.js.map +1 -0
  46. package/dist/src/index.d.ts +11 -0
  47. package/dist/src/index.js +11 -0
  48. package/dist/src/index.js.map +1 -0
  49. package/dist/src/labels.d.ts +10 -0
  50. package/dist/src/labels.js +22 -0
  51. package/dist/src/labels.js.map +1 -0
  52. package/dist/src/manifest.d.ts +499 -0
  53. package/dist/src/manifest.js +188 -0
  54. package/dist/src/manifest.js.map +1 -0
  55. package/dist/src/meaning.d.ts +64 -0
  56. package/dist/src/meaning.js +116 -0
  57. package/dist/src/meaning.js.map +1 -0
  58. package/dist/src/next/index.d.ts +101 -0
  59. package/dist/src/next/index.js +187 -0
  60. package/dist/src/next/index.js.map +1 -0
  61. package/dist/src/node.d.ts +14 -0
  62. package/dist/src/node.js +64 -0
  63. package/dist/src/node.js.map +1 -0
  64. package/dist/src/server.d.ts +229 -0
  65. package/dist/src/server.js +2256 -0
  66. package/dist/src/server.js.map +1 -0
  67. package/dist/src/store.d.ts +129 -0
  68. package/dist/src/store.js +213 -0
  69. package/dist/src/store.js.map +1 -0
  70. package/dist/src/testing.d.ts +133 -0
  71. package/dist/src/testing.js +81 -0
  72. package/dist/src/testing.js.map +1 -0
  73. package/dist/src/types.d.ts +352 -0
  74. package/dist/src/types.js +2 -0
  75. package/dist/src/types.js.map +1 -0
  76. package/dist/src/view.d.ts +35 -0
  77. package/dist/src/view.js +442 -0
  78. package/dist/src/view.js.map +1 -0
  79. package/docs/quickstart.md +350 -0
  80. package/docs/spec.md +997 -0
  81. package/package.json +89 -4
@@ -0,0 +1,129 @@
1
+ /**
2
+ * What the server remembers between requests (spec §7): the results of
3
+ * writes, for idempotency, and the ids of tokens that may be used once.
4
+ * Every method is one atomic step. The default keeps it in memory; a server
5
+ * on several instances passes a shared one (a database row with a unique
6
+ * key, Redis SET NX).
7
+ */
8
+ export type StoredCall = {
9
+ args: string;
10
+ result?: unknown;
11
+ };
12
+ /**
13
+ * A confirmed call kept to run later («approve now, act later»), exactly as the person confirmed it: its
14
+ * arguments as received and their hash, when (`at`, as given) and until when (`until`, epoch seconds) it may
15
+ * run, its author and the permissions it runs with, and the host's signed proof (null when a plain client
16
+ * confirmed it: no proof exists then) with what re-verifies it (`issuer`, `subject`, `installation`, `call`).
17
+ */
18
+ export type LaterRun = {
19
+ id: string;
20
+ /** The tenant (`<installation>@<issuer>`, or the app's own). */
21
+ tenant: string;
22
+ tool: string;
23
+ args: Record<string, unknown>;
24
+ argsHash: string;
25
+ at: string;
26
+ until: number;
27
+ author: {
28
+ id: string;
29
+ name: string;
30
+ } | null;
31
+ permissions: string[];
32
+ proof: string | null;
33
+ issuer: string;
34
+ subject: string;
35
+ /** The installation as its issuer names it (the proof's `installation`). */
36
+ installation: string;
37
+ call: string | null;
38
+ /** When the person confirmed it, epoch seconds (the proof's `iat`). */
39
+ confirmedAt: number;
40
+ };
41
+ /** How a later run ended. */
42
+ export type LaterOutcome = {
43
+ status: "done" | "failed" | "expired" | "refused";
44
+ message: string;
45
+ };
46
+ /**
47
+ * The store's part for later runs. `claim` is the single-use step: it takes a pending run in one atomic step
48
+ * (two callers at the same moment: one gets the run, the other null), and a claimed run is never given again.
49
+ */
50
+ export type LaterStore = {
51
+ add(run: LaterRun): Promise<void>;
52
+ /** Pending runs of the tenant whose `at` is not after `now`, oldest first, at most `limit`. */
53
+ due(tenant: string, now: Date, limit: number): Promise<LaterRun[]>;
54
+ claim(id: string, tenant: string): Promise<LaterRun | null>;
55
+ finish(id: string, outcome: LaterOutcome): Promise<void>;
56
+ /** Cancels a pending run of the tenant: false when there is none (unknown, another tenant's, claimed or finished). */
57
+ cancel(id: string, tenant: string): Promise<boolean>;
58
+ /** Deletes every run of the tenant, whatever its state (the app's data deletion): how many. */
59
+ clear(tenant: string): Promise<number>;
60
+ };
61
+ export type IdempotencyStore = {
62
+ /**
63
+ * Starts the call `key` with these arguments, in one atomic step: null
64
+ * when nothing was there (the caller now runs it and must `finish` or
65
+ * `abandon` it); else what is there: with `result` when it finished,
66
+ * without while it still runs.
67
+ */
68
+ begin(key: string, args: string, ttlMs: number): Promise<StoredCall | null>;
69
+ /** The call's result, kept for `ttlMs`. */
70
+ finish(key: string, value: Required<StoredCall>, ttlMs: number): Promise<void>;
71
+ /** The call did not run (refused, or its handler failed): forgotten, so it can be tried again. */
72
+ abandon(key: string): Promise<void>;
73
+ /** True the first time `key` is seen within `ttlMs`, false after: atomic. */
74
+ once(key: string, ttlMs: number): Promise<boolean>;
75
+ /** Later runs (needed by actions with `later`). */
76
+ later?: LaterStore;
77
+ };
78
+ /** Later runs in memory: what MemoryStore keeps (one process, lost on restart). */
79
+ export declare class MemoryLater implements LaterStore {
80
+ #private;
81
+ add(run: LaterRun): Promise<void>;
82
+ due(tenant: string, now: Date, limit: number): Promise<LaterRun[]>;
83
+ claim(id: string, tenant: string): Promise<LaterRun | null>;
84
+ finish(id: string, outcome: LaterOutcome): Promise<void>;
85
+ cancel(id: string, tenant: string): Promise<boolean>;
86
+ clear(tenant: string): Promise<number>;
87
+ /** For tests: a run as kept, its state included. */
88
+ inspect(id: string): (LaterRun & {
89
+ status: string;
90
+ message?: string;
91
+ }) | undefined;
92
+ }
93
+ export declare class MemoryStore implements IdempotencyStore {
94
+ #private;
95
+ readonly later: MemoryLater;
96
+ begin(key: string, args: string, ttlMs: number): Promise<StoredCall | null>;
97
+ finish(key: string, value: Required<StoredCall>, ttlMs: number): Promise<void>;
98
+ abandon(key: string): Promise<void>;
99
+ once(key: string, ttlMs: number): Promise<boolean>;
100
+ }
101
+ /**
102
+ * Runs one SQL statement with positional parameters (`$1`, `$2`, …) and gives
103
+ * back its rows: whatever the app already talks to its database with
104
+ * (`pg`'s `pool.query`, `postgres`'s `sql.unsafe`, PGlite's `db.query`, a
105
+ * Drizzle `db.execute`). The SDK knows no driver.
106
+ */
107
+ export type SqlQuery = (text: string, params: unknown[]) => Promise<{
108
+ rows: Record<string, unknown>[];
109
+ } | Record<string, unknown>[]>;
110
+ /**
111
+ * A store in the app's own Postgres (two tables), for serverless and several
112
+ * instances: every method is a single statement, atomic on its own. Create the
113
+ * tables once with `SqlStore.schema()` in a migration (the SDK never migrates;
114
+ * the SQL is idempotent, so a new migration may run it again).
115
+ * Expired rows are taken over in place and swept now and then.
116
+ */
117
+ export declare class SqlStore implements IdempotencyStore {
118
+ #private;
119
+ readonly later: LaterStore;
120
+ constructor(query: SqlQuery, options?: {
121
+ table?: string;
122
+ });
123
+ /** The tables (`<table>` and `<table>_later`), as SQL for a migration: `CREATE … IF NOT EXISTS`, safe to run again. */
124
+ static schema(table?: string): string;
125
+ begin(key: string, args: string, ttlMs: number): Promise<StoredCall | null>;
126
+ finish(key: string, value: Required<StoredCall>, ttlMs: number): Promise<void>;
127
+ abandon(key: string): Promise<void>;
128
+ once(key: string, ttlMs: number): Promise<boolean>;
129
+ }
@@ -0,0 +1,213 @@
1
+ /** Later runs in memory: what MemoryStore keeps (one process, lost on restart). */
2
+ export class MemoryLater {
3
+ #runs = new Map();
4
+ async add(run) {
5
+ if (this.#runs.has(run.id))
6
+ throw new Error(`later run ${run.id} exists`);
7
+ this.#runs.set(run.id, { run: structuredClone(run), status: "pending" });
8
+ }
9
+ async due(tenant, now, limit) {
10
+ return [...this.#runs.values()]
11
+ .filter((k) => k.status === "pending" && k.run.tenant === tenant && Date.parse(k.run.at) <= now.getTime())
12
+ .sort((a, b) => Date.parse(a.run.at) - Date.parse(b.run.at))
13
+ .slice(0, limit)
14
+ .map((k) => structuredClone(k.run));
15
+ }
16
+ // No await between the read and the write: one step on Node's single thread.
17
+ async claim(id, tenant) {
18
+ const k = this.#runs.get(id);
19
+ if (!k || k.run.tenant !== tenant || k.status !== "pending")
20
+ return null;
21
+ k.status = "running";
22
+ return structuredClone(k.run);
23
+ }
24
+ async finish(id, outcome) {
25
+ const k = this.#runs.get(id);
26
+ if (k)
27
+ Object.assign(k, { status: outcome.status, message: outcome.message });
28
+ }
29
+ async cancel(id, tenant) {
30
+ const k = this.#runs.get(id);
31
+ if (!k || k.run.tenant !== tenant || k.status !== "pending")
32
+ return false;
33
+ k.status = "cancelled";
34
+ return true;
35
+ }
36
+ async clear(tenant) {
37
+ let n = 0;
38
+ for (const [id, k] of this.#runs)
39
+ if (k.run.tenant === tenant && this.#runs.delete(id))
40
+ n++;
41
+ return n;
42
+ }
43
+ /** For tests: a run as kept, its state included. */
44
+ inspect(id) {
45
+ const k = this.#runs.get(id);
46
+ return k ? { ...structuredClone(k.run), status: k.status, ...(k.message !== undefined ? { message: k.message } : {}) } : undefined;
47
+ }
48
+ }
49
+ export class MemoryStore {
50
+ #items = new Map();
51
+ later = new MemoryLater();
52
+ #live(key) {
53
+ const item = this.#items.get(key);
54
+ if (!item)
55
+ return undefined;
56
+ if (item.until < Date.now()) {
57
+ this.#items.delete(key);
58
+ return undefined;
59
+ }
60
+ return item.value;
61
+ }
62
+ #put(key, value, ttlMs) {
63
+ if (this.#items.size > 50_000)
64
+ for (const [k, v] of this.#items)
65
+ if (v.until < Date.now())
66
+ this.#items.delete(k);
67
+ this.#items.set(key, { value, until: Date.now() + ttlMs });
68
+ }
69
+ // No await between the read and the write: one step on Node's single thread.
70
+ async begin(key, args, ttlMs) {
71
+ const existing = this.#live(key);
72
+ if (existing)
73
+ return existing;
74
+ this.#put(key, { args }, ttlMs);
75
+ return null;
76
+ }
77
+ async finish(key, value, ttlMs) {
78
+ this.#put(key, value, ttlMs);
79
+ }
80
+ async abandon(key) {
81
+ this.#items.delete(key);
82
+ }
83
+ async once(key, ttlMs) {
84
+ if (this.#live(key))
85
+ return false;
86
+ this.#put(key, { args: "" }, ttlMs);
87
+ return true;
88
+ }
89
+ }
90
+ /** A table name SqlStore accepts: a plain lowercase SQL name that leaves room for `_later` (and its index names). */
91
+ function checkTable(table) {
92
+ if (!/^[a-z_][a-z0-9_]{0,44}$/.test(table))
93
+ throw new Error(`SqlStore: table "${table}" must be a plain lowercase SQL name, at most 45 characters`);
94
+ return table;
95
+ }
96
+ const RUN_COLUMNS = "id, tenant, tool, args, args_hash, at, until, author, permissions, proof, issuer, subject, installation, call, confirmed_at";
97
+ function runOf(row) {
98
+ const json = (v) => (typeof v === "string" ? JSON.parse(v) : v);
99
+ return {
100
+ id: String(row.id),
101
+ tenant: String(row.tenant),
102
+ tool: String(row.tool),
103
+ // Kept as the exact text received: its hash is checked again before it runs.
104
+ args: JSON.parse(String(row.args)),
105
+ argsHash: String(row.args_hash),
106
+ at: String(row.at),
107
+ until: Number(row.until),
108
+ author: (json(row.author) ?? null),
109
+ permissions: (json(row.permissions) ?? []),
110
+ proof: row.proof === null || row.proof === undefined ? null : String(row.proof),
111
+ issuer: String(row.issuer),
112
+ subject: String(row.subject),
113
+ installation: String(row.installation),
114
+ call: row.call === null || row.call === undefined ? null : String(row.call),
115
+ confirmedAt: Number(row.confirmed_at),
116
+ };
117
+ }
118
+ /** Later runs in the app's Postgres (`<table>_later`): each method one statement; `claim` takes a pending run atomically. */
119
+ class SqlLater {
120
+ rows;
121
+ table;
122
+ constructor(rows, table) {
123
+ this.rows = rows;
124
+ this.table = table;
125
+ }
126
+ async add(run) {
127
+ await this.rows(`INSERT INTO ${this.table} (${RUN_COLUMNS}, due_at, status) VALUES ($1, $2, $3, $4, $5, $6, $7, $8::jsonb, $9::jsonb, $10, $11, $12, $13, $14, $15, $16::timestamptz, 'pending')`, [run.id, run.tenant, run.tool, JSON.stringify(run.args), run.argsHash, run.at, run.until, JSON.stringify(run.author), JSON.stringify(run.permissions), run.proof, run.issuer, run.subject, run.installation, run.call, run.confirmedAt, new Date(Date.parse(run.at)).toISOString()]);
128
+ }
129
+ async due(tenant, now, limit) {
130
+ const rows = await this.rows(`SELECT ${RUN_COLUMNS} FROM ${this.table} WHERE tenant = $1 AND status = 'pending' AND due_at <= $2::timestamptz ORDER BY due_at LIMIT $3`, [tenant, now.toISOString(), Math.max(1, Math.floor(limit))]);
131
+ return rows.map(runOf);
132
+ }
133
+ async claim(id, tenant) {
134
+ const [row] = await this.rows(`UPDATE ${this.table} SET status = 'running', claimed_at = now() WHERE id = $1 AND tenant = $2 AND status = 'pending' RETURNING ${RUN_COLUMNS}`, [id, tenant]);
135
+ return row ? runOf(row) : null;
136
+ }
137
+ async finish(id, outcome) {
138
+ await this.rows(`UPDATE ${this.table} SET status = $2, message = $3, finished_at = now() WHERE id = $1`, [id, outcome.status, outcome.message]);
139
+ }
140
+ async cancel(id, tenant) {
141
+ return (await this.rows(`UPDATE ${this.table} SET status = 'cancelled', finished_at = now() WHERE id = $1 AND tenant = $2 AND status = 'pending' RETURNING id`, [id, tenant])).length > 0;
142
+ }
143
+ async clear(tenant) {
144
+ return (await this.rows(`DELETE FROM ${this.table} WHERE tenant = $1 RETURNING id`, [tenant])).length;
145
+ }
146
+ }
147
+ /**
148
+ * A store in the app's own Postgres (two tables), for serverless and several
149
+ * instances: every method is a single statement, atomic on its own. Create the
150
+ * tables once with `SqlStore.schema()` in a migration (the SDK never migrates;
151
+ * the SQL is idempotent, so a new migration may run it again).
152
+ * Expired rows are taken over in place and swept now and then.
153
+ */
154
+ export class SqlStore {
155
+ #query;
156
+ #table;
157
+ later;
158
+ #calls = 0;
159
+ constructor(query, options = {}) {
160
+ const table = checkTable(options.table ?? "clegra_store");
161
+ this.#query = query;
162
+ this.#table = table;
163
+ this.later = new SqlLater((text, params) => this.#rows(text, params), `${table}_later`);
164
+ }
165
+ /** The tables (`<table>` and `<table>_later`), as SQL for a migration: `CREATE … IF NOT EXISTS`, safe to run again. */
166
+ static schema(table = "clegra_store") {
167
+ checkTable(table);
168
+ const later = `${table}_later`;
169
+ return [
170
+ `CREATE TABLE IF NOT EXISTS ${table} (key text PRIMARY KEY, args text NOT NULL, result jsonb, done boolean NOT NULL DEFAULT false, expires_at timestamptz NOT NULL);`,
171
+ `CREATE INDEX IF NOT EXISTS ${table}_expires_at ON ${table} (expires_at);`,
172
+ `CREATE TABLE IF NOT EXISTS ${later} (id text PRIMARY KEY, tenant text NOT NULL, tool text NOT NULL, args text NOT NULL, args_hash text NOT NULL, at text NOT NULL, due_at timestamptz NOT NULL, until bigint NOT NULL, author jsonb, permissions jsonb NOT NULL, proof text, issuer text NOT NULL, subject text NOT NULL, installation text NOT NULL, call text, confirmed_at bigint NOT NULL, status text NOT NULL DEFAULT 'pending', message text, created_at timestamptz NOT NULL DEFAULT now(), claimed_at timestamptz, finished_at timestamptz);`,
173
+ `CREATE INDEX IF NOT EXISTS ${later}_due ON ${later} (tenant, due_at) WHERE status = 'pending';`,
174
+ ].join("\n");
175
+ }
176
+ async #rows(text, params) {
177
+ const r = await this.#query(text, params);
178
+ return Array.isArray(r) ? r : r.rows;
179
+ }
180
+ async #sweep() {
181
+ if (++this.#calls % 200 === 0)
182
+ await this.#rows(`DELETE FROM ${this.#table} WHERE expires_at < now()`, []).catch(() => undefined);
183
+ }
184
+ /** Claims `key` when it is free or expired, in one statement: a row back means this caller now holds it. */
185
+ async #claim(key, args, ttlMs) {
186
+ const rows = await this.#rows(`INSERT INTO ${this.#table} (key, args, result, done, expires_at) VALUES ($1, $2, NULL, false, now() + ($3::bigint * interval '1 millisecond'))
187
+ ON CONFLICT (key) DO UPDATE SET args = EXCLUDED.args, result = NULL, done = false, expires_at = EXCLUDED.expires_at WHERE ${this.#table}.expires_at < now()
188
+ RETURNING key`, [key, args, Math.max(1, Math.round(ttlMs))]);
189
+ return rows.length > 0;
190
+ }
191
+ async begin(key, args, ttlMs) {
192
+ await this.#sweep();
193
+ if (await this.#claim(key, args, ttlMs))
194
+ return null;
195
+ const [row] = await this.#rows(`SELECT args, result, done FROM ${this.#table} WHERE key = $1`, [key]);
196
+ // Gone between the two statements (expired and swept): it is free again.
197
+ if (!row)
198
+ return (await this.#claim(key, args, ttlMs)) ? null : { args };
199
+ const result = typeof row.result === "string" ? JSON.parse(row.result) : row.result;
200
+ return row.done ? { args: String(row.args), result } : { args: String(row.args) };
201
+ }
202
+ async finish(key, value, ttlMs) {
203
+ await this.#rows(`UPDATE ${this.#table} SET args = $2, result = $3::jsonb, done = true, expires_at = now() + ($4::bigint * interval '1 millisecond') WHERE key = $1`, [key, value.args, JSON.stringify(value.result ?? null), Math.max(1, Math.round(ttlMs))]);
204
+ }
205
+ async abandon(key) {
206
+ await this.#rows(`DELETE FROM ${this.#table} WHERE key = $1 AND done = false`, [key]);
207
+ }
208
+ async once(key, ttlMs) {
209
+ await this.#sweep();
210
+ return this.#claim(key, "", ttlMs);
211
+ }
212
+ }
213
+ //# sourceMappingURL=store.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"store.js","sourceRoot":"","sources":["../../src/store.ts"],"names":[],"mappings":"AA2EA,mFAAmF;AACnF,MAAM,OAAO,WAAW;IACb,KAAK,GAAG,IAAI,GAAG,EAAmB,CAAA;IAC3C,KAAK,CAAC,GAAG,CAAC,GAAa;QACrB,IAAI,IAAI,CAAC,KAAK,CAAC,GAAG,CAAC,GAAG,CAAC,EAAE,CAAC;YAAE,MAAM,IAAI,KAAK,CAAC,aAAa,GAAG,CAAC,EAAE,SAAS,CAAC,CAAA;QACzE,IAAI,CAAC,KAAK,CAAC,GAAG,CAAC,GAAG,CAAC,EAAE,EAAE,EAAE,GAAG,EAAE,eAAe,CAAC,GAAG,CAAC,EAAE,MAAM,EAAE,SAAS,EAAE,CAAC,CAAA;IAC1E,CAAC;IACD,KAAK,CAAC,GAAG,CAAC,MAAc,EAAE,GAAS,EAAE,KAAa;QAChD,OAAO,CAAC,GAAG,IAAI,CAAC,KAAK,CAAC,MAAM,EAAE,CAAC;aAC5B,MAAM,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,MAAM,KAAK,SAAS,IAAI,CAAC,CAAC,GAAG,CAAC,MAAM,KAAK,MAAM,IAAI,IAAI,CAAC,KAAK,CAAC,CAAC,CAAC,GAAG,C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AAK,CAAC,CAAC,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,EAAE,IAAI,EAAE,CAAA;QACxE,MAAM,MAAM,GAAG,OAAO,GAAG,CAAC,MAAM,KAAK,QAAQ,CAAC,CAAC,CAAE,IAAI,CAAC,KAAK,CAAC,GAAG,CAAC,MAAM,CAAa,CAAC,CAAC,CAAC,GAAG,CAAC,MAAM,CAAA;QAChG,OAAO,GAAG,CAAC,IAAI,CAAC,CAAC,CAAC,EAAE,IAAI,EAAE,MAAM,CAAC,GAAG,CAAC,IAAI,CAAC,EAAE,MAAM,EAAE,CAAC,CAAC,CAAC,EAAE,IAAI,EAAE,MAAM,CAAC,GAAG,CAAC,IAAI,CAAC,EAAE,CAAA;IACnF,CAAC;IAED,KAAK,CAAC,MAAM,CAAC,GAAW,EAAE,KAA2B,EAAE,KAAa;QAClE,MAAM,IAAI,CAAC,KAAK,CAAC,UAAU,IAAI,CAAC,MAAM,8HAA8H,EAAE,CAAC,GAAG,EAAE,KAAK,CAAC,IAAI,EAAE,IAAI,CAAC,SAAS,CAAC,KAAK,CAAC,MAAM,IAAI,IAAI,CAAC,EAAE,IAAI,CAAC,GAAG,CAAC,CAAC,EAAE,IAAI,CAAC,KAAK,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,CAAA;IAChQ,CAAC;IAED,KAAK,CAAC,OAAO,CAAC,GAAW;QACvB,MAAM,IAAI,CAAC,KAAK,CAAC,eAAe,IAAI,CAAC,MAAM,kCAAkC,EAAE,CAAC,GAAG,CAAC,CAAC,CAAA;IACvF,CAAC;IAED,KAAK,CAAC,IAAI,CAAC,GAAW,EAAE,KAAa;QACnC,MAAM,IAAI,CAAC,MAAM,EAAE,CAAA;QACnB,OAAO,IAAI,CAAC,MAAM,CAAC,GAAG,EAAE,EAAE,EAAE,KAAK,CAAC,CAAA;IACpC,CAAC;CACF","sourcesContent":["/**\n * What the server remembers between requests (spec §7): the results of\n * writes, for idempotency, and the ids of tokens that may be used once.\n * Every method is one atomic step. The default keeps it in memory; a server\n * on several instances passes a shared one (a database row with a unique\n * key, Redis SET NX).\n */\nexport type StoredCall = { args: string; result?: unknown }\n\n/**\n * A confirmed call kept to run later («approve now, act later»), exactly as the person confirmed it: its\n * arguments as received and their hash, when (`at`, as given) and until when (`until`, epoch seconds) it may\n * run, its author and the permissions it runs with, and the host's signed proof (null when a plain client\n * confirmed it: no proof exists then) with what re-verifies it (`issuer`, `subject`, `installation`, `call`).\n */\nexport type LaterRun = {\n id: string\n /** The tenant (`<installation>@<issuer>`, or the app's own). */\n tenant: string\n tool: string\n args: Record<string, unknown>\n argsHash: string\n at: string\n until: number\n author: { id: string; name: string } | null\n permissions: string[]\n proof: string | null\n issuer: string\n subject: string\n /** The installation as its issuer names it (the proof's `installation`). */\n installation: string\n call: string | null\n /** When the person confirmed it, epoch seconds (the proof's `iat`). */\n confirmedAt: number\n}\n\n/** How a later run ended. */\nexport type LaterOutcome = { status: \"done\" | \"failed\" | \"expired\" | \"refused\"; message: string }\n\n/**\n * The store's part for later runs. `claim` is the single-use step: it takes a pending run in one atomic step\n * (two callers at the same moment: one gets the run, the other null), and a claimed run is never given again.\n */\nexport type LaterStore = {\n add(run: LaterRun): Promise<void>\n /** Pending runs of the tenant whose `at` is not after `now`, oldest first, at most `limit`. */\n due(tenant: string, now: Date, limit: number): Promise<LaterRun[]>\n claim(id: string, tenant: string): Promise<LaterRun | null>\n finish(id: string, outcome: LaterOutcome): Promise<void>\n /** Cancels a pending run of the tenant: false when there is none (unknown, another tenant's, claimed or finished). */\n cancel(id: string, tenant: string): Promise<boolean>\n /** Deletes every run of the tenant, whatever its state (the app's data deletion): how many. */\n clear(tenant: string): Promise<number>\n}\n\nexport type IdempotencyStore = {\n /**\n * Starts the call `key` with these arguments, in one atomic step: null\n * when nothing was there (the caller now runs it and must `finish` or\n * `abandon` it); else what is there: with `result` when it finished,\n * without while it still runs.\n */\n begin(key: string, args: string, ttlMs: number): Promise<StoredCall | null>\n /** The call's result, kept for `ttlMs`. */\n finish(key: string, value: Required<StoredCall>, ttlMs: number): Promise<void>\n /** The call did not run (refused, or its handler failed): forgotten, so it can be tried again. */\n abandon(key: string): Promise<void>\n /** True the first time `key` is seen within `ttlMs`, false after: atomic. */\n once(key: string, ttlMs: number): Promise<boolean>\n /** Later runs (needed by actions with `later`). */\n later?: LaterStore\n}\n\ntype KeptRun = { run: LaterRun; status: \"pending\" | \"running\" | \"cancelled\" | LaterOutcome[\"status\"]; message?: string }\n\n/** Later runs in memory: what MemoryStore keeps (one process, lost on restart). */\nexport class MemoryLater implements LaterStore {\n readonly #runs = new Map<string, KeptRun>()\n async add(run: LaterRun) {\n if (this.#runs.has(run.id)) throw new Error(`later run ${run.id} exists`)\n this.#runs.set(run.id, { run: structuredClone(run), status: \"pending\" })\n }\n async due(tenant: string, now: Date, limit: number) {\n return [...this.#runs.values()]\n .filter((k) => k.status === \"pending\" && k.run.tenant === tenant && Date.parse(k.run.at) <= now.getTime())\n .sort((a, b) => Date.parse(a.run.at) - Date.parse(b.run.at))\n .slice(0, limit)\n .map((k) => structuredClone(k.run))\n }\n // No await between the read and the write: one step on Node's single thread.\n async claim(id: string, tenant: string) {\n const k = this.#runs.get(id)\n if (!k || k.run.tenant !== tenant || k.status !== \"pending\") return null\n k.status = \"running\"\n return structuredClone(k.run)\n }\n async finish(id: string, outcome: LaterOutcome) {\n const k = this.#runs.get(id)\n if (k) Object.assign(k, { status: outcome.status, message: outcome.message })\n }\n async cancel(id: string, tenant: string) {\n const k = this.#runs.get(id)\n if (!k || k.run.tenant !== tenant || k.status !== \"pending\") return false\n k.status = \"cancelled\"\n return true\n }\n async clear(tenant: string) {\n let n = 0\n for (const [id, k] of this.#runs) if (k.run.tenant === tenant && this.#runs.delete(id)) n++\n return n\n }\n /** For tests: a run as kept, its state included. */\n inspect(id: string): (LaterRun & { status: string; message?: string }) | undefined {\n const k = this.#runs.get(id)\n return k ? { ...structuredClone(k.run), status: k.status, ...(k.message !== undefined ? { message: k.message } : {}) } : undefined\n }\n}\n\nexport class MemoryStore implements IdempotencyStore {\n readonly #items = new Map<string, { value: StoredCall; until: number }>()\n readonly later = new MemoryLater()\n\n #live(key: string): StoredCall | undefined {\n const item = this.#items.get(key)\n if (!item) return undefined\n if (item.until < Date.now()) {\n this.#items.delete(key)\n return undefined\n }\n return item.value\n }\n\n #put(key: string, value: StoredCall, ttlMs: number) {\n if (this.#items.size > 50_000) for (const [k, v] of this.#items) if (v.until < Date.now()) this.#items.delete(k)\n this.#items.set(key, { value, until: Date.now() + ttlMs })\n }\n\n // No await between the read and the write: one step on Node's single thread.\n async begin(key: string, args: string, ttlMs: number) {\n const existing = this.#live(key)\n if (existing) return existing\n this.#put(key, { args }, ttlMs)\n return null\n }\n\n async finish(key: string, value: Required<StoredCall>, ttlMs: number) {\n this.#put(key, value, ttlMs)\n }\n\n async abandon(key: string) {\n this.#items.delete(key)\n }\n\n async once(key: string, ttlMs: number) {\n if (this.#live(key)) return false\n this.#put(key, { args: \"\" }, ttlMs)\n return true\n }\n}\n\n/**\n * Runs one SQL statement with positional parameters (`$1`, `$2`, …) and gives\n * back its rows: whatever the app already talks to its database with\n * (`pg`'s `pool.query`, `postgres`'s `sql.unsafe`, PGlite's `db.query`, a\n * Drizzle `db.execute`). The SDK knows no driver.\n */\nexport type SqlQuery = (text: string, params: unknown[]) => Promise<{ rows: Record<string, unknown>[] } | Record<string, unknown>[]>\n\n/** A table name SqlStore accepts: a plain lowercase SQL name that leaves room for `_later` (and its index names). */\nfunction checkTable(table: string): string {\n if (!/^[a-z_][a-z0-9_]{0,44}$/.test(table)) throw new Error(`SqlStore: table \"${table}\" must be a plain lowercase SQL name, at most 45 characters`)\n return table\n}\n\nconst RUN_COLUMNS = \"id, tenant, tool, args, args_hash, at, until, author, permissions, proof, issuer, subject, installation, call, confirmed_at\"\n\nfunction runOf(row: Record<string, unknown>): LaterRun {\n const json = (v: unknown) => (typeof v === \"string\" ? (JSON.parse(v) as unknown) : v)\n return {\n id: String(row.id),\n tenant: String(row.tenant),\n tool: String(row.tool),\n // Kept as the exact text received: its hash is checked again before it runs.\n args: JSON.parse(String(row.args)) as Record<string, unknown>,\n argsHash: String(row.args_hash),\n at: String(row.at),\n until: Number(row.until),\n author: (json(row.author) ?? null) as LaterRun[\"author\"],\n permissions: (json(row.permissions) ?? []) as string[],\n proof: row.proof === null || row.proof === undefined ? null : String(row.proof),\n issuer: String(row.issuer),\n subject: String(row.subject),\n installation: String(row.installation),\n call: row.call === null || row.call === undefined ? null : String(row.call),\n confirmedAt: Number(row.confirmed_at),\n }\n}\n\n/** Later runs in the app's Postgres (`<table>_later`): each method one statement; `claim` takes a pending run atomically. */\nclass SqlLater implements LaterStore {\n constructor(\n private readonly rows: (text: string, params: unknown[]) => Promise<Record<string, unknown>[]>,\n private readonly table: string,\n ) {}\n async add(run: LaterRun) {\n await this.rows(\n `INSERT INTO ${this.table} (${RUN_COLUMNS}, due_at, status) VALUES ($1, $2, $3, $4, $5, $6, $7, $8::jsonb, $9::jsonb, $10, $11, $12, $13, $14, $15, $16::timestamptz, 'pending')`,\n [run.id, run.tenant, run.tool, JSON.stringify(run.args), run.argsHash, run.at, run.until, JSON.stringify(run.author), JSON.stringify(run.permissions), run.proof, run.issuer, run.subject, run.installation, run.call, run.confirmedAt, new Date(Date.parse(run.at)).toISOString()],\n )\n }\n async due(tenant: string, now: Date, limit: number) {\n const rows = await this.rows(`SELECT ${RUN_COLUMNS} FROM ${this.table} WHERE tenant = $1 AND status = 'pending' AND due_at <= $2::timestamptz ORDER BY due_at LIMIT $3`, [tenant, now.toISOString(), Math.max(1, Math.floor(limit))])\n return rows.map(runOf)\n }\n async claim(id: string, tenant: string) {\n const [row] = await this.rows(`UPDATE ${this.table} SET status = 'running', claimed_at = now() WHERE id = $1 AND tenant = $2 AND status = 'pending' RETURNING ${RUN_COLUMNS}`, [id, tenant])\n return row ? runOf(row) : null\n }\n async finish(id: string, outcome: LaterOutcome) {\n await this.rows(`UPDATE ${this.table} SET status = $2, message = $3, finished_at = now() WHERE id = $1`, [id, outcome.status, outcome.message])\n }\n async cancel(id: string, tenant: string) {\n return (await this.rows(`UPDATE ${this.table} SET status = 'cancelled', finished_at = now() WHERE id = $1 AND tenant = $2 AND status = 'pending' RETURNING id`, [id, tenant])).length > 0\n }\n async clear(tenant: string) {\n return (await this.rows(`DELETE FROM ${this.table} WHERE tenant = $1 RETURNING id`, [tenant])).length\n }\n}\n\n/**\n * A store in the app's own Postgres (two tables), for serverless and several\n * instances: every method is a single statement, atomic on its own. Create the\n * tables once with `SqlStore.schema()` in a migration (the SDK never migrates;\n * the SQL is idempotent, so a new migration may run it again).\n * Expired rows are taken over in place and swept now and then.\n */\nexport class SqlStore implements IdempotencyStore {\n readonly #query: SqlQuery\n readonly #table: string\n readonly later: LaterStore\n #calls = 0\n\n constructor(query: SqlQuery, options: { table?: string } = {}) {\n const table = checkTable(options.table ?? \"clegra_store\")\n this.#query = query\n this.#table = table\n this.later = new SqlLater((text, params) => this.#rows(text, params), `${table}_later`)\n }\n\n /** The tables (`<table>` and `<table>_later`), as SQL for a migration: `CREATE … IF NOT EXISTS`, safe to run again. */\n static schema(table = \"clegra_store\"): string {\n checkTable(table)\n const later = `${table}_later`\n return [\n `CREATE TABLE IF NOT EXISTS ${table} (key text PRIMARY KEY, args text NOT NULL, result jsonb, done boolean NOT NULL DEFAULT false, expires_at timestamptz NOT NULL);`,\n `CREATE INDEX IF NOT EXISTS ${table}_expires_at ON ${table} (expires_at);`,\n `CREATE TABLE IF NOT EXISTS ${later} (id text PRIMARY KEY, tenant text NOT NULL, tool text NOT NULL, args text NOT NULL, args_hash text NOT NULL, at text NOT NULL, due_at timestamptz NOT NULL, until bigint NOT NULL, author jsonb, permissions jsonb NOT NULL, proof text, issuer text NOT NULL, subject text NOT NULL, installation text NOT NULL, call text, confirmed_at bigint NOT NULL, status text NOT NULL DEFAULT 'pending', message text, created_at timestamptz NOT NULL DEFAULT now(), claimed_at timestamptz, finished_at timestamptz);`,\n `CREATE INDEX IF NOT EXISTS ${later}_due ON ${later} (tenant, due_at) WHERE status = 'pending';`,\n ].join(\"\\n\")\n }\n\n async #rows(text: string, params: unknown[]) {\n const r = await this.#query(text, params)\n return Array.isArray(r) ? r : r.rows\n }\n\n async #sweep() {\n if (++this.#calls % 200 === 0) await this.#rows(`DELETE FROM ${this.#table} WHERE expires_at < now()`, []).catch(() => undefined)\n }\n\n /** Claims `key` when it is free or expired, in one statement: a row back means this caller now holds it. */\n async #claim(key: string, args: string, ttlMs: number): Promise<boolean> {\n const rows = await this.#rows(\n `INSERT INTO ${this.#table} (key, args, result, done, expires_at) VALUES ($1, $2, NULL, false, now() + ($3::bigint * interval '1 millisecond'))\n ON CONFLICT (key) DO UPDATE SET args = EXCLUDED.args, result = NULL, done = false, expires_at = EXCLUDED.expires_at WHERE ${this.#table}.expires_at < now()\n RETURNING key`,\n [key, args, Math.max(1, Math.round(ttlMs))],\n )\n return rows.length > 0\n }\n\n async begin(key: string, args: string, ttlMs: number): Promise<StoredCall | null> {\n await this.#sweep()\n if (await this.#claim(key, args, ttlMs)) return null\n const [row] = await this.#rows(`SELECT args, result, done FROM ${this.#table} WHERE key = $1`, [key])\n // Gone between the two statements (expired and swept): it is free again.\n if (!row) return (await this.#claim(key, args, ttlMs)) ? null : { args }\n const result = typeof row.result === \"string\" ? (JSON.parse(row.result) as unknown) : row.result\n return row.done ? { args: String(row.args), result } : { args: String(row.args) }\n }\n\n async finish(key: string, value: Required<StoredCall>, ttlMs: number): Promise<void> {\n await this.#rows(`UPDATE ${this.#table} SET args = $2, result = $3::jsonb, done = true, expires_at = now() + ($4::bigint * interval '1 millisecond') WHERE key = $1`, [key, value.args, JSON.stringify(value.result ?? null), Math.max(1, Math.round(ttlMs))])\n }\n\n async abandon(key: string): Promise<void> {\n await this.#rows(`DELETE FROM ${this.#table} WHERE key = $1 AND done = false`, [key])\n }\n\n async once(key: string, ttlMs: number): Promise<boolean> {\n await this.#sweep()\n return this.#claim(key, \"\", ttlMs)\n }\n}\n"]}
@@ -0,0 +1,133 @@
1
+ import type { App } from "./define.js";
2
+ /**
3
+ * A test client (spec-level, over the real HTTP path): JSON-RPC to
4
+ * `app.fetch` with a dev token, as a plain host or a workspace host (whose
5
+ * tokens are for one request: a new one is signed for each). Needs
6
+ * `auth: { dev: true }` on the app (or `token`).
7
+ */
8
+ export type ToolCallResult = {
9
+ isError?: boolean;
10
+ content?: {
11
+ type: string;
12
+ text?: string;
13
+ resource?: {
14
+ uri: string;
15
+ mimeType?: string;
16
+ blob?: string;
17
+ text?: string;
18
+ };
19
+ }[];
20
+ structuredContent?: Record<string, unknown>;
21
+ _meta?: Record<string, unknown>;
22
+ };
23
+ export type TestClientOptions = {
24
+ /** The person calling (a dev person's id); `null`: nobody — with `host: "workspace"`, the installation itself (see `installationClient`). */
25
+ person?: string | null;
26
+ permissions?: string[] | "all";
27
+ host?: "workspace" | "plain";
28
+ installation?: string;
29
+ locale?: string;
30
+ /** Use this bearer instead of a dev token (null: no Authorization header; a function: a new one per request). */
31
+ token?: string | null | (() => string | Promise<string>);
32
+ /** The address the requests come from (default loopback: dev tokens count only there). */
33
+ remoteAddress?: string;
34
+ };
35
+ /** An export as the test reads it back: the file's facts and its bytes (from the embedded resource). */
36
+ export type ExportedFile = {
37
+ name: string;
38
+ contentType: string;
39
+ bytes: number;
40
+ sha256: string;
41
+ body: Buffer;
42
+ };
43
+ export declare function testClient(app: App, options?: TestClientOptions): Promise<{
44
+ status: number;
45
+ initialize: Record<string, unknown> | undefined;
46
+ rpc: (method: string, params: Record<string, unknown>) => Promise<{
47
+ status: number;
48
+ result?: unknown;
49
+ error?: {
50
+ code: number;
51
+ message: string;
52
+ };
53
+ }>;
54
+ listTools(): Promise<{
55
+ name: string;
56
+ inputSchema: Record<string, unknown>;
57
+ annotations?: Record<string, unknown>;
58
+ _meta?: Record<string, unknown>;
59
+ title?: string;
60
+ description?: string;
61
+ }[]>;
62
+ call(name: string, args?: Record<string, unknown>, meta?: Record<string, unknown>): Promise<ToolCallResult>;
63
+ /**
64
+ * A write as a workspace host does it after the person's «Confirm»: a call id and a proof. For an action with
65
+ * `later` the proof carries the run's deadline (`until`), as a host signs it; `until` overrides it.
66
+ */
67
+ confirmed(name: string, args: Record<string, unknown>, call?: string, proof?: {
68
+ until?: number;
69
+ }): Promise<ToolCallResult>;
70
+ readResource(uri: string): Promise<{
71
+ uri: string;
72
+ mimeType?: string;
73
+ text?: string;
74
+ _meta?: Record<string, unknown>;
75
+ }[]>;
76
+ /** A schedule's run, as the workspace host makes it: its tool, called with `_meta.clegra.schedule` (use an `installationClient`). */
77
+ schedule(name: string, settings?: Record<string, unknown>): Promise<ToolCallResult>;
78
+ /** One pass over the due later runs, as the host's `clegra_later` schedule makes it (use an `installationClient`). */
79
+ runLater(settings?: Record<string, unknown>): Promise<ToolCallResult>;
80
+ /** `clegra_export`, its file read back from the embedded resource: null when the app keeps nothing (use an `installationClient`). */
81
+ exportData(): Promise<{
82
+ result: ToolCallResult;
83
+ file: ExportedFile | null;
84
+ }>;
85
+ }>;
86
+ /**
87
+ * A client that is the installation itself: a workspace host's token with no person, as a host calls schedules,
88
+ * later runs (`runLater`) and the lifecycle tools. `permissions`: what its token lists (default none; a host lists
89
+ * exactly the permission the called action declares).
90
+ */
91
+ export declare function installationClient(app: App, options?: Omit<TestClientOptions, "person" | "host">): Promise<{
92
+ status: number;
93
+ initialize: Record<string, unknown> | undefined;
94
+ rpc: (method: string, params: Record<string, unknown>) => Promise<{
95
+ status: number;
96
+ result?: unknown;
97
+ error?: {
98
+ code: number;
99
+ message: string;
100
+ };
101
+ }>;
102
+ listTools(): Promise<{
103
+ name: string;
104
+ inputSchema: Record<string, unknown>;
105
+ annotations?: Record<string, unknown>;
106
+ _meta?: Record<string, unknown>;
107
+ title?: string;
108
+ description?: string;
109
+ }[]>;
110
+ call(name: string, args?: Record<string, unknown>, meta?: Record<string, unknown>): Promise<ToolCallResult>;
111
+ /**
112
+ * A write as a workspace host does it after the person's «Confirm»: a call id and a proof. For an action with
113
+ * `later` the proof carries the run's deadline (`until`), as a host signs it; `until` overrides it.
114
+ */
115
+ confirmed(name: string, args: Record<string, unknown>, call?: string, proof?: {
116
+ until?: number;
117
+ }): Promise<ToolCallResult>;
118
+ readResource(uri: string): Promise<{
119
+ uri: string;
120
+ mimeType?: string;
121
+ text?: string;
122
+ _meta?: Record<string, unknown>;
123
+ }[]>;
124
+ /** A schedule's run, as the workspace host makes it: its tool, called with `_meta.clegra.schedule` (use an `installationClient`). */
125
+ schedule(name: string, settings?: Record<string, unknown>): Promise<ToolCallResult>;
126
+ /** One pass over the due later runs, as the host's `clegra_later` schedule makes it (use an `installationClient`). */
127
+ runLater(settings?: Record<string, unknown>): Promise<ToolCallResult>;
128
+ /** `clegra_export`, its file read back from the embedded resource: null when the app keeps nothing (use an `installationClient`). */
129
+ exportData(): Promise<{
130
+ result: ToolCallResult;
131
+ file: ExportedFile | null;
132
+ }>;
133
+ }>;
@@ -0,0 +1,81 @@
1
+ import { randomUUID } from "node:crypto";
2
+ import { LATER_TOOL, META_KEY } from "../spec/src/protocol.js";
3
+ export async function testClient(app, options = {}) {
4
+ const { token: given, remoteAddress = "127.0.0.1", ...who } = options;
5
+ const plain = given === undefined && who.host !== "workspace" ? await app.devToken(who) : null;
6
+ const bearer = async () => (typeof given === "function" ? given() : given !== undefined ? given : (plain ?? app.devToken(who)));
7
+ let id = 0;
8
+ const rpc = async (method, params) => {
9
+ const token = await bearer();
10
+ const response = await app.fetch(new Request("http://127.0.0.1/mcp", {
11
+ method: "POST",
12
+ headers: { "content-type": "application/json", accept: "application/json, text/event-stream", "mcp-protocol-version": "2025-06-18", ...(token ? { authorization: `Bearer ${token}` } : {}) },
13
+ body: JSON.stringify({ jsonrpc: "2.0", id: ++id, method, params }),
14
+ }), { remoteAddress });
15
+ const raw = await response.text();
16
+ if (response.status !== 200)
17
+ return { status: response.status };
18
+ const json = response.headers.get("content-type")?.includes("text/event-stream")
19
+ ? JSON.parse(raw.split("\n").filter((l) => l.startsWith("data:")).map((l) => l.slice(5).trim()).filter(Boolean).pop() ?? "{}")
20
+ : JSON.parse(raw);
21
+ return { status: 200, ...(json.result !== undefined ? { result: json.result } : {}), ...(json.error ? { error: json.error } : {}) };
22
+ };
23
+ const init = await rpc("initialize", { protocolVersion: "2025-06-18", capabilities: {}, clientInfo: { name: "clegra-test", version: "1.0.0" } });
24
+ const client = {
25
+ status: init.status,
26
+ initialize: init.result,
27
+ rpc,
28
+ async listTools() {
29
+ const r = await rpc("tools/list", {});
30
+ return (r.result?.tools ?? []);
31
+ },
32
+ async call(name, args = {}, meta = {}) {
33
+ const r = await rpc("tools/call", { name, arguments: args, _meta: meta });
34
+ if (r.error)
35
+ return { isError: true, content: [{ type: "text", text: r.error.message }], structuredContent: { error: { code: "protocol", message: r.error.message } } };
36
+ return r.result;
37
+ },
38
+ /**
39
+ * A write as a workspace host does it after the person's «Confirm»: a call id and a proof. For an action with
40
+ * `later` the proof carries the run's deadline (`until`), as a host signs it; `until` overrides it.
41
+ */
42
+ async confirmed(name, args, call = randomUUID(), proof = {}) {
43
+ const signed = await app.devConfirmation({ tool: name, args, call, ...(options.person ? { person: options.person } : {}), ...(options.installation ? { installation: options.installation } : {}), ...proof });
44
+ return client.call(name, args, { [META_KEY]: { call, confirmation: signed } });
45
+ },
46
+ async readResource(uri) {
47
+ const r = await rpc("resources/read", { uri });
48
+ return (r.result?.contents ?? []);
49
+ },
50
+ /** A schedule's run, as the workspace host makes it: its tool, called with `_meta.clegra.schedule` (use an `installationClient`). */
51
+ async schedule(name, settings) {
52
+ const s = app.manifest().schedules?.find((x) => x.name === name);
53
+ if (!s)
54
+ throw new Error(`testClient.schedule: "${name}" is not a schedule of ${app.name}`);
55
+ return client.call(s.tool, {}, { [META_KEY]: { schedule: name, ...(settings ? { settings } : {}) } });
56
+ },
57
+ /** One pass over the due later runs, as the host's `clegra_later` schedule makes it (use an `installationClient`). */
58
+ async runLater(settings) {
59
+ return client.call(LATER_TOOL, {}, { [META_KEY]: { schedule: LATER_TOOL, ...(settings ? { settings } : {}) } });
60
+ },
61
+ /** `clegra_export`, its file read back from the embedded resource: null when the app keeps nothing (use an `installationClient`). */
62
+ async exportData() {
63
+ const result = await client.call("clegra_export");
64
+ const s = result.structuredContent;
65
+ const blob = result.content?.find((c) => c.type === "resource")?.resource?.blob;
66
+ if (result.isError || !s || s.empty || typeof blob !== "string")
67
+ return { result, file: null };
68
+ return { result, file: { name: String(s.name), contentType: String(s.contentType), bytes: Number(s.bytes), sha256: String(s.sha256), body: Buffer.from(blob, "base64") } };
69
+ },
70
+ };
71
+ return client;
72
+ }
73
+ /**
74
+ * A client that is the installation itself: a workspace host's token with no person, as a host calls schedules,
75
+ * later runs (`runLater`) and the lifecycle tools. `permissions`: what its token lists (default none; a host lists
76
+ * exactly the permission the called action declares).
77
+ */
78
+ export function installationClient(app, options = {}) {
79
+ return testClient(app, { ...options, host: "workspace", person: null });
80
+ }
81
+ //# sourceMappingURL=testing.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"testing.js","sourceRoot":"","sources":["../../src/testing.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,MAAM,aAAa,CAAA;AAExC,OAAO,EAAE,UAAU,EAAE,QAAQ,EAAE,MAAM,sBAAsB,CAAA;AAgC3D,MAAM,CAAC,KAAK,UAAU,UAAU,CAAC,GAAQ,EAAE,UAA6B,EAAE;IACxE,MAAM,EAAE,KAAK,EAAE,KAAK,EAAE,aAAa,GAAG,WAAW,EAAE,GAAG,GAAG,EAAE,GAAG,OAAO,CAAA;IACrE,MAAM,KAAK,GAAG,KAAK,KAAK,SAAS,IAAI,GAAG,CAAC,IAAI,KAAK,WAAW,CAAC,CAAC,CAAC,MAAM,GAAG,CAAC,QAAQ,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,IAAI,CAAA;IAC9F,MAAM,MAAM,GAAG,KAAK,IAAI,EAAE,CAAC,CAAC,OAAO,KAAK,KAAK,UAAU,CA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I,KAAK,UAAU,CAAC,EAAE,QAAQ,EAAE,IAAI,CAAA;YAC/E,IAAI,MAAM,CAAC,OAAO,IAAI,CAAC,CAAC,IAAI,CAAC,CAAC,KAAK,IAAI,OAAO,IAAI,KAAK,QAAQ;gBAAE,OAAO,EAAE,MAAM,EAAE,IAAI,EAAE,IAAI,EAAE,CAAA;YAC9F,OAAO,EAAE,MAAM,EAAE,IAAI,EAAE,EAAE,IAAI,EAAE,MAAM,CAAC,CAAC,CAAC,IAAI,CAAC,EAAE,WAAW,EAAE,MAAM,CAAC,CAAC,CAAC,WAAW,CAAC,EAAE,KAAK,EAAE,MAAM,CAAC,CAAC,CAAC,KAAK,CAAC,EAAE,MAAM,EAAE,MAAM,CAAC,CAAC,CAAC,MAAM,CAAC,EAAE,IAAI,EAAE,MAAM,CAAC,IAAI,CAAC,IAAI,EAAE,QAAQ,CAAC,EAAE,EAAE,CAAA;QAC5K,CAAC;KACF,CAAA;IACD,OAAO,MAAM,CAAA;AACf,CAAC;AAED;;;;GAIG;AACH,MAAM,UAAU,kBAAkB,CAAC,GAAQ,EAAE,UAAsD,EAAE;IACnG,OAAO,UAAU,CAAC,GAAG,EAAE,EAAE,GAAG,OAAO,EAAE,IAAI,EAAE,WAAW,EAAE,MAAM,EAAE,IAAI,EAAE,CAAC,CAAA;AACzE,CAAC","sourcesContent":["import { randomUUID } from \"node:crypto\"\n\nimport { LATER_TOOL, META_KEY } from \"../spec/src/protocol\"\nimport type { App } from \"./define\"\n\n/**\n * A test client (spec-level, over the real HTTP path): JSON-RPC to\n * `app.fetch` with a dev token, as a plain host or a workspace host (whose\n * tokens are for one request: a new one is signed for each). Needs\n * `auth: { dev: true }` on the app (or `token`).\n */\nexport type ToolCallResult = {\n isError?: boolean\n content?: { type: string; text?: string; resource?: { uri: string; mimeType?: string; blob?: string; text?: string } }[]\n structuredContent?: Record<string, unknown>\n _meta?: Record<string, unknown>\n}\n\nexport type TestClientOptions = {\n /** The person calling (a dev person's id); `null`: nobody — with `host: \"workspace\"`, the installation itself (see `installationClient`). */\n person?: string | null\n permissions?: string[] | \"all\"\n host?: \"workspace\" | \"plain\"\n installation?: string\n locale?: string\n /** Use this bearer instead of a dev token (null: no Authorization header; a function: a new one per request). */\n token?: string | null | (() => string | Promise<string>)\n /** The address the requests come from (default loopback: dev tokens count only there). */\n remoteAddress?: string\n}\n\n/** An export as the test reads it back: the file's facts and its bytes (from the embedded resource). */\nexport type ExportedFile = { name: string; contentType: string; bytes: number; sha256: string; body: Buffer }\n\nexport async function testClient(app: App, options: TestClientOptions = {}) {\n const { token: given, remoteAddress = \"127.0.0.1\", ...who } = options\n const plain = given === undefined && who.host !== \"workspace\" ? await app.devToken(who) : null\n const bearer = async () => (typeof given === \"function\" ? given() : given !== undefined ? given : (plain ?? app.devToken(who)))\n let id = 0\n const rpc = async (method: string, params: Record<string, unknown>): Promise<{ status: number; result?: unknown; error?: { code: number; message: string } }> => {\n const token = await bearer()\n const response = await app.fetch(\n new Request(\"http://127.0.0.1/mcp\", {\n method: \"POST\",\n headers: { \"content-type\": \"application/json\", accept: \"application/json, text/event-stream\", \"mcp-protocol-version\": \"2025-06-18\", ...(token ? { authorization: `Bearer ${token}` } : {}) },\n body: JSON.stringify({ jsonrpc: \"2.0\", id: ++id, method, params }),\n }),\n { remoteAddress },\n )\n const raw = await response.text()\n if (response.status !== 200) return { status: response.status }\n const json = response.headers.get(\"content-type\")?.includes(\"text/event-stream\")\n ? JSON.parse(raw.split(\"\\n\").filter((l) => l.startsWith(\"data:\")).map((l) => l.slice(5).trim()).filter(Boolean).pop() ?? \"{}\")\n : JSON.parse(raw)\n return { status: 200, ...(json.result !== undefined ? { result: json.result } : {}), ...(json.error ? { error: json.error } : {}) }\n }\n const init = await rpc(\"initialize\", { protocolVersion: \"2025-06-18\", capabilities: {}, clientInfo: { name: \"clegra-test\", version: \"1.0.0\" } })\n const client = {\n status: init.status,\n initialize: init.result as Record<string, unknown> | undefined,\n rpc,\n async listTools(): Promise<{ name: string; inputSchema: Record<string, unknown>; annotations?: Record<string, unknown>; _meta?: Record<string, unknown>; title?: string; description?: string }[]> {\n const r = await rpc(\"tools/list\", {})\n return ((r.result as { tools?: never[] } | undefined)?.tools ?? []) as never\n },\n async call(name: string, args: Record<string, unknown> = {}, meta: Record<string, unknown> = {}): Promise<ToolCallResult> {\n const r = await rpc(\"tools/call\", { name, arguments: args, _meta: meta })\n if (r.error) return { isError: true, content: [{ type: \"text\", text: r.error.message }], structuredContent: { error: { code: \"protocol\", message: r.error.message } } }\n return r.result as ToolCallResult\n },\n /**\n * A write as a workspace host does it after the person's «Confirm»: a call id and a proof. For an action with\n * `later` the proof carries the run's deadline (`until`), as a host signs it; `until` overrides it.\n */\n async confirmed(name: string, args: Record<string, unknown>, call: string = randomUUID(), proof: { until?: number } = {}): Promise<ToolCallResult> {\n const signed = await app.devConfirmation({ tool: name, args, call, ...(options.person ? { person: options.person } : {}), ...(options.installation ? { installation: options.installation } : {}), ...proof })\n return client.call(name, args, { [META_KEY]: { call, confirmation: signed } })\n },\n async readResource(uri: string): Promise<{ uri: string; mimeType?: string; text?: string; _meta?: Record<string, unknown> }[]> {\n const r = await rpc(\"resources/read\", { uri })\n return ((r.result as { contents?: never[] } | undefined)?.contents ?? []) as never\n },\n /** A schedule's run, as the workspace host makes it: its tool, called with `_meta.clegra.schedule` (use an `installationClient`). */\n async schedule(name: string, settings?: Record<string, unknown>): Promise<ToolCallResult> {\n const s = app.manifest().schedules?.find((x) => x.name === name)\n if (!s) throw new Error(`testClient.schedule: \"${name}\" is not a schedule of ${app.name}`)\n return client.call(s.tool, {}, { [META_KEY]: { schedule: name, ...(settings ? { settings } : {}) } })\n },\n /** One pass over the due later runs, as the host's `clegra_later` schedule makes it (use an `installationClient`). */\n async runLater(settings?: Record<string, unknown>): Promise<ToolCallResult> {\n return client.call(LATER_TOOL, {}, { [META_KEY]: { schedule: LATER_TOOL, ...(settings ? { settings } : {}) } })\n },\n /** `clegra_export`, its file read back from the embedded resource: null when the app keeps nothing (use an `installationClient`). */\n async exportData(): Promise<{ result: ToolCallResult; file: ExportedFile | null }> {\n const result = await client.call(\"clegra_export\")\n const s = result.structuredContent as { name?: string; contentType?: string; bytes?: number; sha256?: string; empty?: boolean } | undefined\n const blob = result.content?.find((c) => c.type === \"resource\")?.resource?.blob\n if (result.isError || !s || s.empty || typeof blob !== \"string\") return { result, file: null }\n return { result, file: { name: String(s.name), contentType: String(s.contentType), bytes: Number(s.bytes), sha256: String(s.sha256), body: Buffer.from(blob, \"base64\") } }\n },\n }\n return client\n}\n\n/**\n * A client that is the installation itself: a workspace host's token with no person, as a host calls schedules,\n * later runs (`runLater`) and the lifecycle tools. `permissions`: what its token lists (default none; a host lists\n * exactly the permission the called action declares).\n */\nexport function installationClient(app: App, options: Omit<TestClientOptions, \"person\" | \"host\"> = {}) {\n return testClient(app, { ...options, host: \"workspace\", person: null })\n}\n"]}