@jush-agent/sdk 0.2.6325 → 0.2.6342

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/dist/index.mjs CHANGED
@@ -158,7 +158,9 @@ const queuedMessageSchema = z.object({
158
158
  * The schedule's run that sent it, which its `user` block keeps;
159
159
  * absent for a message the user wrote.
160
160
  */
161
- schedule: scheduleMarkSchema.optional()
161
+ schedule: scheduleMarkSchema.optional(),
162
+ /** Who sent it, which its `user` block keeps. */
163
+ senderId: z.string().min(1).max(255).optional()
162
164
  });
163
165
  /** What an `abort` stopped, and whether another `abort` would stop more. */
164
166
  const abortResultSchema = z.object({
@@ -530,7 +532,9 @@ const pendingSteerSchema = z.object({
530
532
  * The comments it carries, which its `steer` block keeps; omitted when
531
533
  * there are none.
532
534
  */
533
- comments: z.array(messageCommentSchema).optional()
535
+ comments: z.array(messageCommentSchema).optional(),
536
+ /** Who sent it, which its `steer` block keeps. */
537
+ senderId: z.string().min(1).max(255).optional()
534
538
  });
535
539
  /** One agent of the conversation. */
536
540
  const agentEntrySchema = z.object({
@@ -723,7 +727,17 @@ const agentMessageSchema = z.object({
723
727
  * last answer. None for any other completion, for a failure with no record
724
728
  * and for a message no agent sent.
725
729
  */
726
- origin: z.string().min(1).nullable().optional()
730
+ origin: z.string().min(1).nullable().optional(),
731
+ /**
732
+ * Whom the work the message tells of is for, by the id its program
733
+ * gave its sender (`crate::UserBlock`'s `sender_id`): for an explicit
734
+ * message, whom the sending agent worked for
735
+ * (`crate::Block::sender_id`); for a child's end, whom the child worked
736
+ * for as it closed; for the end of another conversation's work, whom
737
+ * the message that asked for it named. Absent for any other message,
738
+ * and when no one was named.
739
+ */
740
+ senderId: z.string().min(1).max(255).nullable().optional()
727
741
  });
728
742
  /** How the video an edit or an extension changes went to the vendor. */
729
743
  const sentSourceSchema = z.discriminatedUnion("type", [
@@ -1031,7 +1045,13 @@ const commandReportSchema = z.object({
1031
1045
  * reference, or the part that took its place, then the text of the
1032
1046
  * lines about them; none for a report of progress.
1033
1047
  */
1034
- media: z.array(toolResultContentBlockSchema).optional()
1048
+ media: z.array(toolResultContentBlockSchema).optional(),
1049
+ /**
1050
+ * Whom the command's work is for: the sender of the call that started
1051
+ * it, which its record keeps; absent when that call's work was for no
1052
+ * one named.
1053
+ */
1054
+ senderId: z.string().min(1).max(255).optional()
1035
1055
  });
1036
1056
  /** Where a vendor's step is. */
1037
1057
  const opaqueStatusSchema = z.enum([
@@ -1455,7 +1475,12 @@ const blockSchema = z.discriminatedUnion("type", [
1455
1475
  * names above it as a receipt names the agent that sent one; absent
1456
1476
  * for a message the user wrote.
1457
1477
  */
1458
- schedule: scheduleMarkSchema.optional()
1478
+ schedule: scheduleMarkSchema.optional(),
1479
+ /**
1480
+ * Who sent the message, by the id the program that sent it gave
1481
+ * ([`SENDER_ID_LIMIT`]); absent when it named no one.
1482
+ */
1483
+ senderId: z.string().min(1).max(255).optional()
1459
1484
  }),
1460
1485
  z.object({
1461
1486
  type: z.literal("context"),
@@ -1471,7 +1496,8 @@ const blockSchema = z.discriminatedUnion("type", [
1471
1496
  request: z.string().min(1).optional(),
1472
1497
  model: modelSelectionSchema,
1473
1498
  /**
1474
- * The source that answered: `execution`, [`INSTRUCTIONS_SOURCE`],
1499
+ * The source that answered: [`USER_TIME_SOURCE`], `execution`,
1500
+ * [`INSTRUCTIONS_SOURCE`], [`PINNED_DOCUMENTS_SOURCE`],
1475
1501
  * [`WORKING_DIRECTORY_SOURCE`], or a plugin's id.
1476
1502
  */
1477
1503
  source: z.string().min(1).max(64),
@@ -1503,7 +1529,10 @@ const blockSchema = z.discriminatedUnion("type", [
1503
1529
  request: z.string().min(1).optional(),
1504
1530
  model: modelSelectionSchema,
1505
1531
  placement: wakeupPlacementSchema,
1506
- /** The reports, in the order they arrived. */
1532
+ /**
1533
+ * The reports, in the order they arrived; for a block that opens its
1534
+ * turn, those that opened it first.
1535
+ */
1507
1536
  reports: z.array(commandReportSchema),
1508
1537
  /**
1509
1538
  * The run of steps the block belongs to: the id of the run's first
@@ -1530,7 +1559,9 @@ const blockSchema = z.discriminatedUnion("type", [
1530
1559
  * The comments sent with it, which the model reads before its content
1531
1560
  * as a message's; omitted when there are none.
1532
1561
  */
1533
- comments: z.array(messageCommentSchema).optional()
1562
+ comments: z.array(messageCommentSchema).optional(),
1563
+ /** Who sent it, as a `user` block names its sender. */
1564
+ senderId: z.string().min(1).max(255).optional()
1534
1565
  }),
1535
1566
  z.object({
1536
1567
  type: z.literal("agent_message"),
@@ -1547,6 +1578,11 @@ const blockSchema = z.discriminatedUnion("type", [
1547
1578
  model: modelSelectionSchema,
1548
1579
  message: agentMessageSchema,
1549
1580
  /**
1581
+ * The message opened its turn, a continuation of an agent at rest, as
1582
+ * the first message written there; absent for any other.
1583
+ */
1584
+ opensTurn: z.boolean().optional(),
1585
+ /**
1550
1586
  * The run of steps the block belongs to: the id of the run's first
1551
1587
  * block, which the backend sets as it stores the block and never
1552
1588
  * changes.
@@ -2266,7 +2302,14 @@ z.discriminatedUnion("type", [
2266
2302
  * The comments the message carries, which may make it without content;
2267
2303
  * omitted when there are none.
2268
2304
  */
2269
- comments: z.array(clientCommentSchema).optional()
2305
+ comments: z.array(clientCommentSchema).optional(),
2306
+ /**
2307
+ * Who sent it, by a program's own id, such as a person of a team's
2308
+ * chat, which its `user` block keeps: the calls its agent makes after
2309
+ * reading it are that sender's in the usage ledger. Absent for the
2310
+ * core's own user, as the web app sends.
2311
+ */
2312
+ senderId: z.string().min(1).max(255).nullable().optional()
2270
2313
  }),
2271
2314
  z.strictObject({
2272
2315
  type: z.literal("edit_and_send"),
@@ -2290,7 +2333,9 @@ z.discriminatedUnion("type", [
2290
2333
  * The comments the steer carries, as a message's; omitted when
2291
2334
  * there are none.
2292
2335
  */
2293
- comments: z.array(clientCommentSchema).optional()
2336
+ comments: z.array(clientCommentSchema).optional(),
2337
+ /** Who sent it, as a message's sender. */
2338
+ senderId: z.string().min(1).max(255).nullable().optional()
2294
2339
  }),
2295
2340
  z.strictObject({
2296
2341
  type: z.literal("send_saved"),
@@ -3090,7 +3135,13 @@ const jobCallerSchema = z.object({
3090
3135
  * (`crates/core-store/src/usage.rs`); none for a job recorded before
3091
3136
  * records kept it.
3092
3137
  */
3093
- turn: z.string().min(1).nullable().optional()
3138
+ turn: z.string().min(1).nullable().optional(),
3139
+ /**
3140
+ * Whom the call's agent worked for, by its program's id, whom a
3141
+ * command's call to a vendor is counted for; none when no one was
3142
+ * named.
3143
+ */
3144
+ senderId: z.string().nullable().optional()
3094
3145
  });
3095
3146
  /** The ids of a call's relayed pipes. */
3096
3147
  const relayedPipesSchema = z.object({
@@ -5408,7 +5459,12 @@ z.strictObject({
5408
5459
  /** The picture asked of, for a side question about a picture. */
5409
5460
  picture: mediaSourceSchema.nullable().optional(),
5410
5461
  /** What is asked, a message's content, as a frame names it. */
5411
- question: z.array(clientContentSchema)
5462
+ question: z.array(clientContentSchema),
5463
+ /**
5464
+ * Who asked, as a message's sender
5465
+ * (`crates/conversation-lane-protocol/src/client.rs`).
5466
+ */
5467
+ senderId: z.string().min(1).max(255).nullable().optional()
5412
5468
  });
5413
5469
  /** `AuthenticatorAssertionResponseJSON`. */
5414
5470
  const assertionResponseJsonSchema = z.strictObject({
@@ -5451,7 +5507,8 @@ const attachmentDtoSchema = z.object({
5451
5507
  createdAt: z.iso.datetime({ precision: 3 }),
5452
5508
  snippet: z.string().optional()
5453
5509
  });
5454
- z.object({ attachment: attachmentDtoSchema });
5510
+ /** The answer of an upload that sent the file's bytes. */
5511
+ const attachmentAnswerSchema = z.object({ attachment: attachmentDtoSchema });
5455
5512
  z.object({ attachment: attachmentDtoSchema.nullable() });
5456
5513
  /** `AuthenticatorAttestationResponseJSON`. */
5457
5514
  const attestationResponseJsonSchema = z.strictObject({
@@ -5893,8 +5950,8 @@ const patchFieldSchema = z.enum([
5893
5950
  "service_tier_id",
5894
5951
  "workflow",
5895
5952
  "browser_profile",
5896
- "identity",
5897
- "plugins",
5953
+ "system_prompt",
5954
+ "commands",
5898
5955
  "target"
5899
5956
  ]);
5900
5957
  /**
@@ -5926,7 +5983,8 @@ const batchResultSchema = z.discriminatedUnion("status", [z.object({
5926
5983
  code: errorCodeSchema,
5927
5984
  message: z.string()
5928
5985
  })]);
5929
- z.object({ results: z.array(batchResultSchema) });
5986
+ /** The answer of a batch: an outcome per item, in the order given. */
5987
+ const batchAnswerSchema = z.object({ results: z.array(batchResultSchema) });
5930
5988
  /** A provider entry of the user's scope and one of its models. */
5931
5989
  const modelChoiceSchema = z.strictObject({
5932
5990
  providerId: z.string().min(1),
@@ -5966,15 +6024,15 @@ const conversationPatchSchema = z.strictObject({
5966
6024
  */
5967
6025
  browserProfile: z.string().regex(/* @__PURE__ */ new RegExp("^[a-z0-9_-]{1,64}$", "u")).nullable().optional(),
5968
6026
  /**
5969
- * The sentences that open its agents' system prompts in place of
5970
- * Jush's, from each agent's next request; null for Jush's.
6027
+ * The system prompt its agents read in place of Jush's, from each
6028
+ * agent's next request; null for Jush's.
5971
6029
  */
5972
- identity: z.string().nullable().optional(),
6030
+ systemPrompt: z.string().nullable().optional(),
5973
6031
  /**
5974
- * The program's plugins its agents have, by id, from each agent's next
5975
- * command; null for all of them.
6032
+ * The commands its agents have, by path without `jush`, from each
6033
+ * agent's next command; null for every command.
5976
6034
  */
5977
- plugins: z.array(z.string()).nullable().optional(),
6035
+ commands: z.array(z.string()).nullable().optional(),
5978
6036
  /** A switch of the conversation's execution target. */
5979
6037
  target: conversationTargetSchema.optional()
5980
6038
  });
@@ -6142,7 +6200,12 @@ z.strictObject({
6142
6200
  lastModel: modelSettingsSchema.optional(),
6143
6201
  lastWorkflow: workflowChoiceSchema.optional()
6144
6202
  });
6145
- z.object({
6203
+ /**
6204
+ * One changed file's two sides: `original` as the last commit or the edit
6205
+ * has it, empty for a new file; `modified` as the working tree or the edit
6206
+ * has it, empty for a deleted one.
6207
+ */
6208
+ const changeSidesSchema = z.object({
6146
6209
  original: z.string(),
6147
6210
  modified: z.string()
6148
6211
  });
@@ -6503,13 +6566,6 @@ const cloudStorageSchema = z.object({
6503
6566
  * counting from one, which `codesTaken` and a refusal of it then name.
6504
6567
  */
6505
6568
  const codeTakenSchema = z.object({ code: z.int().min(0).max(4294967295) });
6506
- z.object({
6507
- commandId: z.string().min(1),
6508
- /** The agent that ran it. */
6509
- node: z.string().min(1),
6510
- /** The call's block in that agent's transcript. */
6511
- blockId: z.string().min(1)
6512
- });
6513
6569
  /**
6514
6570
  * How a command ended, as the conversation's record of its output keeps
6515
6571
  * it (`crates/core-store/src/command_outputs.rs`).
@@ -6526,6 +6582,17 @@ const commandEndSchema = z.discriminatedUnion("kind", [
6526
6582
  }),
6527
6583
  z.object({ kind: z.literal("unrecorded") })
6528
6584
  ]);
6585
+ /**
6586
+ * `GET /conversations/:id/commands/:commandId`: where the `shell` call that
6587
+ * started a command lies, which a report's title brings into view.
6588
+ */
6589
+ const commandOriginSchema = z.object({
6590
+ commandId: z.string().min(1),
6591
+ /** The agent that ran it. */
6592
+ node: z.string().min(1),
6593
+ /** The call's block in that agent's transcript. */
6594
+ blockId: z.string().min(1)
6595
+ });
6529
6596
  /** A compaction marker of a page and its boundary's summary size. */
6530
6597
  const compactionSummarySchema = z.object({
6531
6598
  marker: z.string().min(1),
@@ -6538,6 +6605,13 @@ const compactionSummarySchema = z.object({
6538
6605
  * that vendor's entry with the gateway's endpoint.
6539
6606
  */
6540
6607
  const compatibleShapesSchema = z.object({ audio: z.array(audioShapeSchema) });
6608
+ z.strictObject({
6609
+ /** The core that started the sign-in. */
6610
+ core: z.string(),
6611
+ plugin: z.string(),
6612
+ /** The query of the address, such as `code=…&state=…`. */
6613
+ query: z.string()
6614
+ });
6541
6615
  /**
6542
6616
  * What a configured model makes (`crates/core/src/provider_settings.rs`):
6543
6617
  * text, the model menu's, unless its user added it as an audio model of a
@@ -6832,10 +6906,16 @@ const conversationMetadataSchema = z.object({
6832
6906
  workflow: workflowChoiceSchema,
6833
6907
  /** The browser profile it names; null for a profile of its own. */
6834
6908
  browserProfile: z.string().regex(/* @__PURE__ */ new RegExp("^[a-z0-9_-]{1,64}$", "u")).nullable(),
6835
- /** The sentences that open its agents' system prompts; null for Jush's. */
6836
- identity: z.string().nullable(),
6837
- /** The program's plugins its agents have, by id; null for all of them. */
6838
- plugins: z.array(z.string()).nullable(),
6909
+ /**
6910
+ * The system prompt its agents read in place of Jush's; null for
6911
+ * Jush's.
6912
+ */
6913
+ systemPrompt: z.string().nullable(),
6914
+ /**
6915
+ * The commands its agents have, by path without `jush`; null for every
6916
+ * command.
6917
+ */
6918
+ commands: z.array(z.string()).nullable(),
6839
6919
  /**
6840
6920
  * The directory the conversation's work runs in, resolved by the backend
6841
6921
  * for every kind of target, so the web app never derives it.
@@ -7249,7 +7329,11 @@ z.discriminatedUnion("type", [
7249
7329
  keys: z.array(z.string()).max(4096)
7250
7330
  })
7251
7331
  ]);
7252
- z.object({ conversations: z.array(conversationSummarySchema) });
7332
+ /**
7333
+ * `GET /conversations`: the caller's conversations: those not archived in
7334
+ * sidebar order, pinned first, or the archived ones, the last archived first.
7335
+ */
7336
+ const conversationsSchema = z.object({ conversations: z.array(conversationSummarySchema) });
7253
7337
  /**
7254
7338
  * Who configures providers: each user their own, or the master for every
7255
7339
  * user, which the master changes in Settings › Users.
@@ -8060,7 +8144,14 @@ const sendMessageSchema = z.strictObject({
8060
8144
  * The comments the message carries, which may make it without content;
8061
8145
  * omitted when there are none.
8062
8146
  */
8063
- comments: z.array(clientCommentSchema).optional()
8147
+ comments: z.array(clientCommentSchema).optional(),
8148
+ /**
8149
+ * Who sent it, by a program's own id, such as a person of a team's
8150
+ * chat, which its `user` block keeps: the calls its agent makes after
8151
+ * reading it are that sender's in the usage ledger. Absent for the
8152
+ * core's own user, as the web app sends.
8153
+ */
8154
+ senderId: z.string().min(1).max(255).nullable().optional()
8064
8155
  });
8065
8156
  z.strictObject({
8066
8157
  id: z.string().regex(/* @__PURE__ */ new RegExp("^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$", "u")),
@@ -8090,16 +8181,15 @@ z.strictObject({
8090
8181
  */
8091
8182
  browserProfile: z.string().regex(/* @__PURE__ */ new RegExp("^[a-z0-9_-]{1,64}$", "u")).optional(),
8092
8183
  /**
8093
- * The sentences that open its agents' system prompts in place of
8094
- * Jush's, such as "You are the help desk's assistant."; Jush's when
8095
- * absent.
8184
+ * The system prompt its agents read in place of Jush's, such as "You
8185
+ * are the help desk's assistant. …"; Jush's when absent.
8096
8186
  */
8097
- identity: z.string().optional(),
8187
+ systemPrompt: z.string().optional(),
8098
8188
  /**
8099
- * The program's plugins its agents have, by id; all of them when
8100
- * absent.
8189
+ * The commands its agents have, by path without `jush`, such as
8190
+ * `browser` or `conversation history`; every command when absent.
8101
8191
  */
8102
- plugins: z.array(z.string()).optional(),
8192
+ commands: z.array(z.string()).optional(),
8103
8193
  /**
8104
8194
  * The message the conversation starts with, as the socket's `send`
8105
8195
  * frame carries it.
@@ -8200,7 +8290,8 @@ const createdConversationSchema = z.object({
8200
8290
  /** Absent when the request carried no first message. */
8201
8291
  firstMessage: firstMessageAnswerSchema.optional()
8202
8292
  });
8203
- z.object({ path: z.string() });
8293
+ /** `{ path }`: the directory a create made. */
8294
+ const createdDirectorySchema = z.object({ path: z.string() });
8204
8295
  /** An account's role. A role administers only the roles below it. */
8205
8296
  const roleSchema = z.enum([
8206
8297
  "admin",
@@ -8336,8 +8427,13 @@ const credentialDtoSchema = z.object({
8336
8427
  createdAt: z.iso.datetime({ precision: 3 }),
8337
8428
  updatedAt: z.iso.datetime({ precision: 3 })
8338
8429
  });
8339
- z.object({ credential: credentialDtoSchema });
8340
- z.object({ credentials: z.array(credentialDtoSchema) });
8430
+ /** What a route that saves a credential answers. */
8431
+ const credentialAnswerSchema = z.object({ credential: credentialDtoSchema });
8432
+ /**
8433
+ * `GET /credentials`, and the synchronization channel's `credentials`
8434
+ * part: the user's credentials in name order.
8435
+ */
8436
+ const credentialListSchema = z.object({ credentials: z.array(credentialDtoSchema) });
8341
8437
  z.strictObject({
8342
8438
  /** A credential's name: trimmed, then at least one character. */
8343
8439
  name: z.string().trim().min(1).optional(),
@@ -8440,7 +8536,13 @@ const deviceAnswerSchema = z.object({ device: deviceDtoSchema });
8440
8536
  * elevated, and a No leaves it as it was.
8441
8537
  */
8442
8538
  const elevationOutcomeSchema = z.enum(["shown", "unavailable"]);
8443
- z.object({ outcome: elevationOutcomeSchema });
8539
+ /**
8540
+ * What came of a request that a device's Windows runner run elevated
8541
+ * (`POST /api/devices/{id}/elevation`): whether a User Account Control
8542
+ * prompt shows on its desktop. The device's elevation says later what came
8543
+ * of the prompt.
8544
+ */
8545
+ const deviceElevationSchema = z.object({ outcome: elevationOutcomeSchema });
8444
8546
  z.strictObject({
8445
8547
  script: z.string(),
8446
8548
  /**
@@ -8494,7 +8596,8 @@ const deviceStorageSchema = z.object({
8494
8596
  /** Null before its runner first measured. */
8495
8597
  report: deviceStorageReportSchema.nullable()
8496
8598
  });
8497
- z.object({ devices: z.array(deviceDtoSchema) });
8599
+ /** `GET /devices`: the caller's paired devices, oldest first. */
8600
+ const devicesSchema = z.object({ devices: z.array(deviceDtoSchema) });
8498
8601
  /**
8499
8602
  * Which of the page's two peers with a device a signaling message is about
8500
8603
  * (`crates/runner-direct/src/lib.rs`): the one for files and calls,
@@ -8585,7 +8688,11 @@ const directoryEntrySchema = z.object({
8585
8688
  modifiedAt: z.iso.datetime({ precision: 3 }),
8586
8689
  link: symbolicLinkSchema.nullable().optional()
8587
8690
  });
8588
- z.object({
8691
+ /**
8692
+ * `{ path, home, entries }`: a directory as a device lists it. `home` is the
8693
+ * device's home directory, null while it is unknown.
8694
+ */
8695
+ const directorySchema = z.object({
8589
8696
  path: z.string(),
8590
8697
  home: z.string().nullable(),
8591
8698
  entries: z.array(directoryEntrySchema)
@@ -8673,7 +8780,11 @@ z.strictObject({
8673
8780
  password: z.string().min(1)
8674
8781
  });
8675
8782
  z.object({ challenge: emailChallengeDtoSchema });
8676
- z.object({
8783
+ /**
8784
+ * `GET /conversations/:id/commands/:commandId/output`: an ended command's
8785
+ * output as its terminal shows it, with the script its call ran.
8786
+ */
8787
+ const endedOutputSchema = z.object({
8677
8788
  /**
8678
8789
  * The script its call ran; empty when the conversation holds no call
8679
8790
  * of it.
@@ -8689,7 +8800,8 @@ z.object({
8689
8800
  /** Why its output was not stored; null when it was. */
8690
8801
  notStored: z.string().nullable()
8691
8802
  });
8692
- z.object({
8803
+ /** `GET .../fs/file`: a file's text. */
8804
+ const fileTextSchema = z.object({
8693
8805
  path: z.string(),
8694
8806
  text: z.string()
8695
8807
  });
@@ -8745,13 +8857,26 @@ z.discriminatedUnion("type", [
8745
8857
  keys: z.array(z.string()).max(4096)
8746
8858
  })
8747
8859
  ]);
8748
- z.object({
8860
+ /**
8861
+ * The answer of a Fork: the new conversation as the list shows it, and its
8862
+ * metadata, whose model settings are the ones it inherited from its source.
8863
+ */
8864
+ const forkAnswerSchema = z.object({
8749
8865
  conversation: conversationSummarySchema,
8750
8866
  metadata: conversationMetadataSchema
8751
8867
  });
8752
8868
  z.strictObject({
8753
8869
  id: z.string().regex(/* @__PURE__ */ new RegExp("^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$", "u")),
8754
- blockId: z.string().min(1)
8870
+ /**
8871
+ * The main agent's completed assistant text the history is kept
8872
+ * through.
8873
+ */
8874
+ blockId: z.string().min(1).nullable().optional(),
8875
+ /**
8876
+ * A turn of the main agent, by the id of the message that started it:
8877
+ * the history is everything before that message.
8878
+ */
8879
+ beforeTurn: z.string().min(1).nullable().optional()
8755
8880
  });
8756
8881
  const forwardAddressSchema = z.string().min(3).max(260);
8757
8882
  /** A side of a pair, as the direct channel names a page's and a device's. */
@@ -8818,7 +8943,12 @@ z.object({
8818
8943
  draft: conversationDraftSchema,
8819
8944
  revisions: revisionsSchema
8820
8945
  });
8821
- z.object({
8946
+ /**
8947
+ * A repository's local branches (`crates/runner-device/src/git.rs`): by name,
8948
+ * most recently committed first; the one checked out, or null with `head`
8949
+ * when HEAD is detached.
8950
+ */
8951
+ const gitBranchesSchema = z.object({
8822
8952
  branches: z.array(z.string()),
8823
8953
  /** Null while HEAD is detached. */
8824
8954
  current: z.string().nullable(),
@@ -8861,7 +8991,12 @@ const gitCommitFileSchema = z.object({
8861
8991
  added: z.int().min(0),
8862
8992
  removed: z.int().min(0)
8863
8993
  });
8864
- z.object({
8994
+ /**
8995
+ * A commit as `git_commit` answers it: its entry with its parents, its
8996
+ * files against its first parent, cut at 5,000 (`truncated`), and the local
8997
+ * branches it is on, the checked-out one first.
8998
+ */
8999
+ const gitCommitSchema = z.object({
8865
9000
  commit: gitCommitEntrySchema,
8866
9001
  files: z.array(gitCommitFileSchema),
8867
9002
  truncated: z.boolean(),
@@ -8877,11 +9012,16 @@ const gitLogEntrySchema = z.object({
8877
9012
  author: z.string(),
8878
9013
  time: z.iso.datetime({ precision: 3 })
8879
9014
  });
8880
- z.object({
9015
+ /**
9016
+ * One page of a first-parent history, newest first; `more` when older
9017
+ * commits follow.
9018
+ */
9019
+ const gitLogSchema = z.object({
8881
9020
  commits: z.array(gitLogEntrySchema),
8882
9021
  more: z.boolean()
8883
9022
  });
8884
- z.object({
9023
+ /** The repositories around a directory (`crates/runner-device/src/repositories.rs`). */
9024
+ const gitRepositoriesSchema = z.object({
8885
9025
  /** Whether the directory lies in a repository, at it or above it. */
8886
9026
  inRepository: z.boolean(),
8887
9027
  /**
@@ -8944,7 +9084,11 @@ const userUsageSchema = z.object({
8944
9084
  totals: z.array(usageGroupSchema)
8945
9085
  });
8946
9086
  z.object({ users: z.array(userUsageSchema) });
8947
- z.object({ instructions: z.string() });
9087
+ /**
9088
+ * `GET /settings/instructions`: the caller's personal instructions; empty
9089
+ * when they have none.
9090
+ */
9091
+ const instructionsAnswerSchema = z.object({ instructions: z.string() });
8948
9092
  z.strictObject({ text: z.string() });
8949
9093
  z.object({
8950
9094
  ok: z.boolean(),
@@ -8971,7 +9115,8 @@ const listedDirectorySchema = z.discriminatedUnion("type", [z.object({
8971
9115
  status: z.int().min(0).max(65535),
8972
9116
  error: errorBodySchema
8973
9117
  })]);
8974
- z.object({ lists: z.array(listedDirectorySchema) });
9118
+ /** `POST .../fs/lists`: one answer for each path asked, in its order. */
9119
+ const listedDirectoriesSchema = z.object({ lists: z.array(listedDirectorySchema) });
8975
9120
  /** An account as an administrator's list shows it. */
8976
9121
  const listedUserSchema = z.object({
8977
9122
  id: z.string().min(1),
@@ -9037,7 +9182,12 @@ const messageResultSchema = z.object({
9037
9182
  text: z.string(),
9038
9183
  ranges: z.array(z.array(z.int().min(0).max(4294967295)).min(2).max(2))
9039
9184
  });
9040
- z.object({
9185
+ /**
9186
+ * What `GET /conversations/{id}/search` answers: the messages of the
9187
+ * conversation's main agent, the user's and the agent's answers, that hold
9188
+ * every word of the query, newest first, at most [`RESULTS_MAX`] of them.
9189
+ */
9190
+ const messageResultsSchema = z.object({
9041
9191
  messages: z.array(messageResultSchema),
9042
9192
  /** More messages hold the words than the answer lists. */
9043
9193
  limited: z.boolean()
@@ -9076,7 +9226,11 @@ const modelMatchSchema = z.object({
9076
9226
  /** The release date as models.dev states it, such as `2026-06-17`. */
9077
9227
  releaseDate: z.string().nullable()
9078
9228
  });
9079
- z.object({ results: z.array(modelMatchSchema) });
9229
+ /**
9230
+ * `{ results }`: at most 20 matches, newest release first, because the
9231
+ * catalogue has no end of matches and a search answers whole.
9232
+ */
9233
+ const modelSearchResultsSchema = z.object({ results: z.array(modelMatchSchema) });
9080
9234
  /** A plugin's reply block a reply names, by its tag and its ID. */
9081
9235
  const namedReplyBlockSchema = z.strictObject({
9082
9236
  tag: z.string().min(1).max(64),
@@ -9191,6 +9345,42 @@ z.object({ ok: z.boolean() });
9191
9345
  * `/cores/{id}/api`.
9192
9346
  */
9193
9347
  const openedCoreSchema = z.object({ id: z.string().min(1) });
9348
+ /**
9349
+ * What a user does on a program's page of a conversation, each a control
9350
+ * of its views and the requests behind it. A page reads its conversation
9351
+ * with none of them.
9352
+ */
9353
+ const pageOperationSchema = z.enum([
9354
+ "send",
9355
+ "attach",
9356
+ "steer",
9357
+ "edit",
9358
+ "stop",
9359
+ "retry",
9360
+ "compact",
9361
+ "clear",
9362
+ "ask",
9363
+ "messageAgents",
9364
+ "decide",
9365
+ "fork",
9366
+ "delete",
9367
+ "rename",
9368
+ "chooseModel",
9369
+ "chooseDevice",
9370
+ "chooseWorkflow",
9371
+ "pins",
9372
+ "schedules",
9373
+ "files",
9374
+ "writeFiles",
9375
+ "changes",
9376
+ "browser",
9377
+ "simulators",
9378
+ "plugins"
9379
+ ]);
9380
+ z.object({
9381
+ conversation: z.string().regex(/* @__PURE__ */ new RegExp("^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$", "u")),
9382
+ allow: z.array(pageOperationSchema)
9383
+ });
9194
9384
  /** The level of a line the page wrote. */
9195
9385
  const pageLogLevelSchema = z.enum([
9196
9386
  "debug",
@@ -9299,7 +9489,12 @@ z.strictObject({
9299
9489
  current: z.string().nullable().optional(),
9300
9490
  next: z.string().min(8)
9301
9491
  });
9302
- z.object({
9492
+ /**
9493
+ * `GET /conversations/:id/plugins/:plugin/state`: the plugin's state for the
9494
+ * conversation, valid against the plugin's declared schema, and the revision
9495
+ * it was read at.
9496
+ */
9497
+ const pluginStateAnswerSchema = z.object({
9303
9498
  revision: z.int().min(0),
9304
9499
  state: z.json()
9305
9500
  });
@@ -9321,8 +9516,10 @@ const portForwardDtoSchema = z.object({
9321
9516
  state: forwardRunStateSchema.nullable(),
9322
9517
  createdAt: z.iso.datetime({ precision: 3 })
9323
9518
  });
9324
- z.object({ forward: portForwardDtoSchema });
9325
- z.object({ forwards: z.array(portForwardDtoSchema) });
9519
+ /** The answer of a create and a change: the forward as it stands. */
9520
+ const portForwardAnswerSchema = z.object({ forward: portForwardDtoSchema });
9521
+ /** `GET /port-forwards`: the user's forwards, oldest first. */
9522
+ const portForwardListSchema = z.object({ forwards: z.array(portForwardDtoSchema) });
9326
9523
  z.strictObject({
9327
9524
  listenDevice: z.string().min(1).optional(),
9328
9525
  listenPort: z.int().min(1).max(65535).optional(),
@@ -9718,7 +9915,8 @@ const subagentProfileSchema = z.object({
9718
9915
  /** Whether agents may use the profile. */
9719
9916
  enabled: z.boolean()
9720
9917
  });
9721
- z.object({ profile: subagentProfileSchema });
9918
+ /** `{ profile }`: the answer of a create and of a patch. */
9919
+ const profileAnswerSchema = z.object({ profile: subagentProfileSchema });
9722
9920
  z.strictObject({
9723
9921
  name: z.string().optional(),
9724
9922
  description: z.string().optional(),
@@ -9728,8 +9926,23 @@ z.strictObject({
9728
9926
  canSpawn: z.boolean().optional(),
9729
9927
  enabled: z.boolean().optional()
9730
9928
  });
9731
- z.object({ project: projectDtoSchema });
9732
- z.object({ projects: z.array(projectDtoSchema) });
9929
+ z.strictObject({
9930
+ /**
9931
+ * A schedule's URL, with `{id}`, the schedule's id, such as
9932
+ * `https://bot.example.com/hooks/{id}`.
9933
+ */
9934
+ schedule: z.string().nullable().optional(),
9935
+ /**
9936
+ * Where a plugin's sign-in sends the browser back to, with `{core}`,
9937
+ * the core's id, and `{plugin}`, the plugin's, as the program needs
9938
+ * them, such as `https://bot.example.com/sign-in/{core}/{plugin}`.
9939
+ */
9940
+ signInReturn: z.string().nullable().optional()
9941
+ });
9942
+ /** `{ project }`: the answer of a creation and a change. */
9943
+ const projectAnswerSchema = z.object({ project: projectDtoSchema });
9944
+ /** `GET /projects`: the user's projects, in their sidebar order. */
9945
+ const projectsSchema = z.object({ projects: z.array(projectDtoSchema) });
9733
9946
  /**
9734
9947
  * An entry as the web app sees it: its family, label, kind, endpoint, vendor
9735
9948
  * and model list, never its key.
@@ -9810,7 +10023,13 @@ const providerDtoSchema = z.object({
9810
10023
  });
9811
10024
  /** `{ provider }`: the answer of a create and an edit. */
9812
10025
  const providerAnswerSchema = z.object({ provider: providerDtoSchema });
9813
- z.object({ newest: newestVersionSchema });
10026
+ /**
10027
+ * `GET /providers/:id/cli`: the newest version of the command-line tool
10028
+ * of an entry whose provider runs one on the Subscriptions machine. Reading
10029
+ * it wakes nothing; the install's state is the entry's
10030
+ * ([`ProviderState::cli_install`]).
10031
+ */
10032
+ const providerCliSchema = z.object({ newest: newestVersionSchema });
9814
10033
  z.strictObject({ providerIds: z.array(z.string().min(1)) });
9815
10034
  /**
9816
10035
  * A change of an entry's search switches; each only for a search its
@@ -9949,7 +10168,11 @@ z.strictObject({
9949
10168
  */
9950
10169
  quietWhileElsewhere: z.boolean()
9951
10170
  });
9952
- z.object({ quota: quotaSnapshotSchema.nullable() });
10171
+ /**
10172
+ * `{ quota }`: the account's snapshot after the probe, or the kept one of a
10173
+ * family that cannot probe; null when there is none.
10174
+ */
10175
+ const quotaAnswerSchema = z.object({ quota: quotaSnapshotSchema.nullable() });
9953
10176
  z.strictObject({ credentialId: z.string().min(1).optional() });
9954
10177
  z.object({
9955
10178
  ok: z.boolean(),
@@ -9974,7 +10197,12 @@ const recentAgentSchema = z.object({
9974
10197
  */
9975
10198
  rate: z.number().nullable()
9976
10199
  });
9977
- z.object({
10200
+ /**
10201
+ * `GET /conversations/:id/cost/recent?window=hour|day`: what the
10202
+ * conversation's calls of the window cost, counted by the backend from its
10203
+ * usage ledger.
10204
+ */
10205
+ const recentCostSchema = z.object({
9978
10206
  /**
9979
10207
  * Each agent that made a call in the window, and the rows of no agent, such
9980
10208
  * as a title's, when there are some: the rows of no agent first, then the
@@ -10028,7 +10256,11 @@ const restartStepSchema = z.object({
10028
10256
  */
10029
10257
  kept: z.boolean().optional()
10030
10258
  });
10031
- z.object({ value: z.string() });
10259
+ /**
10260
+ * `POST /credentials/:id/fields/:field/reveal`: one field's value, which
10261
+ * a card in a reply copies or shows to the vault's owner.
10262
+ */
10263
+ const revealedValueSchema = z.object({ value: z.string() });
10032
10264
  z.object({ removed: z.array(z.string().min(1)) });
10033
10265
  /** What fired a run. */
10034
10266
  const runCauseSchema = z.enum([
@@ -10128,6 +10360,21 @@ const scheduleAnswerSchema = z.object({
10128
10360
  schedule: scheduleDtoSchema,
10129
10361
  secret: z.string().nullable()
10130
10362
  });
10363
+ /** Why a schedule refused a call. */
10364
+ const scheduleCallRefusalSchema = z.enum([
10365
+ "unknown",
10366
+ "secret",
10367
+ "tooMany",
10368
+ "tooLarge"
10369
+ ]);
10370
+ /**
10371
+ * What became of a call of a schedule's URL that the program handed on
10372
+ * (`POST /schedules/calls?id=`).
10373
+ */
10374
+ const scheduleCallAnswerSchema = z.discriminatedUnion("type", [z.object({ type: z.literal("taken") }), z.object({
10375
+ type: z.literal("refused"),
10376
+ reason: scheduleCallRefusalSchema
10377
+ })]);
10131
10378
  z.strictObject({
10132
10379
  name: z.string().trim().optional(),
10133
10380
  trigger: triggerSchema.optional(),
@@ -10143,7 +10390,8 @@ z.strictObject({
10143
10390
  * newest first, [`RUNS_SHOWN`] at most.
10144
10391
  */
10145
10392
  const scheduleRunsSchema = z.object({ runs: z.array(scheduleRunDtoSchema) });
10146
- z.discriminatedUnion("type", [z.object({
10393
+ /** One line of a search's output. */
10394
+ const searchLineSchema = z.discriminatedUnion("type", [z.object({
10147
10395
  type: z.literal("file"),
10148
10396
  /** Relative to the directory searched, with `/` between its parts. */
10149
10397
  path: z.string(),
@@ -10195,7 +10443,11 @@ const searchResultSchema = z.object({
10195
10443
  /** The message that matched; null when only the title does. */
10196
10444
  match: searchMatchSchema.nullable()
10197
10445
  });
10198
- z.object({ results: z.array(searchResultSchema) });
10446
+ /**
10447
+ * What `GET /search` answers: the caller's conversations that match, title
10448
+ * matches first, then the others, each group most recently active first.
10449
+ */
10450
+ const searchResultsSchema = z.object({ results: z.array(searchResultSchema) });
10199
10451
  /**
10200
10452
  * What the server keeps. An administrator sees all of it and the log's
10201
10453
  * rules; anyone else sees only their own conversations and attachments,
@@ -10357,10 +10609,17 @@ z.object({
10357
10609
  /** The reply blocks its texts name. */
10358
10610
  replyBlocks: z.array(replyBlockFactsSchema).optional()
10359
10611
  });
10360
- z.strictObject({
10361
- /** A message's content, as a frame names it. */
10362
- content: z.array(clientContentSchema) });
10363
- z.object({
10612
+ z.strictObject({
10613
+ /** A message's content, as a frame names it. */
10614
+ content: z.array(clientContentSchema),
10615
+ /** Who sent it, as a message's sender. */
10616
+ senderId: z.string().min(1).max(255).nullable().optional()
10617
+ });
10618
+ /**
10619
+ * The answer of a side question's creation and of its patch: the side
10620
+ * question as its agent entry shows it.
10621
+ */
10622
+ const sideQuestionAnswerSchema = z.object({
10364
10623
  id: z.string().min(1),
10365
10624
  sideQuestion: sideQuestionSchema
10366
10625
  });
@@ -10374,6 +10633,21 @@ z.discriminatedUnion("kind", [z.strictObject({
10374
10633
  id: z.string().min(1),
10375
10634
  beforeId: z.string().min(1).nullable()
10376
10635
  })]);
10636
+ /** Why a sign-in did not end signed in. */
10637
+ const signInRefusalSchema = z.enum([
10638
+ "unknownPlugin",
10639
+ "expired",
10640
+ "declined",
10641
+ "vendorFailed"
10642
+ ]);
10643
+ /** How a plugin's sign-in ended. */
10644
+ const signInAnswerSchema = z.discriminatedUnion("type", [z.object({
10645
+ type: z.literal("signedIn"),
10646
+ vendor: z.string()
10647
+ }), z.object({
10648
+ type: z.literal("refused"),
10649
+ reason: signInRefusalSchema
10650
+ })]);
10377
10651
  z.object({
10378
10652
  challengeId: z.string().min(1),
10379
10653
  options: requestOptionsJsonSchema
@@ -10450,7 +10724,12 @@ z.strictObject({
10450
10724
  * when none.
10451
10725
  */
10452
10726
  id: z.string().min(1).nullable().optional(),
10453
- text: z.string()
10727
+ text: z.string(),
10728
+ /**
10729
+ * Who sent it, as a message's sender
10730
+ * (`crates/conversation-lane-protocol/src/client.rs`).
10731
+ */
10732
+ senderId: z.string().min(1).max(255).nullable().optional()
10454
10733
  });
10455
10734
  /**
10456
10735
  * What a message to a subagent answers: its id, the one it named or the one
@@ -10687,7 +10966,11 @@ z.strictObject({
10687
10966
  modelId: z.string().optional(),
10688
10967
  credentialId: z.string().min(1).optional()
10689
10968
  });
10690
- z.discriminatedUnion("type", [z.object({
10969
+ /**
10970
+ * What a test found. A test that ran and failed is a result, with the
10971
+ * provider's own reason.
10972
+ */
10973
+ const testResultSchema = z.discriminatedUnion("type", [z.object({
10691
10974
  type: z.literal("passed"),
10692
10975
  model: z.string()
10693
10976
  }), z.object({
@@ -10772,7 +11055,66 @@ const turnStateSchema = z.discriminatedUnion("state", [
10772
11055
  outcome: turnOutcomeSchema
10773
11056
  })
10774
11057
  ]);
10775
- z.object({ totals: z.array(usageGroupSchema) });
11058
+ /** Amounts by currency; a currency no call cost in is absent. */
11059
+ const usageCostsSchema = z.object({
11060
+ usd: z.number().nullable().optional(),
11061
+ cny: z.number().nullable().optional()
11062
+ });
11063
+ /**
11064
+ * The calls of a bucket that share each of the report's dimensions, which
11065
+ * it names; a dimension the report does not group by is absent, and one
11066
+ * a call has no value of, such as the sender of a title's call, is null.
11067
+ */
11068
+ const usageReportGroupSchema = z.object({
11069
+ conversation: z.string().nullable().optional(),
11070
+ sender: z.string().nullable().optional(),
11071
+ model: z.string().nullable().optional(),
11072
+ provider: z.string().nullable().optional(),
11073
+ account: z.string().nullable().optional(),
11074
+ turn: z.string().nullable().optional(),
11075
+ purpose: z.string().nullable().optional(),
11076
+ calls: z.int().min(0),
11077
+ inputTokens: z.int().min(0),
11078
+ outputTokens: z.int().min(0),
11079
+ cacheReadTokens: z.int().min(0),
11080
+ cacheWriteTokens: z.int().min(0),
11081
+ /** What the vendors said the calls cost, by currency, never converted. */
11082
+ cost: usageCostsSchema,
11083
+ /**
11084
+ * What the calls' tokens would cost at their models' API prices, in
11085
+ * dollars, as each row fixed it when it was written.
11086
+ */
11087
+ apiPrice: z.number(),
11088
+ /**
11089
+ * The calls whose tokens `api_price` leaves out, their model having no
11090
+ * price for a kind they used. A call the vendor counted no tokens
11091
+ * for, as a refused one, is none of them.
11092
+ */
11093
+ unpricedCalls: z.int().min(0)
11094
+ });
11095
+ /** One hour or day of a report, and its calls' groups. */
11096
+ const usageBucketSchema = z.object({
11097
+ start: z.iso.datetime({ precision: 3 }),
11098
+ end: z.iso.datetime({ precision: 3 }),
11099
+ groups: z.array(usageReportGroupSchema)
11100
+ });
11101
+ z.enum(["hour", "day"]);
11102
+ z.enum([
11103
+ "conversation",
11104
+ "model",
11105
+ "provider",
11106
+ "turn",
11107
+ "sender",
11108
+ "account",
11109
+ "purpose"
11110
+ ]);
11111
+ /**
11112
+ * `GET /usage/report`: each bucket of the period that holds a call, oldest
11113
+ * first; the first and the last start and end with the period.
11114
+ */
11115
+ const usageReportSchema = z.object({ buckets: z.array(usageBucketSchema) });
11116
+ /** `GET /usage`: the caller's totals. */
11117
+ const usageTotalsSchema = z.object({ totals: z.array(usageGroupSchema) });
10776
11118
  z.strictObject({
10777
11119
  role: newRoleSchema.nullable().optional(),
10778
11120
  disabled: z.boolean().nullable().optional(),
@@ -10803,7 +11145,12 @@ const vendorSchema = z.object({
10803
11145
  baseUrl: z.string().nullable(),
10804
11146
  doc: z.string().nullable()
10805
11147
  });
10806
- z.object({
11148
+ /**
11149
+ * `GET /providers/catalog`: what the page can add, the same for every user
11150
+ * of a backend. The page reads it once per backend version, so a vendor
11151
+ * models.dev adds meanwhile is offered from the next version on.
11152
+ */
11153
+ const vendorCatalogSchema = z.object({
10807
11154
  /** Each subscription family. */
10808
11155
  subscriptions: z.array(subscriptionFamilySchema),
10809
11156
  /** The models.dev vendors a family speaks to, by name. */
@@ -10816,7 +11163,8 @@ z.object({
10816
11163
  ok: z.boolean(),
10817
11164
  id: z.int().min(0).max(4294967295)
10818
11165
  });
10819
- z.object({
11166
+ /** `GET /conversations/:id/agents/:node/blocks/:blockId`: a block whole. */
11167
+ const wholeBlockSchema = z.object({
10820
11168
  block: blockSchema,
10821
11169
  failures: z.record(z.string(), providerFailureFactsSchema).optional()
10822
11170
  });
@@ -10855,7 +11203,11 @@ const workChangeSchema = z.discriminatedUnion("op", [
10855
11203
  ]);
10856
11204
  z.strictObject({ changes: z.array(workChangeSchema).min(1) });
10857
11205
  z.object({ count: z.int().min(0).max(4294967295) });
10858
- z.object({
11206
+ /**
11207
+ * `GET .../changes`: the runner's list of uncommitted changes, and the
11208
+ * directory its paths are relative to.
11209
+ */
11210
+ const workingTreeChangesSchema = z.object({
10859
11211
  root: z.string(),
10860
11212
  repository: z.boolean(),
10861
11213
  /**
@@ -10870,13 +11222,15 @@ z.object({
10870
11222
  truncated: z.boolean(),
10871
11223
  watched: z.boolean()
10872
11224
  });
10873
- z.object({ workspace: workspaceDtoSchema });
11225
+ /** `{ workspace }`: the answer of a creation and a change. */
11226
+ const workspaceAnswerSchema = z.object({ workspace: workspaceDtoSchema });
10874
11227
  z.strictObject({
10875
11228
  conversations: z.array(z.string().regex(/* @__PURE__ */ new RegExp("^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$", "u"))).optional(),
10876
11229
  projects: z.array(z.string().min(1)).optional()
10877
11230
  });
10878
11231
  z.strictObject({ ids: z.array(z.string().min(1)).min(1) });
10879
- z.object({ workspaces: z.array(workspaceDtoSchema) });
11232
+ /** `GET /workspaces`: the user's workspaces, in their order. */
11233
+ const workspacesSchema = z.object({ workspaces: z.array(workspaceDtoSchema) });
10880
11234
  z.strictObject({ end: z.boolean() });
10881
11235
  //#endregion
10882
11236
  //#region ../protocol/src/product-state.ts
@@ -11553,13 +11907,14 @@ var ConversationClient = class {
11553
11907
  * the transcript or the queue. The wait has no deadline of its own: the
11554
11908
  * backend decides that a delivery failed, and says why.
11555
11909
  */
11556
- submit(content, messageId = createId(), comments = []) {
11910
+ submit(content, messageId = createId(), comments = [], senderId) {
11557
11911
  let at;
11558
11912
  return this.request({
11559
11913
  type: "send",
11560
11914
  messageId,
11561
11915
  content,
11562
- ...comments.length > 0 ? { comments: [...comments] } : {}
11916
+ ...comments.length > 0 ? { comments: [...comments] } : {},
11917
+ ...senderId === void 0 ? {} : { senderId }
11563
11918
  }, (event) => {
11564
11919
  if (event.type === "send_result" && event.messageId === messageId) at = event.at;
11565
11920
  if (at !== void 0 && this.holdsVersion(at)) return { resolve: void 0 };
@@ -11675,13 +12030,14 @@ var ConversationClient = class {
11675
12030
  * version the answer names, which shows the steer, and rejects with
11676
12031
  * `SteerRejectedError` when the session refuses it.
11677
12032
  */
11678
- steer(content, steerId = createId(), comments = []) {
12033
+ steer(content, steerId = createId(), comments = [], senderId) {
11679
12034
  let at;
11680
12035
  return this.request({
11681
12036
  type: "steer",
11682
12037
  steerId,
11683
12038
  content,
11684
- ...comments.length > 0 ? { comments: [...comments] } : {}
12039
+ ...comments.length > 0 ? { comments: [...comments] } : {},
12040
+ ...senderId === void 0 ? {} : { senderId }
11685
12041
  }, (event) => {
11686
12042
  if (event.type === "steer_result" && event.steerId === steerId) {
11687
12043
  if (event.outcome.status !== "accepted") return { reject: new SteerRejectedError(event.outcome) };
@@ -13615,16 +13971,28 @@ var CoreRoutes = class {
13615
13971
  }
13616
13972
  /** The process's path of the core's route `path`, such as `/conversations`. */
13617
13973
  path(path) {
13618
- return `/cores/${encodeURIComponent(this.id)}/api${path}`;
13974
+ return `/cores/${segment(this.id)}/api${path}`;
13619
13975
  }
13620
- /** Calls the route `path` with `body` as JSON; throws `JushError` for an answer other than 2xx. */
13976
+ /**
13977
+ * Calls the route `path` with `body`, a `Blob` as its bytes of its type
13978
+ * and anything else as JSON; throws `JushError` for an answer other than
13979
+ * 2xx. A `Blob`'s length is declared, so a route refuses one over its
13980
+ * limit before it reads a byte of it.
13981
+ */
13621
13982
  async request(method, path, body, signal) {
13983
+ const sent = body === void 0 ? {} : body instanceof Blob ? {
13984
+ body,
13985
+ headers: {
13986
+ "content-type": body.type || "application/octet-stream",
13987
+ "content-length": String(body.size)
13988
+ }
13989
+ } : {
13990
+ body: JSON.stringify(body),
13991
+ headers: { "content-type": "application/json" }
13992
+ };
13622
13993
  const response = await this.process.fetch(new Request(PROCESS_ORIGIN + this.path(path), {
13623
13994
  method,
13624
- ...body === void 0 ? {} : {
13625
- body: JSON.stringify(body),
13626
- headers: { "content-type": "application/json" }
13627
- },
13995
+ ...sent,
13628
13996
  ...signal === void 0 ? {} : { signal }
13629
13997
  }));
13630
13998
  if (!response.ok) throw await refusal(response, `${method} ${path}`);
@@ -13641,55 +14009,477 @@ var CoreRoutes = class {
13641
14009
  async send(method, path, body) {
13642
14010
  await (await this.request(method, path, body)).body?.cancel();
13643
14011
  }
14012
+ /** The bytes the route `path` answers. */
14013
+ async bytes(method, path, body, signal) {
14014
+ const response = await this.request(method, path, body, signal);
14015
+ return new Uint8Array(await response.arrayBuffer());
14016
+ }
14017
+ /** Each JSON value the route `path` answers, one a line, read with `schema` as it comes. */
14018
+ async *lines(method, path, schema, body, signal) {
14019
+ const response = await this.request(method, path, body, signal);
14020
+ if (response.body === null) return;
14021
+ const decoder = new TextDecoder();
14022
+ let held = "";
14023
+ for await (const chunk of response.body) {
14024
+ held += decoder.decode(chunk, { stream: true });
14025
+ let end = held.indexOf("\n");
14026
+ while (end >= 0) {
14027
+ const line = held.slice(0, end).trim();
14028
+ held = held.slice(end + 1);
14029
+ if (line !== "") yield parsed(schema, line);
14030
+ end = held.indexOf("\n");
14031
+ }
14032
+ }
14033
+ const last = (held + decoder.decode()).trim();
14034
+ if (last !== "") yield parsed(schema, last);
14035
+ }
13644
14036
  };
14037
+ /** `line`, one JSON value, read with `schema`. */
14038
+ function parsed(schema, line) {
14039
+ const read = schema.safeParse(JSON.parse(line));
14040
+ if (!read.success) throw new Error(schemaRefusal(read.error));
14041
+ return read.data;
14042
+ }
14043
+ /** The query of `values`, `?a=1&b=x`, leaving out each one undefined; empty for none. */
14044
+ function query(values) {
14045
+ const search = new URLSearchParams();
14046
+ for (const [name, value] of Object.entries(values)) if (value !== void 0) search.set(name, String(value));
14047
+ const text = search.toString();
14048
+ return text === "" ? "" : `?${text}`;
14049
+ }
14050
+ /** `segment` as one segment of a route's path. */
14051
+ const segment = encodeURIComponent;
13645
14052
  //#endregion
13646
- //#region src/conversation.ts
14053
+ //#region src/files.ts
13647
14054
  /**
13648
- * A conversation of a core, driven as the web app drives one: a
13649
- * `ConversationClient` on the conversation's lane, which reads with the
13650
- * core's routes, holds the root's transcript with the one patch applier, and
13651
- * sends what the program asks.
14055
+ * The files of a conversation's devices and the working tree's changes, as
14056
+ * the conversation's Files and Changes show them.
14057
+ */
14058
+ function conversationFiles(routes, id) {
14059
+ const base = `/conversations/${segment(id)}`;
14060
+ return {
14061
+ list: (options = {}) => routes.json("GET", `${options.device === void 0 ? `${base}/fs` : `${base}/devices/${segment(options.device)}/fs`}${query({ path: options.path })}`, directorySchema),
14062
+ lists: (paths) => routes.json("POST", `${base}/fs/lists`, listedDirectoriesSchema, { paths }),
14063
+ read: (path) => routes.json("GET", `${base}/fs/file${query({ path })}`, fileTextSchema),
14064
+ readBytes: (path) => routes.bytes("GET", `${base}/fs/raw${query({ path })}`),
14065
+ write: (path, bytes, options = {}) => routes.send("PUT", `${base}/fs/raw${query({
14066
+ path,
14067
+ replace: options.replace
14068
+ })}`, bytes instanceof Blob ? bytes : new Blob([bytes])),
14069
+ makeDirectory: (path, options = {}) => routes.json("POST", options.device === void 0 ? `${base}/fs` : `${base}/devices/${segment(options.device)}/fs`, createdDirectorySchema, { path }),
14070
+ remove: (path) => routes.send("DELETE", `${base}/fs${query({ path })}`),
14071
+ search: (request, signal) => routes.lines("POST", `${base}/fs/search`, searchLineSchema, request, signal)
14072
+ };
14073
+ }
14074
+ function conversationChanges(routes, id) {
14075
+ const base = `/conversations/${segment(id)}/changes`;
14076
+ return {
14077
+ status: (options = {}) => routes.json("GET", `${base}${query({ directory: options.directory })}`, workingTreeChangesSchema),
14078
+ file: (path, options = {}) => routes.json("GET", `${base}/file${query({
14079
+ path,
14080
+ ...options
14081
+ })}`, changeSidesSchema),
14082
+ committed: (path, options = {}) => routes.bytes("GET", `${base}/raw${query({
14083
+ path,
14084
+ ...options
14085
+ })}`),
14086
+ branches: (options = {}) => routes.json("GET", `${base}/branches${query({ directory: options.directory })}`, gitBranchesSchema),
14087
+ repositories: (paths) => routes.json("POST", `${base}/repositories`, gitRepositoriesSchema, { paths }),
14088
+ log: (options = {}) => routes.json("GET", `${base}/log${query({ ...options })}`, gitLogSchema),
14089
+ show: (commit, options = {}) => routes.json("GET", `${base}/commit${query({
14090
+ commit,
14091
+ directory: options.directory
14092
+ })}`, gitCommitSchema)
14093
+ };
14094
+ }
14095
+ function deviceFiles(routes, id) {
14096
+ const base = `/devices/${segment(id)}/fs`;
14097
+ return {
14098
+ list: (path) => routes.json("GET", `${base}${query({ path })}`, directorySchema),
14099
+ makeDirectory: (path) => routes.json("POST", base, createdDirectorySchema, { path })
14100
+ };
14101
+ }
14102
+ //#endregion
14103
+ //#region src/history.ts
14104
+ /**
14105
+ * What a conversation holds beyond its lane's window: any agent's
14106
+ * transcript by pages, a whole block, a turn, and a command and its output.
14107
+ */
14108
+ function conversationHistory(routes, id) {
14109
+ const base = `/conversations/${segment(id)}`;
14110
+ return {
14111
+ transcript: (agent, page) => {
14112
+ const values = "latest" in page ? {
14113
+ latest: true,
14114
+ blocks: page.blocks
14115
+ } : "around" in page ? { around: page.around } : "before" in page ? {
14116
+ before: page.before,
14117
+ edge: page.edge
14118
+ } : {
14119
+ after: page.after,
14120
+ edge: page.edge
14121
+ };
14122
+ return routes.json("GET", `${base}/agents/${segment(agent)}/transcript${query(values)}`, transcriptPageSchema);
14123
+ },
14124
+ block: (agent, block) => routes.json("GET", `${base}/agents/${segment(agent)}/blocks/${segment(block)}`, wholeBlockSchema),
14125
+ turn: (turn) => routes.json("GET", `${base}/turns/${segment(turn)}`, turnStateSchema),
14126
+ commandOrigin: (command) => routes.json("GET", `${base}/commands/${segment(command)}`, commandOriginSchema),
14127
+ commandOutput: (command) => routes.json("GET", `${base}/commands/${segment(command)}/output`, endedOutputSchema)
14128
+ };
14129
+ }
14130
+ //#endregion
14131
+ //#region src/input.ts
14132
+ /** `input` as content blocks. */
14133
+ function content(input) {
14134
+ return typeof input === "string" ? [{
14135
+ type: "text",
14136
+ text: input
14137
+ }] : input;
14138
+ }
14139
+ //#endregion
14140
+ //#region src/socket.ts
14141
+ /**
14142
+ * A WebSocket on a stream of the process's HTTP/2 connection (RFC 8441):
14143
+ * the stream is the socket's, and its bytes are WebSocket frames (RFC 6455),
14144
+ * which Node's `http2` does not write, so this module does. A client masks
14145
+ * each frame it sends; the process's frames come unmasked.
13652
14146
  *
13653
- * `run(input)` sends a message and waits for the turn it starts to end, as
13654
- * the Codex SDK's `thread.run`; `events()` is everything the conversation's
13655
- * lane tells, as an async iterator, with a `permission` event for each
13656
- * request the conversation's metadata adds.
14147
+ * It has the part of a browser's `WebSocket` the page connection and a
14148
+ * forwarded page's socket use: `send`, `close`, `bufferedAmount`,
14149
+ * `binaryType`, and the `open`, `message` and `close` events.
13657
14150
  */
13658
- var Conversation = class {
13659
- id;
13660
- routes;
13661
- client = null;
13662
- opening = null;
13663
- /** The root's transcript, as the lane keeps it. */
13664
- transcript = EMPTY_TRANSCRIPT;
13665
- metadata = null;
13666
- /** The permission requests told already. */
13667
- told = /* @__PURE__ */ new Set();
13668
- listeners = /* @__PURE__ */ new Set();
13669
- /** What waits for a change of the transcript or the metadata, and fails once the conversation closes. */
13670
- changes = /* @__PURE__ */ new Set();
13671
- /** Whether the lane is being opened again after it dropped. */
13672
- reopening = false;
13673
- /** Whether the lane dropped again while it was being opened again. */
13674
- droppedAgain = false;
13675
- schedules;
13676
- constructor(id, routes) {
13677
- this.id = id;
13678
- this.routes = routes;
13679
- const path = `/conversations/${encodeURIComponent(id)}/schedules`;
13680
- const one = (schedule) => `${path}/${encodeURIComponent(schedule)}`;
13681
- this.schedules = {
13682
- create: (patch) => routes.json("POST", path, scheduleAnswerSchema, patch),
13683
- get: (schedule) => routes.json("GET", one(schedule), scheduleDtoSchema),
13684
- update: (schedule, patch) => routes.json("PATCH", one(schedule), scheduleAnswerSchema, patch),
13685
- remove: (schedule) => routes.send("DELETE", one(schedule)),
13686
- run: (schedule, task) => routes.json("POST", `${one(schedule)}/runs`, scheduleRunDtoSchema, task === void 0 ? {} : { task }),
13687
- runs: async (schedule, before) => {
13688
- const query = before === void 0 ? "" : `?before=${encodeURIComponent(before)}`;
13689
- return (await routes.json("GET", `${one(schedule)}/runs${query}`, scheduleRunsSchema)).runs;
13690
- }
13691
- };
13692
- }
14151
+ const TEXT = 1;
14152
+ const BINARY = 2;
14153
+ const CLOSE = 8;
14154
+ const PING = 9;
14155
+ const PONG = 10;
14156
+ const CONTINUATION = 0;
14157
+ /** The close of a socket that ended without a close frame. */
14158
+ const ABNORMAL_CLOSURE = 1006;
14159
+ /** The close frame's code when it carries none. */
14160
+ const NO_STATUS = 1005;
14161
+ /** A WebSocket on the stream `opening` answers once the process took it. */
14162
+ var StreamSocket = class {
14163
+ binaryType = "arraybuffer";
14164
+ stream = null;
14165
+ listeners = /* @__PURE__ */ new Map();
14166
+ /** The bytes read that do not make a whole frame yet. */
14167
+ pending = /* @__PURE__ */ new Uint8Array(0);
14168
+ /** The fragments of a message whose last frame has not come. */
14169
+ fragments = null;
14170
+ closed = false;
14171
+ /** Whether this end sent its close frame. */
14172
+ closing = false;
14173
+ constructor(opening) {
14174
+ opening.then((stream) => {
14175
+ if (this.closed) {
14176
+ stream.close();
14177
+ return;
14178
+ }
14179
+ this.stream = stream;
14180
+ stream.on("data", (chunk) => this.read(chunk));
14181
+ stream.once("close", () => this.ended(ABNORMAL_CLOSURE, ""));
14182
+ stream.on("error", () => {});
14183
+ this.emit("open");
14184
+ }, () => this.ended(ABNORMAL_CLOSURE, ""));
14185
+ }
14186
+ /** The bytes sent that the stream has not written yet. */
14187
+ get bufferedAmount() {
14188
+ return this.stream?.writableLength ?? 0;
14189
+ }
14190
+ addEventListener(type, listener) {
14191
+ let set = this.listeners.get(type);
14192
+ if (!set) {
14193
+ set = /* @__PURE__ */ new Set();
14194
+ this.listeners.set(type, set);
14195
+ }
14196
+ set.add(listener);
14197
+ }
14198
+ removeEventListener(type, listener) {
14199
+ this.listeners.get(type)?.delete(listener);
14200
+ }
14201
+ /** Sends a message: text for a string, binary for bytes. */
14202
+ send(data) {
14203
+ if (typeof data === "string") this.write(TEXT, new TextEncoder().encode(data));
14204
+ else this.write(BINARY, data instanceof ArrayBuffer ? new Uint8Array(data) : data);
14205
+ }
14206
+ /** Closes the socket with `code` and `reason`; its `close` event follows. */
14207
+ close(code = 1e3, reason = "") {
14208
+ if (this.closed || this.closing) return;
14209
+ this.closing = true;
14210
+ if (this.stream === null) {
14211
+ this.ended(ABNORMAL_CLOSURE, "");
14212
+ return;
14213
+ }
14214
+ const text = new TextEncoder().encode(reason);
14215
+ const body = new Uint8Array(2 + text.length);
14216
+ new DataView(body.buffer).setUint16(0, code);
14217
+ body.set(text, 2);
14218
+ this.write(CLOSE, body);
14219
+ this.stream.end();
14220
+ }
14221
+ emit(type, ...event) {
14222
+ for (const listener of [...this.listeners.get(type) ?? []]) listener(...event);
14223
+ }
14224
+ /** Writes one frame of `opcode` with `payload`, masked. */
14225
+ write(opcode, payload) {
14226
+ const stream = this.stream;
14227
+ if (stream === null || this.closed || stream.destroyed) return;
14228
+ const length = payload.length;
14229
+ const extended = length < 126 ? 0 : length < 65536 ? 2 : 8;
14230
+ const frame = new Uint8Array(2 + extended + 4 + length);
14231
+ const view = new DataView(frame.buffer);
14232
+ frame[0] = 128 | opcode;
14233
+ if (extended === 0) frame[1] = 128 | length;
14234
+ else if (extended === 2) {
14235
+ frame[1] = 254;
14236
+ view.setUint16(2, length);
14237
+ } else {
14238
+ frame[1] = 255;
14239
+ view.setBigUint64(2, BigInt(length));
14240
+ }
14241
+ const at = 2 + extended;
14242
+ const mask = frame.subarray(at, at + 4);
14243
+ randomFillSync(mask);
14244
+ const body = frame.subarray(at + 4);
14245
+ for (let index = 0; index < length; index += 1) body[index] = payload[index] ^ mask[index & 3];
14246
+ stream.write(frame);
14247
+ }
14248
+ /** Takes bytes of the stream, and handles each whole frame they complete. */
14249
+ read(chunk) {
14250
+ let bytes = this.pending.length === 0 ? chunk : concat([this.pending, chunk]);
14251
+ while (bytes.length >= 2) {
14252
+ const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
14253
+ const fin = (bytes[0] & 128) !== 0;
14254
+ const opcode = bytes[0] & 15;
14255
+ let length = bytes[1] & 127;
14256
+ let at = 2;
14257
+ if (length === 126) {
14258
+ if (bytes.length < 4) break;
14259
+ length = view.getUint16(2);
14260
+ at = 4;
14261
+ } else if (length === 127) {
14262
+ if (bytes.length < 10) break;
14263
+ length = Number(view.getBigUint64(2));
14264
+ at = 10;
14265
+ }
14266
+ if (bytes.length < at + length) break;
14267
+ const payload = bytes.slice(at, at + length);
14268
+ bytes = bytes.subarray(at + length);
14269
+ this.frame(fin, opcode, payload);
14270
+ }
14271
+ this.pending = bytes.slice();
14272
+ }
14273
+ frame(fin, opcode, payload) {
14274
+ switch (opcode) {
14275
+ case PING:
14276
+ this.write(PONG, payload);
14277
+ return;
14278
+ case PONG: return;
14279
+ case CLOSE: {
14280
+ const code = payload.length >= 2 ? new DataView(payload.buffer, payload.byteOffset).getUint16(0) : NO_STATUS;
14281
+ const reason = new TextDecoder().decode(payload.subarray(2));
14282
+ if (!this.closing) {
14283
+ this.closing = true;
14284
+ this.write(CLOSE, payload.subarray(0, 2));
14285
+ this.stream?.end();
14286
+ }
14287
+ this.ended(code, reason);
14288
+ return;
14289
+ }
14290
+ case CONTINUATION:
14291
+ if (this.fragments === null) return;
14292
+ this.fragments.parts.push(payload);
14293
+ if (fin) {
14294
+ const { opcode: first, parts } = this.fragments;
14295
+ this.fragments = null;
14296
+ this.message(first, concat(parts));
14297
+ }
14298
+ return;
14299
+ case TEXT:
14300
+ case BINARY: if (fin) this.message(opcode, payload);
14301
+ else this.fragments = {
14302
+ opcode,
14303
+ parts: [payload]
14304
+ };
14305
+ }
14306
+ }
14307
+ message(opcode, payload) {
14308
+ const data = opcode === TEXT ? new TextDecoder().decode(payload) : payload.buffer.slice(payload.byteOffset, payload.byteOffset + payload.byteLength);
14309
+ this.emit("message", { data });
14310
+ }
14311
+ ended(code, reason) {
14312
+ if (this.closed) return;
14313
+ this.closed = true;
14314
+ this.stream?.close();
14315
+ this.emit("close", {
14316
+ code,
14317
+ reason
14318
+ });
14319
+ }
14320
+ };
14321
+ function concat(parts) {
14322
+ const whole = new Uint8Array(parts.reduce((total, part) => total + part.length, 0));
14323
+ let at = 0;
14324
+ for (const part of parts) {
14325
+ whole.set(part, at);
14326
+ at += part.length;
14327
+ }
14328
+ return whole;
14329
+ }
14330
+ //#endregion
14331
+ //#region src/page.ts
14332
+ /** The header that names the page's operations on the process's channel. */
14333
+ const OPERATIONS_HEADER = "jush-page-operations";
14334
+ /** A program's page of one conversation, which holds nothing: make one for each request. */
14335
+ var ConversationPage = class {
14336
+ routes;
14337
+ conversation;
14338
+ options;
14339
+ operations;
14340
+ constructor(routes, conversation, options) {
14341
+ this.routes = routes;
14342
+ this.conversation = conversation;
14343
+ this.options = options;
14344
+ this.operations = options.allow.join(",");
14345
+ }
14346
+ /** Answers one of the page's requests below `base`. */
14347
+ fetch(request) {
14348
+ const url = new URL(request.url);
14349
+ const forwarded = new Request(PROCESS_ORIGIN + this.path(below(url.pathname, this.options.base)) + url.search, request);
14350
+ forwarded.headers.set(OPERATIONS_HEADER, this.operations);
14351
+ return this.routes.process.fetch(forwarded);
14352
+ }
14353
+ /**
14354
+ * Carries the page's connection, `socket`, opened at `url` below `base`,
14355
+ * to the core, both ways, until either end closes; `socket` is a
14356
+ * WebSocket of the standard interface, as Deno's `upgradeWebSocket` and
14357
+ * the `ws` package give.
14358
+ */
14359
+ accept(socket, url) {
14360
+ const query = new URL(url, PROCESS_ORIGIN).search;
14361
+ const core = new StreamSocket(this.routes.process.connect(this.path(`/connect${query}`), "websocket", {
14362
+ "sec-websocket-version": "13",
14363
+ [OPERATIONS_HEADER]: this.operations
14364
+ }));
14365
+ const early = [];
14366
+ let open = false;
14367
+ let pageClosed = false;
14368
+ socket.binaryType = "arraybuffer";
14369
+ socket.addEventListener("message", (event) => {
14370
+ const data = event.data;
14371
+ if (open) core.send(data);
14372
+ else early.push(data);
14373
+ });
14374
+ socket.addEventListener("close", () => {
14375
+ pageClosed = true;
14376
+ core.close();
14377
+ });
14378
+ core.addEventListener("open", () => {
14379
+ open = true;
14380
+ for (const data of early.splice(0)) core.send(data);
14381
+ });
14382
+ core.addEventListener("message", (event) => socket.send(event.data));
14383
+ core.addEventListener("close", (event) => {
14384
+ if (!pageClosed) socket.close(event.code === 1006 || event.code === 1005 ? 1011 : event.code, event.reason);
14385
+ });
14386
+ }
14387
+ /** The process's path of the page's route `path`. */
14388
+ path(path) {
14389
+ return `/cores/${segment(this.routes.id)}/pages/${segment(this.conversation)}${path}`;
14390
+ }
14391
+ };
14392
+ //#endregion
14393
+ //#region src/side-questions.ts
14394
+ /**
14395
+ * A conversation's side questions: a question about a passage of an answer,
14396
+ * which its own agent answers beside the conversation.
14397
+ */
14398
+ function sideQuestions(routes, id) {
14399
+ const base = `/conversations/${segment(id)}/side-questions`;
14400
+ const one = (side) => `${base}/${segment(side)}`;
14401
+ return {
14402
+ ask: (question) => routes.json("POST", base, sideQuestionAnswerSchema, {
14403
+ ...question,
14404
+ id: question.id ?? randomUUID(),
14405
+ question: content(question.question)
14406
+ }),
14407
+ followUp: (side, input, options = {}) => routes.send("POST", `${one(side)}/messages`, {
14408
+ content: content(input),
14409
+ senderId: options.senderId
14410
+ }),
14411
+ retry: (side) => routes.send("POST", `${one(side)}/retry`),
14412
+ stop: (side) => routes.send("POST", `${one(side)}/stop`),
14413
+ fold: (side, folded) => routes.json("PATCH", one(side), sideQuestionAnswerSchema, { folded }),
14414
+ remove: (side) => routes.send("DELETE", one(side))
14415
+ };
14416
+ }
14417
+ //#endregion
14418
+ //#region src/conversation.ts
14419
+ /**
14420
+ * A conversation of a core, driven as the web app drives one: a
14421
+ * `ConversationClient` on the conversation's lane, which reads with the
14422
+ * core's routes, holds the root's transcript with the one patch applier, and
14423
+ * sends what the program asks.
14424
+ *
14425
+ * `run(input)` sends a message and waits for the turn it starts to end, as
14426
+ * the Codex SDK's `thread.run`; `events()` is everything the conversation's
14427
+ * lane tells, as an async iterator, with a `permission` event for each
14428
+ * request the conversation's metadata adds.
14429
+ */
14430
+ var Conversation = class {
14431
+ id;
14432
+ routes;
14433
+ registry;
14434
+ client = null;
14435
+ opening = null;
14436
+ /** The root's transcript, as the lane keeps it. */
14437
+ transcript = EMPTY_TRANSCRIPT;
14438
+ metadata = null;
14439
+ /** The permission requests told already. */
14440
+ told = /* @__PURE__ */ new Set();
14441
+ listeners = /* @__PURE__ */ new Set();
14442
+ /** What waits for a change of the transcript or the metadata, and fails once the conversation closes. */
14443
+ waiters = /* @__PURE__ */ new Set();
14444
+ /** Whether the lane is being opened again after it dropped. */
14445
+ reopening = false;
14446
+ /** Whether the lane dropped again while it was being opened again. */
14447
+ droppedAgain = false;
14448
+ schedules;
14449
+ /** Any agent's transcript by pages, and the turns and commands it names. */
14450
+ history;
14451
+ sideQuestions;
14452
+ /** The files of the conversation's devices. */
14453
+ files;
14454
+ /** The working tree's changes. */
14455
+ changes;
14456
+ plugins;
14457
+ constructor(id, routes, registry) {
14458
+ this.id = id;
14459
+ this.routes = routes;
14460
+ this.registry = registry;
14461
+ this.history = conversationHistory(routes, id);
14462
+ this.sideQuestions = sideQuestions(routes, id);
14463
+ this.files = conversationFiles(routes, id);
14464
+ this.changes = conversationChanges(routes, id);
14465
+ const plugin = (name) => `/conversations/${segment(id)}/plugins/${segment(name)}`;
14466
+ this.plugins = {
14467
+ state: (name) => routes.json("GET", `${plugin(name)}/state`, pluginStateAnswerSchema),
14468
+ call: (name, method, input = {}, options = {}) => routes.json("POST", `${plugin(name)}/calls/${segment(method)}${query({ device: options.device })}`, z.unknown(), input)
14469
+ };
14470
+ const path = `/conversations/${segment(id)}/schedules`;
14471
+ const one = (schedule) => `${path}/${segment(schedule)}`;
14472
+ this.schedules = {
14473
+ create: (patch) => routes.json("POST", path, scheduleAnswerSchema, patch),
14474
+ get: (schedule) => routes.json("GET", one(schedule), scheduleDtoSchema),
14475
+ update: (schedule, patch) => routes.json("PATCH", one(schedule), scheduleAnswerSchema, patch),
14476
+ remove: (schedule) => routes.send("DELETE", one(schedule)),
14477
+ run: (schedule, task) => routes.json("POST", `${one(schedule)}/runs`, scheduleRunDtoSchema, task === void 0 ? {} : { task }),
14478
+ runs: async (schedule, before) => {
14479
+ return (await routes.json("GET", `${one(schedule)}/runs${query({ before })}`, scheduleRunsSchema)).runs;
14480
+ }
14481
+ };
14482
+ }
13693
14483
  /** Opens the conversation's lane, once; each action opens it first. */
13694
14484
  open() {
13695
14485
  this.opening ??= this.connect().catch((error) => {
@@ -13699,7 +14489,7 @@ var Conversation = class {
13699
14489
  return this.opening;
13700
14490
  }
13701
14491
  async connect() {
13702
- const path = `/conversations/${encodeURIComponent(this.id)}`;
14492
+ const path = `/conversations/${segment(this.id)}`;
13703
14493
  const client = createConversationClient(this.routes.connection, this.id, {
13704
14494
  reader: {
13705
14495
  conversation: async (signal) => {
@@ -13712,7 +14502,7 @@ var Conversation = class {
13712
14502
  };
13713
14503
  },
13714
14504
  transcript: async (node, signal) => {
13715
- const page = await this.routes.json("GET", `${path}/agents/${encodeURIComponent(node)}/transcript?latest=true`, transcriptPageSchema, void 0, signal);
14505
+ const page = await this.routes.json("GET", `${path}/agents/${segment(node)}/transcript${query({ latest: true })}`, transcriptPageSchema, void 0, signal);
13716
14506
  if (!page.version) throw new Error("The latest page names no version of its transcript");
13717
14507
  return {
13718
14508
  ...page,
@@ -13800,10 +14590,10 @@ var Conversation = class {
13800
14590
  this.changed();
13801
14591
  }
13802
14592
  changed() {
13803
- for (const change of [...this.changes]) change.changed();
14593
+ for (const waiter of [...this.waiters]) waiter.changed();
13804
14594
  }
13805
14595
  permission(request) {
13806
- const decide = (body) => this.routes.send("POST", `/conversations/${encodeURIComponent(this.id)}/permissions/requests/${encodeURIComponent(request.id)}`, body);
14596
+ const decide = (body) => this.routes.send("POST", `/conversations/${segment(this.id)}/permissions/requests/${segment(request.id)}`, body);
13807
14597
  return {
13808
14598
  request,
13809
14599
  allow: (values) => decide({
@@ -13837,8 +14627,8 @@ var Conversation = class {
13837
14627
  * The conversation takes it once however often it is sent under
13838
14628
  * `messageId`, which messages and steers share.
13839
14629
  */
13840
- async send(input, messageId = randomUUID()) {
13841
- await (await this.open()).submit(content(input), messageId);
14630
+ async send(input, messageId = randomUUID(), options = {}) {
14631
+ await (await this.open()).submit(content(input), messageId, [], options.senderId);
13842
14632
  }
13843
14633
  /**
13844
14634
  * Changes what `patch` names of the conversation, as the app's settings
@@ -13846,7 +14636,62 @@ var Conversation = class {
13846
14636
  * refused while the others apply.
13847
14637
  */
13848
14638
  async update(patch) {
13849
- return this.routes.json("PATCH", `/conversations/${encodeURIComponent(this.id)}`, conversationUpdateSchema, patch);
14639
+ return this.routes.json("PATCH", `/conversations/${segment(this.id)}`, conversationUpdateSchema, patch);
14640
+ }
14641
+ /** The conversation as the list shows it, with its metadata and its agents. */
14642
+ get() {
14643
+ return this.routes.json("GET", `/conversations/${segment(this.id)}`, conversationDetailSchema);
14644
+ }
14645
+ /** Deletes the conversation, with its history and its files. */
14646
+ async remove() {
14647
+ await this.routes.send("DELETE", `/conversations/${segment(this.id)}`);
14648
+ this.close();
14649
+ this.registry.removed(this.id);
14650
+ }
14651
+ /**
14652
+ * The conversation's page for `<jush-conversation src>`, which the
14653
+ * program's server answers below `options.base` with `fetch` and `accept`,
14654
+ * doing what `options.allow` names; make one for each request.
14655
+ */
14656
+ page(options) {
14657
+ return new ConversationPage(this.routes, this.id, options);
14658
+ }
14659
+ /**
14660
+ * A new conversation holding this one's history through the completed text
14661
+ * `through`, or everything before the turn `before`, which the message of
14662
+ * that id started; under `id`, made unless named, which a retry repeats.
14663
+ */
14664
+ async fork(options) {
14665
+ const answer = await this.routes.json("POST", `/conversations/${segment(this.id)}/fork`, forkAnswerSchema, {
14666
+ id: options.id ?? randomUUID(),
14667
+ blockId: options.through,
14668
+ beforeTurn: options.before
14669
+ });
14670
+ return this.registry.open(answer.conversation.id);
14671
+ }
14672
+ /** Opens the conversation's agents again with the core's plugins as they are now, as after `core.plugins.enable`. */
14673
+ reloadPlugins() {
14674
+ return this.routes.send("POST", `/conversations/${segment(this.id)}/reload`);
14675
+ }
14676
+ /** The conversation's messages that match `text`. */
14677
+ search(text) {
14678
+ return this.routes.json("GET", `/conversations/${segment(this.id)}/search${query({ q: text })}`, messageResultsSchema);
14679
+ }
14680
+ /** What the calls of the last hour or day cost, by agent. */
14681
+ cost(window) {
14682
+ return this.routes.json("GET", `/conversations/${segment(this.id)}/cost/recent${query({ window })}`, recentCostSchema);
14683
+ }
14684
+ /** The workflows the conversation's agents can start, as its directory keeps them. */
14685
+ workflows() {
14686
+ return this.routes.json("GET", `/conversations/${segment(this.id)}/workflows`, conversationWorkflowListSchema);
14687
+ }
14688
+ /** Takes the pinned document `pin`, one of the metadata's `pins`, back from the conversation's agents. */
14689
+ unpin(pin) {
14690
+ return this.routes.send("DELETE", `/conversations/${segment(this.id)}/pins/${pin}`);
14691
+ }
14692
+ /** Detaches the device `device` the conversation brought in. */
14693
+ detach(device) {
14694
+ return this.routes.send("DELETE", `/conversations/${segment(this.id)}/devices/${segment(device)}`);
13850
14695
  }
13851
14696
  /**
13852
14697
  * Sends `text` to the subagent `node`, the id of one of `agents` whose
@@ -13855,11 +14700,12 @@ var Conversation = class {
13855
14700
  * with it. Resolves with the message's id, the one made for it when
13856
14701
  * `messageId` is absent.
13857
14702
  */
13858
- async sendToAgent(node, text, messageId) {
13859
- const path = `/conversations/${encodeURIComponent(this.id)}/agents/${encodeURIComponent(node)}/messages`;
14703
+ async sendToAgent(node, text, messageId, options = {}) {
14704
+ const path = `/conversations/${segment(this.id)}/agents/${segment(node)}/messages`;
13860
14705
  const { id } = await this.routes.json("POST", path, subagentMessageAnswerSchema, {
13861
14706
  id: messageId,
13862
- text
14707
+ text,
14708
+ senderId: options.senderId
13863
14709
  });
13864
14710
  return id;
13865
14711
  }
@@ -13868,8 +14714,8 @@ var Conversation = class {
13868
14714
  * The conversation takes it once however often it is sent under
13869
14715
  * `steerId`, which messages and steers share.
13870
14716
  */
13871
- async steer(input, steerId = randomUUID()) {
13872
- await (await this.open()).steer(content(input), steerId);
14717
+ async steer(input, steerId = randomUUID(), options = {}) {
14718
+ await (await this.open()).steer(content(input), steerId, [], options.senderId);
13873
14719
  }
13874
14720
  async abort() {
13875
14721
  return (await this.open()).abort();
@@ -13893,20 +14739,20 @@ var Conversation = class {
13893
14739
  * holds. It fails when the message left the queue without running, as an
13894
14740
  * abort's clearing of the queue removes it.
13895
14741
  */
13896
- async run(input) {
14742
+ async run(input, options = {}) {
13897
14743
  const messageId = randomUUID();
13898
14744
  let sent = false;
13899
14745
  let answered = null;
13900
14746
  let asked = null;
13901
14747
  let reading = false;
13902
14748
  let failures = 0;
13903
- let change = {
14749
+ let waiter = {
13904
14750
  changed: () => {},
13905
14751
  closed: () => {}
13906
14752
  };
13907
14753
  const ended = new Promise((resolve, reject) => {
13908
14754
  const again = () => {
13909
- if (this.changes.has(change)) change.changed();
14755
+ if (this.waiters.has(waiter)) waiter.changed();
13910
14756
  };
13911
14757
  const later = () => {
13912
14758
  failures += 1;
@@ -13917,7 +14763,7 @@ var Conversation = class {
13917
14763
  this.turnState(messageId).then((state) => {
13918
14764
  if (asked !== view) return;
13919
14765
  if (state === null) {
13920
- this.changes.delete(change);
14766
+ this.waiters.delete(waiter);
13921
14767
  reject(/* @__PURE__ */ new Error("The message left the queue without running"));
13922
14768
  } else if (state.state === "ended") {
13923
14769
  failures = 0;
@@ -13948,7 +14794,7 @@ var Conversation = class {
13948
14794
  later();
13949
14795
  });
13950
14796
  };
13951
- change = {
14797
+ waiter = {
13952
14798
  changed: () => {
13953
14799
  const last = this.metadata?.lastTurn;
13954
14800
  const end = last?.turnId === messageId ? {
@@ -13958,7 +14804,7 @@ var Conversation = class {
13958
14804
  if (end) {
13959
14805
  const turn = this.turnOf(messageId, end);
13960
14806
  if (turn) {
13961
- this.changes.delete(change);
14807
+ this.waiters.delete(waiter);
13962
14808
  resolve(turn);
13963
14809
  return;
13964
14810
  }
@@ -13972,15 +14818,15 @@ var Conversation = class {
13972
14818
  };
13973
14819
  });
13974
14820
  ended.catch(() => {});
13975
- this.changes.add(change);
14821
+ this.waiters.add(waiter);
13976
14822
  try {
13977
- await this.send(input, messageId);
14823
+ await this.send(input, messageId, options);
13978
14824
  } catch (error) {
13979
- this.changes.delete(change);
14825
+ this.waiters.delete(waiter);
13980
14826
  throw error;
13981
14827
  }
13982
14828
  sent = true;
13983
- change.changed();
14829
+ waiter.changed();
13984
14830
  return ended;
13985
14831
  }
13986
14832
  /**
@@ -14007,7 +14853,7 @@ var Conversation = class {
14007
14853
  }
14008
14854
  /** Where the turn `messageId` stands, as the conversation answers; null when it holds no turn of it. */
14009
14855
  async turnState(messageId) {
14010
- const path = `/conversations/${encodeURIComponent(this.id)}/turns/${encodeURIComponent(messageId)}`;
14856
+ const path = `/conversations/${segment(this.id)}/turns/${segment(messageId)}`;
14011
14857
  try {
14012
14858
  return await this.routes.json("GET", path, turnStateSchema);
14013
14859
  } catch (error) {
@@ -14024,6 +14870,7 @@ var Conversation = class {
14024
14870
  const after = blocks.slice(at + 1, end + 1);
14025
14871
  const text = after.flatMap((block) => block.type === "text" ? [block.text] : []).join("\n\n");
14026
14872
  return {
14873
+ id: messageId,
14027
14874
  outcome: ending.outcome,
14028
14875
  blocks: after,
14029
14876
  text
@@ -14041,8 +14888,8 @@ var Conversation = class {
14041
14888
  }
14042
14889
  /** Reads the page of the root's transcript before `window` into what the conversation holds. */
14043
14890
  async readBefore(window) {
14044
- const root = encodeURIComponent(this.id);
14045
- const edge = encodeURIComponent(window.blocks[0].id);
14891
+ const root = segment(this.id);
14892
+ const edge = segment(window.blocks[0].id);
14046
14893
  const path = `/conversations/${root}/agents/${root}/transcript?before=${window.start}&edge=${edge}`;
14047
14894
  const page = await this.routes.json("GET", path, transcriptPageSchema);
14048
14895
  this.transcript = addPage(this.transcript, page, true);
@@ -14059,7 +14906,7 @@ var Conversation = class {
14059
14906
  waiting.push(event);
14060
14907
  wake?.();
14061
14908
  };
14062
- const change = {
14909
+ const waiter = {
14063
14910
  changed: () => {},
14064
14911
  closed: () => {
14065
14912
  closed = true;
@@ -14067,7 +14914,7 @@ var Conversation = class {
14067
14914
  }
14068
14915
  };
14069
14916
  this.listeners.add(listener);
14070
- this.changes.add(change);
14917
+ this.waiters.add(waiter);
14071
14918
  try {
14072
14919
  await this.open();
14073
14920
  for (;;) {
@@ -14082,7 +14929,7 @@ var Conversation = class {
14082
14929
  }
14083
14930
  } finally {
14084
14931
  this.listeners.delete(listener);
14085
- this.changes.delete(change);
14932
+ this.waiters.delete(waiter);
14086
14933
  }
14087
14934
  }
14088
14935
  /**
@@ -14095,17 +14942,61 @@ var Conversation = class {
14095
14942
  this.client = null;
14096
14943
  this.opening = null;
14097
14944
  client?.dispose();
14098
- for (const change of [...this.changes]) {
14099
- this.changes.delete(change);
14100
- change.closed();
14945
+ for (const waiter of [...this.waiters]) {
14946
+ this.waiters.delete(waiter);
14947
+ waiter.closed();
14101
14948
  }
14102
14949
  }
14103
14950
  };
14104
- function content(input) {
14105
- return typeof input === "string" ? [{
14106
- type: "text",
14107
- text: input
14108
- }] : input;
14951
+ //#endregion
14952
+ //#region src/models.ts
14953
+ /** The models a core's entries offer, and what their calls used. */
14954
+ function models(routes) {
14955
+ return {
14956
+ search: async (text, options = {}) => (await routes.json("GET", `/models/search${query({
14957
+ q: text,
14958
+ entry: options.provider
14959
+ })}`, modelSearchResultsSchema)).results,
14960
+ refresh: () => routes.send("POST", "/models/refresh")
14961
+ };
14962
+ }
14963
+ function usage$1(routes) {
14964
+ return {
14965
+ totals: async () => (await routes.json("GET", "/usage", usageTotalsSchema)).totals,
14966
+ report: async (options) => routes.json("GET", `/usage/report${query({
14967
+ from: options.from.toISOString(),
14968
+ to: options.to.toISOString(),
14969
+ bucket: options.bucket,
14970
+ timeZone: options.timeZone,
14971
+ groupBy: options.groupBy !== void 0 && options.groupBy.length > 0 ? options.groupBy.join(",") : void 0
14972
+ })}`, usageReportSchema)
14973
+ };
14974
+ }
14975
+ //#endregion
14976
+ //#region src/organize.ts
14977
+ /** How a core's conversations are organized: workspaces and projects. */
14978
+ function workspaces(routes) {
14979
+ const one = (id) => `/workspaces/${segment(id)}`;
14980
+ return {
14981
+ list: async () => (await routes.json("GET", "/workspaces", workspacesSchema)).workspaces,
14982
+ create: async (workspace) => (await routes.json("POST", "/workspaces", workspaceAnswerSchema, workspace)).workspace,
14983
+ update: async (id, patch) => (await routes.json("PATCH", one(id), workspaceAnswerSchema, patch)).workspace,
14984
+ remove: (id) => routes.send("DELETE", one(id)),
14985
+ order: (ids) => routes.send("PUT", "/workspaces/order", { ids }),
14986
+ move: (id, moved) => routes.send("POST", `${one(id)}/moves`, {
14987
+ conversations: moved.conversations ?? [],
14988
+ projects: moved.projects ?? []
14989
+ })
14990
+ };
14991
+ }
14992
+ function projects(routes) {
14993
+ const one = (id) => `/projects/${segment(id)}`;
14994
+ return {
14995
+ list: async () => (await routes.json("GET", "/projects", projectsSchema)).projects,
14996
+ create: async (project) => (await routes.json("POST", "/projects", projectAnswerSchema, project)).project,
14997
+ update: async (id, patch) => (await routes.json("PATCH", one(id), projectAnswerSchema, patch)).project,
14998
+ remove: (id) => routes.send("DELETE", one(id))
14999
+ };
14109
15000
  }
14110
15001
  //#endregion
14111
15002
  //#region src/apart.ts
@@ -14405,277 +15296,141 @@ function commandCall(invocation, port) {
14405
15296
  }),
14406
15297
  readStdin: async () => {
14407
15298
  const response = await rpc({ type: "read_stdin" });
14408
- return response.type === "input" ? response.bytes ?? null : null;
14409
- },
14410
- awaitsUser: async (awaits) => void await rpc({
14411
- type: "awaits_user",
14412
- awaits
14413
- }),
14414
- medium: async (facts, data) => void await rpc({
14415
- type: "medium",
14416
- facts,
14417
- bytes: bytes(data)
14418
- })
14419
- };
14420
- }
14421
- /** The reply to `call`, by the definition's handler of it. */
14422
- async function answer(definition, call, port) {
14423
- switch (call.type) {
14424
- case "command": {
14425
- const leaf = leafAt(definition, call.invocation.path);
14426
- if (leaf === void 0) throw usage(`No command ${call.invocation.path.join(" ")}`);
14427
- const parsed = (leaf.input ?? z.object({})).safeParse(call.invocation.args);
14428
- if (!parsed.success) throw usage(schemaRefusal(parsed.error));
14429
- const commandPort = commandCall(call.invocation, port);
14430
- try {
14431
- return {
14432
- type: "exit",
14433
- code: await leaf.run(parsed.data, commandPort) ?? 0
14434
- };
14435
- } catch (error) {
14436
- if (error instanceof PortFailure) throw error;
14437
- await commandPort.stderr(`${error instanceof Error ? error.message : String(error)}\n`);
14438
- return {
14439
- type: "exit",
14440
- code: 1
14441
- };
14442
- }
14443
- }
14444
- case "context": {
14445
- const text = await definition.context?.(call, port);
14446
- return text === void 0 ? { type: "context" } : {
14447
- type: "context",
14448
- text
14449
- };
14450
- }
14451
- case "project_search":
14452
- if (definition.projectSearch === void 0) throw undeclared("a project search");
14453
- return await definition.projectSearch(call, port);
14454
- case "conversation_deleted":
14455
- await definition.onConversationDeleted?.(call, port);
14456
- return { type: "done" };
14457
- case "conversation_forked":
14458
- await definition.onConversationForked?.(call, port);
14459
- return { type: "done" };
14460
- default: throw undeclared(call.type);
14461
- }
14462
- }
14463
- var RequestFailure = class extends Error {
14464
- error;
14465
- constructor(error) {
14466
- super("message" in error ? error.message : error.type);
14467
- this.error = error;
14468
- }
14469
- };
14470
- function usage(message) {
14471
- return new RequestFailure({
14472
- type: "usage",
14473
- message
14474
- });
14475
- }
14476
- function undeclared(what) {
14477
- return new RequestFailure({
14478
- type: "failed",
14479
- message: `The plugin declares no ${what}`
14480
- });
14481
- }
14482
- function pluginError(error) {
14483
- if (error instanceof RequestFailure) return error.error;
14484
- return {
14485
- type: "failed",
14486
- message: error instanceof Error ? error.message : String(error)
14487
- };
14488
- }
14489
- //#endregion
14490
- //#region src/socket.ts
14491
- /**
14492
- * A WebSocket on a stream of the process's HTTP/2 connection (RFC 8441):
14493
- * the stream is the socket's, and its bytes are WebSocket frames (RFC 6455),
14494
- * which Node's `http2` does not write, so this module does. A client masks
14495
- * each frame it sends; the process's frames come unmasked.
14496
- *
14497
- * It has the part of a browser's `WebSocket` the page connection and a
14498
- * forwarded page's socket use: `send`, `close`, `bufferedAmount`,
14499
- * `binaryType`, and the `open`, `message` and `close` events.
14500
- */
14501
- const TEXT = 1;
14502
- const BINARY = 2;
14503
- const CLOSE = 8;
14504
- const PING = 9;
14505
- const PONG = 10;
14506
- const CONTINUATION = 0;
14507
- /** The close of a socket that ended without a close frame. */
14508
- const ABNORMAL_CLOSURE = 1006;
14509
- /** The close frame's code when it carries none. */
14510
- const NO_STATUS = 1005;
14511
- /** A WebSocket on the stream `opening` answers once the process took it. */
14512
- var StreamSocket = class {
14513
- binaryType = "arraybuffer";
14514
- stream = null;
14515
- listeners = /* @__PURE__ */ new Map();
14516
- /** The bytes read that do not make a whole frame yet. */
14517
- pending = /* @__PURE__ */ new Uint8Array(0);
14518
- /** The fragments of a message whose last frame has not come. */
14519
- fragments = null;
14520
- closed = false;
14521
- /** Whether this end sent its close frame. */
14522
- closing = false;
14523
- constructor(opening) {
14524
- opening.then((stream) => {
14525
- if (this.closed) {
14526
- stream.close();
14527
- return;
14528
- }
14529
- this.stream = stream;
14530
- stream.on("data", (chunk) => this.read(chunk));
14531
- stream.once("close", () => this.ended(ABNORMAL_CLOSURE, ""));
14532
- stream.on("error", () => {});
14533
- this.emit("open");
14534
- }, () => this.ended(ABNORMAL_CLOSURE, ""));
14535
- }
14536
- /** The bytes sent that the stream has not written yet. */
14537
- get bufferedAmount() {
14538
- return this.stream?.writableLength ?? 0;
14539
- }
14540
- addEventListener(type, listener) {
14541
- let set = this.listeners.get(type);
14542
- if (!set) {
14543
- set = /* @__PURE__ */ new Set();
14544
- this.listeners.set(type, set);
14545
- }
14546
- set.add(listener);
14547
- }
14548
- removeEventListener(type, listener) {
14549
- this.listeners.get(type)?.delete(listener);
14550
- }
14551
- /** Sends a message: text for a string, binary for bytes. */
14552
- send(data) {
14553
- if (typeof data === "string") this.write(TEXT, new TextEncoder().encode(data));
14554
- else this.write(BINARY, data instanceof ArrayBuffer ? new Uint8Array(data) : data);
14555
- }
14556
- /** Closes the socket with `code` and `reason`; its `close` event follows. */
14557
- close(code = 1e3, reason = "") {
14558
- if (this.closed || this.closing) return;
14559
- this.closing = true;
14560
- if (this.stream === null) {
14561
- this.ended(ABNORMAL_CLOSURE, "");
14562
- return;
14563
- }
14564
- const text = new TextEncoder().encode(reason);
14565
- const body = new Uint8Array(2 + text.length);
14566
- new DataView(body.buffer).setUint16(0, code);
14567
- body.set(text, 2);
14568
- this.write(CLOSE, body);
14569
- this.stream.end();
14570
- }
14571
- emit(type, ...event) {
14572
- for (const listener of [...this.listeners.get(type) ?? []]) listener(...event);
14573
- }
14574
- /** Writes one frame of `opcode` with `payload`, masked. */
14575
- write(opcode, payload) {
14576
- const stream = this.stream;
14577
- if (stream === null || this.closed || stream.destroyed) return;
14578
- const length = payload.length;
14579
- const extended = length < 126 ? 0 : length < 65536 ? 2 : 8;
14580
- const frame = new Uint8Array(2 + extended + 4 + length);
14581
- const view = new DataView(frame.buffer);
14582
- frame[0] = 128 | opcode;
14583
- if (extended === 0) frame[1] = 128 | length;
14584
- else if (extended === 2) {
14585
- frame[1] = 254;
14586
- view.setUint16(2, length);
14587
- } else {
14588
- frame[1] = 255;
14589
- view.setBigUint64(2, BigInt(length));
14590
- }
14591
- const at = 2 + extended;
14592
- const mask = frame.subarray(at, at + 4);
14593
- randomFillSync(mask);
14594
- const body = frame.subarray(at + 4);
14595
- for (let index = 0; index < length; index += 1) body[index] = payload[index] ^ mask[index & 3];
14596
- stream.write(frame);
14597
- }
14598
- /** Takes bytes of the stream, and handles each whole frame they complete. */
14599
- read(chunk) {
14600
- let bytes = this.pending.length === 0 ? chunk : concat([this.pending, chunk]);
14601
- while (bytes.length >= 2) {
14602
- const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
14603
- const fin = (bytes[0] & 128) !== 0;
14604
- const opcode = bytes[0] & 15;
14605
- let length = bytes[1] & 127;
14606
- let at = 2;
14607
- if (length === 126) {
14608
- if (bytes.length < 4) break;
14609
- length = view.getUint16(2);
14610
- at = 4;
14611
- } else if (length === 127) {
14612
- if (bytes.length < 10) break;
14613
- length = Number(view.getBigUint64(2));
14614
- at = 10;
15299
+ return response.type === "input" ? response.bytes ?? null : null;
15300
+ },
15301
+ awaitsUser: async (awaits) => void await rpc({
15302
+ type: "awaits_user",
15303
+ awaits
15304
+ }),
15305
+ medium: async (facts, data) => void await rpc({
15306
+ type: "medium",
15307
+ facts,
15308
+ bytes: bytes(data)
15309
+ })
15310
+ };
15311
+ }
15312
+ /** The reply to `call`, by the definition's handler of it. */
15313
+ async function answer(definition, call, port) {
15314
+ switch (call.type) {
15315
+ case "command": {
15316
+ const leaf = leafAt(definition, call.invocation.path);
15317
+ if (leaf === void 0) throw usage(`No command ${call.invocation.path.join(" ")}`);
15318
+ const parsed = (leaf.input ?? z.object({})).safeParse(call.invocation.args);
15319
+ if (!parsed.success) throw usage(schemaRefusal(parsed.error));
15320
+ const commandPort = commandCall(call.invocation, port);
15321
+ try {
15322
+ return {
15323
+ type: "exit",
15324
+ code: await leaf.run(parsed.data, commandPort) ?? 0
15325
+ };
15326
+ } catch (error) {
15327
+ if (error instanceof PortFailure) throw error;
15328
+ await commandPort.stderr(`${error instanceof Error ? error.message : String(error)}\n`);
15329
+ return {
15330
+ type: "exit",
15331
+ code: 1
15332
+ };
14615
15333
  }
14616
- if (bytes.length < at + length) break;
14617
- const payload = bytes.slice(at, at + length);
14618
- bytes = bytes.subarray(at + length);
14619
- this.frame(fin, opcode, payload);
14620
15334
  }
14621
- this.pending = bytes.slice();
14622
- }
14623
- frame(fin, opcode, payload) {
14624
- switch (opcode) {
14625
- case PING:
14626
- this.write(PONG, payload);
14627
- return;
14628
- case PONG: return;
14629
- case CLOSE: {
14630
- const code = payload.length >= 2 ? new DataView(payload.buffer, payload.byteOffset).getUint16(0) : NO_STATUS;
14631
- const reason = new TextDecoder().decode(payload.subarray(2));
14632
- if (!this.closing) {
14633
- this.closing = true;
14634
- this.write(CLOSE, payload.subarray(0, 2));
14635
- this.stream?.end();
14636
- }
14637
- this.ended(code, reason);
14638
- return;
14639
- }
14640
- case CONTINUATION:
14641
- if (this.fragments === null) return;
14642
- this.fragments.parts.push(payload);
14643
- if (fin) {
14644
- const { opcode: first, parts } = this.fragments;
14645
- this.fragments = null;
14646
- this.message(first, concat(parts));
14647
- }
14648
- return;
14649
- case TEXT:
14650
- case BINARY: if (fin) this.message(opcode, payload);
14651
- else this.fragments = {
14652
- opcode,
14653
- parts: [payload]
15335
+ case "context": {
15336
+ const text = await definition.context?.(call, port);
15337
+ return text === void 0 ? { type: "context" } : {
15338
+ type: "context",
15339
+ text
14654
15340
  };
14655
15341
  }
15342
+ case "project_search":
15343
+ if (definition.projectSearch === void 0) throw undeclared("a project search");
15344
+ return await definition.projectSearch(call, port);
15345
+ case "conversation_deleted":
15346
+ await definition.onConversationDeleted?.(call, port);
15347
+ return { type: "done" };
15348
+ case "conversation_forked":
15349
+ await definition.onConversationForked?.(call, port);
15350
+ return { type: "done" };
15351
+ default: throw undeclared(call.type);
14656
15352
  }
14657
- message(opcode, payload) {
14658
- const data = opcode === TEXT ? new TextDecoder().decode(payload) : payload.buffer.slice(payload.byteOffset, payload.byteOffset + payload.byteLength);
14659
- this.emit("message", { data });
14660
- }
14661
- ended(code, reason) {
14662
- if (this.closed) return;
14663
- this.closed = true;
14664
- this.stream?.close();
14665
- this.emit("close", {
14666
- code,
14667
- reason
14668
- });
15353
+ }
15354
+ var RequestFailure = class extends Error {
15355
+ error;
15356
+ constructor(error) {
15357
+ super("message" in error ? error.message : error.type);
15358
+ this.error = error;
14669
15359
  }
14670
15360
  };
14671
- function concat(parts) {
14672
- const whole = new Uint8Array(parts.reduce((total, part) => total + part.length, 0));
14673
- let at = 0;
14674
- for (const part of parts) {
14675
- whole.set(part, at);
14676
- at += part.length;
14677
- }
14678
- return whole;
15361
+ function usage(message) {
15362
+ return new RequestFailure({
15363
+ type: "usage",
15364
+ message
15365
+ });
15366
+ }
15367
+ function undeclared(what) {
15368
+ return new RequestFailure({
15369
+ type: "failed",
15370
+ message: `The plugin declares no ${what}`
15371
+ });
15372
+ }
15373
+ function pluginError(error) {
15374
+ if (error instanceof RequestFailure) return error.error;
15375
+ return {
15376
+ type: "failed",
15377
+ message: error instanceof Error ? error.message : String(error)
15378
+ };
15379
+ }
15380
+ //#endregion
15381
+ //#region src/port-forwards.ts
15382
+ /** The ports a core's devices forward. */
15383
+ function portForwards(routes) {
15384
+ const one = (id) => `/port-forwards/${segment(id)}`;
15385
+ return {
15386
+ list: async () => (await routes.json("GET", "/port-forwards", portForwardListSchema)).forwards,
15387
+ create: async (forward) => (await routes.json("POST", "/port-forwards", portForwardAnswerSchema, forward)).forward,
15388
+ update: async (id, patch) => (await routes.json("PATCH", one(id), portForwardAnswerSchema, patch)).forward,
15389
+ remove: (id) => routes.send("DELETE", one(id)),
15390
+ retry: (id) => routes.send("POST", `${one(id)}/retry`)
15391
+ };
15392
+ }
15393
+ //#endregion
15394
+ //#region src/settings.ts
15395
+ /**
15396
+ * A core's settings a program manages: credentials, the instructions every
15397
+ * agent reads, subagents and their profiles, and plugins.
15398
+ */
15399
+ function credentials(routes) {
15400
+ const one = (id) => `/credentials/${segment(id)}`;
15401
+ return {
15402
+ list: async () => (await routes.json("GET", "/credentials", credentialListSchema)).credentials,
15403
+ create: async (credential) => (await routes.json("POST", "/credentials", credentialAnswerSchema, credential)).credential,
15404
+ update: async (id, patch) => (await routes.json("PATCH", one(id), credentialAnswerSchema, patch)).credential,
15405
+ remove: (id) => routes.send("DELETE", one(id)),
15406
+ reveal: async (id, field) => (await routes.json("POST", `${one(id)}/fields/${segment(field)}/reveal`, revealedValueSchema)).value
15407
+ };
15408
+ }
15409
+ function instructions(routes) {
15410
+ return {
15411
+ get: async () => (await routes.json("GET", "/settings/instructions", instructionsAnswerSchema)).instructions,
15412
+ set: (text) => routes.send("PUT", "/instructions", { text })
15413
+ };
15414
+ }
15415
+ function subagents(routes) {
15416
+ const one = (id) => `/subagents/profiles/${segment(id)}`;
15417
+ return {
15418
+ get: () => routes.json("GET", "/settings/subagents", subagentSettingsSchema),
15419
+ update: (patch) => routes.send("PUT", "/subagents", patch),
15420
+ profiles: {
15421
+ create: async (profile) => (await routes.json("POST", "/subagents/profiles", profileAnswerSchema, profile)).profile,
15422
+ update: async (id, patch) => (await routes.json("PATCH", one(id), profileAnswerSchema, patch)).profile,
15423
+ remove: (id) => routes.send("DELETE", one(id))
15424
+ }
15425
+ };
15426
+ }
15427
+ function corePlugins(routes) {
15428
+ const one = (plugin) => `/plugins/${segment(plugin)}`;
15429
+ return {
15430
+ enable: (plugin, enabled) => routes.send("PUT", one(plugin), { enabled }),
15431
+ enableFeature: (plugin, feature, enabled) => routes.send("PUT", `${one(plugin)}/features/${segment(feature)}`, { enabled }),
15432
+ call: (plugin, method, input = {}) => routes.json("POST", `${one(plugin)}/calls/${segment(method)}`, z.unknown(), input)
15433
+ };
14679
15434
  }
14680
15435
  //#endregion
14681
15436
  //#region src/core.ts
@@ -14694,6 +15449,15 @@ var Core = class {
14694
15449
  conversations;
14695
15450
  providers;
14696
15451
  devices;
15452
+ credentials;
15453
+ instructions;
15454
+ subagents;
15455
+ plugins;
15456
+ models;
15457
+ usage;
15458
+ workspaces;
15459
+ projects;
15460
+ portForwards;
14697
15461
  routes;
14698
15462
  connection;
14699
15463
  stateRead;
@@ -14706,12 +15470,21 @@ var Core = class {
14706
15470
  this.closing = closing;
14707
15471
  this.id = opening.id;
14708
15472
  this.dir = opening.dir;
14709
- this.connection = new PageConnection(processConnection(opening.process, `/cores/${encodeURIComponent(opening.id)}/api/connect`));
15473
+ this.connection = new PageConnection(processConnection(opening.process, `/cores/${segment(opening.id)}/api/connect`));
14710
15474
  this.connection.start();
14711
15475
  this.routes = new CoreRoutes(opening.process, opening.id, this.connection);
14712
15476
  this.conversations = new Conversations(this.routes, () => this.stateRead);
14713
15477
  this.providers = new Providers(this.routes);
14714
15478
  this.devices = new Devices(this.routes, opening.process, opening.runner, opening.dir, (id, ended) => this.online(id, ended));
15479
+ this.credentials = credentials(this.routes);
15480
+ this.instructions = instructions(this.routes);
15481
+ this.subagents = subagents(this.routes);
15482
+ this.plugins = corePlugins(this.routes);
15483
+ this.models = models(this.routes);
15484
+ this.usage = usage$1(this.routes);
15485
+ this.workspaces = workspaces(this.routes);
15486
+ this.projects = projects(this.routes);
15487
+ this.portForwards = portForwards(this.routes);
14715
15488
  for (const plugin of opening.plugins) this.servePlugin(plugin);
14716
15489
  }
14717
15490
  /** Reads the core's product state and follows it from then on. */
@@ -14740,6 +15513,37 @@ var Core = class {
14740
15513
  };
14741
15514
  }
14742
15515
  /**
15516
+ * Keeps `file` as an upload of the core's, as the web app's composer does,
15517
+ * and answers the block a message, a steer or a run sends it in.
15518
+ */
15519
+ async upload(file) {
15520
+ const named = clientContentSchema.safeParse({
15521
+ type: "upload",
15522
+ ref: "unsent",
15523
+ fileName: file.name
15524
+ });
15525
+ if (!named.success) throw new Error(`${JSON.stringify(file.name)} is not a file's name: ${schemaRefusal(named.error)}`);
15526
+ const type = file.mediaType || (file.bytes instanceof Blob ? file.bytes.type : "");
15527
+ const query = new URLSearchParams({ name: file.name });
15528
+ const { attachment } = await this.routes.json("POST", `/attachments?${query}`, attachmentAnswerSchema, new Blob([file.bytes], { type }));
15529
+ return {
15530
+ type: "upload",
15531
+ ref: attachment.id,
15532
+ fileName: file.name
15533
+ };
15534
+ }
15535
+ /** The conversations whose titles and messages match `text`, of the workspace `workspace` alone when named. */
15536
+ async search(text, options = {}) {
15537
+ return (await this.routes.json("GET", `/search${query({
15538
+ q: text,
15539
+ workspace: options.workspace
15540
+ })}`, searchResultsSchema)).results;
15541
+ }
15542
+ /** The bytes of the blob `sha256`, such as a medium a block names. */
15543
+ blob(sha256) {
15544
+ return this.routes.bytes("GET", `/blobs/${segment(sha256)}`);
15545
+ }
15546
+ /**
14743
15547
  * Changes what `patch` names of the core's preferences, the web app's
14744
15548
  * Settings, and answers them, such as `commandLocale`, the time zone and
14745
15549
  * languages its commands and browsers run in.
@@ -14747,46 +15551,6 @@ var Core = class {
14747
15551
  async updatePreferences(patch) {
14748
15552
  return (await this.routes.json("PATCH", "/settings/preferences", userPreferencesSchema, patch)).preferences;
14749
15553
  }
14750
- /**
14751
- * Answers `request` with the core's route it names below `base`, such as
14752
- * `/jush/api/conversations` below `/jush/api`, as the program's server
14753
- * forwards a page's request.
14754
- */
14755
- fetch(request, base = "/api") {
14756
- const url = new URL(request.url);
14757
- const forwarded = new Request(PROCESS_ORIGIN + this.routes.path(below(url.pathname, base)) + url.search, request);
14758
- return this.routes.process.fetch(forwarded);
14759
- }
14760
- /**
14761
- * Carries the page connection a page opened on the program's server,
14762
- * `socket`, to the core, both ways, until either end closes; `url` is the
14763
- * address the page opened, whose query goes with it.
14764
- */
14765
- accept(socket, url) {
14766
- const query = url === void 0 ? "" : new URL(url, PROCESS_ORIGIN).search;
14767
- const core = new StreamSocket(this.routes.process.connect(this.routes.path(`/connect${query}`), "websocket", { "sec-websocket-version": "13" }));
14768
- const early = [];
14769
- let open = false;
14770
- let pageClosed = false;
14771
- socket.binaryType = "arraybuffer";
14772
- socket.addEventListener("message", (event) => {
14773
- const data = event.data;
14774
- if (open) core.send(data);
14775
- else early.push(data);
14776
- });
14777
- socket.addEventListener("close", () => {
14778
- pageClosed = true;
14779
- core.close();
14780
- });
14781
- core.addEventListener("open", () => {
14782
- open = true;
14783
- for (const data of early.splice(0)) core.send(data);
14784
- });
14785
- core.addEventListener("message", (event) => socket.send(event.data));
14786
- core.addEventListener("close", (event) => {
14787
- if (!pageClosed) socket.close(event.code === 1006 || event.code === 1005 ? 1011 : event.code, event.reason);
14788
- });
14789
- }
14790
15554
  /** Closes the core, for every program: its lanes end, and the process closes it. */
14791
15555
  async close() {
14792
15556
  if (this.closed) return;
@@ -14963,11 +15727,30 @@ var Conversations = class {
14963
15727
  const created = await this.routes.json("POST", "/conversations", createdConversationSchema, body);
14964
15728
  return this.open(created.conversation.id);
14965
15729
  }
15730
+ /** The core's conversations that are not archived, or with `archived` the ones that are. */
15731
+ async list(options = {}) {
15732
+ return (await this.routes.json("GET", `/conversations${query({ archived: options.archived })}`, conversationsSchema)).conversations;
15733
+ }
15734
+ /** The conversation `id` as the list shows it, with its metadata and its agents. */
15735
+ get(id) {
15736
+ return this.open(id).get();
15737
+ }
15738
+ /** Deletes the conversation `id`, with its history and its files. */
15739
+ remove(id) {
15740
+ return this.open(id).remove();
15741
+ }
15742
+ /** Changes several conversations at once, such as archiving them; each item answers apart. */
15743
+ async updateMany(items) {
15744
+ return (await this.routes.json("POST", "/conversations/batch", batchAnswerSchema, { items })).results;
15745
+ }
14966
15746
  /** The conversation `id`, whose lane opens at its first use. */
14967
15747
  open(id) {
14968
15748
  let conversation = this.opened.get(id);
14969
15749
  if (conversation === void 0) {
14970
- conversation = new Conversation(id, this.routes);
15750
+ conversation = new Conversation(id, this.routes, {
15751
+ open: (other) => this.open(other),
15752
+ removed: (gone) => this.opened.delete(gone)
15753
+ });
14971
15754
  this.opened.set(id, conversation);
14972
15755
  }
14973
15756
  return conversation;
@@ -14990,18 +15773,46 @@ var Providers = class {
14990
15773
  return (await this.routes.json("POST", "/providers", providerAnswerSchema, provider)).provider;
14991
15774
  }
14992
15775
  async update(id, patch) {
14993
- return (await this.routes.json("PATCH", `/providers/${encodeURIComponent(id)}`, providerAnswerSchema, patch)).provider;
15776
+ return (await this.routes.json("PATCH", `/providers/${segment(id)}`, providerAnswerSchema, patch)).provider;
14994
15777
  }
14995
15778
  async remove(id) {
14996
- await this.routes.send("DELETE", `/providers/${encodeURIComponent(id)}`);
15779
+ await this.routes.send("DELETE", `/providers/${segment(id)}`);
15780
+ }
15781
+ /** The vendors and subscriptions an entry can be made of, and the shapes of a compatible endpoint. */
15782
+ catalog() {
15783
+ return this.routes.json("GET", "/providers/catalog", vendorCatalogSchema);
15784
+ }
15785
+ /** Orders the entries, each once. */
15786
+ order(providerIds) {
15787
+ return this.routes.send("PUT", "/providers/order", { providerIds });
15788
+ }
15789
+ /** The entry `id` as Settings shows it: its models, accounts and state. */
15790
+ status(id) {
15791
+ return this.routes.json("GET", `/providers/${segment(id)}/status`, providerDetailsSchema);
15792
+ }
15793
+ /** The quota of the entry's subscription, its active account's or `credentialId`'s, read now. */
15794
+ async quota(id, options = {}) {
15795
+ return (await this.routes.json("POST", `/providers/${segment(id)}/quota`, quotaAnswerSchema, options)).quota;
15796
+ }
15797
+ /** Calls the entry's model, or `modelId`, once, with its active account or `credentialId`. */
15798
+ test(id, options = {}) {
15799
+ return this.routes.json("POST", `/providers/${segment(id)}/test`, testResultSchema, options);
15800
+ }
15801
+ /** The newest version of the command-line program the entry's subscription runs, read again with `refresh`. */
15802
+ async cli(id, options = {}) {
15803
+ return (await this.routes.json("GET", `/providers/${segment(id)}/cli${query({ refresh: options.refresh })}`, providerCliSchema)).newest;
15804
+ }
15805
+ /** Starts installing that program's newest version; the entry's status says when it is in place. */
15806
+ installCli(id) {
15807
+ return this.routes.send("POST", `/providers/${segment(id)}/cli/install`);
14997
15808
  }
14998
15809
  accounts(id) {
14999
- const path = `/providers/${encodeURIComponent(id)}/accounts`;
15810
+ const path = `/providers/${segment(id)}/accounts`;
15000
15811
  return {
15001
15812
  list: () => this.routes.json("GET", path, accountsSchema),
15002
15813
  activate: async (credentialId) => void await this.routes.json("PUT", `${path}/active`, activeAccountSchema, { credentialId }),
15003
15814
  order: (credentialIds) => this.routes.send("PUT", `${path}/order`, { credentialIds }),
15004
- remove: async (credentialId) => void await this.routes.json("DELETE", `${path}/${encodeURIComponent(credentialId)}`, removedAccountSchema),
15815
+ remove: async (credentialId) => void await this.routes.json("DELETE", `${path}/${segment(credentialId)}`, removedAccountSchema),
15005
15816
  signIn: async () => this.signInOf((await this.routes.json("POST", `${path}/login`, loginStartedSchema)).login.id)
15006
15817
  };
15007
15818
  }
@@ -15010,7 +15821,7 @@ var Providers = class {
15010
15821
  return this.signInOf((await this.routes.json("POST", "/providers/subscription-login", loginStartedSchema, login)).login.id);
15011
15822
  }
15012
15823
  signInOf(id) {
15013
- const path = `/providers/subscription-login/${encodeURIComponent(id)}`;
15824
+ const path = `/providers/subscription-login/${segment(id)}`;
15014
15825
  return {
15015
15826
  id,
15016
15827
  submitCode: async (code) => void await this.routes.json("POST", `${path}/code`, codeTakenSchema, { code }),
@@ -15044,7 +15855,7 @@ var Device = class {
15044
15855
  * channel ends before the device came online.
15045
15856
  */
15046
15857
  async connect(stream) {
15047
- const channel = await this.process.connect(this.routes.path(`/devices/${encodeURIComponent(this.id)}/runner`), "h2c");
15858
+ const channel = await this.process.connect(this.routes.path(`/devices/${segment(this.id)}/runner`), "h2c");
15048
15859
  stream.readable.pipe(channel);
15049
15860
  channel.pipe(stream.writable);
15050
15861
  const ended = new Promise((resolve) => {
@@ -15123,7 +15934,7 @@ var Device = class {
15123
15934
  ...where,
15124
15935
  ...limited ? { timeoutMs: Math.ceil(timeout) } : {}
15125
15936
  };
15126
- const ran = await this.routes.json("POST", `/devices/${encodeURIComponent(this.id)}/exec`, deviceExecResultSchema, body, signal);
15937
+ const ran = await this.routes.json("POST", `/devices/${segment(this.id)}/exec`, deviceExecResultSchema, body, signal);
15127
15938
  return {
15128
15939
  exitCode: ran.exitCode,
15129
15940
  ...ran.output
@@ -15138,7 +15949,23 @@ var Device = class {
15138
15949
  * or is a filesystem's root, such as a volume's mount point.
15139
15950
  */
15140
15951
  async revoke() {
15141
- await this.routes.send("DELETE", `/devices/${encodeURIComponent(this.id)}`);
15952
+ await this.routes.send("DELETE", `/devices/${segment(this.id)}`);
15953
+ }
15954
+ /** Renames the device, or changes how the core reaches it. */
15955
+ async update(patch) {
15956
+ return (await this.routes.json("PATCH", `/devices/${segment(this.id)}`, deviceAnswerSchema, patch)).device;
15957
+ }
15958
+ /** Asks the device's runner to run as an administrator, as the user allows on the device. */
15959
+ async elevate() {
15960
+ return (await this.routes.json("POST", `/devices/${segment(this.id)}/elevation`, deviceElevationSchema)).outcome;
15961
+ }
15962
+ /** The device's files, by absolute paths. */
15963
+ get files() {
15964
+ return deviceFiles(this.routes, this.id);
15965
+ }
15966
+ /** The workflows a new conversation working in the absolute `directory` on the device would offer. */
15967
+ workflows(directory) {
15968
+ return this.routes.json("GET", `/devices/${segment(this.id)}/workflows${query({ directory })}`, keptWorkflowListSchema);
15142
15969
  }
15143
15970
  };
15144
15971
  var Devices = class {
@@ -15154,6 +15981,10 @@ var Devices = class {
15154
15981
  this.dir = dir;
15155
15982
  this.online = online;
15156
15983
  }
15984
+ /** The core's devices, as the product state lists them; `of` gives the one a listing names. */
15985
+ async list() {
15986
+ return (await this.routes.json("GET", "/devices", devicesSchema)).devices;
15987
+ }
15157
15988
  /** Creates a device, which serves the core once a runner connects to it. */
15158
15989
  async create() {
15159
15990
  const { device } = await this.routes.json("POST", "/devices", deviceAnswerSchema);
@@ -15233,7 +16064,6 @@ var Process = class Process {
15233
16064
  ...process.env,
15234
16065
  JUSH_RELEASE: start.release.join(pathListSeparator())
15235
16066
  };
15236
- if (start.publicUrl !== void 0) env.JUSH_PUBLIC_URL = start.publicUrl;
15237
16067
  const child = spawn(start.executable, [], {
15238
16068
  stdio: [
15239
16069
  "pipe",
@@ -15251,7 +16081,10 @@ var Process = class Process {
15251
16081
  readable: child.stdout,
15252
16082
  writable: child.stdin
15253
16083
  });
15254
- const session = http2.connect("http://jush-core", { createConnection: () => stdio });
16084
+ const session = http2.connect("http://jush-core", {
16085
+ ...SESSION_OPTIONS,
16086
+ createConnection: () => stdio
16087
+ });
15255
16088
  exited.then(() => session.destroy());
15256
16089
  return {
15257
16090
  session,
@@ -15268,7 +16101,7 @@ var Process = class Process {
15268
16101
  static connect(address) {
15269
16102
  const url = new URL(address.url);
15270
16103
  const dial = () => {
15271
- const session = http2.connect(url);
16104
+ const session = http2.connect(url, SESSION_OPTIONS);
15272
16105
  return {
15273
16106
  session,
15274
16107
  settled: settled(session, new Promise(() => {}))
@@ -15326,29 +16159,30 @@ var Process = class Process {
15326
16159
  Object.assign(headers, this.credentials);
15327
16160
  const stream = session.request(headers, { endStream: request.body === null });
15328
16161
  stream.on("error", () => {});
16162
+ let broken;
15329
16163
  if (request.body !== null) {
15330
16164
  const body = Readable.fromWeb(request.body);
15331
16165
  body.pipe(stream);
15332
- stream.once("close", () => body.destroy());
16166
+ body.once("error", (error) => {
16167
+ broken = error;
16168
+ stream.close(http2.constants.NGHTTP2_CANCEL);
16169
+ });
16170
+ const stop = () => {
16171
+ body.unpipe(stream);
16172
+ body.destroy();
16173
+ };
16174
+ stream.once("aborted", stop);
16175
+ stream.once("close", stop);
15333
16176
  }
15334
16177
  const abort = () => stream.close(http2.constants.NGHTTP2_CANCEL);
15335
16178
  if (request.signal.aborted) abort();
15336
16179
  request.signal.addEventListener("abort", abort, { once: true });
15337
- const answer = await answered(stream).catch((error) => {
15338
- throw request.signal.aborted ? request.signal.reason : error;
16180
+ const bodied = (status) => request.method !== "HEAD" && status !== 204 && status !== 304;
16181
+ const response = await answered(stream, bodied).catch((error) => {
16182
+ throw request.signal.aborted ? request.signal.reason : broken ?? error;
15339
16183
  }).finally(() => request.signal.removeEventListener("abort", abort));
15340
- const status = Number(answer[":status"]);
15341
- const responseHeaders = new Headers();
15342
- for (const [name, value] of Object.entries(answer)) {
15343
- if (name.startsWith(":") || value === void 0) continue;
15344
- for (const each of Array.isArray(value) ? value : [value]) responseHeaders.append(name, String(each));
15345
- }
15346
- const empty = request.method === "HEAD" || status === 204 || status === 304;
15347
- if (empty) stream.resume();
15348
- return new Response(empty ? null : webBody(stream), {
15349
- status,
15350
- headers: responseHeaders
15351
- });
16184
+ if (response.body === null) stream.resume();
16185
+ return response;
15352
16186
  }
15353
16187
  /**
15354
16188
  * Opens `path` by an extended CONNECT of `protocol` (RFC 8441), such as
@@ -15366,19 +16200,8 @@ var Process = class Process {
15366
16200
  ":path": path
15367
16201
  });
15368
16202
  stream.on("error", () => {});
15369
- const body = [];
15370
- stream.once("response", (headers) => {
15371
- if (Number(headers[":status"]) !== 200) stream.on("data", (chunk) => body.push(chunk));
15372
- });
15373
- const answer = await answered(stream);
15374
- const status = Number(answer[":status"]);
15375
- if (status !== 200) {
15376
- if (!stream.readableEnded && !stream.closed) await new Promise((resolve) => {
15377
- stream.once("end", resolve);
15378
- stream.once("close", resolve);
15379
- });
15380
- throw await refusal(new Response(Buffer.concat(body), { status }), `CONNECT ${path}`);
15381
- }
16203
+ const response = await answered(stream, (status) => status !== 200);
16204
+ if (response.status !== 200) throw await refusal(response, `CONNECT ${path}`);
15382
16205
  this.lasting.add(stream);
15383
16206
  stream.once("close", () => this.lasting.delete(stream));
15384
16207
  return stream;
@@ -15407,14 +16230,44 @@ function settled(session, failed) {
15407
16230
  session.on("error", () => {});
15408
16231
  return settling;
15409
16232
  }
15410
- /** The headers `stream` is answered with; throws when it closes unanswered. */
15411
- function answered(stream) {
16233
+ /**
16234
+ * The options of a session to a process. Node counts the request bodies it
16235
+ * queued against the session's memory, 10 MB by default, and past it
16236
+ * refuses the streams and the answers that come: the answer to an upload of
16237
+ * more, when the process answers before it read it all, never comes, and a
16238
+ * request sent while one is queued fails. The process is the program's own,
16239
+ * which the cap does not guard against, so it is the largest the option's
16240
+ * 32 bits of megabytes hold; Bun has no such cap.
16241
+ */
16242
+ const SESSION_OPTIONS = { maxSessionMemory: 2 ** 32 - 1 };
16243
+ /**
16244
+ * The response `stream` brings, with a body when `bodied` says its status
16245
+ * has one, else with none and the stream left to the caller; throws when it
16246
+ * closes unanswered.
16247
+ *
16248
+ * The body is made as the headers come, not once they are awaited: Bun's
16249
+ * streams flow before anyone reads them, and when the process answers
16250
+ * before it read the whole request, as a refusal of a body over its limit
16251
+ * does, Bun emits the body, its end and the stream's close in the same
16252
+ * tick as the headers, so a body made a microtask later never hears them
16253
+ * and its reader waits forever.
16254
+ */
16255
+ function answered(stream, bodied) {
15412
16256
  return new Promise((resolve, reject) => {
15413
16257
  const closed = () => reject(/* @__PURE__ */ new Error(`The process closed the stream unanswered (${stream.rstCode ?? "no code"})`));
15414
16258
  stream.once("close", closed);
15415
- stream.once("response", (headers) => {
16259
+ stream.once("response", (answer) => {
15416
16260
  stream.off("close", closed);
15417
- resolve(headers);
16261
+ const status = Number(answer[":status"]);
16262
+ const headers = new Headers();
16263
+ for (const [name, value] of Object.entries(answer)) {
16264
+ if (name.startsWith(":") || value === void 0) continue;
16265
+ for (const each of Array.isArray(value) ? value : [value]) headers.append(name, String(each));
16266
+ }
16267
+ resolve(new Response(bodied(status) ? webBody(stream) : null, {
16268
+ status,
16269
+ headers
16270
+ }));
15418
16271
  });
15419
16272
  });
15420
16273
  }
@@ -15423,12 +16276,15 @@ function answered(stream) {
15423
16276
  * cancels it once cancelled. Node's `Readable.toWeb` is not used: it throws
15424
16277
  * from its listener when data comes after the reader cancelled, which
15425
16278
  * crashes the program.
16279
+ *
16280
+ * The stream flows until the queue holds what the stream itself buffers:
16281
+ * Bun emits no end for a stream paused as it ends and reset right after,
16282
+ * as one answered before it read the whole request is.
15426
16283
  */
15427
16284
  function webBody(stream) {
15428
16285
  let settled = false;
15429
16286
  return new ReadableStream({
15430
16287
  start(controller) {
15431
- stream.pause();
15432
16288
  stream.on("data", (chunk) => {
15433
16289
  if (settled) return;
15434
16290
  controller.enqueue(new Uint8Array(chunk.buffer, chunk.byteOffset, chunk.byteLength));
@@ -15454,7 +16310,7 @@ function webBody(stream) {
15454
16310
  settled = true;
15455
16311
  stream.close(http2.constants.NGHTTP2_CANCEL);
15456
16312
  }
15457
- });
16313
+ }, new ByteLengthQueuingStrategy({ highWaterMark: stream.readableHighWaterMark }));
15458
16314
  }
15459
16315
  /** What separates the paths of a list, as `PATH` writes them. */
15460
16316
  function pathListSeparator() {
@@ -15464,47 +16320,65 @@ function pathListSeparator() {
15464
16320
  //#region src/jush.ts
15465
16321
  /**
15466
16322
  * A program's Jush: the process its cores run in, which `Jush.start` starts
15467
- * or `Jush.connect` connects to, with the program's plugins, and the cores
15468
- * it opens.
16323
+ * or `Jush.connect` connects to, with the program's plugins and addresses,
16324
+ * the cores it opens, and the calls from outside that the program's server
16325
+ * takes at its addresses and hands on.
15469
16326
  */
15470
16327
  var Jush = class Jush {
15471
16328
  process;
15472
- plugins;
16329
+ declared;
16330
+ addresses;
15473
16331
  runner;
15474
16332
  owned;
16333
+ /** A schedule's URL, as the program's server takes its calls. */
16334
+ schedules;
16335
+ /** The plugins' sign-ins, as the program's server takes their returns. */
16336
+ plugins;
15475
16337
  cores = /* @__PURE__ */ new Map();
15476
- constructor(process, plugins, runner, owned) {
16338
+ constructor(process, declared, addresses, runner, owned) {
15477
16339
  this.process = process;
15478
- this.plugins = plugins;
16340
+ this.declared = declared;
16341
+ this.addresses = addresses;
15479
16342
  this.runner = runner;
15480
16343
  this.owned = owned;
16344
+ this.schedules = { call: (id, request) => this.callSchedule(id, request) };
16345
+ this.plugins = { completeSignIn: (signIn) => this.completeSignIn(signIn) };
15481
16346
  }
15482
- /** Starts a process of the program's own, with the program's plugins. */
16347
+ /** Starts a process of the program's own, with the program's plugins and addresses. */
15483
16348
  static async start(options = {}) {
15484
16349
  const found = binaries();
15485
16350
  const process = Process.start({
15486
16351
  executable: found.core,
15487
- release: found.release,
15488
- ...options.publicUrl === void 0 ? {} : { publicUrl: options.publicUrl }
16352
+ release: found.release
15489
16353
  });
15490
- const jush = new Jush(process, options.plugins ?? [], () => found.runner, true);
15491
- await process.greet((fetch) => jush.greet(fetch));
15492
- return jush;
16354
+ return Jush.greeted(new Jush(process, options.plugins ?? [], options.addresses, () => found.runner, true));
15493
16355
  }
15494
16356
  /**
15495
16357
  * Connects to a process that runs on its own, and declares the program's
15496
- * plugins: the cores it holds, their conversations and their turns went
15497
- * on while the program was away. A connection made again, as after the
15498
- * process restarted, declares them again and opens the program's cores
15499
- * again before anything else.
16358
+ * addresses and plugins: the cores it holds, their conversations and
16359
+ * their turns went on while the program was away. A connection made
16360
+ * again, as after the process restarted, declares them again and opens
16361
+ * the program's cores again before anything else.
15500
16362
  */
15501
16363
  static async connect(connection) {
15502
16364
  const process = Process.connect({
15503
16365
  url: connection.url,
15504
16366
  token: connection.token
15505
16367
  });
15506
- const jush = new Jush(process, connection.plugins ?? [], () => binaries().runner, false);
15507
- await process.greet((fetch) => jush.greet(fetch));
16368
+ return Jush.greeted(new Jush(process, connection.plugins ?? [], connection.addresses, () => binaries().runner, false));
16369
+ }
16370
+ /**
16371
+ * `jush` once it greeted its process; a greeting the process refused,
16372
+ * such as an address that is no template, ends the process the program
16373
+ * started, or the connection to one on its own.
16374
+ */
16375
+ static async greeted(jush) {
16376
+ try {
16377
+ await jush.process.greet((fetch) => jush.greet(fetch));
16378
+ } catch (error) {
16379
+ await jush.process.close();
16380
+ throw error;
16381
+ }
15508
16382
  return jush;
15509
16383
  }
15510
16384
  /**
@@ -15523,25 +16397,17 @@ var Jush = class Jush {
15523
16397
  process: this.process,
15524
16398
  id,
15525
16399
  dir: path,
15526
- plugins: this.plugins,
16400
+ plugins: this.declared,
15527
16401
  runner: this.runner
15528
16402
  }, async () => {
15529
16403
  this.cores.delete(id);
15530
- await (await this.call("DELETE", `/cores/${encodeURIComponent(id)}`)).body?.cancel();
16404
+ await (await this.call("DELETE", `/cores/${segment(id)}`)).body?.cancel();
15531
16405
  });
15532
16406
  this.cores.set(id, core);
15533
16407
  await core.follow();
15534
16408
  return core;
15535
16409
  }
15536
16410
  /**
15537
- * Answers a call of a schedule's URL, `/hooks/{id}` below `base`, as the
15538
- * program's server forwards it.
15539
- */
15540
- fetch(request, base = "") {
15541
- const url = new URL(request.url);
15542
- return this.process.fetch(new Request(PROCESS_ORIGIN + below(url.pathname, base) + url.search, request));
15543
- }
15544
- /**
15545
16411
  * Ends the program's use of Jush: a process the program started closes
15546
16412
  * every core and exits; one on its own keeps its cores, which the
15547
16413
  * program's next run opens again.
@@ -15554,12 +16420,43 @@ var Jush = class Jush {
15554
16420
  await this.process.close();
15555
16421
  }
15556
16422
  /**
16423
+ * The call `request` as one HTTP message (`message/http`, RFC 9112
16424
+ * § 10.1): its head, then its body's bytes as they arrive, which a
16425
+ * signature over them verifies.
16426
+ */
16427
+ async callSchedule(id, request) {
16428
+ const url = new URL(request.url);
16429
+ const lines = [`${request.method} ${url.pathname}${url.search} HTTP/1.1`];
16430
+ request.headers.forEach((value, name) => lines.push(`${name}: ${value}`));
16431
+ const head = Buffer.from(`${lines.join("\r\n")}\r\n\r\n`, "latin1");
16432
+ const path = `/schedules/calls?${new URLSearchParams({ id })}`;
16433
+ const sent = {
16434
+ method: "POST",
16435
+ body: request.body === null ? head : headed(head, request.body),
16436
+ headers: { "content-type": "message/http" },
16437
+ duplex: "half"
16438
+ };
16439
+ const response = await this.process.fetch(new Request(PROCESS_ORIGIN + path, sent));
16440
+ if (!response.ok) throw await refusal(response, `POST ${path}`);
16441
+ return scheduleCallAnswerSchema.parse(await response.json());
16442
+ }
16443
+ async completeSignIn(signIn) {
16444
+ const query = new URLSearchParams(signIn.query).toString();
16445
+ const response = await this.call("POST", "/sign-ins", {
16446
+ core: signIn.core,
16447
+ plugin: signIn.plugin,
16448
+ query
16449
+ });
16450
+ return signInAnswerSchema.parse(await response.json());
16451
+ }
16452
+ /**
15557
16453
  * What each connection to the process begins with: the program's
15558
- * plugins, then its cores, which a process that restarted holds no
15559
- * longer.
16454
+ * addresses and plugins, then its cores, which a process that
16455
+ * restarted holds no longer.
15560
16456
  */
15561
16457
  async greet(fetch) {
15562
- for (const plugin of this.plugins) await (await this.call("PUT", `/plugins/${encodeURIComponent(plugin.manifest.id)}`, plugin.manifest, fetch)).body?.cancel();
16458
+ if (this.addresses !== void 0) await (await this.call("PUT", "/addresses", this.addresses, fetch)).body?.cancel();
16459
+ for (const plugin of this.declared) await (await this.call("PUT", `/plugins/${segment(plugin.manifest.id)}`, plugin.manifest, fetch)).body?.cancel();
15563
16460
  for (const core of this.cores.values()) await (await this.call("POST", "/cores", { dir: core.dir }, fetch)).body?.cancel();
15564
16461
  }
15565
16462
  async call(method, path, body, fetch = (request) => this.process.fetch(request)) {
@@ -15574,5 +16471,26 @@ var Jush = class Jush {
15574
16471
  return response;
15575
16472
  }
15576
16473
  };
16474
+ /**
16475
+ * `head`, then `body`'s bytes as they arrive; cancelling it, as the process
16476
+ * does once it answered, cancels `body`.
16477
+ */
16478
+ function headed(head, body) {
16479
+ const reader = body.getReader();
16480
+ let sent = false;
16481
+ return new ReadableStream({
16482
+ async pull(controller) {
16483
+ if (!sent) {
16484
+ sent = true;
16485
+ controller.enqueue(head);
16486
+ return;
16487
+ }
16488
+ const read = await reader.read();
16489
+ if (read.done) controller.close();
16490
+ else controller.enqueue(read.value);
16491
+ },
16492
+ cancel: (reason) => reader.cancel(reason)
16493
+ });
16494
+ }
15577
16495
  //#endregion
15578
- export { Conversation, Conversations, Core, Device, Devices, Jush, JushError, PortFailure, Providers, definePlugin, leaf };
16496
+ export { Conversation, ConversationPage, Conversations, Core, Device, Devices, Jush, JushError, PortFailure, Providers, definePlugin, leaf };