@keemakr/operator-sdk 0.8.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.8.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
@@ -332,6 +332,11 @@ export interface ConnectionOperation {
332
332
  // core keeps its own copy, so the card still works after the provider's link
333
333
  // expires. Omitted ⇒ the result holds no media.
334
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 };
335
340
  // A Standard Schema (zod/valibot/…) validating the agent-supplied args. Typed
336
341
  // loosely here so the connector contract doesn't hard-depend on zod; adapters
337
342
  // pass a zod schema and the route validates with `.parse`/`.safeParse`.
@@ -396,25 +401,37 @@ export type ProviderDefinition<Ops extends Record<string, OperationInputSchema>>
396
401
  // can be the connector's own client credentials.
397
402
  // egress_blocked → the governed fetch refused a non-allowlisted host
398
403
  // rate_limited → upstream 429 (platform applies backoff)
399
- export type OperationErrorCode =
400
- | 'provider_unavailable'
401
- | 'connector_error'
402
- | 'auth_revoked'
403
- | 'egress_blocked'
404
- | 'rate_limited'
404
+ export const OPERATION_ERROR_CODES = [
405
+ 'provider_unavailable',
406
+ 'connector_error',
407
+ 'auth_revoked',
408
+ 'egress_blocked',
409
+ 'rate_limited',
405
410
  // The CONNECTOR refused the call on policy — typically an action that must be attributable
406
411
  // reached it unattended. A denial, not a failure: it does not count against the connector's
407
412
  // health or the provider's circuit breaker, so refusing correctly cannot degrade you.
408
- | 'forbidden'
413
+ 'forbidden',
409
414
  // The provider ANSWERED and rejected what the caller sent — bad args, an unknown record, a
410
415
  // failed validation. The caller's fault, not the provider's: like `forbidden` it does not count
411
416
  // against health or the circuit breaker, so one client's bad input cannot shed the connector
412
417
  // for every tenant.
413
- | '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');
414
430
 
415
431
  // Throw from a ConnectionOperation.call to surface a typed, agent-safe failure
416
432
  // (maps to a 4xx with a clean message — never leaks the credential).
417
433
  export class OperationError extends Error {
434
+ readonly [OPERATION_ERROR_BRAND] = 1 as const;
418
435
  status: number;
419
436
  code?: OperationErrorCode;
420
437
  constructor(message: string, status = 400, code?: OperationErrorCode) {
package/src/manifest.ts CHANGED
@@ -127,6 +127,36 @@ 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
 
132
162
  // A name inside a push scheme's envelope (`page`, `leadgen`): lowercase, underscores allowed.
@@ -353,6 +383,65 @@ export const connectorManifestSchema = z
353
383
  'declare exactly one lane — entrypoint, runtime_url, and mcp are mutually exclusive',
354
384
  });
355
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
+ });
356
445
  if (m.runtime_url && !m.runtime_url.startsWith('https://')) {
357
446
  ctx.addIssue({ code: 'custom', path: ['runtime_url'], message: 'runtime_url must be https' });
358
447
  }
@@ -398,6 +487,90 @@ export const connectorManifestSchema = z
398
487
  }
399
488
  });
400
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
+
401
574
  export type ConnectorOperationDeclaration = z.infer<typeof connectorOperationDeclaration>;
402
575
  export type OperationInputJsonSchema = z.infer<typeof operationInputJsonSchema>;
403
576
  export type ConnectorManifest = z.infer<typeof connectorManifestSchema>;