@jush-agent/sdk 0.2.6332 → 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"),
@@ -1504,7 +1529,10 @@ const blockSchema = z.discriminatedUnion("type", [
1504
1529
  request: z.string().min(1).optional(),
1505
1530
  model: modelSelectionSchema,
1506
1531
  placement: wakeupPlacementSchema,
1507
- /** 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
+ */
1508
1536
  reports: z.array(commandReportSchema),
1509
1537
  /**
1510
1538
  * The run of steps the block belongs to: the id of the run's first
@@ -1531,7 +1559,9 @@ const blockSchema = z.discriminatedUnion("type", [
1531
1559
  * The comments sent with it, which the model reads before its content
1532
1560
  * as a message's; omitted when there are none.
1533
1561
  */
1534
- 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()
1535
1565
  }),
1536
1566
  z.object({
1537
1567
  type: z.literal("agent_message"),
@@ -1548,6 +1578,11 @@ const blockSchema = z.discriminatedUnion("type", [
1548
1578
  model: modelSelectionSchema,
1549
1579
  message: agentMessageSchema,
1550
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
+ /**
1551
1586
  * The run of steps the block belongs to: the id of the run's first
1552
1587
  * block, which the backend sets as it stores the block and never
1553
1588
  * changes.
@@ -2267,7 +2302,14 @@ z.discriminatedUnion("type", [
2267
2302
  * The comments the message carries, which may make it without content;
2268
2303
  * omitted when there are none.
2269
2304
  */
2270
- 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()
2271
2313
  }),
2272
2314
  z.strictObject({
2273
2315
  type: z.literal("edit_and_send"),
@@ -2291,7 +2333,9 @@ z.discriminatedUnion("type", [
2291
2333
  * The comments the steer carries, as a message's; omitted when
2292
2334
  * there are none.
2293
2335
  */
2294
- 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()
2295
2339
  }),
2296
2340
  z.strictObject({
2297
2341
  type: z.literal("send_saved"),
@@ -3091,7 +3135,13 @@ const jobCallerSchema = z.object({
3091
3135
  * (`crates/core-store/src/usage.rs`); none for a job recorded before
3092
3136
  * records kept it.
3093
3137
  */
3094
- 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()
3095
3145
  });
3096
3146
  /** The ids of a call's relayed pipes. */
3097
3147
  const relayedPipesSchema = z.object({
@@ -5409,7 +5459,12 @@ z.strictObject({
5409
5459
  /** The picture asked of, for a side question about a picture. */
5410
5460
  picture: mediaSourceSchema.nullable().optional(),
5411
5461
  /** What is asked, a message's content, as a frame names it. */
5412
- 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()
5413
5468
  });
5414
5469
  /** `AuthenticatorAssertionResponseJSON`. */
5415
5470
  const assertionResponseJsonSchema = z.strictObject({
@@ -5895,8 +5950,8 @@ const patchFieldSchema = z.enum([
5895
5950
  "service_tier_id",
5896
5951
  "workflow",
5897
5952
  "browser_profile",
5898
- "identity",
5899
- "plugins",
5953
+ "system_prompt",
5954
+ "commands",
5900
5955
  "target"
5901
5956
  ]);
5902
5957
  /**
@@ -5928,7 +5983,8 @@ const batchResultSchema = z.discriminatedUnion("status", [z.object({
5928
5983
  code: errorCodeSchema,
5929
5984
  message: z.string()
5930
5985
  })]);
5931
- 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) });
5932
5988
  /** A provider entry of the user's scope and one of its models. */
5933
5989
  const modelChoiceSchema = z.strictObject({
5934
5990
  providerId: z.string().min(1),
@@ -5968,15 +6024,15 @@ const conversationPatchSchema = z.strictObject({
5968
6024
  */
5969
6025
  browserProfile: z.string().regex(/* @__PURE__ */ new RegExp("^[a-z0-9_-]{1,64}$", "u")).nullable().optional(),
5970
6026
  /**
5971
- * The sentences that open its agents' system prompts in place of
5972
- * 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.
5973
6029
  */
5974
- identity: z.string().nullable().optional(),
6030
+ systemPrompt: z.string().nullable().optional(),
5975
6031
  /**
5976
- * The program's plugins its agents have, by id, from each agent's next
5977
- * 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.
5978
6034
  */
5979
- plugins: z.array(z.string()).nullable().optional(),
6035
+ commands: z.array(z.string()).nullable().optional(),
5980
6036
  /** A switch of the conversation's execution target. */
5981
6037
  target: conversationTargetSchema.optional()
5982
6038
  });
@@ -6144,7 +6200,12 @@ z.strictObject({
6144
6200
  lastModel: modelSettingsSchema.optional(),
6145
6201
  lastWorkflow: workflowChoiceSchema.optional()
6146
6202
  });
6147
- 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({
6148
6209
  original: z.string(),
6149
6210
  modified: z.string()
6150
6211
  });
@@ -6505,13 +6566,6 @@ const cloudStorageSchema = z.object({
6505
6566
  * counting from one, which `codesTaken` and a refusal of it then name.
6506
6567
  */
6507
6568
  const codeTakenSchema = z.object({ code: z.int().min(0).max(4294967295) });
6508
- z.object({
6509
- commandId: z.string().min(1),
6510
- /** The agent that ran it. */
6511
- node: z.string().min(1),
6512
- /** The call's block in that agent's transcript. */
6513
- blockId: z.string().min(1)
6514
- });
6515
6569
  /**
6516
6570
  * How a command ended, as the conversation's record of its output keeps
6517
6571
  * it (`crates/core-store/src/command_outputs.rs`).
@@ -6528,6 +6582,17 @@ const commandEndSchema = z.discriminatedUnion("kind", [
6528
6582
  }),
6529
6583
  z.object({ kind: z.literal("unrecorded") })
6530
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
+ });
6531
6596
  /** A compaction marker of a page and its boundary's summary size. */
6532
6597
  const compactionSummarySchema = z.object({
6533
6598
  marker: z.string().min(1),
@@ -6540,6 +6605,13 @@ const compactionSummarySchema = z.object({
6540
6605
  * that vendor's entry with the gateway's endpoint.
6541
6606
  */
6542
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
+ });
6543
6615
  /**
6544
6616
  * What a configured model makes (`crates/core/src/provider_settings.rs`):
6545
6617
  * text, the model menu's, unless its user added it as an audio model of a
@@ -6834,10 +6906,16 @@ const conversationMetadataSchema = z.object({
6834
6906
  workflow: workflowChoiceSchema,
6835
6907
  /** The browser profile it names; null for a profile of its own. */
6836
6908
  browserProfile: z.string().regex(/* @__PURE__ */ new RegExp("^[a-z0-9_-]{1,64}$", "u")).nullable(),
6837
- /** The sentences that open its agents' system prompts; null for Jush's. */
6838
- identity: z.string().nullable(),
6839
- /** The program's plugins its agents have, by id; null for all of them. */
6840
- 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(),
6841
6919
  /**
6842
6920
  * The directory the conversation's work runs in, resolved by the backend
6843
6921
  * for every kind of target, so the web app never derives it.
@@ -7251,7 +7329,11 @@ z.discriminatedUnion("type", [
7251
7329
  keys: z.array(z.string()).max(4096)
7252
7330
  })
7253
7331
  ]);
7254
- 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) });
7255
7337
  /**
7256
7338
  * Who configures providers: each user their own, or the master for every
7257
7339
  * user, which the master changes in Settings › Users.
@@ -8062,7 +8144,14 @@ const sendMessageSchema = z.strictObject({
8062
8144
  * The comments the message carries, which may make it without content;
8063
8145
  * omitted when there are none.
8064
8146
  */
8065
- 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()
8066
8155
  });
8067
8156
  z.strictObject({
8068
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")),
@@ -8092,16 +8181,15 @@ z.strictObject({
8092
8181
  */
8093
8182
  browserProfile: z.string().regex(/* @__PURE__ */ new RegExp("^[a-z0-9_-]{1,64}$", "u")).optional(),
8094
8183
  /**
8095
- * The sentences that open its agents' system prompts in place of
8096
- * Jush's, such as "You are the help desk's assistant."; Jush's when
8097
- * 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.
8098
8186
  */
8099
- identity: z.string().optional(),
8187
+ systemPrompt: z.string().optional(),
8100
8188
  /**
8101
- * The program's plugins its agents have, by id; all of them when
8102
- * absent.
8189
+ * The commands its agents have, by path without `jush`, such as
8190
+ * `browser` or `conversation history`; every command when absent.
8103
8191
  */
8104
- plugins: z.array(z.string()).optional(),
8192
+ commands: z.array(z.string()).optional(),
8105
8193
  /**
8106
8194
  * The message the conversation starts with, as the socket's `send`
8107
8195
  * frame carries it.
@@ -8202,7 +8290,8 @@ const createdConversationSchema = z.object({
8202
8290
  /** Absent when the request carried no first message. */
8203
8291
  firstMessage: firstMessageAnswerSchema.optional()
8204
8292
  });
8205
- z.object({ path: z.string() });
8293
+ /** `{ path }`: the directory a create made. */
8294
+ const createdDirectorySchema = z.object({ path: z.string() });
8206
8295
  /** An account's role. A role administers only the roles below it. */
8207
8296
  const roleSchema = z.enum([
8208
8297
  "admin",
@@ -8338,8 +8427,13 @@ const credentialDtoSchema = z.object({
8338
8427
  createdAt: z.iso.datetime({ precision: 3 }),
8339
8428
  updatedAt: z.iso.datetime({ precision: 3 })
8340
8429
  });
8341
- z.object({ credential: credentialDtoSchema });
8342
- 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) });
8343
8437
  z.strictObject({
8344
8438
  /** A credential's name: trimmed, then at least one character. */
8345
8439
  name: z.string().trim().min(1).optional(),
@@ -8442,7 +8536,13 @@ const deviceAnswerSchema = z.object({ device: deviceDtoSchema });
8442
8536
  * elevated, and a No leaves it as it was.
8443
8537
  */
8444
8538
  const elevationOutcomeSchema = z.enum(["shown", "unavailable"]);
8445
- 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 });
8446
8546
  z.strictObject({
8447
8547
  script: z.string(),
8448
8548
  /**
@@ -8496,7 +8596,8 @@ const deviceStorageSchema = z.object({
8496
8596
  /** Null before its runner first measured. */
8497
8597
  report: deviceStorageReportSchema.nullable()
8498
8598
  });
8499
- 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) });
8500
8601
  /**
8501
8602
  * Which of the page's two peers with a device a signaling message is about
8502
8603
  * (`crates/runner-direct/src/lib.rs`): the one for files and calls,
@@ -8587,7 +8688,11 @@ const directoryEntrySchema = z.object({
8587
8688
  modifiedAt: z.iso.datetime({ precision: 3 }),
8588
8689
  link: symbolicLinkSchema.nullable().optional()
8589
8690
  });
8590
- 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({
8591
8696
  path: z.string(),
8592
8697
  home: z.string().nullable(),
8593
8698
  entries: z.array(directoryEntrySchema)
@@ -8675,7 +8780,11 @@ z.strictObject({
8675
8780
  password: z.string().min(1)
8676
8781
  });
8677
8782
  z.object({ challenge: emailChallengeDtoSchema });
8678
- 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({
8679
8788
  /**
8680
8789
  * The script its call ran; empty when the conversation holds no call
8681
8790
  * of it.
@@ -8691,7 +8800,8 @@ z.object({
8691
8800
  /** Why its output was not stored; null when it was. */
8692
8801
  notStored: z.string().nullable()
8693
8802
  });
8694
- z.object({
8803
+ /** `GET .../fs/file`: a file's text. */
8804
+ const fileTextSchema = z.object({
8695
8805
  path: z.string(),
8696
8806
  text: z.string()
8697
8807
  });
@@ -8747,13 +8857,26 @@ z.discriminatedUnion("type", [
8747
8857
  keys: z.array(z.string()).max(4096)
8748
8858
  })
8749
8859
  ]);
8750
- 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({
8751
8865
  conversation: conversationSummarySchema,
8752
8866
  metadata: conversationMetadataSchema
8753
8867
  });
8754
8868
  z.strictObject({
8755
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")),
8756
- 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()
8757
8880
  });
8758
8881
  const forwardAddressSchema = z.string().min(3).max(260);
8759
8882
  /** A side of a pair, as the direct channel names a page's and a device's. */
@@ -8820,7 +8943,12 @@ z.object({
8820
8943
  draft: conversationDraftSchema,
8821
8944
  revisions: revisionsSchema
8822
8945
  });
8823
- 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({
8824
8952
  branches: z.array(z.string()),
8825
8953
  /** Null while HEAD is detached. */
8826
8954
  current: z.string().nullable(),
@@ -8863,7 +8991,12 @@ const gitCommitFileSchema = z.object({
8863
8991
  added: z.int().min(0),
8864
8992
  removed: z.int().min(0)
8865
8993
  });
8866
- 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({
8867
9000
  commit: gitCommitEntrySchema,
8868
9001
  files: z.array(gitCommitFileSchema),
8869
9002
  truncated: z.boolean(),
@@ -8879,11 +9012,16 @@ const gitLogEntrySchema = z.object({
8879
9012
  author: z.string(),
8880
9013
  time: z.iso.datetime({ precision: 3 })
8881
9014
  });
8882
- 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({
8883
9020
  commits: z.array(gitLogEntrySchema),
8884
9021
  more: z.boolean()
8885
9022
  });
8886
- z.object({
9023
+ /** The repositories around a directory (`crates/runner-device/src/repositories.rs`). */
9024
+ const gitRepositoriesSchema = z.object({
8887
9025
  /** Whether the directory lies in a repository, at it or above it. */
8888
9026
  inRepository: z.boolean(),
8889
9027
  /**
@@ -8946,7 +9084,11 @@ const userUsageSchema = z.object({
8946
9084
  totals: z.array(usageGroupSchema)
8947
9085
  });
8948
9086
  z.object({ users: z.array(userUsageSchema) });
8949
- 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() });
8950
9092
  z.strictObject({ text: z.string() });
8951
9093
  z.object({
8952
9094
  ok: z.boolean(),
@@ -8973,7 +9115,8 @@ const listedDirectorySchema = z.discriminatedUnion("type", [z.object({
8973
9115
  status: z.int().min(0).max(65535),
8974
9116
  error: errorBodySchema
8975
9117
  })]);
8976
- 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) });
8977
9120
  /** An account as an administrator's list shows it. */
8978
9121
  const listedUserSchema = z.object({
8979
9122
  id: z.string().min(1),
@@ -9039,7 +9182,12 @@ const messageResultSchema = z.object({
9039
9182
  text: z.string(),
9040
9183
  ranges: z.array(z.array(z.int().min(0).max(4294967295)).min(2).max(2))
9041
9184
  });
9042
- 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({
9043
9191
  messages: z.array(messageResultSchema),
9044
9192
  /** More messages hold the words than the answer lists. */
9045
9193
  limited: z.boolean()
@@ -9078,7 +9226,11 @@ const modelMatchSchema = z.object({
9078
9226
  /** The release date as models.dev states it, such as `2026-06-17`. */
9079
9227
  releaseDate: z.string().nullable()
9080
9228
  });
9081
- 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) });
9082
9234
  /** A plugin's reply block a reply names, by its tag and its ID. */
9083
9235
  const namedReplyBlockSchema = z.strictObject({
9084
9236
  tag: z.string().min(1).max(64),
@@ -9193,6 +9345,42 @@ z.object({ ok: z.boolean() });
9193
9345
  * `/cores/{id}/api`.
9194
9346
  */
9195
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
+ });
9196
9384
  /** The level of a line the page wrote. */
9197
9385
  const pageLogLevelSchema = z.enum([
9198
9386
  "debug",
@@ -9301,7 +9489,12 @@ z.strictObject({
9301
9489
  current: z.string().nullable().optional(),
9302
9490
  next: z.string().min(8)
9303
9491
  });
9304
- 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({
9305
9498
  revision: z.int().min(0),
9306
9499
  state: z.json()
9307
9500
  });
@@ -9323,8 +9516,10 @@ const portForwardDtoSchema = z.object({
9323
9516
  state: forwardRunStateSchema.nullable(),
9324
9517
  createdAt: z.iso.datetime({ precision: 3 })
9325
9518
  });
9326
- z.object({ forward: portForwardDtoSchema });
9327
- 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) });
9328
9523
  z.strictObject({
9329
9524
  listenDevice: z.string().min(1).optional(),
9330
9525
  listenPort: z.int().min(1).max(65535).optional(),
@@ -9720,7 +9915,8 @@ const subagentProfileSchema = z.object({
9720
9915
  /** Whether agents may use the profile. */
9721
9916
  enabled: z.boolean()
9722
9917
  });
9723
- z.object({ profile: subagentProfileSchema });
9918
+ /** `{ profile }`: the answer of a create and of a patch. */
9919
+ const profileAnswerSchema = z.object({ profile: subagentProfileSchema });
9724
9920
  z.strictObject({
9725
9921
  name: z.string().optional(),
9726
9922
  description: z.string().optional(),
@@ -9730,8 +9926,23 @@ z.strictObject({
9730
9926
  canSpawn: z.boolean().optional(),
9731
9927
  enabled: z.boolean().optional()
9732
9928
  });
9733
- z.object({ project: projectDtoSchema });
9734
- 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) });
9735
9946
  /**
9736
9947
  * An entry as the web app sees it: its family, label, kind, endpoint, vendor
9737
9948
  * and model list, never its key.
@@ -9812,7 +10023,13 @@ const providerDtoSchema = z.object({
9812
10023
  });
9813
10024
  /** `{ provider }`: the answer of a create and an edit. */
9814
10025
  const providerAnswerSchema = z.object({ provider: providerDtoSchema });
9815
- 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 });
9816
10033
  z.strictObject({ providerIds: z.array(z.string().min(1)) });
9817
10034
  /**
9818
10035
  * A change of an entry's search switches; each only for a search its
@@ -9951,7 +10168,11 @@ z.strictObject({
9951
10168
  */
9952
10169
  quietWhileElsewhere: z.boolean()
9953
10170
  });
9954
- 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() });
9955
10176
  z.strictObject({ credentialId: z.string().min(1).optional() });
9956
10177
  z.object({
9957
10178
  ok: z.boolean(),
@@ -9976,7 +10197,12 @@ const recentAgentSchema = z.object({
9976
10197
  */
9977
10198
  rate: z.number().nullable()
9978
10199
  });
9979
- 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({
9980
10206
  /**
9981
10207
  * Each agent that made a call in the window, and the rows of no agent, such
9982
10208
  * as a title's, when there are some: the rows of no agent first, then the
@@ -10030,7 +10256,11 @@ const restartStepSchema = z.object({
10030
10256
  */
10031
10257
  kept: z.boolean().optional()
10032
10258
  });
10033
- 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() });
10034
10264
  z.object({ removed: z.array(z.string().min(1)) });
10035
10265
  /** What fired a run. */
10036
10266
  const runCauseSchema = z.enum([
@@ -10130,6 +10360,21 @@ const scheduleAnswerSchema = z.object({
10130
10360
  schedule: scheduleDtoSchema,
10131
10361
  secret: z.string().nullable()
10132
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
+ })]);
10133
10378
  z.strictObject({
10134
10379
  name: z.string().trim().optional(),
10135
10380
  trigger: triggerSchema.optional(),
@@ -10145,7 +10390,8 @@ z.strictObject({
10145
10390
  * newest first, [`RUNS_SHOWN`] at most.
10146
10391
  */
10147
10392
  const scheduleRunsSchema = z.object({ runs: z.array(scheduleRunDtoSchema) });
10148
- z.discriminatedUnion("type", [z.object({
10393
+ /** One line of a search's output. */
10394
+ const searchLineSchema = z.discriminatedUnion("type", [z.object({
10149
10395
  type: z.literal("file"),
10150
10396
  /** Relative to the directory searched, with `/` between its parts. */
10151
10397
  path: z.string(),
@@ -10197,7 +10443,11 @@ const searchResultSchema = z.object({
10197
10443
  /** The message that matched; null when only the title does. */
10198
10444
  match: searchMatchSchema.nullable()
10199
10445
  });
10200
- 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) });
10201
10451
  /**
10202
10452
  * What the server keeps. An administrator sees all of it and the log's
10203
10453
  * rules; anyone else sees only their own conversations and attachments,
@@ -10359,10 +10609,17 @@ z.object({
10359
10609
  /** The reply blocks its texts name. */
10360
10610
  replyBlocks: z.array(replyBlockFactsSchema).optional()
10361
10611
  });
10362
- z.strictObject({
10363
- /** A message's content, as a frame names it. */
10364
- content: z.array(clientContentSchema) });
10365
- 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({
10366
10623
  id: z.string().min(1),
10367
10624
  sideQuestion: sideQuestionSchema
10368
10625
  });
@@ -10376,6 +10633,21 @@ z.discriminatedUnion("kind", [z.strictObject({
10376
10633
  id: z.string().min(1),
10377
10634
  beforeId: z.string().min(1).nullable()
10378
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
+ })]);
10379
10651
  z.object({
10380
10652
  challengeId: z.string().min(1),
10381
10653
  options: requestOptionsJsonSchema
@@ -10452,7 +10724,12 @@ z.strictObject({
10452
10724
  * when none.
10453
10725
  */
10454
10726
  id: z.string().min(1).nullable().optional(),
10455
- 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()
10456
10733
  });
10457
10734
  /**
10458
10735
  * What a message to a subagent answers: its id, the one it named or the one
@@ -10689,7 +10966,11 @@ z.strictObject({
10689
10966
  modelId: z.string().optional(),
10690
10967
  credentialId: z.string().min(1).optional()
10691
10968
  });
10692
- 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({
10693
10974
  type: z.literal("passed"),
10694
10975
  model: z.string()
10695
10976
  }), z.object({
@@ -10774,7 +11055,66 @@ const turnStateSchema = z.discriminatedUnion("state", [
10774
11055
  outcome: turnOutcomeSchema
10775
11056
  })
10776
11057
  ]);
10777
- 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) });
10778
11118
  z.strictObject({
10779
11119
  role: newRoleSchema.nullable().optional(),
10780
11120
  disabled: z.boolean().nullable().optional(),
@@ -10805,7 +11145,12 @@ const vendorSchema = z.object({
10805
11145
  baseUrl: z.string().nullable(),
10806
11146
  doc: z.string().nullable()
10807
11147
  });
10808
- 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({
10809
11154
  /** Each subscription family. */
10810
11155
  subscriptions: z.array(subscriptionFamilySchema),
10811
11156
  /** The models.dev vendors a family speaks to, by name. */
@@ -10818,7 +11163,8 @@ z.object({
10818
11163
  ok: z.boolean(),
10819
11164
  id: z.int().min(0).max(4294967295)
10820
11165
  });
10821
- z.object({
11166
+ /** `GET /conversations/:id/agents/:node/blocks/:blockId`: a block whole. */
11167
+ const wholeBlockSchema = z.object({
10822
11168
  block: blockSchema,
10823
11169
  failures: z.record(z.string(), providerFailureFactsSchema).optional()
10824
11170
  });
@@ -10857,7 +11203,11 @@ const workChangeSchema = z.discriminatedUnion("op", [
10857
11203
  ]);
10858
11204
  z.strictObject({ changes: z.array(workChangeSchema).min(1) });
10859
11205
  z.object({ count: z.int().min(0).max(4294967295) });
10860
- 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({
10861
11211
  root: z.string(),
10862
11212
  repository: z.boolean(),
10863
11213
  /**
@@ -10872,13 +11222,15 @@ z.object({
10872
11222
  truncated: z.boolean(),
10873
11223
  watched: z.boolean()
10874
11224
  });
10875
- z.object({ workspace: workspaceDtoSchema });
11225
+ /** `{ workspace }`: the answer of a creation and a change. */
11226
+ const workspaceAnswerSchema = z.object({ workspace: workspaceDtoSchema });
10876
11227
  z.strictObject({
10877
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(),
10878
11229
  projects: z.array(z.string().min(1)).optional()
10879
11230
  });
10880
11231
  z.strictObject({ ids: z.array(z.string().min(1)).min(1) });
10881
- 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) });
10882
11234
  z.strictObject({ end: z.boolean() });
10883
11235
  //#endregion
10884
11236
  //#region ../protocol/src/product-state.ts
@@ -11555,13 +11907,14 @@ var ConversationClient = class {
11555
11907
  * the transcript or the queue. The wait has no deadline of its own: the
11556
11908
  * backend decides that a delivery failed, and says why.
11557
11909
  */
11558
- submit(content, messageId = createId(), comments = []) {
11910
+ submit(content, messageId = createId(), comments = [], senderId) {
11559
11911
  let at;
11560
11912
  return this.request({
11561
11913
  type: "send",
11562
11914
  messageId,
11563
11915
  content,
11564
- ...comments.length > 0 ? { comments: [...comments] } : {}
11916
+ ...comments.length > 0 ? { comments: [...comments] } : {},
11917
+ ...senderId === void 0 ? {} : { senderId }
11565
11918
  }, (event) => {
11566
11919
  if (event.type === "send_result" && event.messageId === messageId) at = event.at;
11567
11920
  if (at !== void 0 && this.holdsVersion(at)) return { resolve: void 0 };
@@ -11677,13 +12030,14 @@ var ConversationClient = class {
11677
12030
  * version the answer names, which shows the steer, and rejects with
11678
12031
  * `SteerRejectedError` when the session refuses it.
11679
12032
  */
11680
- steer(content, steerId = createId(), comments = []) {
12033
+ steer(content, steerId = createId(), comments = [], senderId) {
11681
12034
  let at;
11682
12035
  return this.request({
11683
12036
  type: "steer",
11684
12037
  steerId,
11685
12038
  content,
11686
- ...comments.length > 0 ? { comments: [...comments] } : {}
12039
+ ...comments.length > 0 ? { comments: [...comments] } : {},
12040
+ ...senderId === void 0 ? {} : { senderId }
11687
12041
  }, (event) => {
11688
12042
  if (event.type === "steer_result" && event.steerId === steerId) {
11689
12043
  if (event.outcome.status !== "accepted") return { reject: new SteerRejectedError(event.outcome) };
@@ -13617,7 +13971,7 @@ var CoreRoutes = class {
13617
13971
  }
13618
13972
  /** The process's path of the core's route `path`, such as `/conversations`. */
13619
13973
  path(path) {
13620
- return `/cores/${encodeURIComponent(this.id)}/api${path}`;
13974
+ return `/cores/${segment(this.id)}/api${path}`;
13621
13975
  }
13622
13976
  /**
13623
13977
  * Calls the route `path` with `body`, a `Blob` as its bytes of its type
@@ -13655,188 +14009,610 @@ var CoreRoutes = class {
13655
14009
  async send(method, path, body) {
13656
14010
  await (await this.request(method, path, body)).body?.cancel();
13657
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
+ }
13658
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;
13659
14052
  //#endregion
13660
- //#region src/conversation.ts
14053
+ //#region src/files.ts
13661
14054
  /**
13662
- * A conversation of a core, driven as the web app drives one: a
13663
- * `ConversationClient` on the conversation's lane, which reads with the
13664
- * core's routes, holds the root's transcript with the one patch applier, and
13665
- * 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.
13666
14146
  *
13667
- * `run(input)` sends a message and waits for the turn it starts to end, as
13668
- * the Codex SDK's `thread.run`; `events()` is everything the conversation's
13669
- * lane tells, as an async iterator, with a `permission` event for each
13670
- * 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.
13671
14150
  */
13672
- var Conversation = class {
13673
- id;
13674
- routes;
13675
- client = null;
13676
- opening = null;
13677
- /** The root's transcript, as the lane keeps it. */
13678
- transcript = EMPTY_TRANSCRIPT;
13679
- metadata = null;
13680
- /** The permission requests told already. */
13681
- told = /* @__PURE__ */ new Set();
13682
- listeners = /* @__PURE__ */ new Set();
13683
- /** What waits for a change of the transcript or the metadata, and fails once the conversation closes. */
13684
- changes = /* @__PURE__ */ new Set();
13685
- /** Whether the lane is being opened again after it dropped. */
13686
- reopening = false;
13687
- /** Whether the lane dropped again while it was being opened again. */
13688
- droppedAgain = false;
13689
- schedules;
13690
- constructor(id, routes) {
13691
- this.id = id;
13692
- this.routes = routes;
13693
- const path = `/conversations/${encodeURIComponent(id)}/schedules`;
13694
- const one = (schedule) => `${path}/${encodeURIComponent(schedule)}`;
13695
- this.schedules = {
13696
- create: (patch) => routes.json("POST", path, scheduleAnswerSchema, patch),
13697
- get: (schedule) => routes.json("GET", one(schedule), scheduleDtoSchema),
13698
- update: (schedule, patch) => routes.json("PATCH", one(schedule), scheduleAnswerSchema, patch),
13699
- remove: (schedule) => routes.send("DELETE", one(schedule)),
13700
- run: (schedule, task) => routes.json("POST", `${one(schedule)}/runs`, scheduleRunDtoSchema, task === void 0 ? {} : { task }),
13701
- runs: async (schedule, before) => {
13702
- const query = before === void 0 ? "" : `?before=${encodeURIComponent(before)}`;
13703
- return (await routes.json("GET", `${one(schedule)}/runs${query}`, scheduleRunsSchema)).runs;
13704
- }
13705
- };
13706
- }
13707
- /** Opens the conversation's lane, once; each action opens it first. */
13708
- open() {
13709
- this.opening ??= this.connect().catch((error) => {
13710
- this.opening = null;
13711
- throw error;
13712
- });
13713
- return this.opening;
13714
- }
13715
- async connect() {
13716
- const path = `/conversations/${encodeURIComponent(this.id)}`;
13717
- const client = createConversationClient(this.routes.connection, this.id, {
13718
- reader: {
13719
- conversation: async (signal) => {
13720
- const detail = await this.routes.json("GET", path, conversationDetailSchema, void 0, signal);
13721
- this.takeMetadata(detail.metadata);
13722
- return {
13723
- agents: detail.agents,
13724
- entries: detail.entries,
13725
- tags: { metadata: detail.metadataTag }
13726
- };
13727
- },
13728
- transcript: async (node, signal) => {
13729
- const page = await this.routes.json("GET", `${path}/agents/${encodeURIComponent(node)}/transcript?latest=true`, transcriptPageSchema, void 0, signal);
13730
- if (!page.version) throw new Error("The latest page names no version of its transcript");
13731
- return {
13732
- ...page,
13733
- version: page.version
13734
- };
13735
- }
13736
- },
13737
- shows: (node) => node === null || node === this.id,
13738
- conversationFrame: (frame) => {
13739
- const parsed = conversationFrameSchema.safeParse(frame);
13740
- if (!parsed.success) return null;
13741
- const data = parsed.data;
13742
- if (data.type === "conversation") return {
13743
- apply: () => this.takeMetadata(data.metadata),
13744
- tagged: {
13745
- value: "metadata",
13746
- tag: data.etag
13747
- }
13748
- };
13749
- return { apply: () => {} };
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;
13750
14178
  }
13751
- });
13752
- client.subscribe((event) => this.receive(event));
13753
- this.client = client;
13754
- try {
13755
- await client.open({ root: this.id });
13756
- } catch (error) {
13757
- client.dispose();
13758
- if (this.client === client) this.client = null;
13759
- throw error;
13760
- }
13761
- return client;
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, ""));
13762
14185
  }
13763
- receive(event) {
13764
- switch (event.type) {
13765
- case "closed":
13766
- case "disconnected":
13767
- this.reopen();
13768
- break;
13769
- case "transcript_reset":
13770
- if (event.node === this.id) this.transcript = resetTranscript(this.transcript, event, event.asked);
13771
- break;
13772
- case "transcript_patch": if (event.node === this.id) this.transcript = applyTranscriptPatches(this.transcript, event.patches, performance.now(), event.version);
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);
13773
14195
  }
13774
- this.emit(event);
13775
- this.changed();
14196
+ set.add(listener);
13776
14197
  }
13777
- /** Opens the lane of the client again until it opens, unless the program closes the conversation first. */
13778
- reopen() {
13779
- const client = this.client;
13780
- if (client === null) return;
13781
- if (this.reopening) {
13782
- this.droppedAgain = true;
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, "");
13783
14212
  return;
13784
14213
  }
13785
- this.reopening = true;
13786
- const opening = (async () => {
13787
- try {
13788
- for (let failures = 0;; failures++) try {
13789
- this.droppedAgain = false;
13790
- await client.open({ root: this.id });
13791
- await client.reopened();
13792
- if (!this.droppedAgain) return client;
13793
- } catch (error) {
13794
- if (this.client !== client) throw error;
13795
- await new Promise((resolve) => setTimeout(resolve, reconnectWait(failures)));
13796
- }
13797
- } finally {
13798
- this.reopening = false;
13799
- this.changed();
13800
- }
13801
- })();
13802
- this.opening = opening;
13803
- opening.catch(() => {});
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();
13804
14220
  }
13805
- takeMetadata(metadata) {
13806
- this.metadata = metadata;
13807
- for (const request of metadata.permissions.requests) if (!this.told.has(request.id)) {
13808
- this.told.add(request.id);
13809
- this.emit({
13810
- type: "permission",
13811
- permission: this.permission(request)
13812
- });
13813
- }
13814
- this.changed();
14221
+ emit(type, ...event) {
14222
+ for (const listener of [...this.listeners.get(type) ?? []]) listener(...event);
13815
14223
  }
13816
- changed() {
13817
- for (const change of [...this.changes]) change.changed();
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);
13818
14247
  }
13819
- permission(request) {
13820
- const decide = (body) => this.routes.send("POST", `/conversations/${encodeURIComponent(this.id)}/permissions/requests/${encodeURIComponent(request.id)}`, body);
13821
- return {
13822
- request,
13823
- allow: (values) => decide({
13824
- decision: "allow",
13825
- ...values === void 0 ? {} : { credential: values }
13826
- }),
13827
- deny: () => decide({ decision: "deny" })
13828
- };
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();
13829
14272
  }
13830
- emit(event) {
13831
- for (const listener of [...this.listeners]) listener(event);
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
+ }
13832
14306
  }
13833
- /** The permission requests waiting for a decision. */
13834
- get permissions() {
13835
- return (this.metadata?.permissions.requests ?? []).map((request) => this.permission(request));
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 });
13836
14310
  }
13837
- /** The root's blocks the conversation holds, oldest first. */
13838
- get blocks() {
13839
- return heldBlocks(this.transcript);
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
+ }
14483
+ /** Opens the conversation's lane, once; each action opens it first. */
14484
+ open() {
14485
+ this.opening ??= this.connect().catch((error) => {
14486
+ this.opening = null;
14487
+ throw error;
14488
+ });
14489
+ return this.opening;
14490
+ }
14491
+ async connect() {
14492
+ const path = `/conversations/${segment(this.id)}`;
14493
+ const client = createConversationClient(this.routes.connection, this.id, {
14494
+ reader: {
14495
+ conversation: async (signal) => {
14496
+ const detail = await this.routes.json("GET", path, conversationDetailSchema, void 0, signal);
14497
+ this.takeMetadata(detail.metadata);
14498
+ return {
14499
+ agents: detail.agents,
14500
+ entries: detail.entries,
14501
+ tags: { metadata: detail.metadataTag }
14502
+ };
14503
+ },
14504
+ transcript: async (node, signal) => {
14505
+ const page = await this.routes.json("GET", `${path}/agents/${segment(node)}/transcript${query({ latest: true })}`, transcriptPageSchema, void 0, signal);
14506
+ if (!page.version) throw new Error("The latest page names no version of its transcript");
14507
+ return {
14508
+ ...page,
14509
+ version: page.version
14510
+ };
14511
+ }
14512
+ },
14513
+ shows: (node) => node === null || node === this.id,
14514
+ conversationFrame: (frame) => {
14515
+ const parsed = conversationFrameSchema.safeParse(frame);
14516
+ if (!parsed.success) return null;
14517
+ const data = parsed.data;
14518
+ if (data.type === "conversation") return {
14519
+ apply: () => this.takeMetadata(data.metadata),
14520
+ tagged: {
14521
+ value: "metadata",
14522
+ tag: data.etag
14523
+ }
14524
+ };
14525
+ return { apply: () => {} };
14526
+ }
14527
+ });
14528
+ client.subscribe((event) => this.receive(event));
14529
+ this.client = client;
14530
+ try {
14531
+ await client.open({ root: this.id });
14532
+ } catch (error) {
14533
+ client.dispose();
14534
+ if (this.client === client) this.client = null;
14535
+ throw error;
14536
+ }
14537
+ return client;
14538
+ }
14539
+ receive(event) {
14540
+ switch (event.type) {
14541
+ case "closed":
14542
+ case "disconnected":
14543
+ this.reopen();
14544
+ break;
14545
+ case "transcript_reset":
14546
+ if (event.node === this.id) this.transcript = resetTranscript(this.transcript, event, event.asked);
14547
+ break;
14548
+ case "transcript_patch": if (event.node === this.id) this.transcript = applyTranscriptPatches(this.transcript, event.patches, performance.now(), event.version);
14549
+ }
14550
+ this.emit(event);
14551
+ this.changed();
14552
+ }
14553
+ /** Opens the lane of the client again until it opens, unless the program closes the conversation first. */
14554
+ reopen() {
14555
+ const client = this.client;
14556
+ if (client === null) return;
14557
+ if (this.reopening) {
14558
+ this.droppedAgain = true;
14559
+ return;
14560
+ }
14561
+ this.reopening = true;
14562
+ const opening = (async () => {
14563
+ try {
14564
+ for (let failures = 0;; failures++) try {
14565
+ this.droppedAgain = false;
14566
+ await client.open({ root: this.id });
14567
+ await client.reopened();
14568
+ if (!this.droppedAgain) return client;
14569
+ } catch (error) {
14570
+ if (this.client !== client) throw error;
14571
+ await new Promise((resolve) => setTimeout(resolve, reconnectWait(failures)));
14572
+ }
14573
+ } finally {
14574
+ this.reopening = false;
14575
+ this.changed();
14576
+ }
14577
+ })();
14578
+ this.opening = opening;
14579
+ opening.catch(() => {});
14580
+ }
14581
+ takeMetadata(metadata) {
14582
+ this.metadata = metadata;
14583
+ for (const request of metadata.permissions.requests) if (!this.told.has(request.id)) {
14584
+ this.told.add(request.id);
14585
+ this.emit({
14586
+ type: "permission",
14587
+ permission: this.permission(request)
14588
+ });
14589
+ }
14590
+ this.changed();
14591
+ }
14592
+ changed() {
14593
+ for (const waiter of [...this.waiters]) waiter.changed();
14594
+ }
14595
+ permission(request) {
14596
+ const decide = (body) => this.routes.send("POST", `/conversations/${segment(this.id)}/permissions/requests/${segment(request.id)}`, body);
14597
+ return {
14598
+ request,
14599
+ allow: (values) => decide({
14600
+ decision: "allow",
14601
+ ...values === void 0 ? {} : { credential: values }
14602
+ }),
14603
+ deny: () => decide({ decision: "deny" })
14604
+ };
14605
+ }
14606
+ emit(event) {
14607
+ for (const listener of [...this.listeners]) listener(event);
14608
+ }
14609
+ /** The permission requests waiting for a decision. */
14610
+ get permissions() {
14611
+ return (this.metadata?.permissions.requests ?? []).map((request) => this.permission(request));
14612
+ }
14613
+ /** The root's blocks the conversation holds, oldest first. */
14614
+ get blocks() {
14615
+ return heldBlocks(this.transcript);
13840
14616
  }
13841
14617
  /**
13842
14618
  * The conversation's agents as its lane holds them: the root's entry,
@@ -13851,8 +14627,8 @@ var Conversation = class {
13851
14627
  * The conversation takes it once however often it is sent under
13852
14628
  * `messageId`, which messages and steers share.
13853
14629
  */
13854
- async send(input, messageId = randomUUID()) {
13855
- 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);
13856
14632
  }
13857
14633
  /**
13858
14634
  * Changes what `patch` names of the conversation, as the app's settings
@@ -13860,7 +14636,62 @@ var Conversation = class {
13860
14636
  * refused while the others apply.
13861
14637
  */
13862
14638
  async update(patch) {
13863
- 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)}`);
13864
14695
  }
13865
14696
  /**
13866
14697
  * Sends `text` to the subagent `node`, the id of one of `agents` whose
@@ -13869,11 +14700,12 @@ var Conversation = class {
13869
14700
  * with it. Resolves with the message's id, the one made for it when
13870
14701
  * `messageId` is absent.
13871
14702
  */
13872
- async sendToAgent(node, text, messageId) {
13873
- 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`;
13874
14705
  const { id } = await this.routes.json("POST", path, subagentMessageAnswerSchema, {
13875
14706
  id: messageId,
13876
- text
14707
+ text,
14708
+ senderId: options.senderId
13877
14709
  });
13878
14710
  return id;
13879
14711
  }
@@ -13882,8 +14714,8 @@ var Conversation = class {
13882
14714
  * The conversation takes it once however often it is sent under
13883
14715
  * `steerId`, which messages and steers share.
13884
14716
  */
13885
- async steer(input, steerId = randomUUID()) {
13886
- 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);
13887
14719
  }
13888
14720
  async abort() {
13889
14721
  return (await this.open()).abort();
@@ -13907,20 +14739,20 @@ var Conversation = class {
13907
14739
  * holds. It fails when the message left the queue without running, as an
13908
14740
  * abort's clearing of the queue removes it.
13909
14741
  */
13910
- async run(input) {
14742
+ async run(input, options = {}) {
13911
14743
  const messageId = randomUUID();
13912
14744
  let sent = false;
13913
14745
  let answered = null;
13914
14746
  let asked = null;
13915
14747
  let reading = false;
13916
14748
  let failures = 0;
13917
- let change = {
14749
+ let waiter = {
13918
14750
  changed: () => {},
13919
14751
  closed: () => {}
13920
14752
  };
13921
14753
  const ended = new Promise((resolve, reject) => {
13922
14754
  const again = () => {
13923
- if (this.changes.has(change)) change.changed();
14755
+ if (this.waiters.has(waiter)) waiter.changed();
13924
14756
  };
13925
14757
  const later = () => {
13926
14758
  failures += 1;
@@ -13931,7 +14763,7 @@ var Conversation = class {
13931
14763
  this.turnState(messageId).then((state) => {
13932
14764
  if (asked !== view) return;
13933
14765
  if (state === null) {
13934
- this.changes.delete(change);
14766
+ this.waiters.delete(waiter);
13935
14767
  reject(/* @__PURE__ */ new Error("The message left the queue without running"));
13936
14768
  } else if (state.state === "ended") {
13937
14769
  failures = 0;
@@ -13962,7 +14794,7 @@ var Conversation = class {
13962
14794
  later();
13963
14795
  });
13964
14796
  };
13965
- change = {
14797
+ waiter = {
13966
14798
  changed: () => {
13967
14799
  const last = this.metadata?.lastTurn;
13968
14800
  const end = last?.turnId === messageId ? {
@@ -13972,7 +14804,7 @@ var Conversation = class {
13972
14804
  if (end) {
13973
14805
  const turn = this.turnOf(messageId, end);
13974
14806
  if (turn) {
13975
- this.changes.delete(change);
14807
+ this.waiters.delete(waiter);
13976
14808
  resolve(turn);
13977
14809
  return;
13978
14810
  }
@@ -13986,15 +14818,15 @@ var Conversation = class {
13986
14818
  };
13987
14819
  });
13988
14820
  ended.catch(() => {});
13989
- this.changes.add(change);
14821
+ this.waiters.add(waiter);
13990
14822
  try {
13991
- await this.send(input, messageId);
14823
+ await this.send(input, messageId, options);
13992
14824
  } catch (error) {
13993
- this.changes.delete(change);
14825
+ this.waiters.delete(waiter);
13994
14826
  throw error;
13995
14827
  }
13996
14828
  sent = true;
13997
- change.changed();
14829
+ waiter.changed();
13998
14830
  return ended;
13999
14831
  }
14000
14832
  /**
@@ -14021,7 +14853,7 @@ var Conversation = class {
14021
14853
  }
14022
14854
  /** Where the turn `messageId` stands, as the conversation answers; null when it holds no turn of it. */
14023
14855
  async turnState(messageId) {
14024
- const path = `/conversations/${encodeURIComponent(this.id)}/turns/${encodeURIComponent(messageId)}`;
14856
+ const path = `/conversations/${segment(this.id)}/turns/${segment(messageId)}`;
14025
14857
  try {
14026
14858
  return await this.routes.json("GET", path, turnStateSchema);
14027
14859
  } catch (error) {
@@ -14038,6 +14870,7 @@ var Conversation = class {
14038
14870
  const after = blocks.slice(at + 1, end + 1);
14039
14871
  const text = after.flatMap((block) => block.type === "text" ? [block.text] : []).join("\n\n");
14040
14872
  return {
14873
+ id: messageId,
14041
14874
  outcome: ending.outcome,
14042
14875
  blocks: after,
14043
14876
  text
@@ -14055,8 +14888,8 @@ var Conversation = class {
14055
14888
  }
14056
14889
  /** Reads the page of the root's transcript before `window` into what the conversation holds. */
14057
14890
  async readBefore(window) {
14058
- const root = encodeURIComponent(this.id);
14059
- const edge = encodeURIComponent(window.blocks[0].id);
14891
+ const root = segment(this.id);
14892
+ const edge = segment(window.blocks[0].id);
14060
14893
  const path = `/conversations/${root}/agents/${root}/transcript?before=${window.start}&edge=${edge}`;
14061
14894
  const page = await this.routes.json("GET", path, transcriptPageSchema);
14062
14895
  this.transcript = addPage(this.transcript, page, true);
@@ -14073,7 +14906,7 @@ var Conversation = class {
14073
14906
  waiting.push(event);
14074
14907
  wake?.();
14075
14908
  };
14076
- const change = {
14909
+ const waiter = {
14077
14910
  changed: () => {},
14078
14911
  closed: () => {
14079
14912
  closed = true;
@@ -14081,7 +14914,7 @@ var Conversation = class {
14081
14914
  }
14082
14915
  };
14083
14916
  this.listeners.add(listener);
14084
- this.changes.add(change);
14917
+ this.waiters.add(waiter);
14085
14918
  try {
14086
14919
  await this.open();
14087
14920
  for (;;) {
@@ -14096,7 +14929,7 @@ var Conversation = class {
14096
14929
  }
14097
14930
  } finally {
14098
14931
  this.listeners.delete(listener);
14099
- this.changes.delete(change);
14932
+ this.waiters.delete(waiter);
14100
14933
  }
14101
14934
  }
14102
14935
  /**
@@ -14109,17 +14942,61 @@ var Conversation = class {
14109
14942
  this.client = null;
14110
14943
  this.opening = null;
14111
14944
  client?.dispose();
14112
- for (const change of [...this.changes]) {
14113
- this.changes.delete(change);
14114
- change.closed();
14945
+ for (const waiter of [...this.waiters]) {
14946
+ this.waiters.delete(waiter);
14947
+ waiter.closed();
14115
14948
  }
14116
14949
  }
14117
14950
  };
14118
- function content(input) {
14119
- return typeof input === "string" ? [{
14120
- type: "text",
14121
- text: input
14122
- }] : 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
+ };
14123
15000
  }
14124
15001
  //#endregion
14125
15002
  //#region src/apart.ts
@@ -14375,321 +15252,185 @@ function portOf(number, resent, request, send) {
14375
15252
  return {
14376
15253
  request: number,
14377
15254
  resent,
14378
- signal: request.stop.signal,
14379
- ask: (message) => new Promise((resolve, reject) => {
14380
- if (request.over) {
14381
- reject(new PortFailure("The request is over"));
14382
- return;
14383
- }
14384
- const port = request.nextPort;
14385
- request.nextPort += 1;
14386
- request.answers.set(port, {
14387
- resolve,
14388
- reject
14389
- });
14390
- send({
14391
- request: number,
14392
- port,
14393
- message
14394
- });
14395
- })
14396
- };
14397
- }
14398
- /** The command call of `invocation` on `port`. */
14399
- function commandCall(invocation, port) {
14400
- const rpc = async (request) => {
14401
- const answer = await port.ask({
14402
- type: "rpc",
14403
- request
14404
- });
14405
- if (answer.type !== "rpc") throw new PortFailure(`The port answered ${answer.type} to an rpc operation`);
14406
- return answer.response;
14407
- };
14408
- const bytes = (data) => typeof data === "string" ? new TextEncoder().encode(data) : data.buffer instanceof ArrayBuffer ? data : new Uint8Array(data);
14409
- return {
14410
- ...port,
14411
- invocation,
14412
- stdout: async (data) => void await rpc({
14413
- type: "stdout",
14414
- bytes: bytes(data)
14415
- }),
14416
- stderr: async (data) => void await rpc({
14417
- type: "stderr",
14418
- bytes: bytes(data)
14419
- }),
14420
- readStdin: async () => {
14421
- const response = await rpc({ type: "read_stdin" });
14422
- return response.type === "input" ? response.bytes ?? null : null;
14423
- },
14424
- awaitsUser: async (awaits) => void await rpc({
14425
- type: "awaits_user",
14426
- awaits
14427
- }),
14428
- medium: async (facts, data) => void await rpc({
14429
- type: "medium",
14430
- facts,
14431
- bytes: bytes(data)
14432
- })
14433
- };
14434
- }
14435
- /** The reply to `call`, by the definition's handler of it. */
14436
- async function answer(definition, call, port) {
14437
- switch (call.type) {
14438
- case "command": {
14439
- const leaf = leafAt(definition, call.invocation.path);
14440
- if (leaf === void 0) throw usage(`No command ${call.invocation.path.join(" ")}`);
14441
- const parsed = (leaf.input ?? z.object({})).safeParse(call.invocation.args);
14442
- if (!parsed.success) throw usage(schemaRefusal(parsed.error));
14443
- const commandPort = commandCall(call.invocation, port);
14444
- try {
14445
- return {
14446
- type: "exit",
14447
- code: await leaf.run(parsed.data, commandPort) ?? 0
14448
- };
14449
- } catch (error) {
14450
- if (error instanceof PortFailure) throw error;
14451
- await commandPort.stderr(`${error instanceof Error ? error.message : String(error)}\n`);
14452
- return {
14453
- type: "exit",
14454
- code: 1
14455
- };
14456
- }
14457
- }
14458
- case "context": {
14459
- const text = await definition.context?.(call, port);
14460
- return text === void 0 ? { type: "context" } : {
14461
- type: "context",
14462
- text
14463
- };
14464
- }
14465
- case "project_search":
14466
- if (definition.projectSearch === void 0) throw undeclared("a project search");
14467
- return await definition.projectSearch(call, port);
14468
- case "conversation_deleted":
14469
- await definition.onConversationDeleted?.(call, port);
14470
- return { type: "done" };
14471
- case "conversation_forked":
14472
- await definition.onConversationForked?.(call, port);
14473
- return { type: "done" };
14474
- default: throw undeclared(call.type);
14475
- }
14476
- }
14477
- var RequestFailure = class extends Error {
14478
- error;
14479
- constructor(error) {
14480
- super("message" in error ? error.message : error.type);
14481
- this.error = error;
14482
- }
14483
- };
14484
- function usage(message) {
14485
- return new RequestFailure({
14486
- type: "usage",
14487
- message
14488
- });
14489
- }
14490
- function undeclared(what) {
14491
- return new RequestFailure({
14492
- type: "failed",
14493
- message: `The plugin declares no ${what}`
14494
- });
14495
- }
14496
- function pluginError(error) {
14497
- if (error instanceof RequestFailure) return error.error;
14498
- return {
14499
- type: "failed",
14500
- message: error instanceof Error ? error.message : String(error)
14501
- };
14502
- }
14503
- //#endregion
14504
- //#region src/socket.ts
14505
- /**
14506
- * A WebSocket on a stream of the process's HTTP/2 connection (RFC 8441):
14507
- * the stream is the socket's, and its bytes are WebSocket frames (RFC 6455),
14508
- * which Node's `http2` does not write, so this module does. A client masks
14509
- * each frame it sends; the process's frames come unmasked.
14510
- *
14511
- * It has the part of a browser's `WebSocket` the page connection and a
14512
- * forwarded page's socket use: `send`, `close`, `bufferedAmount`,
14513
- * `binaryType`, and the `open`, `message` and `close` events.
14514
- */
14515
- const TEXT = 1;
14516
- const BINARY = 2;
14517
- const CLOSE = 8;
14518
- const PING = 9;
14519
- const PONG = 10;
14520
- const CONTINUATION = 0;
14521
- /** The close of a socket that ended without a close frame. */
14522
- const ABNORMAL_CLOSURE = 1006;
14523
- /** The close frame's code when it carries none. */
14524
- const NO_STATUS = 1005;
14525
- /** A WebSocket on the stream `opening` answers once the process took it. */
14526
- var StreamSocket = class {
14527
- binaryType = "arraybuffer";
14528
- stream = null;
14529
- listeners = /* @__PURE__ */ new Map();
14530
- /** The bytes read that do not make a whole frame yet. */
14531
- pending = /* @__PURE__ */ new Uint8Array(0);
14532
- /** The fragments of a message whose last frame has not come. */
14533
- fragments = null;
14534
- closed = false;
14535
- /** Whether this end sent its close frame. */
14536
- closing = false;
14537
- constructor(opening) {
14538
- opening.then((stream) => {
14539
- if (this.closed) {
14540
- stream.close();
14541
- return;
14542
- }
14543
- this.stream = stream;
14544
- stream.on("data", (chunk) => this.read(chunk));
14545
- stream.once("close", () => this.ended(ABNORMAL_CLOSURE, ""));
14546
- stream.on("error", () => {});
14547
- this.emit("open");
14548
- }, () => this.ended(ABNORMAL_CLOSURE, ""));
14549
- }
14550
- /** The bytes sent that the stream has not written yet. */
14551
- get bufferedAmount() {
14552
- return this.stream?.writableLength ?? 0;
14553
- }
14554
- addEventListener(type, listener) {
14555
- let set = this.listeners.get(type);
14556
- if (!set) {
14557
- set = /* @__PURE__ */ new Set();
14558
- this.listeners.set(type, set);
14559
- }
14560
- set.add(listener);
14561
- }
14562
- removeEventListener(type, listener) {
14563
- this.listeners.get(type)?.delete(listener);
14564
- }
14565
- /** Sends a message: text for a string, binary for bytes. */
14566
- send(data) {
14567
- if (typeof data === "string") this.write(TEXT, new TextEncoder().encode(data));
14568
- else this.write(BINARY, data instanceof ArrayBuffer ? new Uint8Array(data) : data);
14569
- }
14570
- /** Closes the socket with `code` and `reason`; its `close` event follows. */
14571
- close(code = 1e3, reason = "") {
14572
- if (this.closed || this.closing) return;
14573
- this.closing = true;
14574
- if (this.stream === null) {
14575
- this.ended(ABNORMAL_CLOSURE, "");
14576
- return;
14577
- }
14578
- const text = new TextEncoder().encode(reason);
14579
- const body = new Uint8Array(2 + text.length);
14580
- new DataView(body.buffer).setUint16(0, code);
14581
- body.set(text, 2);
14582
- this.write(CLOSE, body);
14583
- this.stream.end();
14584
- }
14585
- emit(type, ...event) {
14586
- for (const listener of [...this.listeners.get(type) ?? []]) listener(...event);
14587
- }
14588
- /** Writes one frame of `opcode` with `payload`, masked. */
14589
- write(opcode, payload) {
14590
- const stream = this.stream;
14591
- if (stream === null || this.closed || stream.destroyed) return;
14592
- const length = payload.length;
14593
- const extended = length < 126 ? 0 : length < 65536 ? 2 : 8;
14594
- const frame = new Uint8Array(2 + extended + 4 + length);
14595
- const view = new DataView(frame.buffer);
14596
- frame[0] = 128 | opcode;
14597
- if (extended === 0) frame[1] = 128 | length;
14598
- else if (extended === 2) {
14599
- frame[1] = 254;
14600
- view.setUint16(2, length);
14601
- } else {
14602
- frame[1] = 255;
14603
- view.setBigUint64(2, BigInt(length));
14604
- }
14605
- const at = 2 + extended;
14606
- const mask = frame.subarray(at, at + 4);
14607
- randomFillSync(mask);
14608
- const body = frame.subarray(at + 4);
14609
- for (let index = 0; index < length; index += 1) body[index] = payload[index] ^ mask[index & 3];
14610
- stream.write(frame);
14611
- }
14612
- /** Takes bytes of the stream, and handles each whole frame they complete. */
14613
- read(chunk) {
14614
- let bytes = this.pending.length === 0 ? chunk : concat([this.pending, chunk]);
14615
- while (bytes.length >= 2) {
14616
- const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
14617
- const fin = (bytes[0] & 128) !== 0;
14618
- const opcode = bytes[0] & 15;
14619
- let length = bytes[1] & 127;
14620
- let at = 2;
14621
- if (length === 126) {
14622
- if (bytes.length < 4) break;
14623
- length = view.getUint16(2);
14624
- at = 4;
14625
- } else if (length === 127) {
14626
- if (bytes.length < 10) break;
14627
- length = Number(view.getBigUint64(2));
14628
- at = 10;
14629
- }
14630
- if (bytes.length < at + length) break;
14631
- const payload = bytes.slice(at, at + length);
14632
- bytes = bytes.subarray(at + length);
14633
- this.frame(fin, opcode, payload);
14634
- }
14635
- this.pending = bytes.slice();
14636
- }
14637
- frame(fin, opcode, payload) {
14638
- switch (opcode) {
14639
- case PING:
14640
- this.write(PONG, payload);
14641
- return;
14642
- case PONG: return;
14643
- case CLOSE: {
14644
- const code = payload.length >= 2 ? new DataView(payload.buffer, payload.byteOffset).getUint16(0) : NO_STATUS;
14645
- const reason = new TextDecoder().decode(payload.subarray(2));
14646
- if (!this.closing) {
14647
- this.closing = true;
14648
- this.write(CLOSE, payload.subarray(0, 2));
14649
- this.stream?.end();
14650
- }
14651
- this.ended(code, reason);
15255
+ signal: request.stop.signal,
15256
+ ask: (message) => new Promise((resolve, reject) => {
15257
+ if (request.over) {
15258
+ reject(new PortFailure("The request is over"));
14652
15259
  return;
14653
15260
  }
14654
- case CONTINUATION:
14655
- if (this.fragments === null) return;
14656
- this.fragments.parts.push(payload);
14657
- if (fin) {
14658
- const { opcode: first, parts } = this.fragments;
14659
- this.fragments = null;
14660
- this.message(first, concat(parts));
14661
- }
14662
- return;
14663
- case TEXT:
14664
- case BINARY: if (fin) this.message(opcode, payload);
14665
- else this.fragments = {
14666
- opcode,
14667
- parts: [payload]
15261
+ const port = request.nextPort;
15262
+ request.nextPort += 1;
15263
+ request.answers.set(port, {
15264
+ resolve,
15265
+ reject
15266
+ });
15267
+ send({
15268
+ request: number,
15269
+ port,
15270
+ message
15271
+ });
15272
+ })
15273
+ };
15274
+ }
15275
+ /** The command call of `invocation` on `port`. */
15276
+ function commandCall(invocation, port) {
15277
+ const rpc = async (request) => {
15278
+ const answer = await port.ask({
15279
+ type: "rpc",
15280
+ request
15281
+ });
15282
+ if (answer.type !== "rpc") throw new PortFailure(`The port answered ${answer.type} to an rpc operation`);
15283
+ return answer.response;
15284
+ };
15285
+ const bytes = (data) => typeof data === "string" ? new TextEncoder().encode(data) : data.buffer instanceof ArrayBuffer ? data : new Uint8Array(data);
15286
+ return {
15287
+ ...port,
15288
+ invocation,
15289
+ stdout: async (data) => void await rpc({
15290
+ type: "stdout",
15291
+ bytes: bytes(data)
15292
+ }),
15293
+ stderr: async (data) => void await rpc({
15294
+ type: "stderr",
15295
+ bytes: bytes(data)
15296
+ }),
15297
+ readStdin: async () => {
15298
+ const response = await rpc({ type: "read_stdin" });
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
+ };
15333
+ }
15334
+ }
15335
+ case "context": {
15336
+ const text = await definition.context?.(call, port);
15337
+ return text === void 0 ? { type: "context" } : {
15338
+ type: "context",
15339
+ text
14668
15340
  };
14669
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);
14670
15352
  }
14671
- message(opcode, payload) {
14672
- const data = opcode === TEXT ? new TextDecoder().decode(payload) : payload.buffer.slice(payload.byteOffset, payload.byteOffset + payload.byteLength);
14673
- this.emit("message", { data });
14674
- }
14675
- ended(code, reason) {
14676
- if (this.closed) return;
14677
- this.closed = true;
14678
- this.stream?.close();
14679
- this.emit("close", {
14680
- code,
14681
- reason
14682
- });
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;
14683
15359
  }
14684
15360
  };
14685
- function concat(parts) {
14686
- const whole = new Uint8Array(parts.reduce((total, part) => total + part.length, 0));
14687
- let at = 0;
14688
- for (const part of parts) {
14689
- whole.set(part, at);
14690
- at += part.length;
14691
- }
14692
- 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
+ };
14693
15434
  }
14694
15435
  //#endregion
14695
15436
  //#region src/core.ts
@@ -14708,6 +15449,15 @@ var Core = class {
14708
15449
  conversations;
14709
15450
  providers;
14710
15451
  devices;
15452
+ credentials;
15453
+ instructions;
15454
+ subagents;
15455
+ plugins;
15456
+ models;
15457
+ usage;
15458
+ workspaces;
15459
+ projects;
15460
+ portForwards;
14711
15461
  routes;
14712
15462
  connection;
14713
15463
  stateRead;
@@ -14720,12 +15470,21 @@ var Core = class {
14720
15470
  this.closing = closing;
14721
15471
  this.id = opening.id;
14722
15472
  this.dir = opening.dir;
14723
- 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`));
14724
15474
  this.connection.start();
14725
15475
  this.routes = new CoreRoutes(opening.process, opening.id, this.connection);
14726
15476
  this.conversations = new Conversations(this.routes, () => this.stateRead);
14727
15477
  this.providers = new Providers(this.routes);
14728
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);
14729
15488
  for (const plugin of opening.plugins) this.servePlugin(plugin);
14730
15489
  }
14731
15490
  /** Reads the core's product state and follows it from then on. */
@@ -14773,6 +15532,17 @@ var Core = class {
14773
15532
  fileName: file.name
14774
15533
  };
14775
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
+ }
14776
15546
  /**
14777
15547
  * Changes what `patch` names of the core's preferences, the web app's
14778
15548
  * Settings, and answers them, such as `commandLocale`, the time zone and
@@ -14781,46 +15551,6 @@ var Core = class {
14781
15551
  async updatePreferences(patch) {
14782
15552
  return (await this.routes.json("PATCH", "/settings/preferences", userPreferencesSchema, patch)).preferences;
14783
15553
  }
14784
- /**
14785
- * Answers `request` with the core's route it names below `base`, such as
14786
- * `/jush/api/conversations` below `/jush/api`, as the program's server
14787
- * forwards a page's request.
14788
- */
14789
- fetch(request, base = "/api") {
14790
- const url = new URL(request.url);
14791
- const forwarded = new Request(PROCESS_ORIGIN + this.routes.path(below(url.pathname, base)) + url.search, request);
14792
- return this.routes.process.fetch(forwarded);
14793
- }
14794
- /**
14795
- * Carries the page connection a page opened on the program's server,
14796
- * `socket`, to the core, both ways, until either end closes; `url` is the
14797
- * address the page opened, whose query goes with it.
14798
- */
14799
- accept(socket, url) {
14800
- const query = url === void 0 ? "" : new URL(url, PROCESS_ORIGIN).search;
14801
- const core = new StreamSocket(this.routes.process.connect(this.routes.path(`/connect${query}`), "websocket", { "sec-websocket-version": "13" }));
14802
- const early = [];
14803
- let open = false;
14804
- let pageClosed = false;
14805
- socket.binaryType = "arraybuffer";
14806
- socket.addEventListener("message", (event) => {
14807
- const data = event.data;
14808
- if (open) core.send(data);
14809
- else early.push(data);
14810
- });
14811
- socket.addEventListener("close", () => {
14812
- pageClosed = true;
14813
- core.close();
14814
- });
14815
- core.addEventListener("open", () => {
14816
- open = true;
14817
- for (const data of early.splice(0)) core.send(data);
14818
- });
14819
- core.addEventListener("message", (event) => socket.send(event.data));
14820
- core.addEventListener("close", (event) => {
14821
- if (!pageClosed) socket.close(event.code === 1006 || event.code === 1005 ? 1011 : event.code, event.reason);
14822
- });
14823
- }
14824
15554
  /** Closes the core, for every program: its lanes end, and the process closes it. */
14825
15555
  async close() {
14826
15556
  if (this.closed) return;
@@ -14997,11 +15727,30 @@ var Conversations = class {
14997
15727
  const created = await this.routes.json("POST", "/conversations", createdConversationSchema, body);
14998
15728
  return this.open(created.conversation.id);
14999
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
+ }
15000
15746
  /** The conversation `id`, whose lane opens at its first use. */
15001
15747
  open(id) {
15002
15748
  let conversation = this.opened.get(id);
15003
15749
  if (conversation === void 0) {
15004
- 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
+ });
15005
15754
  this.opened.set(id, conversation);
15006
15755
  }
15007
15756
  return conversation;
@@ -15024,18 +15773,46 @@ var Providers = class {
15024
15773
  return (await this.routes.json("POST", "/providers", providerAnswerSchema, provider)).provider;
15025
15774
  }
15026
15775
  async update(id, patch) {
15027
- 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;
15028
15777
  }
15029
15778
  async remove(id) {
15030
- 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`);
15031
15808
  }
15032
15809
  accounts(id) {
15033
- const path = `/providers/${encodeURIComponent(id)}/accounts`;
15810
+ const path = `/providers/${segment(id)}/accounts`;
15034
15811
  return {
15035
15812
  list: () => this.routes.json("GET", path, accountsSchema),
15036
15813
  activate: async (credentialId) => void await this.routes.json("PUT", `${path}/active`, activeAccountSchema, { credentialId }),
15037
15814
  order: (credentialIds) => this.routes.send("PUT", `${path}/order`, { credentialIds }),
15038
- 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),
15039
15816
  signIn: async () => this.signInOf((await this.routes.json("POST", `${path}/login`, loginStartedSchema)).login.id)
15040
15817
  };
15041
15818
  }
@@ -15044,7 +15821,7 @@ var Providers = class {
15044
15821
  return this.signInOf((await this.routes.json("POST", "/providers/subscription-login", loginStartedSchema, login)).login.id);
15045
15822
  }
15046
15823
  signInOf(id) {
15047
- const path = `/providers/subscription-login/${encodeURIComponent(id)}`;
15824
+ const path = `/providers/subscription-login/${segment(id)}`;
15048
15825
  return {
15049
15826
  id,
15050
15827
  submitCode: async (code) => void await this.routes.json("POST", `${path}/code`, codeTakenSchema, { code }),
@@ -15078,7 +15855,7 @@ var Device = class {
15078
15855
  * channel ends before the device came online.
15079
15856
  */
15080
15857
  async connect(stream) {
15081
- 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");
15082
15859
  stream.readable.pipe(channel);
15083
15860
  channel.pipe(stream.writable);
15084
15861
  const ended = new Promise((resolve) => {
@@ -15157,7 +15934,7 @@ var Device = class {
15157
15934
  ...where,
15158
15935
  ...limited ? { timeoutMs: Math.ceil(timeout) } : {}
15159
15936
  };
15160
- 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);
15161
15938
  return {
15162
15939
  exitCode: ran.exitCode,
15163
15940
  ...ran.output
@@ -15172,7 +15949,23 @@ var Device = class {
15172
15949
  * or is a filesystem's root, such as a volume's mount point.
15173
15950
  */
15174
15951
  async revoke() {
15175
- 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);
15176
15969
  }
15177
15970
  };
15178
15971
  var Devices = class {
@@ -15188,6 +15981,10 @@ var Devices = class {
15188
15981
  this.dir = dir;
15189
15982
  this.online = online;
15190
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
+ }
15191
15988
  /** Creates a device, which serves the core once a runner connects to it. */
15192
15989
  async create() {
15193
15990
  const { device } = await this.routes.json("POST", "/devices", deviceAnswerSchema);
@@ -15267,7 +16064,6 @@ var Process = class Process {
15267
16064
  ...process.env,
15268
16065
  JUSH_RELEASE: start.release.join(pathListSeparator())
15269
16066
  };
15270
- if (start.publicUrl !== void 0) env.JUSH_PUBLIC_URL = start.publicUrl;
15271
16067
  const child = spawn(start.executable, [], {
15272
16068
  stdio: [
15273
16069
  "pipe",
@@ -15363,17 +16159,27 @@ var Process = class Process {
15363
16159
  Object.assign(headers, this.credentials);
15364
16160
  const stream = session.request(headers, { endStream: request.body === null });
15365
16161
  stream.on("error", () => {});
16162
+ let broken;
15366
16163
  if (request.body !== null) {
15367
16164
  const body = Readable.fromWeb(request.body);
15368
16165
  body.pipe(stream);
15369
- 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);
15370
16176
  }
15371
16177
  const abort = () => stream.close(http2.constants.NGHTTP2_CANCEL);
15372
16178
  if (request.signal.aborted) abort();
15373
16179
  request.signal.addEventListener("abort", abort, { once: true });
15374
16180
  const bodied = (status) => request.method !== "HEAD" && status !== 204 && status !== 304;
15375
16181
  const response = await answered(stream, bodied).catch((error) => {
15376
- throw request.signal.aborted ? request.signal.reason : error;
16182
+ throw request.signal.aborted ? request.signal.reason : broken ?? error;
15377
16183
  }).finally(() => request.signal.removeEventListener("abort", abort));
15378
16184
  if (response.body === null) stream.resume();
15379
16185
  return response;
@@ -15514,47 +16320,65 @@ function pathListSeparator() {
15514
16320
  //#region src/jush.ts
15515
16321
  /**
15516
16322
  * A program's Jush: the process its cores run in, which `Jush.start` starts
15517
- * or `Jush.connect` connects to, with the program's plugins, and the cores
15518
- * 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.
15519
16326
  */
15520
16327
  var Jush = class Jush {
15521
16328
  process;
15522
- plugins;
16329
+ declared;
16330
+ addresses;
15523
16331
  runner;
15524
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;
15525
16337
  cores = /* @__PURE__ */ new Map();
15526
- constructor(process, plugins, runner, owned) {
16338
+ constructor(process, declared, addresses, runner, owned) {
15527
16339
  this.process = process;
15528
- this.plugins = plugins;
16340
+ this.declared = declared;
16341
+ this.addresses = addresses;
15529
16342
  this.runner = runner;
15530
16343
  this.owned = owned;
16344
+ this.schedules = { call: (id, request) => this.callSchedule(id, request) };
16345
+ this.plugins = { completeSignIn: (signIn) => this.completeSignIn(signIn) };
15531
16346
  }
15532
- /** 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. */
15533
16348
  static async start(options = {}) {
15534
16349
  const found = binaries();
15535
16350
  const process = Process.start({
15536
16351
  executable: found.core,
15537
- release: found.release,
15538
- ...options.publicUrl === void 0 ? {} : { publicUrl: options.publicUrl }
16352
+ release: found.release
15539
16353
  });
15540
- const jush = new Jush(process, options.plugins ?? [], () => found.runner, true);
15541
- await process.greet((fetch) => jush.greet(fetch));
15542
- return jush;
16354
+ return Jush.greeted(new Jush(process, options.plugins ?? [], options.addresses, () => found.runner, true));
15543
16355
  }
15544
16356
  /**
15545
16357
  * Connects to a process that runs on its own, and declares the program's
15546
- * plugins: the cores it holds, their conversations and their turns went
15547
- * on while the program was away. A connection made again, as after the
15548
- * process restarted, declares them again and opens the program's cores
15549
- * 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.
15550
16362
  */
15551
16363
  static async connect(connection) {
15552
16364
  const process = Process.connect({
15553
16365
  url: connection.url,
15554
16366
  token: connection.token
15555
16367
  });
15556
- const jush = new Jush(process, connection.plugins ?? [], () => binaries().runner, false);
15557
- 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
+ }
15558
16382
  return jush;
15559
16383
  }
15560
16384
  /**
@@ -15573,25 +16397,17 @@ var Jush = class Jush {
15573
16397
  process: this.process,
15574
16398
  id,
15575
16399
  dir: path,
15576
- plugins: this.plugins,
16400
+ plugins: this.declared,
15577
16401
  runner: this.runner
15578
16402
  }, async () => {
15579
16403
  this.cores.delete(id);
15580
- await (await this.call("DELETE", `/cores/${encodeURIComponent(id)}`)).body?.cancel();
16404
+ await (await this.call("DELETE", `/cores/${segment(id)}`)).body?.cancel();
15581
16405
  });
15582
16406
  this.cores.set(id, core);
15583
16407
  await core.follow();
15584
16408
  return core;
15585
16409
  }
15586
16410
  /**
15587
- * Answers a call of a schedule's URL, `/hooks/{id}` below `base`, as the
15588
- * program's server forwards it.
15589
- */
15590
- fetch(request, base = "") {
15591
- const url = new URL(request.url);
15592
- return this.process.fetch(new Request(PROCESS_ORIGIN + below(url.pathname, base) + url.search, request));
15593
- }
15594
- /**
15595
16411
  * Ends the program's use of Jush: a process the program started closes
15596
16412
  * every core and exits; one on its own keeps its cores, which the
15597
16413
  * program's next run opens again.
@@ -15604,12 +16420,43 @@ var Jush = class Jush {
15604
16420
  await this.process.close();
15605
16421
  }
15606
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
+ /**
15607
16453
  * What each connection to the process begins with: the program's
15608
- * plugins, then its cores, which a process that restarted holds no
15609
- * longer.
16454
+ * addresses and plugins, then its cores, which a process that
16455
+ * restarted holds no longer.
15610
16456
  */
15611
16457
  async greet(fetch) {
15612
- 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();
15613
16460
  for (const core of this.cores.values()) await (await this.call("POST", "/cores", { dir: core.dir }, fetch)).body?.cancel();
15614
16461
  }
15615
16462
  async call(method, path, body, fetch = (request) => this.process.fetch(request)) {
@@ -15624,5 +16471,26 @@ var Jush = class Jush {
15624
16471
  return response;
15625
16472
  }
15626
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
+ }
15627
16495
  //#endregion
15628
- 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 };