@keemakr/operator-sdk 0.4.0 → 0.6.0-dev-20261124154625

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@keemakr/operator-sdk",
3
- "version": "0.4.0",
3
+ "version": "0.6.0-dev-20261124154625",
4
4
  "description": "The keemakr connector contract: defineProvider + ConnectionProvider/ConnectionOperation types + OperationContext (governed fetch) + the connector manifest schema, shared by keemakr-core's built-in adapters and external connector repos. One shape, two consumers.",
5
5
  "type": "module",
6
6
  "license": "MIT",
@@ -110,11 +110,14 @@ export async function runConformance(
110
110
  // 9/10 — per-op access + idempotency match the reviewed declarations.
111
111
  const accessMismatch: string[] = [];
112
112
  const idemMismatch: string[] = [];
113
+ const decisionMismatch: string[] = [];
113
114
  for (const decl of manifest.operations) {
114
115
  const op = provider.operations?.[decl.name];
115
116
  if (!op) continue;
116
117
  if ((op.access ?? 'write') !== decl.readWrite) accessMismatch.push(decl.name);
117
118
  if ((op.idempotent ?? false) !== decl.idempotent) idemMismatch.push(decl.name);
119
+ if ((op.decisionOnly ?? false) !== (decl.decision_only ?? false))
120
+ decisionMismatch.push(decl.name);
118
121
  }
119
122
  add(
120
123
  'ops-access',
@@ -128,6 +131,14 @@ export async function runConformance(
128
131
  idemMismatch.length === 0,
129
132
  idemMismatch.length ? idemMismatch.join(', ') : undefined,
130
133
  );
134
+ // The code runs the op, so a decision the manifest names but the code does not would be
135
+ // callable by anyone.
136
+ add(
137
+ 'ops-decision-only',
138
+ 'op decision-only flags match the manifest',
139
+ decisionMismatch.length === 0,
140
+ decisionMismatch.length ? decisionMismatch.join(', ') : undefined,
141
+ );
131
142
 
132
143
  // 11/12 — schemas parse safely; call signatures accept (cred, args).
133
144
  const badSchema: string[] = [];
package/src/index.ts CHANGED
@@ -52,6 +52,44 @@ export interface TestResult {
52
52
  detail?: string;
53
53
  }
54
54
 
55
+ // ─── Who a call acts for ─────────────────────────────────────────────────────
56
+ //
57
+ // The VERIFIED answer to "which member is behind this call", handed to an operation on
58
+ // `ctx.actor`. Without it a connector sees only the install, so a connector that must attribute
59
+ // an action would take the person as a tool argument: a value the model fills.
60
+ //
61
+ // Core fills it from what it authenticated (a grant it signed, a member session, the stored
62
+ // requester of an approved write), never from the operation's args. It names the member whose
63
+ // personal connection the call runs on, so it is set only for a `connection_mode: 'user'`
64
+ // connection; on an org-shared (`tenant`) connection `ctx.actor` is null. It is a principal, not
65
+ // an authorization: scopes and the operation's access class are checked before your code runs.
66
+ export interface OperationActor {
67
+ /** The keemakr org this call is scoped to. */
68
+ tenantId: string;
69
+ /** The member whose personal connection this call runs on. */
70
+ userId: string;
71
+ /**
72
+ * That member's org role, read when the call ran, or null when none was proven (no longer a
73
+ * member, or the lookup failed). Fail closed on null; never default it to a role.
74
+ */
75
+ role: 'owner' | 'admin' | 'member' | 'viewer' | null;
76
+ /**
77
+ * What the platform authenticated. `grant` is a Pack's capability grant acting for a member,
78
+ * `schedule` an Automation acting as its owner, `operator` a member in the app, `mcp` a member
79
+ * through the platform's MCP server, `approval` a parked write a person released.
80
+ *
81
+ * Treat this union as OPEN: switch on the values you accept and refuse the rest, so a lane
82
+ * added later fails closed in your connector instead of matching a default branch.
83
+ */
84
+ via: 'grant' | 'schedule' | 'operator' | 'mcp' | 'approval';
85
+ /**
86
+ * True when a person is behind this call as it runs. False on `schedule`, and on a `grant` call
87
+ * whose grant was not minted for a person's session (a Pack task nobody is watching still names
88
+ * the member it acts for). Do not infer it from `via`.
89
+ */
90
+ attended: boolean;
91
+ }
92
+
55
93
  // ─── Execution context ───────────────────────────────────────────────────────
56
94
  //
57
95
  // Handed to an operation (and test()) by the platform at call time. Marketplace
@@ -71,6 +109,11 @@ export interface OperationContext {
71
109
  config?: Record<string, string>;
72
110
  // Trace-correlated logger. Never log credentials or response payloads.
73
111
  log?: (msg: string) => void;
112
+ // WHO this call acts for, as the platform verified it (see OperationActor): the member on a
113
+ // `user`-mode connection, null on a `tenant`-mode one. Absent where core builds no ctx (a
114
+ // built-in adapter, a connect-time probe). An operation that needs attribution treats null and
115
+ // absent alike and refuses, rather than falling back to an args value. Frozen: never write it.
116
+ actor?: Readonly<OperationActor> | null;
74
117
  }
75
118
 
76
119
  // Slim context for the OAuth lifecycle hooks (buildAuthUrl/exchangeCode/refresh):
@@ -100,6 +143,24 @@ export interface ConnectField {
100
143
  help?: string;
101
144
  }
102
145
 
146
+ // Outcome of a connect-time (or on-demand) health probe. `status` is the user-
147
+ // facing vocabulary the Hub renders: 'connected' (probe passed), 'needs_rescope'
148
+ // (OAuth completed but the granted scopes can't run this provider's operations —
149
+ // e.g. Google's granular-consent checkboxes were left unticked), 'no_mailbox'
150
+ // (the account exists but has no mailbox/service behind it — a Workspace account
151
+ // on a Microsoft-mail domain), 'unusable' (probe failed for another reason).
152
+ export interface ProbeResult {
153
+ status: 'connected' | 'needs_rescope' | 'no_mailbox' | 'unusable';
154
+ /** One human-readable sentence for the Hub's status chip. */
155
+ detail?: string;
156
+ /** Scopes the credential actually carries, when the probe can read them. */
157
+ grantedScopes?: string[];
158
+ /** Probed account identity (e.g. the mailbox email) — becomes account_label. */
159
+ accountLabel?: string | null;
160
+ /** Extra provider facts worth persisting under meta.probe. */
161
+ meta?: Record<string, unknown>;
162
+ }
163
+
103
164
  export interface ConnectionProvider {
104
165
  provider: string;
105
166
  displayName: string;
@@ -112,6 +173,29 @@ export interface ConnectionProvider {
112
173
  // Connect-path maturity. Omitted ⇒ 'ready'. See Maturity above.
113
174
  maturity?: Maturity;
114
175
 
176
+ // NOTE: a connection's scope (personal 'user' vs org-shared 'tenant') is NOT
177
+ // declared on the adapter. The live value is connections_registry.connection_mode
178
+ // (the platform-controlled overlay + rollback lever). Marketplace connectors
179
+ // seed it by declaring `connection_mode` in the MANIFEST (first publish only —
180
+ // the registry column is authoritative afterward, and reclassifying a live
181
+ // provider is a guarded staff console action). Built-ins still seed from
182
+ // registry-state's DEFAULT_USER_MODE_PROVIDERS, which stays the fail-closed
183
+ // fallback for unreadable registry reads.
184
+
185
+ // OAuth scopes this provider's operations actually NEED — unlike `scopes`
186
+ // (display-only), these are compared against the granted scope string by the
187
+ // connect-time probe; missing entries mark the connection 'needs_rescope'.
188
+ requiredScopes?: string[];
189
+
190
+ // Connect-time health probe: one cheap read (a profile fetch) that proves the
191
+ // credential can actually operate, run after the OAuth reports success and on
192
+ // demand from the Hub's "Check connection". Omitted ⇒ the connection is
193
+ // trusted as-is (status stays whatever the OAuth layer reported).
194
+ probe?(
195
+ cred: { accessToken: string; meta: Record<string, unknown> },
196
+ ctx?: OperationContext,
197
+ ): Promise<ProbeResult>;
198
+
115
199
  // Audience classification — see ConnectorSurface. Drives whether the end-user
116
200
  // client surfaces this connector and how. Optional in the type for now so
117
201
  // existing/external adapters compile through the SDK bump; defineProvider warns
@@ -188,6 +272,13 @@ export interface ConnectionProvider {
188
272
  token: TokenSet,
189
273
  ): Promise<{ accountLabel: string | null; meta: Record<string, unknown> }>;
190
274
 
275
+ // The provider's stable account id for this credential, never an email or a label; null when the
276
+ // provider cannot tell. A personal connection without one cannot back a recurring grant.
277
+ subject?(cred: { accessToken: string; meta: Record<string, unknown> }): Promise<string | null>;
278
+
279
+ // The published connector version a remote adapter was built from (set by the platform).
280
+ version?: number;
281
+
191
282
  // Named proxy operations a marketplace agent may invoke through the Capability
192
283
  // API (L11). Co-located with the credential logic here so the platform owns
193
284
  // them; agents call by name and never see the credential. Each operation:
@@ -204,10 +295,26 @@ export interface ConnectionProvider {
204
295
  // sees it. Keep `call` pure-ish: do the request, return JSON-serializable data.
205
296
  export interface ConnectionOperation {
206
297
  description?: string;
298
+ // Platform-only provider primitive. It remains available to trusted internal callers that
299
+ // invoke the adapter directly, but is omitted from catalogs and agent/user operation surfaces.
300
+ internal?: boolean;
207
301
  // Access class, for grant scoping + install consent. Omitted ⇒ 'write' (the
208
302
  // most restrictive assumption: unlabeled ops require the write scope and are
209
303
  // listed as writes on the consent screen).
210
304
  access?: 'read' | 'write';
305
+ // An op that discloses a person's personal data, spends paid credits or makes the provider send
306
+ // mail. Workspace test mode refuses it outright, even on a test-target connection.
307
+ refusedInTestMode?: boolean;
308
+ // Cancels or pauses existing work. Never starts a new provider action.
309
+ control?: 'cancel';
310
+ // A decision a person makes. The platform runs it only from a person's approval of these exact
311
+ // args, and names that approver to the connector; a direct call is refused. Omitted ⇒ false.
312
+ decisionOnly?: boolean;
313
+ // Takes a calling Pack's own files as `{ pack_file: <id> }` where its schema allows one. The
314
+ // platform swaps each for a short-lived signed URL before `call`, and only for an op that sets
315
+ // this, so a reference in a free-form field of any other op never becomes a URL the Pack could
316
+ // read back. Omitted ⇒ false.
317
+ packFiles?: boolean;
211
318
  // Safe-to-retry marker. Omitted ⇒ false. The platform NEVER auto-retries a
212
319
  // non-idempotent operation; callers (agents) read this to know what is safe.
213
320
  idempotent?: boolean;
@@ -224,6 +331,44 @@ export interface ConnectionOperation {
224
331
  ): Promise<unknown>;
225
332
  }
226
333
 
334
+ /** An operation's input schema: anything with `safeParse` (zod, valibot, a hand-rolled check). */
335
+ export type OperationInputSchema = ConnectionOperation['inputSchema'];
336
+
337
+ /**
338
+ * The `args` a `call` receives for an input schema: what the schema parses to, when it says (a
339
+ * Standard Schema, zod among them, declares its output type), intersected with an open record;
340
+ * an open record when it does not. Known keys are typed and any other key still reads as
341
+ * `unknown`, so code written against `Record<string, unknown>` keeps compiling.
342
+ */
343
+ export type OperationArgs<S> = S extends { readonly '~standard': { readonly types?: infer T } }
344
+ ? NonNullable<T> extends { readonly output: infer O }
345
+ ? O extends Record<string, unknown>
346
+ ? O & Record<string, unknown>
347
+ : Record<string, unknown>
348
+ : Record<string, unknown>
349
+ : Record<string, unknown>;
350
+
351
+ /** A ConnectionOperation whose `call` is typed by its own input schema (see defineProvider). */
352
+ export interface TypedConnectionOperation<S extends OperationInputSchema> extends Omit<
353
+ ConnectionOperation,
354
+ 'inputSchema' | 'call'
355
+ > {
356
+ inputSchema: S;
357
+ call(
358
+ cred: { accessToken: string; meta: Record<string, unknown> },
359
+ args: OperationArgs<S>,
360
+ ctx?: OperationContext,
361
+ ): Promise<unknown>;
362
+ }
363
+
364
+ /** What `defineProvider` takes: a ConnectionProvider whose operations are typed by their schemas. */
365
+ export type ProviderDefinition<Ops extends Record<string, OperationInputSchema>> = Omit<
366
+ ConnectionProvider,
367
+ 'operations'
368
+ > & {
369
+ operations?: { [K in keyof Ops]: TypedConnectionOperation<Ops[K]> };
370
+ };
371
+
227
372
  // Machine-readable failure classes. The capability proxy maps these to HTTP
228
373
  // codes + health-machine outcomes; a provider outage must never read as a
229
374
  // broken connector, and an auth failure must revoke, not retry.
@@ -232,23 +377,50 @@ export interface ConnectionOperation {
232
377
  // auth_revoked → the credential is dead (401-class, invalid_grant)
233
378
  // egress_blocked → the governed fetch refused a non-allowlisted host
234
379
  // rate_limited → upstream 429 (platform applies backoff)
380
+ // not_found → the provider answered that the named record does not exist
381
+ // provider_credits_exhausted → the provider refused the account for billing before acting.
382
+ // Core treats it as proof that nothing happened, so never throw it
383
+ // after an earlier request of the same call may have acted.
384
+ // forbidden → the provider refused this call on policy: an object the login may
385
+ // not touch, a permission the provider has not approved for the app.
386
+ // A reconnect does not fix it.
387
+ // missing_permission → the login lacks a permission the connector asks for at sign-in, so
388
+ // reconnecting and allowing it fixes the call. The message names what
389
+ // to allow; Core asks the connection's owner to reconnect.
390
+ // recruiting_not_active → the account has no recruiting product, so a recruiting read has no answer
391
+ // invalid_request → the provider refused the request as malformed (a 4xx that says
392
+ // nothing about the provider's health)
393
+ // call_not_placed → a built-in call operation refused before dialling, or the provider
394
+ // said it did not dial. Core treats it as proof that no call rang.
395
+ // org_not_allowed → the call named an organization the calling workspace may not read
235
396
  export type OperationErrorCode =
236
397
  | 'provider_unavailable'
237
398
  | 'connector_error'
238
399
  | 'auth_revoked'
239
400
  | 'egress_blocked'
240
- | 'rate_limited';
401
+ | 'rate_limited'
402
+ | 'not_found'
403
+ | 'provider_credits_exhausted'
404
+ | 'forbidden'
405
+ | 'missing_permission'
406
+ | 'recruiting_not_active'
407
+ | 'invalid_request'
408
+ | 'call_not_placed'
409
+ | 'org_not_allowed';
241
410
 
242
411
  // Throw from a ConnectionOperation.call to surface a typed, agent-safe failure
243
412
  // (maps to a 4xx with a clean message — never leaks the credential).
244
413
  export class OperationError extends Error {
245
414
  status: number;
246
415
  code?: OperationErrorCode;
247
- constructor(message: string, status = 400, code?: OperationErrorCode) {
416
+ // Seconds the provider asked to wait (its Retry-After), for a rate_limited failure.
417
+ retryAfter?: number;
418
+ constructor(message: string, status = 400, code?: OperationErrorCode, retryAfter?: number) {
248
419
  super(message);
249
420
  this.name = 'OperationError';
250
421
  this.status = status;
251
422
  this.code = code;
423
+ this.retryAfter = retryAfter;
252
424
  }
253
425
  }
254
426
 
@@ -280,8 +452,18 @@ export class EgressViolationError extends OperationError {
280
452
  // - a provider key that isn't lowercase-kebab (must match the URL segment and
281
453
  // the connections_registry row)
282
454
  //
455
+ // It also TYPES each operation's `call`: `args` is what the operation's own inputSchema parses
456
+ // to (z.infer of a zod schema, or any Standard Schema's output), so `args.limit` is a number when
457
+ // the schema says so. Known keys are typed; any other key still reads as `unknown`, so connectors
458
+ // that annotate `args` as `Record<string, unknown>` or parse it themselves compile unchanged.
459
+ //
283
460
  // Usage: see keemakr-core's lib/connections/providers/_template.ts.
284
- export function defineProvider(p: ConnectionProvider): ConnectionProvider {
461
+ export function defineProvider<
462
+ Ops extends Record<string, OperationInputSchema> = Record<string, OperationInputSchema>,
463
+ >(definition: ProviderDefinition<Ops>): ConnectionProvider {
464
+ // The typed operations are a narrowing of ConnectionOperation's, never a widening: each `call`
465
+ // accepts at least what its schema parses to, which is all the platform ever passes it.
466
+ const p = definition as unknown as ConnectionProvider;
285
467
  if (!/^[a-z0-9]+(-[a-z0-9]+)*$/.test(p.provider)) {
286
468
  throw new Error(
287
469
  `connections: provider key '${p.provider}' must be lowercase-kebab (e.g. 'mailchimp', 'google-ads')`,
package/src/manifest.ts CHANGED
@@ -26,11 +26,111 @@ const domainPattern =
26
26
  // ('contacts.search', 'weather.current'), hyphens allowed within a segment.
27
27
  const opName = /^[a-z0-9]+(?:[.-][a-z0-9]+)*$/;
28
28
 
29
+ // Top-level JSON Schema keywords an operation's declared input may NOT use. Each one lets the
30
+ // input mean something its top-level `properties` do not say — a union or intersection of shapes,
31
+ // a negation or a condition, a pattern of names, a reference resolved elsewhere — and the declared
32
+ // input exists precisely so that the list of argument names a caller may send can be READ off it:
33
+ // by a reviewer, and by the forwarder that refuses anything else.
34
+ const REFUSED_INPUT_KEYWORDS = [
35
+ 'oneOf',
36
+ 'anyOf',
37
+ 'allOf',
38
+ 'not',
39
+ 'if',
40
+ 'then',
41
+ 'else',
42
+ 'patternProperties',
43
+ 'dependentSchemas',
44
+ '$ref',
45
+ '$dynamicRef',
46
+ ] as const;
47
+
48
+ /** The most arguments one operation may declare, and the longest a declared input may be. */
49
+ const MAX_INPUT_PROPERTIES = 100;
50
+ const MAX_INPUT_SCHEMA_BYTES = 16_384;
51
+
52
+ /**
53
+ * An operation's declared INPUT, as a JSON Schema object: the arguments a caller may send and
54
+ * nothing else. Optional, and read by core only for the lanes that have no adapter code to carry a
55
+ * schema of their own — remote (Lane B) and MCP connectors. There, core builds the operation's
56
+ * input validator from it (unknown arguments refused, required ones and primitive types checked).
57
+ *
58
+ * Deliberately narrow: `type: 'object'`, `properties` listed, `additionalProperties: false`, and
59
+ * none of the keywords above at the top level. Property schemas are ordinary JSON Schema; core
60
+ * checks their `type` and `enum` and leaves the rest to the connector.
61
+ */
62
+ export const operationInputJsonSchema = z
63
+ .looseObject({
64
+ type: z.literal('object'),
65
+ properties: z.record(
66
+ z.string().min(1).max(100),
67
+ z.record(z.string(), z.unknown(), 'each property must be a JSON Schema object'),
68
+ ),
69
+ required: z.array(z.string()).max(MAX_INPUT_PROPERTIES).optional(),
70
+ additionalProperties: z.literal(
71
+ false,
72
+ 'input_schema must set additionalProperties: false — an operation that accepts arguments it does not list cannot be reviewed by its arguments',
73
+ ),
74
+ description: z.string().max(500).optional(),
75
+ })
76
+ .superRefine((schema, ctx) => {
77
+ for (const keyword of REFUSED_INPUT_KEYWORDS) {
78
+ if (keyword in schema) {
79
+ ctx.addIssue({
80
+ code: 'custom',
81
+ path: [keyword],
82
+ message: `input_schema may not use '${keyword}' at the top level — declare the arguments as plain properties`,
83
+ });
84
+ }
85
+ }
86
+ const names = Object.keys(schema.properties);
87
+ if (names.length > MAX_INPUT_PROPERTIES) {
88
+ ctx.addIssue({
89
+ code: 'custom',
90
+ path: ['properties'],
91
+ message: `input_schema may declare at most ${MAX_INPUT_PROPERTIES} properties`,
92
+ });
93
+ }
94
+ const seen = new Set<string>();
95
+ for (const [i, name] of (schema.required ?? []).entries()) {
96
+ if (!names.includes(name)) {
97
+ ctx.addIssue({
98
+ code: 'custom',
99
+ path: ['required', i],
100
+ message: `required names '${name}', which is not one of its properties`,
101
+ });
102
+ }
103
+ if (seen.has(name)) {
104
+ ctx.addIssue({
105
+ code: 'custom',
106
+ path: ['required', i],
107
+ message: `required names '${name}' twice`,
108
+ });
109
+ }
110
+ seen.add(name);
111
+ }
112
+ if (JSON.stringify(schema).length > MAX_INPUT_SCHEMA_BYTES) {
113
+ ctx.addIssue({
114
+ code: 'custom',
115
+ message: `input_schema must be at most ${MAX_INPUT_SCHEMA_BYTES} characters of JSON`,
116
+ });
117
+ }
118
+ });
119
+
29
120
  export const connectorOperationDeclaration = z.object({
30
121
  name: z.string().regex(opName, 'operation names are lowercase, dot/hyphen-scoped'),
31
122
  readWrite: z.enum(['read', 'write']),
32
123
  idempotent: z.boolean(),
33
124
  description: z.string().max(500).optional(),
125
+ // A cancel operation a run may bind as its stop command (work.stop.bind).
126
+ control: z.literal('cancel').optional(),
127
+ // A decision a person makes (approve a task, start a paid render). Core runs it only from the
128
+ // approved exact action of a reviewed Work run, as the approver, and refuses every other caller.
129
+ // Optional for the same reason as input_schema below.
130
+ decision_only: z.boolean().optional(),
131
+ // OPTIONAL, and it must stay optional: stored manifests of already-published versions are
132
+ // re-parsed with the current schema at every publish, and they do not carry it.
133
+ input_schema: operationInputJsonSchema.optional(),
34
134
  });
35
135
 
36
136
  export const connectorManifestSchema = z
@@ -46,6 +146,19 @@ export const connectorManifestSchema = z
46
146
  // publish gate. Optional (the adapter is authoritative); declaring it lets
47
147
  // the upload preview show it before any code runs.
48
148
  auth_kind: z.enum(['oauth2', 'api_key', 'app_password']).optional(),
149
+ // OWNERSHIP axis (orthogonal to `surface`): 'user' = each member connects
150
+ // their OWN account (one row per member, invisible to everyone else — a
151
+ // personal mailbox/drive/calendar); 'tenant' = one org-shared connection.
152
+ // Declare 'user' whenever the credential is one person's own account.
153
+ //
154
+ // Contract: this value SEEDS connections_registry.connection_mode at FIRST
155
+ // publish only — the platform column is authoritative afterward. Changing
156
+ // it in a later version raises a publish-diff warning and does NOT apply;
157
+ // live reclassification is a guarded staff console action (adopt/clean-cut).
158
+ // NEVER make this required, and never make the schema strict: stored
159
+ // manifests of already-published versions are re-parsed with the current
160
+ // schema at every publish, and only a defaulted optional field survives that.
161
+ connection_mode: z.enum(['tenant', 'user']).default('tenant'),
49
162
  // The operator-sdk contract version the connector targets (semver).
50
163
  sdk_version: z.string().regex(/^\d+\.\d+\.\d+$/, 'sdk_version must be exact semver'),
51
164
  // Module (relative path inside the bundle) whose named export is the
@@ -170,6 +283,7 @@ export const connectorManifestSchema = z
170
283
  });
171
284
 
172
285
  export type ConnectorOperationDeclaration = z.infer<typeof connectorOperationDeclaration>;
286
+ export type OperationInputJsonSchema = z.infer<typeof operationInputJsonSchema>;
173
287
  export type ConnectorManifest = z.infer<typeof connectorManifestSchema>;
174
288
 
175
289
  // Parse + normalize an entry.json object. Throws ZodError on invalid input;