@zackbart/connecta 0.26.3 → 0.28.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (69) hide show
  1. package/AGENTS.md +11 -11
  2. package/CHANGELOG.md +128 -1
  3. package/README.md +15 -19
  4. package/bin/connecta.mjs +10 -6
  5. package/dist/access-tokens.js +13 -2
  6. package/dist/activity.d.ts +5 -4
  7. package/dist/activity.js +1 -10
  8. package/dist/artifacts/connector.d.ts +3 -0
  9. package/dist/artifacts/connector.js +6 -0
  10. package/dist/artifacts/document.js +6 -0
  11. package/dist/artifacts/json.js +10 -0
  12. package/dist/artifacts/module.js +7 -1
  13. package/dist/artifacts/operations.d.ts +3 -1
  14. package/dist/artifacts/operations.js +69 -11
  15. package/dist/artifacts/refresh.d.ts +2 -0
  16. package/dist/artifacts/refresh.js +3 -2
  17. package/dist/artifacts/routes.js +4 -15
  18. package/dist/artifacts/validate.js +2 -4
  19. package/dist/auth/downstream-oauth.js +95 -36
  20. package/dist/catalog-service.js +1 -1
  21. package/dist/connector-scope.d.ts +2 -0
  22. package/dist/connector-scope.js +27 -0
  23. package/dist/connectors/api.js +8 -2
  24. package/dist/connectors/remote-mcp.js +57 -17
  25. package/dist/credentials.js +2 -1
  26. package/dist/execute.js +107 -368
  27. package/dist/executors/quickjs.js +1 -1
  28. package/dist/exempt-writes.js +162 -0
  29. package/dist/index.d.ts +12 -31
  30. package/dist/index.js +15 -47
  31. package/dist/invocation.js +6 -19
  32. package/dist/meta-tools.js +1 -2
  33. package/dist/oauth-partition.js +32 -0
  34. package/dist/operator-ui/generated.js +1 -1
  35. package/dist/operator-ui/model.d.ts +3 -3
  36. package/dist/operator-ui/view.js +6 -4
  37. package/dist/providers/notion.js +4 -1
  38. package/dist/providers/vercel.js +13 -9
  39. package/dist/registry.d.ts +1 -0
  40. package/dist/registry.js +58 -25
  41. package/dist/routes/credentials.js +16 -8
  42. package/dist/routes/mcp.js +5 -21
  43. package/dist/routes/oauth.js +70 -64
  44. package/dist/routes/shared.d.ts +1 -6
  45. package/dist/runtime/run.js +7 -1
  46. package/dist/server.js +0 -4
  47. package/dist/skills.js +8 -23
  48. package/dist/storage/file.js +57 -20
  49. package/dist/storage/memory.js +8 -1
  50. package/dist/tool-safety.d.ts +1 -1
  51. package/dist/tool-safety.js +1 -1
  52. package/dist/types.d.ts +2 -2
  53. package/dist/version.d.ts +1 -1
  54. package/dist/version.js +1 -1
  55. package/documentation/architecture.md +51 -14
  56. package/documentation/auth.md +7 -4
  57. package/documentation/code-mode.md +91 -194
  58. package/documentation/meta-tools.md +38 -41
  59. package/ethos.md +6 -7
  60. package/examples/worker/README.md +14 -17
  61. package/examples/worker/src/d1-activity-row.ts +4 -1
  62. package/examples/worker/src/d1-storage.ts +27 -5
  63. package/examples/worker/src/index.ts +1 -9
  64. package/package.json +4 -4
  65. package/templates/node/AGENTS.md +4 -3
  66. package/templates/node/README.md +3 -4
  67. package/templates/node/package.json +2 -2
  68. package/dist/resumable.js +0 -1291
  69. package/dist/run-journal.js +0 -347
@@ -1,347 +0,0 @@
1
- // The paused-run journal: layout, tokens, and the storage it lives in.
2
- //
3
- // A paused `execute_code` run is not a held program. It is data — the
4
- // program's source, every host call it made and what each returned, and one
5
- // header that says where the run stands — written to the same subject-
6
- // partitioned storage the result stash uses, at the same trust level, and
7
- // expiring on its own. Resuming replays the program from the top against
8
- // those records. Nothing request-bound is in here: a journal is data, not a
9
- // request (ethos, "Nothing request-bound survives a request").
10
- //
11
- // Web-API only, like everything reachable from the root entry.
12
- import { withDeadline } from "./timeout.js";
13
- /** Entry chunks are the result stash's size (`RESULT_CHUNK_BYTES`), in characters. */
14
- const JOURNAL_CHUNK_CHARS = 49_152;
15
- /**
16
- * The most one run may journal: its source plus every recorded host call.
17
- * Internal rather than configurable — it bounds what one caller can park in
18
- * shared storage for half an hour, and nothing about a deployment makes a
19
- * larger notebook the right answer. L6 bounds each host call's result at 256
20
- * KiB on QuickJS, so a run near the host-call budget can reach it.
21
- */
22
- export const MAX_JOURNAL_BYTES = 4 * 1024 * 1024;
23
- /**
24
- * The largest pending write a pause will hold, serialized. The arguments are
25
- * echoed whole in the pause result and must be repeated whole to resume, so
26
- * this is a bound on what a human is asked to read in a prompt, not a storage
27
- * limit. A bigger write goes through `call_destructive_tool`.
28
- */
29
- export const MAX_PENDING_ARGS_BYTES = 16 * 1024;
30
- /** How long an ended run keeps its answer for a repeated resume, in ms. */
31
- const FINAL_HOLD_MS = 30 * 60 * 1_000;
32
- /** A completed run keeps at most this much of its answer for a retried resume. */
33
- export const MAX_FINAL_CHARS = 24_000;
34
- const encoder = new TextEncoder();
35
- export function utf8Bytes(text) {
36
- return encoder.encode(text).byteLength;
37
- }
38
- /**
39
- * JSON with object keys sorted at every depth, so two argument objects that
40
- * differ only in key order serialize identically. Arrays keep their order and
41
- * a type change is a different string: `1` and `"1"` never match.
42
- *
43
- * Written out directly rather than by building sorted objects and handing
44
- * them to `JSON.stringify`: assigning an own `__proto__` key onto a plain
45
- * object sets its prototype instead, so a key that `JSON.parse` kept would
46
- * vanish from the canonical form, and two different writes would compare
47
- * equal.
48
- */
49
- export function canonicalJson(value) {
50
- return canonical(value) ?? "null";
51
- }
52
- function canonical(input) {
53
- let value = input;
54
- if (value !== null &&
55
- typeof value === "object" &&
56
- typeof value.toJSON === "function") {
57
- value = value.toJSON();
58
- }
59
- // Boxed primitives serialize as their value, as JSON.stringify has them.
60
- if (value instanceof Number ||
61
- value instanceof String ||
62
- value instanceof Boolean) {
63
- value = value.valueOf();
64
- }
65
- if (value === null || typeof value !== "object")
66
- return JSON.stringify(value);
67
- if (Array.isArray(value)) {
68
- // Indexed, not mapped: `map` skips a hole, and JSON has none — a hole is
69
- // `null`, as JSON.stringify writes it.
70
- const items = [];
71
- for (let index = 0; index < value.length; index++) {
72
- items.push(canonical(value[index]) ?? "null");
73
- }
74
- return `[${items.join(",")}]`;
75
- }
76
- const parts = [];
77
- for (const key of Object.keys(value).sort()) {
78
- const item = canonical(value[key]);
79
- if (item !== undefined)
80
- parts.push(`${JSON.stringify(key)}:${item}`);
81
- }
82
- return `{${parts.join(",")}}`;
83
- }
84
- /** Whether a `__proto__` key appears anywhere in a JSON value. */
85
- export function hasProtoKey(value) {
86
- if (value === null || typeof value !== "object")
87
- return false;
88
- if (Array.isArray(value))
89
- return value.some(hasProtoKey);
90
- return Object.keys(value).some((key) => key === "__proto__" ||
91
- hasProtoKey(value[key]));
92
- }
93
- /**
94
- * How a replayed host call finds its record: the operation, the address as
95
- * the program wrote it, and its canonical arguments. Several calls may share a
96
- * key; they answer in the order they were first issued.
97
- */
98
- export function journalKey(op, address, args) {
99
- return `${op}\n${address}\n${canonicalJson(args ?? {})}`;
100
- }
101
- const TOKEN_RE = /^r1\.([0-9a-f]{32})\.([0-9a-f]{32})\.(\d{1,15})$/;
102
- export function formatToken(token) {
103
- return `r1.${token.runId}.${token.nonce}.${token.expiresAt}`;
104
- }
105
- export function parseToken(value) {
106
- const match = TOKEN_RE.exec(value);
107
- if (!match)
108
- return undefined;
109
- return {
110
- runId: match[1] ?? "",
111
- nonce: match[2] ?? "",
112
- expiresAt: Number(match[3]),
113
- };
114
- }
115
- /** 128 random bits as hex: a run id, a pause nonce, or a claim id. */
116
- export function randomId() {
117
- const words = new Uint32Array(4);
118
- crypto.getRandomValues(words);
119
- return Array.from(words, (word) => word.toString(16).padStart(8, "0")).join("");
120
- }
121
- export async function sha256Hex(text) {
122
- const digest = await crypto.subtle.digest("SHA-256", encoder.encode(text));
123
- return Array.from(new Uint8Array(digest), (byte) => byte.toString(16).padStart(2, "0")).join("");
124
- }
125
- /**
126
- * Whether a consequential call landed, as far as anyone can know.
127
- *
128
- * `unknown` is the one outcome replay must never paper over: the call left
129
- * connecta and no answer came back, so sending it again could do it twice and
130
- * not sending it could leave it undone. That is a dispatched call that timed
131
- * out, was cancelled, found the service unavailable, or failed any way that
132
- * is not a verdict. A refusal code (`REFUSALS`) or a downstream tool's own
133
- * `isError` is an answer, so it is `failed`, except that an `isError` whose text
134
- * classifies as a timeout is a gateway reporting that it gave up, and stays
135
- * unknown. A call that was never dispatched is `failed`: nothing was sent.
136
- * `result_processing_failed` means the downstream call completed.
137
- */
138
- export function classifyWriteOutcome(outcome) {
139
- if (outcome.ok)
140
- return "ok";
141
- if (!outcome.dispatched)
142
- return "failed";
143
- const code = outcome.error?.code;
144
- if (code === "result_processing_failed")
145
- return "ok";
146
- if (code === "timeout" || code === "cancelled" || code === "unavailable") {
147
- return "unknown";
148
- }
149
- if (code !== undefined && REFUSALS.has(code))
150
- return "failed";
151
- return outcome.answered === true ? "failed" : "unknown";
152
- }
153
- /**
154
- * Codes that say the other side refused the call rather than acted on it:
155
- * the credential, the arguments, the resource, the rate, or a base version
156
- * someone else already moved past (`conflict`). Anything else a
157
- * connector reports after dispatch — `connector_call_failed` from a response
158
- * too large to read, a redirect it would not follow, a body it could not
159
- * parse, a 5xx — may come after the write landed, so only a downstream
160
- * tool's own `isError` answer makes it a known failure.
161
- */
162
- const REFUSALS = new Set([
163
- "auth_required",
164
- "invalid_args",
165
- "not_found",
166
- "rate_limited",
167
- "input_required_unsupported",
168
- "conflict",
169
- ]);
170
- function isRecord(value) {
171
- return value !== null && typeof value === "object" && !Array.isArray(value);
172
- }
173
- /** A header read back from storage, or undefined when it is not one. */
174
- function parseHeader(raw) {
175
- let value;
176
- try {
177
- value = JSON.parse(raw);
178
- }
179
- catch {
180
- return undefined;
181
- }
182
- if (!isRecord(value) ||
183
- value.v !== 1 ||
184
- !["paused", "running", "completed", "failed"].includes(String(value.state)) ||
185
- typeof value.nonce !== "string" ||
186
- typeof value.expiresAt !== "number" ||
187
- typeof value.clock !== "number" ||
188
- !Array.isArray(value.seed) ||
189
- value.seed.length !== 4 ||
190
- !Array.isArray(value.approvals) ||
191
- !Array.isArray(value.writes) ||
192
- typeof value.entries !== "number" ||
193
- typeof value.bytes !== "number" ||
194
- typeof value.playFrom !== "number" ||
195
- typeof value.programHash !== "string") {
196
- return undefined;
197
- }
198
- return value;
199
- }
200
- /**
201
- * One run's keys inside the caller's result storage.
202
- *
203
- * `run:<id>` is the header and the only key ever compare-and-set.
204
- * `run:<id>:src` is the program, written once. `run:<id>:e:<n>` is entry `n`,
205
- * split into `#<k>` continuation keys past one chunk, written before the
206
- * header that counts it. Every key expires with the run.
207
- *
208
- * Every storage call here answers within `timeoutMs` or rejects, as a
209
- * failing store would: a play reserving or settling a write cannot be
210
- * interrupted, and a store that never answers must not hold it — or the
211
- * request waiting on it — forever. A write that timed out may still land;
212
- * each caller treats the call as failed, and every write here is one that is
213
- * safe to find landed later (a compare-and-set that landed after all only
214
- * makes the next one lose).
215
- */
216
- export class RunJournal {
217
- storage;
218
- runId;
219
- timeoutMs;
220
- constructor(storage, runId, timeoutMs) {
221
- this.storage = storage;
222
- this.runId = runId;
223
- this.timeoutMs = timeoutMs;
224
- }
225
- bounded(operation) {
226
- if (this.timeoutMs === undefined)
227
- return operation();
228
- return withDeadline(() => operation(), {
229
- timeoutMs: this.timeoutMs,
230
- timeoutError: new Error(`paused-run storage did not answer within ${this.timeoutMs}ms`),
231
- });
232
- }
233
- get headerKey() {
234
- return `run:${this.runId}`;
235
- }
236
- /** Seconds until `expiresAt`, never less than one. */
237
- static ttlSeconds(expiresAt, now = Date.now()) {
238
- return Math.max(1, Math.ceil((expiresAt - now) / 1_000));
239
- }
240
- async readHeader() {
241
- const raw = await this.bounded(() => this.storage.get(this.headerKey));
242
- if (raw === null)
243
- return undefined;
244
- const header = parseHeader(raw);
245
- return header ? { raw, header } : undefined;
246
- }
247
- /**
248
- * Write `next` only if the header is still exactly `expected` (`null`:
249
- * absent). Returns the stored string on success, `undefined` when another
250
- * writer got there first.
251
- */
252
- async casHeader(expected, next) {
253
- const cas = this.storage.compareAndSet;
254
- if (!cas)
255
- throw new Error("resumable writes need KVStorage.compareAndSet");
256
- const raw = JSON.stringify(next);
257
- // The header outlives `expiresAt` while a claim is live, so a play that
258
- // runs past it can still record what it sent, and after the run ends, so
259
- // a repeated resume gets the same answer rather than "expired, run it
260
- // again" — which would repeat every write the run made. For the same
261
- // reason a run that has sent writes keeps its header past its deadline
262
- // and past a lapsed claim, as a tombstone with their counts.
263
- const sent = next.writes.length > 0;
264
- const keepUntil = Math.max(next.expiresAt, next.claim?.until ?? 0, next.final ? Date.now() + FINAL_HOLD_MS : 0, sent ? next.expiresAt + FINAL_HOLD_MS : 0, sent && next.claim ? next.claim.until + FINAL_HOLD_MS : 0);
265
- const written = await this.bounded(() => cas.call(this.storage, this.headerKey, expected, raw, {
266
- ttlSeconds: RunJournal.ttlSeconds(keepUntil),
267
- }));
268
- return written ? raw : undefined;
269
- }
270
- async writeSource(source, expiresAt) {
271
- await this.bounded(() => this.storage.set(`${this.headerKey}:src`, source, {
272
- ttlSeconds: RunJournal.ttlSeconds(expiresAt),
273
- }));
274
- }
275
- async readSource(programHash) {
276
- const source = await this.bounded(() => this.storage.get(`${this.headerKey}:src`));
277
- if (source === null)
278
- return undefined;
279
- return (await sha256Hex(source)) === programHash ? source : undefined;
280
- }
281
- /** Serialized size of an entry as journaled, for the run's byte bound. */
282
- static entryText(entry) {
283
- return JSON.stringify(entry);
284
- }
285
- writeEntry(index, entry, expiresAt) {
286
- return this.bounded(() => this.writeEntryUnbounded(index, entry, expiresAt));
287
- }
288
- async writeEntryUnbounded(index, entry, expiresAt) {
289
- const text = RunJournal.entryText(entry);
290
- const chunks = [];
291
- for (let at = 0; at < text.length; at += JOURNAL_CHUNK_CHARS) {
292
- chunks.push(text.slice(at, at + JOURNAL_CHUNK_CHARS));
293
- }
294
- if (chunks.length === 0)
295
- chunks.push("");
296
- const ttlSeconds = RunJournal.ttlSeconds(expiresAt);
297
- const key = `${this.headerKey}:e:${index}`;
298
- // Continuations first, the head last: a head that exists names chunks
299
- // that all exist.
300
- for (let part = 1; part < chunks.length; part++) {
301
- await this.storage.set(`${key}#${part}`, chunks[part] ?? "", { ttlSeconds });
302
- }
303
- await this.storage.set(key, `${chunks.length}\n${chunks[0] ?? ""}`, {
304
- ttlSeconds,
305
- });
306
- }
307
- /**
308
- * Entries `0 … count - 1`, or undefined when one is missing or unreadable:
309
- * a journal with a hole cannot be replayed. (A slot a `sending` write
310
- * reserved and never filled is such a hole, and a run holding one has
311
- * failed rather than paused, so it is never read.)
312
- */
313
- readEntries(count) {
314
- return this.bounded(() => this.readEntriesUnbounded(count));
315
- }
316
- async readEntriesUnbounded(count) {
317
- const entries = [];
318
- for (let index = 0; index < count; index++) {
319
- const key = `${this.headerKey}:e:${index}`;
320
- const head = await this.storage.get(key);
321
- if (head === null)
322
- return undefined;
323
- const newline = head.indexOf("\n");
324
- const parts = Number(head.slice(0, newline));
325
- if (newline < 1 || !Number.isSafeInteger(parts) || parts < 1)
326
- return undefined;
327
- let text = head.slice(newline + 1);
328
- for (let part = 1; part < parts; part++) {
329
- const chunk = await this.storage.get(`${key}#${part}`);
330
- if (chunk === null)
331
- return undefined;
332
- text += chunk;
333
- }
334
- try {
335
- const entry = JSON.parse(text);
336
- if (!isRecord(entry) || typeof entry.key !== "string" || !isRecord(entry.outcome)) {
337
- return undefined;
338
- }
339
- entries.push(entry);
340
- }
341
- catch {
342
- return undefined;
343
- }
344
- }
345
- return entries;
346
- }
347
- }