@dual-os/sdk 0.9.2 → 0.11.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.
@@ -1,11 +1,11 @@
1
1
  /** Provider-neutral external Agent Channel contracts. @since 0.0.0 */
2
2
  import type { Context, Effect, Pipeable, SchemaAST } from "effect";
3
- import { Match, Predicate, Schema } from "effect";
3
+ import { Match, Option, Predicate, Schema } from "effect";
4
4
 
5
5
  import * as AuthMethod from "./AuthMethod.ts";
6
+ import { Files } from "./Files.ts";
6
7
  import { validateIdentifier } from "./internal/identifier.ts";
7
8
  import { PipeableProto } from "./internal/proto.ts";
8
- import * as ToolFile from "./ToolFile.ts";
9
9
 
10
10
  export const TypeId = "@dual-os/sdk/AgentChannel" as const;
11
11
  export type TypeId = typeof TypeId;
@@ -43,7 +43,11 @@ export const Features = Schema.Struct({
43
43
  operations: Schema.optionalKey(Schema.Array(OperationKind)),
44
44
  /** Whether `read_context` returns the conversation's earlier messages. */
45
45
  readContext: Schema.optionalKey(Schema.Boolean),
46
+ /** Whether `read_sender` names a sender its messages do not; requires `senderDetails`. */
47
+ readSender: Schema.optionalKey(Schema.Boolean),
46
48
  replies: Schema.Boolean,
49
+ /** Whether messages and context messages may name their sender beyond `senderKey`. */
50
+ senderDetails: Schema.optionalKey(Schema.Boolean),
47
51
  /** Maximum age of the original responding input before preparation and delivery. */
48
52
  responseWindowMs: Schema.optionalKey(Schema.Int.check(Schema.isGreaterThan(0))),
49
53
  threads: Schema.Boolean,
@@ -151,6 +155,55 @@ export const Timestamp = Schema.String.check(
151
155
  }),
152
156
  );
153
157
  export const VerifiedIdentity = Schema.Struct({ conversation: Destination, senderKey: Key });
158
+ const DisplayText = Schema.NonEmptyString.check(
159
+ Schema.isMaxLength(256),
160
+ Schema.isPattern(/^[^\p{Cc}]+$/u),
161
+ );
162
+ const SenderEmail = Schema.NonEmptyString.check(
163
+ Schema.isMaxLength(320),
164
+ Schema.isPattern(/^[^\s@\p{Cc}]+@[^\s@\p{Cc}]+$/u),
165
+ );
166
+ /** What a provider says about a sender besides `senderKey`, the ID to act on; none grants. */
167
+ export const SenderDetails = Schema.Struct({
168
+ /** An address the provider lists for the sender. */
169
+ senderEmail: Schema.optionalKey(SenderEmail),
170
+ /** The name others mention the sender by, such as a username, without a leading `@`. */
171
+ senderHandle: Schema.optionalKey(DisplayText),
172
+ senderName: Schema.optionalKey(DisplayText),
173
+ });
174
+ export type SenderDetails = typeof SenderDetails.Type;
175
+ // Whole characters only, so a cut never splits a surrogate pair.
176
+ const clip = (text: string, max: number) => {
177
+ let kept = "";
178
+ for (const character of text) {
179
+ if (kept.length + character.length > max) break;
180
+ kept += character;
181
+ }
182
+ return kept;
183
+ };
184
+ const display = (value: string | null | undefined) =>
185
+ Option.liftPredicate(
186
+ clip((value ?? "").replace(/\p{Cc}+/gu, " ").trim(), 256).trim(),
187
+ text => text !== "",
188
+ );
189
+ /**
190
+ * Sender details from a provider's raw values: names trimmed, without control characters and cut
191
+ * to 256 characters, a handle without its leading `@`; an empty value or an invalid email is left out.
192
+ */
193
+ export const senderDetails = (values: {
194
+ readonly email?: string | null | undefined;
195
+ readonly handle?: string | null | undefined;
196
+ readonly name?: string | null | undefined;
197
+ }): SenderDetails => {
198
+ const email = Option.liftPredicate((values.email ?? "").trim(), Schema.is(SenderEmail));
199
+ const handle = display((values.handle ?? "").replace(/^@+/u, ""));
200
+ const name = display(values.name);
201
+ return {
202
+ ...Option.match(email, { onNone: () => ({}), onSome: senderEmail => ({ senderEmail }) }),
203
+ ...Option.match(handle, { onNone: () => ({}), onSome: senderHandle => ({ senderHandle }) }),
204
+ ...Option.match(name, { onNone: () => ({}), onSome: senderName => ({ senderName }) }),
205
+ };
206
+ };
154
207
  export type VerifiedIdentity = typeof VerifiedIdentity.Type;
155
208
  export const AccessOutcome = Schema.Struct({ decision: Schema.Literals(["allow", "deny"]) });
156
209
  export type AccessOutcome = typeof AccessOutcome.Type;
@@ -158,7 +211,7 @@ export const Verification = Schema.Struct({ verified: Schema.Literal(true) });
158
211
  export type Verification = typeof Verification.Type;
159
212
  export const Exposure = Schema.Literals(["webhook", "host"]);
160
213
  export const RequiredChecks = Schema.Tuple([Schema.Literal("access")]);
161
- export const Message = Schema.Struct({
214
+ const messageFields = {
162
215
  content: Content,
163
216
  conversation: Destination,
164
217
  eventKey: Key,
@@ -168,7 +221,11 @@ export const Message = Schema.Struct({
168
221
  respond: Schema.Boolean,
169
222
  senderKey: Key,
170
223
  timestamp: Timestamp,
171
- });
224
+ };
225
+ /** Published contracts of versions without `senderDetails` keep this shape. */
226
+ const KeyedMessage = Schema.Struct(messageFields);
227
+ /** A message; sender details only where a version declares `senderDetails`. */
228
+ export const Message = Schema.Struct({ ...messageFields, ...SenderDetails.fields });
172
229
  export const DeliveryUpdate = Schema.Struct({
173
230
  deliveryKey: Key,
174
231
  deliveryUpdateKey: Key,
@@ -199,6 +256,7 @@ export const Stop = Schema.Struct({
199
256
  });
200
257
  export const Event = Schema.Union([Message, Echo, DeliveryUpdate, Stop]);
201
258
  export type Event = typeof Event.Type;
259
+ const KeyedEvent = Schema.Union([KeyedMessage, Echo, DeliveryUpdate, Stop]);
202
260
 
203
261
  /** The reactions every provider can show. Each provider maps them to its own emoji. */
204
262
  export const Reaction = Schema.Literals([
@@ -297,21 +355,35 @@ const contextMessageFields = {
297
355
  text: Text,
298
356
  timestamp: Timestamp,
299
357
  };
300
- /** Published contracts of versions without both `assets` and `readContext` keep this shape. */
301
- const TextContextMessage = Schema.Struct(contextMessageFields);
302
- /** A message read back from history; `assets` only where a version declares assets and context. */
358
+ const contextAssets = {
359
+ assets: Schema.optionalKey(Schema.Array(Asset).check(Schema.isMaxLength(20))),
360
+ };
361
+ const contextSender = {
362
+ senderEmail: SenderDetails.fields.senderEmail,
363
+ senderHandle: SenderDetails.fields.senderHandle,
364
+ };
365
+ /** A message read back from history; each optional group only where its features allow it. */
303
366
  export const ContextMessage = Schema.Struct({
304
367
  ...contextMessageFields,
305
- assets: Schema.optionalKey(Schema.Array(Asset).check(Schema.isMaxLength(20))),
368
+ ...contextAssets,
369
+ ...contextSender,
306
370
  });
307
371
  export type ContextMessage = typeof ContextMessage.Type;
372
+ // Published contracts keep the shape their features had before each optional field existed.
373
+ const TextContextMessage = Schema.Struct(contextMessageFields);
374
+ const AssetContextMessage = Schema.Struct({ ...contextMessageFields, ...contextAssets });
375
+ const SenderContextMessage = Schema.Struct({ ...contextMessageFields, ...contextSender });
376
+ const contextMessageFor = (features: Features) => {
377
+ const sender = features.senderDetails === true;
378
+ if (features.assets && features.readContext === true) {
379
+ return sender ? ContextMessage : AssetContextMessage;
380
+ }
381
+ return sender ? SenderContextMessage : TextContextMessage;
382
+ };
308
383
 
309
384
  /** Decoded originals are limited separately by the host; ordinary command JSON stays bounded. */
310
- export const AssetFile = ToolFile.Schema.check(
311
- Schema.makeFilter(
312
- file =>
313
- file.sizeBytes > 0 && file.sizeBytes <= 10_485_760 && file.contentBase64.length <= 13_981_016,
314
- ),
385
+ export const AssetFile = Files.File.check(
386
+ Schema.makeFilter(file => file.sizeBytes > 0 && file.sizeBytes <= 10_485_760),
315
387
  );
316
388
 
317
389
  /** Closed error vocabulary: provider messages, payloads, and causes never cross this seam. */
@@ -398,7 +470,9 @@ const installedResultSchema = <State extends Schema.Top>(state: State, features?
398
470
  ...operation,
399
471
  verified: Schema.Literal(true),
400
472
  deniedEventKeys: Schema.optionalKey(Schema.Array(Key).check(Schema.isMaxLength(100))),
401
- events: Schema.Array(Event).check(Schema.isMaxLength(100)),
473
+ events: Schema.Array(
474
+ features === undefined || features.senderDetails === true ? Event : KeyedEvent,
475
+ ).check(Schema.isMaxLength(100)),
402
476
  response: Schema.optionalKey(WebhookResponse),
403
477
  /** A provider-native setup challenge or ping proved the configured ingress. */
404
478
  activationProof: Schema.optionalKey(Schema.Literal("verified")),
@@ -435,9 +509,7 @@ const installedResultSchema = <State extends Schema.Top>(state: State, features?
435
509
  ...operation,
436
510
  // Without a version's features, any checked result: the host reads every version's.
437
511
  messages: Schema.Array(
438
- features === undefined || (features.assets && features.readContext === true)
439
- ? ContextMessage
440
- : TextContextMessage,
512
+ features === undefined ? ContextMessage : contextMessageFor(features),
441
513
  ).check(Schema.isMaxLength(200)),
442
514
  }),
443
515
  ]);
@@ -459,11 +531,40 @@ const readAssetResult = Schema.Struct({
459
531
  kind: Schema.Literal("read_asset"),
460
532
  operationKey: Key,
461
533
  });
462
- export const commandSchema = <State extends Schema.Top>(state: State) =>
463
- Schema.Union([installedCommandSchema(state), readAssetCommand(state)]);
534
+ /** What the provider says about the sender of `identity`, after the host checks its access. */
535
+ const readSenderCommand = <State extends Schema.Top>(state: State) =>
536
+ Schema.Struct({
537
+ extensions: Schema.optionalKey(Extensions),
538
+ identity: VerifiedIdentity,
539
+ installationKey: Key,
540
+ kind: Schema.Literal("read_sender"),
541
+ operationKey: Key,
542
+ state,
543
+ });
544
+ const readSenderResult = Schema.Struct({
545
+ ...SenderDetails.fields,
546
+ extensions: Schema.optionalKey(Extensions),
547
+ kind: Schema.Literal("read_sender"),
548
+ operationKey: Key,
549
+ senderKey: Key,
550
+ });
551
+ // Without a version's features, every command and result: the host reads every version's.
552
+ const readsSender = (features: Features | undefined) =>
553
+ features === undefined || features.readSender === true;
554
+ /** Pass a version's features to check its commands against its own contract. */
555
+ export const commandSchema = <State extends Schema.Top>(state: State, features?: Features) =>
556
+ Schema.Union([
557
+ installedCommandSchema(state),
558
+ readAssetCommand(state),
559
+ ...(readsSender(features) ? ([readSenderCommand(state)] as const) : ([] as const)),
560
+ ]);
464
561
  /** Pass a version's features to check its results against its own contract. */
465
562
  export const resultSchema = <State extends Schema.Top>(state: State, features?: Features) =>
466
- Schema.Union([installedResultSchema(state, features), readAssetResult]);
563
+ Schema.Union([
564
+ installedResultSchema(state, features),
565
+ readAssetResult,
566
+ ...(readsSender(features) ? ([readSenderResult] as const) : ([] as const)),
567
+ ]);
467
568
  export type Command<State extends Schema.Top = Schema.Unknown> = ReturnType<
468
569
  typeof commandSchema<State>
469
570
  >["Type"];
@@ -543,7 +644,7 @@ export const projectContract = (
543
644
  Object.entries(definition.extensions ?? {}).map(([key, schema]) => [key, project(schema)]),
544
645
  ),
545
646
  featuresJson: definition.features,
546
- operationInputSchemaJson: project(commandSchema(definition.state)),
647
+ operationInputSchemaJson: project(commandSchema(definition.state, definition.features)),
547
648
  operationOutputSchemaJson: project(resultSchema(definition.state, definition.features)),
548
649
  requiredChecks: definition.requiredChecks,
549
650
  stateSchemaJson: project(definition.state),
@@ -692,7 +793,9 @@ const DefinitionSchema = Schema.Struct({
692
793
  operations.includes("present_outcome") &&
693
794
  new Set(operations).size === operations.length &&
694
795
  // A long text arrives as messages before its outcome.
695
- (features.maxTextLength === undefined || operations.includes("create_message"))
796
+ (features.maxTextLength === undefined || operations.includes("create_message")) &&
797
+ // What a read finds about a sender, its messages may carry too.
798
+ (features.readSender !== true || features.senderDetails === true)
696
799
  );
697
800
  }),
698
801
  );
@@ -415,6 +415,12 @@ export const layer = <P extends Plugin.Any>(
415
415
  ) {
416
416
  return yield* fail("unsupported_feature");
417
417
  }
418
+ if (
419
+ (command.kind === "read_asset" && !definition.features.assets) ||
420
+ (command.kind === "read_sender" && definition.features.readSender !== true)
421
+ ) {
422
+ return yield* fail("unsupported_feature");
423
+ }
418
424
  const handler = Option.fromNullishOr(
419
425
  findHandler(
420
426
  context,
@@ -436,6 +442,7 @@ export const layer = <P extends Plugin.Any>(
436
442
  const kind = command.kind;
437
443
  const deliveryKey = command.kind === "deliver" ? command.deliveryKey : undefined;
438
444
  const assetKey = command.kind === "read_asset" ? command.asset.assetKey : undefined;
445
+ const senderKey = command.kind === "read_sender" ? command.identity.senderKey : undefined;
439
446
  const adapterContext = {
440
447
  definitionSettings,
441
448
  deploymentSettings,
@@ -458,8 +465,8 @@ export const layer = <P extends Plugin.Any>(
458
465
  "invalid_result",
459
466
  );
460
467
  }
461
- if (command.kind === "read_asset") {
462
- if (!definition.features.assets) return yield* fail("unsupported_feature");
468
+ // A read on behalf of a sender acts for that sender, so the sender must have access.
469
+ if (command.kind === "read_asset" || command.kind === "read_sender") {
463
470
  const decision = yield* decodeData(
464
471
  AgentChannel.AccessOutcome,
465
472
  yield* invokeHandler(
@@ -491,7 +498,8 @@ export const layer = <P extends Plugin.Any>(
491
498
  result.kind !== kind ||
492
499
  result.operationKey !== operationKey ||
493
500
  (result.kind === "deliver" && result.deliveryKey !== deliveryKey) ||
494
- (result.kind === "read_asset" && result.assetKey !== assetKey)
501
+ (result.kind === "read_asset" && result.assetKey !== assetKey) ||
502
+ (result.kind === "read_sender" && result.senderKey !== senderKey)
495
503
  ) {
496
504
  return yield* fail("invalid_result");
497
505
  }
package/src/Files.ts CHANGED
@@ -36,7 +36,7 @@ export class FileError extends Schema.TaggedError<FileError>()("FileError", {
36
36
  }) {}
37
37
 
38
38
  /**
39
- * Reads and stores files for the caller of an action: a workflow run, or the person in a chat.
39
+ * Reads and stores files for the caller of an action, trigger or channel operation.
40
40
  *
41
41
  * @since 0.1.0
42
42
  * @category services
@@ -59,7 +59,7 @@ const service = pipe(
59
59
  Effect.serviceOption(Service),
60
60
  Effect.flatMap(
61
61
  Effect.fromOption(() =>
62
- FileError.make({ message: "Files are only available when Dual calls the action" }),
62
+ FileError.make({ message: "Files are only available during a Dual plugin invocation" }),
63
63
  ),
64
64
  ),
65
65
  );
package/src/Http.ts CHANGED
@@ -150,14 +150,17 @@ function sniff(bytes: Uint8Array) {
150
150
  );
151
151
  }
152
152
 
153
+ function fileContentType(bytes: Uint8Array, declared: string | null) {
154
+ return declared === null || pipe(declared, String.startsWith("application/octet-stream"))
155
+ ? (sniff(bytes) ?? declared)
156
+ : declared;
157
+ }
158
+
153
159
  function toolFile(bytes: Uint8Array, declared: string | null, filename: string | null) {
154
160
  return {
155
161
  _tag: "ToolFile",
156
162
  contentBase64: Base64.encode(bytes),
157
- contentType:
158
- declared === null || pipe(declared, String.startsWith("application/octet-stream"))
159
- ? (sniff(bytes) ?? declared)
160
- : declared,
163
+ contentType: fileContentType(bytes, declared),
161
164
  filename,
162
165
  sizeBytes: bytes.byteLength,
163
166
  } satisfies ToolFile.File;
@@ -213,14 +216,30 @@ function textOf(carrier: Carrier, content: Content) {
213
216
 
214
217
  function fileFrom(carrier: Carrier) {
215
218
  return Schema.String.pipe(
216
- Schema.decodeTo(ToolFile.Schema, {
219
+ Schema.decodeTo(Files.File, {
217
220
  decode: SchemaGetter.compose(
218
221
  contentOf(carrier),
219
- SchemaGetter.transform(content => toolFile(content.bytes, content.contentType, null)),
222
+ SchemaGetter.transformEffect((content, options) =>
223
+ pipe(
224
+ Files.write({
225
+ bytes: content.bytes,
226
+ contentType: fileContentType(content.bytes, content.contentType),
227
+ name: "file",
228
+ }),
229
+ Effect.mapError(
230
+ error => new SchemaIssue.InvalidValue({ expected: error.message }, content, options),
231
+ ),
232
+ ),
233
+ ),
220
234
  ),
221
- encode: SchemaGetter.transformEffect((file: ToolFile.File, options) =>
222
- Effect.map(decodeBytes(file.contentBase64, options), bytes =>
223
- textOf(carrier, { bytes, contentType: file.contentType }),
235
+ encode: SchemaGetter.transformEffect((file: Files.File, options) =>
236
+ pipe(
237
+ Files.read(file),
238
+ Effect.mapBoth({
239
+ onSuccess: bytes => textOf(carrier, { bytes, contentType: file.contentType }),
240
+ onFailure: error =>
241
+ new SchemaIssue.InvalidValue({ expected: error.message }, file, options),
242
+ }),
224
243
  ),
225
244
  ),
226
245
  }),
@@ -228,25 +247,11 @@ function fileFrom(carrier: Carrier) {
228
247
  }
229
248
 
230
249
  function encodedFrom(carrier: Carrier) {
231
- return File.pipe(
232
- Schema.decodeTo(Schema.String, {
233
- decode: SchemaGetter.transform(file =>
234
- textOf(carrier, { bytes: file.contentBase64, contentType: file.contentType ?? null }),
235
- ),
236
- encode: SchemaGetter.compose(
237
- contentOf(carrier),
238
- SchemaGetter.transform(content => ({
239
- contentBase64: content.bytes,
240
- contentType: content.contentType,
241
- })),
242
- ),
243
- }),
244
- );
250
+ return Schema.flip(fileFrom(carrier));
245
251
  }
246
252
 
247
253
  /**
248
- * A file the API returns as a Base64 string inside JSON, decoded into a ToolFile with its content
249
- * type recognized from the bytes.
254
+ * A file the API returns as a Base64 string inside JSON, stored by the host and returned by reference.
250
255
  *
251
256
  * @since 0.0.0
252
257
  * @category schemas
@@ -262,7 +267,7 @@ export const FileFromBase64 = fileFrom("base64");
262
267
  export const FileFromBase64Url = fileFrom("base64url");
263
268
 
264
269
  /**
265
- * A {@link File} input the API reads as a Base64 string inside JSON.
270
+ * A {@link Files.File} input the API reads as a Base64 string inside JSON.
266
271
  *
267
272
  * @since 0.0.0
268
273
  * @category schemas
@@ -783,12 +788,9 @@ const read = Effect.fnUntraced(function* (
783
788
  const bytes = new Uint8Array(yield* response.arrayBuffer);
784
789
  const name = dispositionName(response.headers["content-disposition"]);
785
790
  if (body === "file") {
791
+ const declared = response.headers["content-type"] ?? null;
786
792
  return yield* pipe(
787
- Files.write({
788
- bytes,
789
- contentType: Option.getOrNull(Option.fromUndefinedOr(response.headers["content-type"])),
790
- name: name ?? "file",
791
- }),
793
+ Files.write({ bytes, contentType: fileContentType(bytes, declared), name: name ?? "file" }),
792
794
  Effect.mapError(fileFailed),
793
795
  );
794
796
  }
@@ -244,6 +244,7 @@ const FileFailure = Schema.Struct({ message: Schema.String });
244
244
 
245
245
  // The host's file routes do the reading and storing, as the caller the token names.
246
246
  function filesService(access: FileAccess, http: HttpClient.HttpClient) {
247
+ let writes = 0;
247
248
  const client = HttpClient.mapRequest(
248
249
  http,
249
250
  flow(
@@ -281,12 +282,16 @@ function filesService(access: FileAccess, http: HttpClient.HttpClient) {
281
282
  Effect.map(response.arrayBuffer, buffer => new Uint8Array(buffer)),
282
283
  ),
283
284
  write: file =>
284
- call(
285
- pipe(
286
- HttpClientRequest.post("", { urlParams: { name: file.name } }),
287
- HttpClientRequest.bodyUint8Array(file.bytes, file.contentType ?? undefined),
285
+ Effect.suspend(() =>
286
+ call(
287
+ pipe(
288
+ HttpClientRequest.post("", {
289
+ urlParams: { name: file.name, writeIndex: `${writes++}` },
290
+ }),
291
+ HttpClientRequest.bodyUint8Array(file.bytes, file.contentType ?? undefined),
292
+ ),
293
+ response => Effect.flatMap(response.json, Schema.decodeUnknownEffect(Files.File)),
288
294
  ),
289
- response => Effect.flatMap(response.json, Schema.decodeUnknownEffect(Files.File)),
290
295
  ),
291
296
  });
292
297
  }