@keemakr/operator-sdk 0.7.0 → 0.9.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.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@keemakr/operator-sdk",
3
- "version": "0.7.0",
3
+ "version": "0.9.0",
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",
package/src/index.ts CHANGED
@@ -136,11 +136,12 @@ export interface OperationContext {
136
136
  actor?: Readonly<OperationActor>;
137
137
  }
138
138
 
139
- // Slim context for the OAuth lifecycle hooks (buildAuthUrl/exchangeCode/refresh):
140
- // connector-level config, plus the governed fetch for the token exchange —
141
- // marketplace connector code may not touch ambient fetch ANYWHERE (the publish
142
- // scan bans it), so the lifecycle's egress rides the same fenced client as
143
- // operations. There is no tenant credential yet at these steps.
139
+ // Slim context for the lifecycle hooks (buildAuthUrl/exchangeCode/refresh, and
140
+ // extractMeta at connect time): connector-level config, plus the governed fetch
141
+ // for the token exchange and any connect-time lookup — marketplace connector
142
+ // code may not touch ambient fetch ANYWHERE (the publish scan bans it), so the
143
+ // lifecycle's egress rides the same fenced client as operations. There is no
144
+ // stored tenant credential yet at these steps.
144
145
  export interface LifecycleContext {
145
146
  config?: Record<string, string>;
146
147
  fetch?: typeof fetch;
@@ -287,9 +288,15 @@ export interface ConnectionProvider {
287
288
  ): Promise<TestResult>;
288
289
 
289
290
  // Derive a human-readable account_label + durable handle
290
- // (stripe_user_id, store url, ...) to persist alongside the token.
291
+ // (stripe_user_id, store url, ad account id, ...) to persist alongside the
292
+ // token. Runs once per connect, right after exchangeCode (oauth2) or test()
293
+ // (api_key / app_password). `ctx` is the same lifecycle context the connect
294
+ // step used: look the account up with `ctx.fetch` (the governed client,
295
+ // fenced to your `allowed_domains`), never ambient fetch. Optional in the type
296
+ // so one-argument implementations compile unchanged.
291
297
  extractMeta?(
292
298
  token: TokenSet,
299
+ ctx?: LifecycleContext,
293
300
  ): Promise<{ accountLabel: string | null; meta: Record<string, unknown> }>;
294
301
 
295
302
  // Named proxy operations a marketplace agent may invoke through the Capability
@@ -325,6 +332,11 @@ export interface ConnectionOperation {
325
332
  // core keeps its own copy, so the card still works after the provider's link
326
333
  // expires. Omitted ⇒ the result holds no media.
327
334
  media?: ReadonlyArray<{ kind: 'image' | 'audio'; path: string }>;
335
+ // The operation takes one long text argument in ordered parts: `text` is that argument,
336
+ // `index` the part number, `last` (when the operation has one) true on the final part, and
337
+ // `maxChars` the most one part may hold. Lets the Operator pass a chat attachment by id and
338
+ // have core make the calls, one approval for the whole file. Omitted ⇒ no such argument.
339
+ textChunks?: { text: string; index: string; last?: string; maxChars: number };
328
340
  // A Standard Schema (zod/valibot/…) validating the agent-supplied args. Typed
329
341
  // loosely here so the connector contract doesn't hard-depend on zod; adapters
330
342
  // pass a zod schema and the route validates with `.parse`/`.safeParse`.
@@ -382,28 +394,44 @@ export type ProviderDefinition<Ops extends Record<string, OperationInputSchema>>
382
394
  // broken connector, and an auth failure must revoke, not retry.
383
395
  // provider_unavailable → the upstream API is down/5xx/timing out
384
396
  // connector_error → the connector's own fault (bug, bad normalization)
385
- // auth_revoked → the credential is dead (401-class, invalid_grant)
397
+ // auth_revoked → the credential is dead (401-class). From refresh(),
398
+ // it revokes only alongside the token endpoint's
399
+ // `invalid_grant` (keep the word in the message);
400
+ // without it core degrades instead, since a 401 there
401
+ // can be the connector's own client credentials.
386
402
  // egress_blocked → the governed fetch refused a non-allowlisted host
387
403
  // rate_limited → upstream 429 (platform applies backoff)
388
- export type OperationErrorCode =
389
- | 'provider_unavailable'
390
- | 'connector_error'
391
- | 'auth_revoked'
392
- | 'egress_blocked'
393
- | 'rate_limited'
404
+ export const OPERATION_ERROR_CODES = [
405
+ 'provider_unavailable',
406
+ 'connector_error',
407
+ 'auth_revoked',
408
+ 'egress_blocked',
409
+ 'rate_limited',
394
410
  // The CONNECTOR refused the call on policy — typically an action that must be attributable
395
411
  // reached it unattended. A denial, not a failure: it does not count against the connector's
396
412
  // health or the provider's circuit breaker, so refusing correctly cannot degrade you.
397
- | 'forbidden'
413
+ 'forbidden',
398
414
  // The provider ANSWERED and rejected what the caller sent — bad args, an unknown record, a
399
415
  // failed validation. The caller's fault, not the provider's: like `forbidden` it does not count
400
416
  // against health or the circuit breaker, so one client's bad input cannot shed the connector
401
417
  // for every tenant.
402
- | 'invalid_request';
418
+ 'invalid_request',
419
+ ] as const;
420
+
421
+ /** One of {@link OPERATION_ERROR_CODES}. Core drops any other code a connector sends. */
422
+ export type OperationErrorCode = (typeof OPERATION_ERROR_CODES)[number];
423
+
424
+ // How core recognises an OperationError. A vendored connector can load its own copy of this
425
+ // package, and then `instanceof OperationError` is false in core for every error it throws: the
426
+ // two classes are different objects with the same shape. `Symbol.for` returns the same symbol from
427
+ // the global registry in every copy and every realm, so the brand survives where the class does
428
+ // not. Core reads the brand first, then checks `code` against OPERATION_ERROR_CODES.
429
+ export const OPERATION_ERROR_BRAND: unique symbol = Symbol.for('keemakr.operation-error');
403
430
 
404
431
  // Throw from a ConnectionOperation.call to surface a typed, agent-safe failure
405
432
  // (maps to a 4xx with a clean message — never leaks the credential).
406
433
  export class OperationError extends Error {
434
+ readonly [OPERATION_ERROR_BRAND] = 1 as const;
407
435
  status: number;
408
436
  code?: OperationErrorCode;
409
437
  constructor(message: string, status = 400, code?: OperationErrorCode) {
package/src/manifest.ts CHANGED
@@ -127,8 +127,151 @@ export const connectorOperationDeclaration = z.object({
127
127
  // OPTIONAL, and it must stay optional: stored manifests of already-published versions are
128
128
  // re-parsed with the current schema at every publish, and they do not carry it.
129
129
  input_schema: operationInputJsonSchema.optional(),
130
+ // OPTIONAL, for the same reason. The operation takes one long text argument in ordered parts
131
+ // (Kee CRM's crm-csv-import-append: importId, chunkIndex, text, last). Declaring it lets the
132
+ // Operator hand the operation a chat attachment by id: core reads the file and calls the
133
+ // operation once per part, `index` counting up from 0 (a call that sets it is refused: core
134
+ // always sends the whole file, and a retry resends it from 0), `last` true on the final part,
135
+ // all under the person's one approval (KEE-1279). `text`,
136
+ // `index` and `last` name properties of `input_schema`, which must then be declared.
137
+ text_chunks: z
138
+ .object({
139
+ text: z.string().min(1).max(64),
140
+ index: z.string().min(1).max(64),
141
+ last: z.string().min(1).max(64).optional(),
142
+ max_chars: z.number().int().min(1_000).max(1_000_000),
143
+ })
144
+ .optional(),
145
+ // OPTIONAL, for the same reason. The fields this operation RETURNS to the platform, by name and
146
+ // type ('string', 'date', 'number', or a type of the connector's own). PHI never reaches the
147
+ // platform: it stays in the EHR/EMR behind its connector (D-PHI), so this list is what a reviewer
148
+ // reads to see that. Publish warns on a name or type that reads as a patient-record field
149
+ // (patientRecordOutputWarnings); staff review refuses such a connector. Nothing checks call
150
+ // results against it at run time.
151
+ outputs: z
152
+ .array(
153
+ z.object({
154
+ name: z.string().min(1).max(100),
155
+ type: z.string().min(1).max(64),
156
+ }),
157
+ )
158
+ .max(200)
159
+ .optional(),
130
160
  });
131
161
 
162
+ // A name inside a push scheme's envelope (`page`, `leadgen`): lowercase, underscores allowed.
163
+ const pushName = /^[a-z][a-z0-9_]{0,63}$/;
164
+
165
+ /** The op that subscribes (or unsubscribes) an account at the provider, and the arg naming it. */
166
+ const pushAccountOp = z.object({
167
+ op: z.string().regex(opName, 'operation names are lowercase, dot/hyphen-scoped'),
168
+ account_ref_arg: z.string().min(1).max(100),
169
+ });
170
+
171
+ /**
172
+ * PUSHED UPDATES: the provider calls core when something happens, instead of core asking. Core
173
+ * owns the door (`/api/webhooks/connections/<provider>`): it checks the provider's signature with
174
+ * the connector's own config secret, finds the workspaces from the account the update names, and
175
+ * hands each one to the installs that depend on this connector as `core.connection_event.received`.
176
+ *
177
+ * `scheme` is the provider's protocol, implemented once in core. `websub_graph` is the WebSub
178
+ * verification handshake (`hub.challenge`) plus an `X-Hub-Signature-256` HMAC of the raw body and
179
+ * the `{ object, entry: [{ id, changes: [{ field, value }] }] }` envelope.
180
+ *
181
+ * `fields` is the REVIEWED allowlist of what may come through: an update whose (object, field) is
182
+ * not listed is dropped at the door. What a listed field carries reaches a handler under the
183
+ * install's full grant, so a reviewer judges it here, at publish.
184
+ *
185
+ * `register` names the operation that subscribes an account at the provider and the argument that
186
+ * holds the account's id. When that operation runs, core first notes the account for the calling
187
+ * workspace as pending (a call core cannot note is refused), and turns it on only when the provider
188
+ * accepts: only accepted accounts are delivered, so naming an account the workspace's credential
189
+ * does not manage reaches nothing. `unregister`, when the connector has an operation to unsubscribe,
190
+ * turns the account off once the provider accepts. The secret and the verify token must be
191
+ * different keys: the token travels in the clear during the provider's handshake.
192
+ *
193
+ * OPTIONAL, and it must stay optional: stored manifests are re-parsed at every publish.
194
+ */
195
+ export const connectorPushDeclaration = z
196
+ .object({
197
+ scheme: z.enum(['websub_graph']),
198
+ secret_key: z.string().regex(/^[A-Z][A-Z0-9_]*$/, 'config keys are SCREAMING_SNAKE'),
199
+ verify_token_key: z.string().regex(/^[A-Z][A-Z0-9_]*$/, 'config keys are SCREAMING_SNAKE'),
200
+ fields: z
201
+ .array(
202
+ z.object({
203
+ object: z.string().regex(pushName, 'push objects are lowercase, underscores allowed'),
204
+ field: z.string().regex(pushName, 'push fields are lowercase, underscores allowed'),
205
+ }),
206
+ )
207
+ .min(1, 'declare at least one (object, field) the provider may push')
208
+ .max(50),
209
+ register: pushAccountOp,
210
+ unregister: pushAccountOp.optional(),
211
+ })
212
+ .superRefine((p, ctx) => {
213
+ // The verify token is sent in the clear (a URL query) during the provider's handshake; the secret
214
+ // signs every delivery for every customer. One key for both would put the secret in access logs.
215
+ if (p.secret_key === p.verify_token_key) {
216
+ ctx.addIssue({
217
+ code: 'custom',
218
+ path: ['verify_token_key'],
219
+ message: 'verify_token_key must be a different config key from secret_key',
220
+ });
221
+ }
222
+ if (p.unregister && p.unregister.op === p.register.op) {
223
+ ctx.addIssue({
224
+ code: 'custom',
225
+ path: ['unregister', 'op'],
226
+ message: 'push.unregister.op must differ from push.register.op',
227
+ });
228
+ }
229
+ const seen = new Set<string>();
230
+ for (const [i, f] of p.fields.entries()) {
231
+ const k = `${f.object}.${f.field}`;
232
+ if (seen.has(k)) {
233
+ ctx.addIssue({
234
+ code: 'custom',
235
+ path: ['fields', i],
236
+ message: `push.fields lists '${k}' twice`,
237
+ });
238
+ }
239
+ seen.add(k);
240
+ }
241
+ });
242
+
243
+ /**
244
+ * What a push declaration must agree on with the rest of its manifest: the secret and the verify
245
+ * token are declared config keys (staff can only set a declared key), and the register and
246
+ * unregister operations are declared operations. Paths are relative to `push`. Pure. Core runs it
247
+ * again when it reads a pinned manifest, so a block that no longer agrees opens no door.
248
+ */
249
+ export function pushCrossCheckIssues(
250
+ push: ConnectorPushDeclaration,
251
+ manifest: { env: readonly string[]; operations: ReadonlyArray<{ name: string }> },
252
+ ): Array<{ path: (string | number)[]; message: string }> {
253
+ const out: Array<{ path: (string | number)[]; message: string }> = [];
254
+ for (const key of ['secret_key', 'verify_token_key'] as const) {
255
+ if (!manifest.env.includes(push[key])) {
256
+ out.push({
257
+ path: [key],
258
+ message: `push.${key} '${push[key]}' must be one of the config keys declared in env`,
259
+ });
260
+ }
261
+ }
262
+ const ops = new Set(manifest.operations.map((o) => o.name));
263
+ for (const which of ['register', 'unregister'] as const) {
264
+ const decl = push[which];
265
+ if (decl && !ops.has(decl.op)) {
266
+ out.push({
267
+ path: [which, 'op'],
268
+ message: `push.${which}.op '${decl.op}' is not one of the declared operations`,
269
+ });
270
+ }
271
+ }
272
+ return out;
273
+ }
274
+
132
275
  export const connectorManifestSchema = z
133
276
  .object({
134
277
  kind: z.literal('connection'),
@@ -220,6 +363,8 @@ export const connectorManifestSchema = z
220
363
  // the publish gate (both directions: no undeclared ops, no phantom ops). For
221
364
  // remote connectors this list IS the contract core builds the forwarder from.
222
365
  operations: z.array(connectorOperationDeclaration).min(1),
366
+ // Updates the provider pushes to core (see connectorPushDeclaration). Optional.
367
+ push: connectorPushDeclaration.optional(),
223
368
  changelog: z.string().max(5000).optional(),
224
369
  })
225
370
  .superRefine((m, ctx) => {
@@ -238,6 +383,65 @@ export const connectorManifestSchema = z
238
383
  'declare exactly one lane — entrypoint, runtime_url, and mcp are mutually exclusive',
239
384
  });
240
385
  }
386
+ m.operations.forEach((op, i) => {
387
+ if (!op.text_chunks) return;
388
+ const path = ['operations', i, 'text_chunks'];
389
+ // Core sends a file's parts under one approval and a retry resends every part from 0, which
390
+ // is only safe for a write whose parts are idempotent: a read is never held for approval,
391
+ // and a non-idempotent part would land twice on the retry.
392
+ if (op.readWrite !== 'write' || op.idempotent !== true) {
393
+ ctx.addIssue({
394
+ code: 'custom',
395
+ path,
396
+ message:
397
+ 'text_chunks is only for an operation with readWrite: "write" and idempotent: true — a retry resends every part from the start',
398
+ });
399
+ }
400
+ const properties = op.input_schema?.properties;
401
+ if (!properties) {
402
+ ctx.addIssue({
403
+ code: 'custom',
404
+ path,
405
+ message: 'text_chunks needs an input_schema that declares its arguments',
406
+ });
407
+ return;
408
+ }
409
+ const { text, index, last } = op.text_chunks;
410
+ const names = [text, index, ...(last ? [last] : [])];
411
+ if (new Set(names).size !== names.length) {
412
+ ctx.addIssue({
413
+ code: 'custom',
414
+ path,
415
+ message: 'text_chunks must name a different argument for each of text, index and last',
416
+ });
417
+ }
418
+ // Each argument core fills must be declared with the type core sends, or every part fails
419
+ // with a vague "invalid arguments" (a string-typed index, say).
420
+ const expected: [string, string][] = [
421
+ [text, 'string'],
422
+ [index, 'integer'],
423
+ ...(last ? ([[last, 'boolean']] as [string, string][]) : []),
424
+ ];
425
+ for (const [name, type] of expected) {
426
+ const property = properties[name];
427
+ if (!property) {
428
+ ctx.addIssue({
429
+ code: 'custom',
430
+ path,
431
+ message: `text_chunks names '${name}', which is not one of input_schema's properties`,
432
+ });
433
+ continue;
434
+ }
435
+ const declared = property.type;
436
+ if (declared !== type && !(Array.isArray(declared) && declared.includes(type))) {
437
+ ctx.addIssue({
438
+ code: 'custom',
439
+ path,
440
+ message: `text_chunks needs input_schema's '${name}' to be type '${type}' — core sends it as one`,
441
+ });
442
+ }
443
+ }
444
+ });
241
445
  if (m.runtime_url && !m.runtime_url.startsWith('https://')) {
242
446
  ctx.addIssue({ code: 'custom', path: ['runtime_url'], message: 'runtime_url must be https' });
243
447
  }
@@ -276,11 +480,101 @@ export const connectorManifestSchema = z
276
480
  'mcp connectors must declare connect_fields (there is no adapter code to own the form)',
277
481
  });
278
482
  }
483
+ if (m.push) {
484
+ for (const issue of pushCrossCheckIssues(m.push, m)) {
485
+ ctx.addIssue({ code: 'custom', path: ['push', ...issue.path], message: issue.message });
486
+ }
487
+ }
279
488
  });
280
489
 
490
+ /**
491
+ * The category a connector to a health-record system (an EHR or EMR) declares. Its operations are
492
+ * expected to list their `outputs`, because that boundary is where PHI must stop (D-PHI).
493
+ */
494
+ export const HEALTH_RECORD_CATEGORY = 'health-record';
495
+
496
+ // Category is free text, so an EHR connector filed as `ehr` or `emr` is read the same way.
497
+ const HEALTH_RECORD_CATEGORIES: ReadonlySet<string> = new Set([
498
+ HEALTH_RECORD_CATEGORY,
499
+ 'ehr',
500
+ 'emr',
501
+ ]);
502
+
503
+ /** True for a category that names a health-record system: `health-record`, `ehr` or `emr`. Pure. */
504
+ export function isHealthRecordCategory(category: string): boolean {
505
+ return HEALTH_RECORD_CATEGORIES.has(category);
506
+ }
507
+
508
+ // Patient-record fields, matched on a field's name or declared type after splitting camelCase and
509
+ // punctuation into words: "patientDOB", "date-of-birth" and "Lab Results" all match. A short list on
510
+ // purpose: a lint a reviewer reads, not a classifier.
511
+ const PATIENT_RECORD_FIELDS: ReadonlyArray<[label: string, pattern: RegExp]> = [
512
+ ['diagnosis', /(^|_)(diagnos[a-z]*|dx|icd(_?10)?)(_|$)/],
513
+ ['medication', /(^|_)(medications?|meds|prescriptions?)(_|$)/],
514
+ ['MRN', /(^|_)(mrns?|medical_records?(_numbers?)?)(_|$)/],
515
+ ['date of birth', /(^|_)(dobs?|dates?_of_birth|birth_?(date|dt)s?)(_|$)/],
516
+ ['clinical note', /(^|_)clinical_notes?(_|$)/],
517
+ // Not an accounting connector's chart of accounts.
518
+ ['chart', /(^|_)charts?(?!_of_accounts)(_|$)/],
519
+ ['lab result', /(^|_)lab_results?(_|$)/],
520
+ ['insurance member id', /(^|_)insurance_(member_)?(id|number)(_|$)/],
521
+ ];
522
+
523
+ const words = (text: string) =>
524
+ text
525
+ .replace(/([a-z0-9])([A-Z])/g, '$1_$2')
526
+ // An acronym ends where a capitalised word starts ("HTTPServer"), but its plural stays one
527
+ // word ("MRNs", "DOBs").
528
+ .replace(/([A-Z]+)([A-Z][a-z]{2,})/g, '$1_$2')
529
+ .toLowerCase()
530
+ .replace(/[^a-z0-9]+/g, '_')
531
+ .replace(/^_+|_+$/g, '');
532
+
533
+ /** The patient-record field a name or type reads as, or null. Pure. */
534
+ export function patientRecordField(text: string): string | null {
535
+ const normal = words(text);
536
+ for (const [label, pattern] of PATIENT_RECORD_FIELDS) if (pattern.test(normal)) return label;
537
+ return null;
538
+ }
539
+
540
+ /**
541
+ * The D-PHI publish lint: one warning per declared output whose name or type reads as a
542
+ * patient-record field, and, for a connector in a health-record category, one per operation
543
+ * that declares no outputs. Warnings, never errors: staff decide at review. Pure.
544
+ */
545
+ export function patientRecordOutputWarnings(manifest: {
546
+ category: string;
547
+ operations: ReadonlyArray<Pick<ConnectorOperationDeclaration, 'name' | 'outputs'>>;
548
+ }): string[] {
549
+ const out: string[] = [];
550
+ for (const op of manifest.operations) {
551
+ if (!op.outputs) {
552
+ if (isHealthRecordCategory(manifest.category)) {
553
+ out.push(
554
+ `operation '${op.name}' declares no outputs, and this is a health-record connector: ` +
555
+ `list the fields it returns so review can see no patient record reaches the platform (D-PHI)`,
556
+ );
557
+ }
558
+ continue;
559
+ }
560
+ for (const field of op.outputs) {
561
+ const hit = patientRecordField(field.name) ?? patientRecordField(field.type);
562
+ if (hit) {
563
+ out.push(
564
+ `operation '${op.name}' returns '${field.name}' (${field.type}), which reads as a ` +
565
+ `patient record (${hit}): PHI stays in the EMR behind its connector (D-PHI), and ` +
566
+ `review refuses a connector whose outputs carry patient-record fields`,
567
+ );
568
+ }
569
+ }
570
+ }
571
+ return out;
572
+ }
573
+
281
574
  export type ConnectorOperationDeclaration = z.infer<typeof connectorOperationDeclaration>;
282
575
  export type OperationInputJsonSchema = z.infer<typeof operationInputJsonSchema>;
283
576
  export type ConnectorManifest = z.infer<typeof connectorManifestSchema>;
577
+ export type ConnectorPushDeclaration = z.infer<typeof connectorPushDeclaration>;
284
578
 
285
579
  // Parse + normalize an entry.json object. Throws ZodError on invalid input;
286
580
  // callers wanting a report use connectorManifestSchema.safeParse directly.