@alva-ai/toolkit 0.28.0 → 0.28.1-beta.1

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/cli.js CHANGED
@@ -9200,7 +9200,6 @@ var MarketsResource = class {
9200
9200
  // src/resources/schedules.ts
9201
9201
  var SCHEDULE_FIELDS = `
9202
9202
  id
9203
- channel { id }
9204
9203
  name
9205
9204
  rule { kind atMs everyIntervalSeconds cronExpression cronTimezone }
9206
9205
  bounds { startsAtMs untilMs maxOccurrences }
@@ -9217,7 +9216,7 @@ var LIST_SCHEDULES = `
9217
9216
  query ToolkitListAgentSchedules($channelId: ID!, $after: String) {
9218
9217
  viewer { channel(id: $channelId) {
9219
9218
  schedules(input: { first: 64, after: $after }) {
9220
- edges { node { ${SCHEDULE_FIELDS} } }
9219
+ edges { node { channel { id } ${SCHEDULE_FIELDS} } }
9221
9220
  pageInfo { hasNextPage endCursor }
9222
9221
  }
9223
9222
  } }
@@ -9225,6 +9224,20 @@ query ToolkitListAgentSchedules($channelId: ID!, $after: String) {
9225
9224
  var UPDATE_SCHEDULE = `
9226
9225
  mutation ToolkitUpdateAgentSchedule($input: UpdateChannelScheduleInput!) {
9227
9226
  updateChannelSchedule(input: $input) {
9227
+ schedule { channel { id } ${SCHEDULE_FIELDS} }
9228
+ deleted
9229
+ }
9230
+ }`.trim();
9231
+ var LIST_SESSION_SCHEDULES = `
9232
+ query ToolkitListSessionSchedules($inboxPath: String!, $after: String) {
9233
+ viewer { sessionSchedules(inboxPath: $inboxPath, input: { first: 64, after: $after }) {
9234
+ edges { node { ${SCHEDULE_FIELDS} } }
9235
+ pageInfo { hasNextPage endCursor }
9236
+ } }
9237
+ }`.trim();
9238
+ var UPDATE_SESSION_SCHEDULE = `
9239
+ mutation ToolkitUpdateSessionSchedule($input: UpdateSessionScheduleInput!) {
9240
+ updateSessionSchedule(input: $input) {
9228
9241
  schedule { ${SCHEDULE_FIELDS} }
9229
9242
  deleted
9230
9243
  }
@@ -9235,6 +9248,7 @@ query ToolkitAgentChannel {
9235
9248
  }`.trim();
9236
9249
  var SCHEDULE_NAME = /^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/;
9237
9250
  var RFC3339 = /^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})(Z|[+-](\d{2}):(\d{2}))$/i;
9251
+ var RFC3339_FRACTIONAL = /^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})(?:\.\d{1,9})?(Z|[+-](\d{2}):(\d{2}))$/i;
9238
9252
  var ISO_DURATION = /^P(?:(\d+)D)?(?:T(?:(\d+)H)?(?:(\d+)M)?(?:(\d+)S)?)?$/;
9239
9253
  var GRAPHQL_STATUS_BY_CODE = {
9240
9254
  INVALID_ARGUMENT: 400,
@@ -9258,16 +9272,17 @@ var SchedulesResource = class {
9258
9272
  client;
9259
9273
  async list(params) {
9260
9274
  this.client._requireAuth();
9261
- const id = channelID(params.channelId);
9275
+ const target = targetInput(params);
9276
+ const inbox = "inboxPath" in target;
9262
9277
  const schedules = [];
9263
9278
  let after = null;
9264
9279
  const seenCursors = /* @__PURE__ */ new Set();
9265
9280
  for (; ; ) {
9266
9281
  const data = await this.graphql(
9267
- LIST_SCHEDULES,
9268
- { channelId: id, after }
9282
+ inbox ? LIST_SESSION_SCHEDULES : LIST_SCHEDULES,
9283
+ { ...target, after }
9269
9284
  );
9270
- const connection2 = data.viewer?.channel?.schedules;
9285
+ const connection2 = inbox ? data.viewer?.sessionSchedules : data.viewer?.channel?.schedules;
9271
9286
  if (!connection2?.edges) throw scheduleNotFound();
9272
9287
  for (const edge of connection2.edges) {
9273
9288
  if (!edge?.node) throw scheduleEmptyResponse();
@@ -9283,15 +9298,14 @@ var SchedulesResource = class {
9283
9298
  async put(params) {
9284
9299
  this.client._requireAuth();
9285
9300
  const input = {
9286
- channelId: channelID(params.channelId),
9301
+ ...targetInput(params),
9287
9302
  name: requireName(params.name),
9288
9303
  definition: {
9289
9304
  ...ruleInput(params.rule, params.bounds),
9290
9305
  message: { text: requireText(params.text) }
9291
9306
  }
9292
9307
  };
9293
- const data = await this.graphql(UPDATE_SCHEDULE, { input });
9294
- const schedule = data.updateChannelSchedule?.schedule;
9308
+ const schedule = (await this.update(input))?.schedule;
9295
9309
  if (!schedule) throw scheduleEmptyResponse();
9296
9310
  return fromWireSchedule(schedule);
9297
9311
  }
@@ -9303,11 +9317,11 @@ var SchedulesResource = class {
9303
9317
  }
9304
9318
  async delete(params) {
9305
9319
  this.client._requireAuth();
9306
- const data = await this.graphql(UPDATE_SCHEDULE, {
9307
- input: { ...managementInput(params), lifecycle: "REMOVED" }
9320
+ const result = await this.update({
9321
+ ...managementInput(params),
9322
+ lifecycle: "REMOVED"
9308
9323
  });
9309
- if (data.updateChannelSchedule?.deleted !== true)
9310
- throw scheduleEmptyResponse();
9324
+ if (result?.deleted !== true) throw scheduleEmptyResponse();
9311
9325
  }
9312
9326
  /** Resolve the authenticated viewer's unique Agent Channel for CLI defaults. */
9313
9327
  async agentChannelId() {
@@ -9321,13 +9335,15 @@ var SchedulesResource = class {
9321
9335
  }
9322
9336
  async manage(lifecycle, params) {
9323
9337
  this.client._requireAuth();
9324
- const data = await this.graphql(UPDATE_SCHEDULE, {
9325
- input: { ...managementInput(params), lifecycle }
9326
- });
9327
- const schedule = data.updateChannelSchedule?.schedule;
9338
+ const schedule = (await this.update({ ...managementInput(params), lifecycle }))?.schedule;
9328
9339
  if (!schedule) throw scheduleEmptyResponse();
9329
9340
  return fromWireSchedule(schedule);
9330
9341
  }
9342
+ async update(input) {
9343
+ const inbox = "inboxPath" in input;
9344
+ const data = await this.graphql(inbox ? UPDATE_SESSION_SCHEDULE : UPDATE_SCHEDULE, { input });
9345
+ return inbox ? data.updateSessionSchedule : data.updateChannelSchedule;
9346
+ }
9331
9347
  async graphql(query, variables) {
9332
9348
  const response = await this.client._request("POST", "/query", {
9333
9349
  body: variables === void 0 ? { query } : { query, variables }
@@ -9478,10 +9494,24 @@ function fromWireRule(rule) {
9478
9494
  }
9479
9495
  function managementInput(params) {
9480
9496
  return {
9481
- channelId: channelID(params.channelId),
9497
+ ...targetInput(params),
9482
9498
  name: requireName(params.name)
9483
9499
  };
9484
9500
  }
9501
+ function targetInput(target) {
9502
+ if (target.channelId !== void 0 === (target.inboxPath !== void 0))
9503
+ throw invalid("exactly one of channelId or inboxPath is required");
9504
+ if (target.channelId !== void 0)
9505
+ return { channelId: channelID(target.channelId) };
9506
+ const path = target.inboxPath;
9507
+ const size = typeof path === "string" ? utf8Size(path) : void 0;
9508
+ if (typeof path !== "string" || size === void 0 || size > 2048 || !path.startsWith("/") || path.includes("\0") || path.slice(1).split("/").some((segment) => segment === "" || segment === "." || segment === ".."))
9509
+ throw invalid("inboxPath must be a canonical absolute ALFS Inbox path");
9510
+ const transcript = path.endsWith(".inbox.jsonl") ? path.slice(0, -".inbox.jsonl".length) + ".jsonl" : path.endsWith(".inbox") && !path.endsWith(".jsonl.inbox") ? path.slice(0, -".inbox".length) : void 0;
9511
+ if (transcript === void 0 || /\.inbox(?:\.jsonl)?$/.test(transcript) || /\.lock(?:\.recovery|\.heartbeat-[^/]+|\.stale-[^/]+)?$/.test(transcript) || transcript.endsWith("/.jsonl"))
9512
+ throw invalid("inboxPath must identify a standard Session Inbox sidecar");
9513
+ return { inboxPath: path };
9514
+ }
9485
9515
  function channelID(value) {
9486
9516
  if (typeof value === "number" && (!Number.isSafeInteger(value) || value <= 0)) {
9487
9517
  throw invalid(
@@ -9526,8 +9556,11 @@ function durationMilliseconds(value, minimumSeconds) {
9526
9556
  if (!Number.isSafeInteger(result)) throw invalid("duration is out of range");
9527
9557
  return result;
9528
9558
  }
9529
- function timestampMilliseconds(value) {
9530
- const match = RFC3339.exec(value);
9559
+ function parseRfc3339Milliseconds(value) {
9560
+ return timestampMilliseconds(value, true);
9561
+ }
9562
+ function timestampMilliseconds(value, fractional = false) {
9563
+ const match = (fractional ? RFC3339_FRACTIONAL : RFC3339).exec(value);
9531
9564
  if (!match) throw invalid("timestamp must be RFC3339 with a timezone");
9532
9565
  const [year, month, day, hour, minute, second] = match.slice(1, 7).map(Number);
9533
9566
  const offsetHour = Number(match[8] ?? 0);
@@ -9570,6 +9603,243 @@ function scheduleEmptyResponse() {
9570
9603
  );
9571
9604
  }
9572
9605
 
9606
+ // src/resources/steward.ts
9607
+ var GRAPHQL_STATUS_BY_CODE2 = {
9608
+ INVALID_ARGUMENT: 400,
9609
+ UNAUTHENTICATED: 401,
9610
+ PERMISSION_DENIED: 403,
9611
+ NOT_FOUND: 404,
9612
+ ALREADY_EXISTS: 409,
9613
+ ABORTED: 409,
9614
+ FAILED_PRECONDITION: 412,
9615
+ RESOURCE_EXHAUSTED: 429,
9616
+ INTERNAL: 500,
9617
+ UNKNOWN: 500,
9618
+ DATA_LOSS: 500,
9619
+ UNAVAILABLE: 503,
9620
+ DEADLINE_EXCEEDED: 504
9621
+ };
9622
+ var DECIDE = `
9623
+ mutation ToolkitStewardDecide($input: UpdateStewardDeliveryInput!) {
9624
+ updateStewardDelivery(input: $input) { delivery { deliveryId state } }
9625
+ }`.trim();
9626
+ var FORWARD = `
9627
+ mutation ToolkitStewardForward($input: UpdateStewardDeliveryInput!) {
9628
+ updateStewardDelivery(input: $input) { delivery { deliveryId state channelMessageId } }
9629
+ }`.trim();
9630
+ var SEND = `
9631
+ mutation ToolkitStewardSend($input: PostStewardMessageInput!) {
9632
+ postStewardMessage(input: $input) { message { channelMessageId requestId } }
9633
+ }`.trim();
9634
+ var PENDING = `
9635
+ query ToolkitStewardPending($inboxPath: String!, $input: StewardDigestPendingInput) {
9636
+ viewer {
9637
+ stewardDigestPending(inboxPath: $inboxPath, input: $input) {
9638
+ edges {
9639
+ cursor
9640
+ node { deliveryId feedEntryId source { kind id } decisionReason consumedAtMs }
9641
+ }
9642
+ pageInfo { hasNextPage endCursor }
9643
+ windowSinceMs
9644
+ windowUntilMs
9645
+ }
9646
+ }
9647
+ }`.trim();
9648
+ var BRIEFED = `
9649
+ mutation ToolkitStewardBriefed($input: CompleteStewardBriefInput!) {
9650
+ completeStewardBrief(input: $input) { ok }
9651
+ }`.trim();
9652
+ var DECISIONS = /* @__PURE__ */ new Set([
9653
+ "immediate",
9654
+ "digest",
9655
+ "suppress"
9656
+ ]);
9657
+ var DELIVERY_ID = /^[1-9][0-9]{0,18}$/;
9658
+ function invalid2(message) {
9659
+ return new AlvaError("INVALID_ARGUMENT", message, 400);
9660
+ }
9661
+ function requireInboxPath(target) {
9662
+ if (!target || typeof target.inboxPath !== "string" || target.inboxPath === "")
9663
+ throw invalid2("steward commands require the steward Session Inbox path");
9664
+ return target.inboxPath;
9665
+ }
9666
+ function requireDeliveryId(value, label = "delivery id") {
9667
+ if (!DELIVERY_ID.test(value))
9668
+ throw invalid2(`${label} must be a positive integer`);
9669
+ return value;
9670
+ }
9671
+ function requireDeliveryIds(values) {
9672
+ if (values.length === 0)
9673
+ throw invalid2("at least one delivery id is required");
9674
+ const unique = /* @__PURE__ */ new Set();
9675
+ for (const value of values) {
9676
+ requireDeliveryId(value);
9677
+ if (unique.has(value)) throw invalid2(`duplicate delivery id ${value}`);
9678
+ unique.add(value);
9679
+ }
9680
+ return [...unique];
9681
+ }
9682
+ function requireDecision(value) {
9683
+ if (!DECISIONS.has(value))
9684
+ throw invalid2("decision must be one of immediate, digest, suppress");
9685
+ return value;
9686
+ }
9687
+ function generateRequestId() {
9688
+ const webcrypto = globalThis.crypto;
9689
+ if (typeof webcrypto?.randomUUID === "function")
9690
+ return webcrypto.randomUUID();
9691
+ const bytes = new Uint8Array(16);
9692
+ if (typeof webcrypto?.getRandomValues === "function") {
9693
+ webcrypto.getRandomValues(bytes);
9694
+ } else {
9695
+ for (let i = 0; i < bytes.length; i += 1)
9696
+ bytes[i] = Math.floor(Math.random() * 256);
9697
+ }
9698
+ bytes[6] = bytes[6] & 15 | 64;
9699
+ bytes[8] = bytes[8] & 63 | 128;
9700
+ const hex = Array.from(bytes, (b) => b.toString(16).padStart(2, "0")).join(
9701
+ ""
9702
+ );
9703
+ return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`;
9704
+ }
9705
+ function requireRequestId(value) {
9706
+ if (value === void 0) return generateRequestId();
9707
+ if (!/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(
9708
+ value
9709
+ ))
9710
+ throw invalid2("request id must be a UUID");
9711
+ return value;
9712
+ }
9713
+ function emptyResponse() {
9714
+ return new AlvaError("EMPTY_RESPONSE", "steward response was empty", 502);
9715
+ }
9716
+ var StewardResource = class {
9717
+ constructor(client) {
9718
+ this.client = client;
9719
+ }
9720
+ client;
9721
+ async decide(params) {
9722
+ this.client._requireAuth();
9723
+ const reason = params.reason?.trim();
9724
+ if (!reason) throw invalid2("a decision reason is required");
9725
+ const data = await this.graphql(DECIDE, {
9726
+ input: {
9727
+ inboxPath: requireInboxPath(params),
9728
+ deliveryId: requireDeliveryId(params.deliveryId),
9729
+ decision: {
9730
+ decision: requireDecision(params.decision).toUpperCase(),
9731
+ reason
9732
+ }
9733
+ }
9734
+ });
9735
+ const delivery = data.updateStewardDelivery?.delivery;
9736
+ if (!delivery) throw emptyResponse();
9737
+ return { state: delivery.state };
9738
+ }
9739
+ async forward(params) {
9740
+ this.client._requireAuth();
9741
+ const data = await this.graphql(FORWARD, {
9742
+ input: {
9743
+ inboxPath: requireInboxPath(params),
9744
+ deliveryId: requireDeliveryId(params.deliveryId),
9745
+ forward: { requestId: requireRequestId(params.requestId) }
9746
+ }
9747
+ });
9748
+ const delivery = data.updateStewardDelivery?.delivery;
9749
+ if (!delivery || !delivery.channelMessageId) throw emptyResponse();
9750
+ return {
9751
+ channelMessageId: delivery.channelMessageId,
9752
+ state: delivery.state
9753
+ };
9754
+ }
9755
+ async send(params) {
9756
+ this.client._requireAuth();
9757
+ if (typeof params.body !== "string" || params.body.trim() === "")
9758
+ throw invalid2("a message body is required");
9759
+ const data = await this.graphql(SEND, {
9760
+ input: {
9761
+ inboxPath: requireInboxPath(params),
9762
+ requestId: requireRequestId(params.requestId),
9763
+ body: params.body,
9764
+ deliveryIds: requireDeliveryIds(params.deliveryIds)
9765
+ }
9766
+ });
9767
+ const message = data.postStewardMessage?.message;
9768
+ if (!message) throw emptyResponse();
9769
+ return message;
9770
+ }
9771
+ async pending(params) {
9772
+ this.client._requireAuth();
9773
+ const first = params.first ?? 50;
9774
+ if (!Number.isInteger(first) || first < 1 || first > 100)
9775
+ throw invalid2("first must be an integer between 1 and 100");
9776
+ const input = { first };
9777
+ if (params.after !== void 0 && params.after !== "") {
9778
+ input.after = params.after;
9779
+ } else {
9780
+ for (const [label, value] of [
9781
+ ["sinceMs", params.sinceMs],
9782
+ ["untilMs", params.untilMs]
9783
+ ]) {
9784
+ if (value !== void 0 && (!Number.isSafeInteger(value) || value <= 0))
9785
+ throw invalid2(`${label} must be a positive safe integer timestamp`);
9786
+ }
9787
+ if (params.sinceMs !== void 0 && params.untilMs !== void 0 && params.untilMs <= params.sinceMs)
9788
+ throw invalid2("untilMs must be after sinceMs");
9789
+ if (params.sinceMs !== void 0) input.sinceMs = params.sinceMs;
9790
+ if (params.untilMs !== void 0) input.untilMs = params.untilMs;
9791
+ }
9792
+ const data = await this.graphql(PENDING, { inboxPath: requireInboxPath(params), input });
9793
+ const page = data.viewer?.stewardDigestPending;
9794
+ if (!page || !Array.isArray(page.edges)) throw emptyResponse();
9795
+ const windowSinceMs = page.windowSinceMs ?? 0;
9796
+ const windowUntilMs = page.windowUntilMs ?? 0;
9797
+ if (!Number.isSafeInteger(windowSinceMs) || !Number.isSafeInteger(windowUntilMs) || windowSinceMs <= 0 || windowUntilMs <= windowSinceMs)
9798
+ throw emptyResponse();
9799
+ const items = page.edges.map((edge) => edge.node);
9800
+ const nextCursor = page.pageInfo?.hasNextPage === true && page.pageInfo.endCursor ? page.pageInfo.endCursor : null;
9801
+ return {
9802
+ items,
9803
+ nextCursor,
9804
+ windowSinceMs,
9805
+ windowUntilMs
9806
+ };
9807
+ }
9808
+ async briefed(params) {
9809
+ this.client._requireAuth();
9810
+ const digestRunId = params.digestRunId?.trim();
9811
+ if (!digestRunId) throw invalid2("a digest run id is required");
9812
+ const data = await this.graphql(BRIEFED, {
9813
+ input: {
9814
+ inboxPath: requireInboxPath(params),
9815
+ deliveryIds: requireDeliveryIds(params.deliveryIds),
9816
+ digestRunId
9817
+ }
9818
+ });
9819
+ if (data.completeStewardBrief?.ok !== true) throw emptyResponse();
9820
+ return { ok: true };
9821
+ }
9822
+ async graphql(query, variables) {
9823
+ const response = await this.client._request("POST", "/query", {
9824
+ body: { query, variables }
9825
+ });
9826
+ if (!response || typeof response !== "object") throw emptyResponse();
9827
+ if (response.errors?.length) {
9828
+ const codes = response.errors.map((error) => error.extensions?.code);
9829
+ const canonicalCode = new Set(codes).size === 1 && typeof codes[0] === "string" ? codes[0] : void 0;
9830
+ const canonicalStatus = canonicalCode ? GRAPHQL_STATUS_BY_CODE2[canonicalCode] : void 0;
9831
+ throw new AlvaError(
9832
+ canonicalCode !== void 0 && canonicalStatus !== void 0 ? canonicalCode : "GRAPHQL_ERROR",
9833
+ response.errors.map((error) => error.message).filter((message) => typeof message === "string").join("; ") || "GraphQL request failed",
9834
+ canonicalStatus ?? 502,
9835
+ { errors: response.errors }
9836
+ );
9837
+ }
9838
+ if (!response.data) throw emptyResponse();
9839
+ return response.data;
9840
+ }
9841
+ };
9842
+
9573
9843
  // src/resources/tradingPairs.ts
9574
9844
  function isRecord(value) {
9575
9845
  return typeof value === "object" && value !== null && !Array.isArray(value);
@@ -9755,14 +10025,357 @@ var TradingPairsResource = class {
9755
10025
  }
9756
10026
  };
9757
10027
 
10028
+ // src/resources/theses.ts
10029
+ var MAX_SIGNED_INT64 = 9223372036854775807n;
10030
+ var UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
10031
+ var UNPAIRED_SURROGATE = /[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?<![\uD800-\uDBFF])[\uDC00-\uDFFF]/;
10032
+ var encoder = new TextEncoder();
10033
+ var ThesesResource = class {
10034
+ constructor(client) {
10035
+ this.client = client;
10036
+ }
10037
+ client;
10038
+ async create(params) {
10039
+ this.client._requireAuth();
10040
+ const body = createBody(params);
10041
+ return thesisResponse(
10042
+ await this.client._request("POST", "/api/v1/theses", { body })
10043
+ );
10044
+ }
10045
+ async get(id) {
10046
+ this.client._requireAuth();
10047
+ return thesisGetResponse(
10048
+ await this.client._request("GET", `/api/v1/theses/${requireID(id, "id")}`)
10049
+ );
10050
+ }
10051
+ async update(id, params) {
10052
+ this.client._requireAuth();
10053
+ const body = updateBody(params);
10054
+ return thesisResponse(
10055
+ await this.client._request(
10056
+ "PUT",
10057
+ `/api/v1/theses/${requireID(id, "id")}`,
10058
+ {
10059
+ body
10060
+ }
10061
+ )
10062
+ );
10063
+ }
10064
+ async setVisibility(id, params) {
10065
+ this.client._requireAuth();
10066
+ if (!params) {
10067
+ throw invalidArgument("params is required");
10068
+ }
10069
+ const thesisID = requireID(id, "id");
10070
+ const visibility = requireVisibility(params.visibility);
10071
+ const response = thesisResponse(
10072
+ await this.client._request(
10073
+ "POST",
10074
+ `/api/v1/theses/${thesisID}/visibility`,
10075
+ { body: { visibility } }
10076
+ )
10077
+ );
10078
+ if (response.thesis.id !== thesisID || response.thesis.visibility !== visibility) {
10079
+ throw invalidResponse2(
10080
+ "visibility response must match the requested thesis and visibility"
10081
+ );
10082
+ }
10083
+ return response;
10084
+ }
10085
+ async close(id, params) {
10086
+ this.client._requireAuth();
10087
+ const body = {
10088
+ expected_author_version_id: requireID(
10089
+ params.expected_author_version_id,
10090
+ "expected_author_version_id"
10091
+ )
10092
+ };
10093
+ if (params.note !== void 0) body.note = requireText2(params.note, "note");
10094
+ return thesisResponse(
10095
+ await this.client._request(
10096
+ "POST",
10097
+ `/api/v1/theses/${requireID(id, "id")}/close`,
10098
+ { body }
10099
+ )
10100
+ );
10101
+ }
10102
+ async delete(id) {
10103
+ this.client._requireAuth();
10104
+ const response = await this.client._request(
10105
+ "DELETE",
10106
+ `/api/v1/theses/${requireID(id, "id")}`
10107
+ );
10108
+ if (response === void 0) return {};
10109
+ if (!isRecord2(response) || Object.keys(response).length !== 0) {
10110
+ throw invalidResponse2("delete response must be {}");
10111
+ }
10112
+ return {};
10113
+ }
10114
+ async rewrite(params) {
10115
+ this.client._requireAuth();
10116
+ const body = requireBody(params.body);
10117
+ const mode = params.mode === void 0 ? "reformat" : requireRewriteMode(params.mode);
10118
+ const response = await this.client._request(
10119
+ "POST",
10120
+ "/api/v1/theses/rewrite",
10121
+ {
10122
+ body: { body, mode }
10123
+ }
10124
+ );
10125
+ if (!isRecord2(response) || typeof response.body !== "string") {
10126
+ throw invalidResponse2("rewrite response must contain a string body");
10127
+ }
10128
+ return { body: responseBody(response.body) };
10129
+ }
10130
+ };
10131
+ function createBody(params) {
10132
+ const body = {
10133
+ request_id: requireRequestID(params.request_id),
10134
+ body: requireBody(params.body),
10135
+ title: requireTitle(params.title ?? ""),
10136
+ entity_ids: requireIDs(params.entity_ids ?? [], "entity_ids"),
10137
+ visibility: requireVisibility(params.visibility ?? "public")
10138
+ };
10139
+ if (params.tickers !== void 0)
10140
+ body.tickers = requireTickers(params.tickers);
10141
+ return body;
10142
+ }
10143
+ function updateBody(params) {
10144
+ return {
10145
+ request_id: requireRequestID(params.request_id),
10146
+ expected_author_version_id: requireID(
10147
+ params.expected_author_version_id,
10148
+ "expected_author_version_id"
10149
+ ),
10150
+ body: requireBody(params.body),
10151
+ title: requireTitle(params.title ?? ""),
10152
+ entity_ids: requireIDs(params.entity_ids ?? [], "entity_ids"),
10153
+ visibility: requireVisibility(params.visibility),
10154
+ editorial: params.editorial ?? false
10155
+ };
10156
+ }
10157
+ function thesisResponse(response) {
10158
+ if (!isRecord2(response) || !isRecord2(response.thesis)) {
10159
+ throw invalidResponse2("response must contain thesis");
10160
+ }
10161
+ const thesis = response.thesis;
10162
+ const value = {
10163
+ id: responseID(thesis.id, "thesis.id"),
10164
+ author_version_id: responseID(
10165
+ thesis.author_version_id,
10166
+ "thesis.author_version_id"
10167
+ ),
10168
+ material_version_id: responseID(
10169
+ thesis.material_version_id,
10170
+ "thesis.material_version_id"
10171
+ ),
10172
+ title: responseTitle(thesis.title),
10173
+ body: responseBody(thesis.body),
10174
+ entity_ids: responseIDs(thesis.entity_ids, "thesis.entity_ids"),
10175
+ visibility: responseVisibility(thesis.visibility),
10176
+ closed: responseBoolean(thesis.closed, "thesis.closed"),
10177
+ closing_note: responseClosingNote(thesis.closing_note),
10178
+ author_kind: responseText(thesis.author_kind, "thesis.author_kind"),
10179
+ author_ref: responseText(thesis.author_ref, "thesis.author_ref")
10180
+ };
10181
+ return { thesis: value };
10182
+ }
10183
+ function thesisGetResponse(response) {
10184
+ const base = thesisResponse(response);
10185
+ if (!isRecord2(response) || !isRecord2(response.author)) {
10186
+ throw invalidResponse2("response must contain author");
10187
+ }
10188
+ const authorRecord = response.author;
10189
+ const author = {
10190
+ id: responseID(authorRecord.id, "author.id"),
10191
+ kind: responseText(authorRecord.kind, "author.kind"),
10192
+ display_name: responseText(
10193
+ authorRecord.display_name,
10194
+ "author.display_name"
10195
+ ),
10196
+ avatar_url: responseText(authorRecord.avatar_url, "author.avatar_url"),
10197
+ username: responseText(authorRecord.username, "author.username")
10198
+ };
10199
+ if (!Array.isArray(response.entities)) {
10200
+ throw invalidResponse2("response must contain entities");
10201
+ }
10202
+ if (response.entities.length !== base.thesis.entity_ids.length) {
10203
+ throw invalidResponse2("entities must match thesis.entity_ids");
10204
+ }
10205
+ const entities = response.entities.map((item, index) => {
10206
+ if (!isRecord2(item))
10207
+ throw invalidResponse2(`entities[${index}] must be an object`);
10208
+ const entity = {
10209
+ id: responseID(item.id, `entities[${index}].id`),
10210
+ ticker: responseText(item.ticker, `entities[${index}].ticker`),
10211
+ name: responseText(item.name, `entities[${index}].name`),
10212
+ icon_url: responseText(item.icon_url, `entities[${index}].icon_url`),
10213
+ kind: responseText(item.kind, `entities[${index}].kind`)
10214
+ };
10215
+ if (entity.id !== base.thesis.entity_ids[index]) {
10216
+ throw invalidResponse2("entities must preserve thesis.entity_ids order");
10217
+ }
10218
+ return entity;
10219
+ });
10220
+ return { thesis: base.thesis, author, entities };
10221
+ }
10222
+ function requireRequestID(value) {
10223
+ if (!UUID.test(value) || /^0{8}-0{4}-0{4}-0{4}-0{12}$/i.test(value)) {
10224
+ throw invalidArgument("request_id must be a non-zero RFC 4122 UUID");
10225
+ }
10226
+ return value;
10227
+ }
10228
+ function requireID(value, field) {
10229
+ if (typeof value !== "string" || !/^[1-9]\d*$/.test(value)) {
10230
+ throw invalidArgument(`${field} must be a positive int64 decimal string`);
10231
+ }
10232
+ const parsed = BigInt(value);
10233
+ if (parsed > MAX_SIGNED_INT64) {
10234
+ throw invalidArgument(`${field} must be a positive int64 decimal string`);
10235
+ }
10236
+ return value;
10237
+ }
10238
+ function requireIDs(value, field) {
10239
+ if (!Array.isArray(value)) throw invalidArgument(`${field} must be an array`);
10240
+ if (value.length > 20) {
10241
+ throw invalidArgument(`${field} must contain at most 20 IDs`);
10242
+ }
10243
+ return value.map((item, index) => requireID(item, `${field}[${index}]`));
10244
+ }
10245
+ function requireTickers(value) {
10246
+ if (!Array.isArray(value)) throw invalidArgument("tickers must be an array");
10247
+ if (value.length > 100) {
10248
+ throw invalidArgument("tickers must contain at most 100 values");
10249
+ }
10250
+ return value.map((item, index) => {
10251
+ const ticker = requireText2(item, `tickers[${index}]`);
10252
+ if (ticker.trim() === "" || ticker.includes("\0")) {
10253
+ throw invalidArgument(`tickers[${index}] must be non-empty`);
10254
+ }
10255
+ return ticker;
10256
+ });
10257
+ }
10258
+ function requireBody(value) {
10259
+ const body = requireText2(value, "body");
10260
+ if (body.trim().length === 0) throw invalidArgument("body must not be blank");
10261
+ if (encoder.encode(body).byteLength > 65536) {
10262
+ throw invalidArgument("body must be at most 65536 UTF-8 bytes");
10263
+ }
10264
+ return body;
10265
+ }
10266
+ function requireTitle(value) {
10267
+ const title = requireText2(value, "title");
10268
+ if (encoder.encode(title).byteLength > 500) {
10269
+ throw invalidArgument("title must be at most 500 UTF-8 bytes");
10270
+ }
10271
+ return title;
10272
+ }
10273
+ function requireVisibility(value) {
10274
+ const visibility = requireText2(value, "visibility");
10275
+ if (visibility !== "public" && visibility !== "private") {
10276
+ throw invalidArgument("visibility must be public or private");
10277
+ }
10278
+ return visibility;
10279
+ }
10280
+ function requireRewriteMode(value) {
10281
+ const mode = requireText2(value, "mode");
10282
+ if (mode === "reformat" || mode === "shorten" || mode === "enrich") {
10283
+ return mode;
10284
+ }
10285
+ throw invalidArgument("mode must be reformat, shorten, or enrich");
10286
+ }
10287
+ function requireText2(value, field) {
10288
+ if (typeof value !== "string")
10289
+ throw invalidArgument(`${field} must be a string`);
10290
+ if (UNPAIRED_SURROGATE.test(value)) {
10291
+ throw invalidArgument(`${field} contains invalid Unicode`);
10292
+ }
10293
+ if ((field === "body" || field === "title" || field === "note") && value.includes("\0")) {
10294
+ throw invalidArgument(`${field} must not contain NUL`);
10295
+ }
10296
+ return value;
10297
+ }
10298
+ function responseID(value, field) {
10299
+ if (typeof value === "number") {
10300
+ throw invalidResponse2(
10301
+ `${field} must be a decimal string; numeric IDs are unsafe`
10302
+ );
10303
+ }
10304
+ try {
10305
+ return requireID(value, field);
10306
+ } catch {
10307
+ throw invalidResponse2(`${field} must be a positive int64 decimal string`);
10308
+ }
10309
+ }
10310
+ function responseIDs(value, field) {
10311
+ if (!Array.isArray(value)) throw invalidResponse2(`${field} must be an array`);
10312
+ if (value.length > 20) {
10313
+ throw invalidResponse2(`${field} must contain at most 20 IDs`);
10314
+ }
10315
+ return value.map((item, index) => responseID(item, `${field}[${index}]`));
10316
+ }
10317
+ function responseText(value, field) {
10318
+ try {
10319
+ return requireText2(value, field);
10320
+ } catch {
10321
+ throw invalidResponse2(`${field} must be valid text`);
10322
+ }
10323
+ }
10324
+ function responseClosingNote(value) {
10325
+ try {
10326
+ return requireText2(value, "note");
10327
+ } catch {
10328
+ throw invalidResponse2("thesis.closing_note must be valid text");
10329
+ }
10330
+ }
10331
+ function responseBoolean(value, field) {
10332
+ if (typeof value !== "boolean")
10333
+ throw invalidResponse2(`${field} must be boolean`);
10334
+ return value;
10335
+ }
10336
+ function responseVisibility(value) {
10337
+ try {
10338
+ return requireVisibility(value);
10339
+ } catch {
10340
+ throw invalidResponse2("thesis.visibility must be public or private");
10341
+ }
10342
+ }
10343
+ function responseBody(value) {
10344
+ try {
10345
+ return requireBody(value);
10346
+ } catch {
10347
+ throw invalidResponse2(
10348
+ "response body must be nonblank valid text at most 65536 UTF-8 bytes"
10349
+ );
10350
+ }
10351
+ }
10352
+ function responseTitle(value) {
10353
+ try {
10354
+ return requireTitle(value);
10355
+ } catch {
10356
+ throw invalidResponse2(
10357
+ "response title must be valid text at most 500 UTF-8 bytes"
10358
+ );
10359
+ }
10360
+ }
10361
+ function isRecord2(value) {
10362
+ return typeof value === "object" && value !== null && !Array.isArray(value);
10363
+ }
10364
+ function invalidArgument(message) {
10365
+ return new AlvaError("INVALID_ARGUMENT", message, 400);
10366
+ }
10367
+ function invalidResponse2(message) {
10368
+ return new AlvaError("INVALID_RESPONSE", message, 502);
10369
+ }
10370
+
9758
10371
  // src/client.ts
9759
10372
  var DEFAULT_BASE_URL = "https://api-llm.prd.alva.ai";
9760
10373
  var DEFAULT_ARRAYS_BASE_URL = "https://data-tools.prd.space.id";
9761
- function isRecord2(value) {
10374
+ function isRecord3(value) {
9762
10375
  return typeof value === "object" && value !== null;
9763
10376
  }
9764
10377
  function stringField(value, field) {
9765
- if (!isRecord2(value)) return void 0;
10378
+ if (!isRecord3(value)) return void 0;
9766
10379
  const fieldValue = value[field];
9767
10380
  return typeof fieldValue === "string" && fieldValue ? fieldValue : void 0;
9768
10381
  }
@@ -9776,7 +10389,7 @@ function describeCause(cause) {
9776
10389
  if (cause.message) details.message = cause.message;
9777
10390
  const code = stringField(cause, "code");
9778
10391
  if (code) details.code = code;
9779
- } else if (isRecord2(cause)) {
10392
+ } else if (isRecord3(cause)) {
9780
10393
  const code = stringField(cause, "code");
9781
10394
  const name = stringField(cause, "name");
9782
10395
  const message = stringField(cause, "message");
@@ -9804,7 +10417,7 @@ function describeFetchFailure(err) {
9804
10417
  details.message = String(err);
9805
10418
  }
9806
10419
  const { message: causeMessage, details: causeDetails } = describeCause(
9807
- isRecord2(err) ? err.cause : void 0
10420
+ isRecord3(err) ? err.cause : void 0
9808
10421
  );
9809
10422
  if (causeDetails) {
9810
10423
  details.cause = causeDetails;
@@ -9835,6 +10448,8 @@ var AlvaClient = class {
9835
10448
  originSessionId;
9836
10449
  /** Session profile kind associated with originSessionId. */
9837
10450
  originSessionKind;
10451
+ /** Host-attached file Session target, distinct from the chat origin header. */
10452
+ originInboxPath;
9838
10453
  _fs;
9839
10454
  _run;
9840
10455
  _deploy;
@@ -9865,7 +10480,9 @@ var AlvaClient = class {
9865
10480
  _credits;
9866
10481
  _markets;
9867
10482
  _schedules;
10483
+ _steward;
9868
10484
  _tradingPairs;
10485
+ _theses;
9869
10486
  constructor(config) {
9870
10487
  this.baseUrl = config.baseUrl ?? DEFAULT_BASE_URL;
9871
10488
  this.arraysBaseUrl = config.arraysBaseUrl ?? DEFAULT_ARRAYS_BASE_URL;
@@ -9878,6 +10495,7 @@ var AlvaClient = class {
9878
10495
  this.signal = config.signal;
9879
10496
  this.originSessionId = config.originSessionId;
9880
10497
  this.originSessionKind = config.originSessionKind;
10498
+ this.originInboxPath = config.originInboxPath;
9881
10499
  }
9882
10500
  get fs() {
9883
10501
  return this._fs ??= new FsResource(this);
@@ -9969,6 +10587,12 @@ var AlvaClient = class {
9969
10587
  get schedules() {
9970
10588
  return this._schedules ??= new SchedulesResource(this);
9971
10589
  }
10590
+ get steward() {
10591
+ return this._steward ??= new StewardResource(this);
10592
+ }
10593
+ get theses() {
10594
+ return this._theses ??= new ThesesResource(this);
10595
+ }
9972
10596
  _requireAuth() {
9973
10597
  if (!this.pbsvToken && !this.viewer_token && !this.apiKey) {
9974
10598
  throw new AlvaError(
@@ -10389,10 +11013,11 @@ var COMMAND_DEFINITIONS = [
10389
11013
  values: ["id", "workflow-run-id"]
10390
11014
  }),
10391
11015
  command("deploy run-logs", { values: ["id", "run-id"] }),
10392
- command("schedule list", { values: ["channel-id"] }),
11016
+ command("schedule list", { values: ["channel-id", "inbox-path"] }),
10393
11017
  command("schedule put", {
10394
11018
  values: [
10395
11019
  "channel-id",
11020
+ "inbox-path",
10396
11021
  "name",
10397
11022
  "message",
10398
11023
  "at",
@@ -10405,9 +11030,59 @@ var COMMAND_DEFINITIONS = [
10405
11030
  "max-occurrences"
10406
11031
  ]
10407
11032
  }),
10408
- command("schedule pause", { values: ["channel-id", "name"] }),
10409
- command("schedule resume", { values: ["channel-id", "name"] }),
10410
- command("schedule delete", { values: ["channel-id", "name"] }),
11033
+ command("schedule pause", { values: ["channel-id", "inbox-path", "name"] }),
11034
+ command("schedule resume", { values: ["channel-id", "inbox-path", "name"] }),
11035
+ command("schedule delete", { values: ["channel-id", "inbox-path", "name"] }),
11036
+ command("steward decide", {
11037
+ values: ["inbox-path", "delivery-id", "decision", "reason"]
11038
+ }),
11039
+ command("steward forward", {
11040
+ values: ["inbox-path", "delivery-id", "request-id"]
11041
+ }),
11042
+ command("steward send", {
11043
+ values: ["inbox-path", "body", "delivery-ids", "request-id"]
11044
+ }),
11045
+ command("steward pending", {
11046
+ values: ["inbox-path", "after", "since", "until", "first"]
11047
+ }),
11048
+ command("steward briefed", {
11049
+ values: ["inbox-path", "delivery-ids", "digest-run-id"]
11050
+ }),
11051
+ command("thesis create", {
11052
+ values: [
11053
+ "request-id",
11054
+ "body",
11055
+ "body-file",
11056
+ "title",
11057
+ "entity-ids",
11058
+ "tickers",
11059
+ "visibility"
11060
+ ],
11061
+ booleans: ["body-stdin"]
11062
+ }),
11063
+ command("thesis get", { values: ["id"] }),
11064
+ command("thesis set-visibility", { values: ["id", "visibility"] }),
11065
+ command("thesis update", {
11066
+ values: [
11067
+ "id",
11068
+ "request-id",
11069
+ "expected-author-version-id",
11070
+ "body",
11071
+ "body-file",
11072
+ "title",
11073
+ "entity-ids",
11074
+ "visibility"
11075
+ ],
11076
+ booleans: ["body-stdin", "editorial"]
11077
+ }),
11078
+ command("thesis close", {
11079
+ values: ["id", "expected-author-version-id", "note"]
11080
+ }),
11081
+ command("thesis delete", { values: ["id"] }),
11082
+ command("thesis rewrite", {
11083
+ values: ["body", "body-file", "mode"],
11084
+ booleans: ["body-stdin"]
11085
+ }),
10411
11086
  command("service-account create", { values: ["name"] }),
10412
11087
  command("service-account list"),
10413
11088
  command("service-account delete", { values: ["id"] }),
@@ -15076,7 +15751,7 @@ function formatTradingPairResolved(result) {
15076
15751
  }
15077
15752
 
15078
15753
  // src/cli/dispatch.ts
15079
- var CLI_VERSION = true ? "0.28.0" : "dev";
15754
+ var CLI_VERSION = true ? "0.28.1-beta.1" : "dev";
15080
15755
  var DEFAULT_RUN_TIMEOUT_MS = 6e5;
15081
15756
  var RUN_TIMEOUT_ENV = "ALVA_RUN_TIMEOUT_MS";
15082
15757
  var GLOBAL_VALUE_FLAGS = Object.entries(GLOBAL_FLAG_DEFINITIONS).filter(([, kind]) => kind === "value").map(([name]) => `--${name}`);
@@ -15119,6 +15794,8 @@ Commands:
15119
15794
  run Execute code in the Alva runtime
15120
15795
  deploy Cronjob management (create, list, get, update, delete, pause, resume, runs, run-logs)
15121
15796
  schedule Agent-owned named schedules (list, put, pause, resume, delete)
15797
+ steward Push steward reports for a Session Inbox (decide, forward, send, pending, briefed)
15798
+ thesis Authored thesis lifecycle (create, get, set-visibility, update, close, delete, rewrite)
15122
15799
  service-account Restricted run-as identities (create, list, delete, grant, revoke)
15123
15800
  release Feed and playbook releases (feed, playbook-draft, playbook)
15124
15801
  lint Design-system lint (playbook)
@@ -15164,6 +15841,41 @@ Quick start:
15164
15841
  alva configure --api-key alva_your_key_here
15165
15842
  alva whoami`;
15166
15843
  var COMMAND_HELP = {
15844
+ steward: `Usage: alva steward <subcommand> [options]
15845
+
15846
+ Report a push steward's decisions for Feed alerts routed to its Session Inbox,
15847
+ forward or send messages to the steward's own Channel, and run the Daily Brief.
15848
+ Embedded commands target the host-attached Inbox; the terminal CLI requires
15849
+ --inbox-path.
15850
+
15851
+ Subcommands:
15852
+ decide Record the decision for one delivery (required before forward/send)
15853
+ forward Re-post the original alert card by reference (immediate only)
15854
+ send Post steward-authored Markdown covering the listed deliveries
15855
+ pending Page deliveries decided "digest" that no brief has covered yet
15856
+ briefed Record that a Daily Brief covered the listed deliveries
15857
+
15858
+ Flags:
15859
+ --inbox-path <path> Steward Session Inbox (terminal CLI only)
15860
+ --delivery-id <id> One delivery (decide, forward)
15861
+ --delivery-ids <a,b,c> Comma-separated deliveries (send, briefed)
15862
+ --decision <immediate|digest|suppress>
15863
+ --reason <text> Short audit note stored with the decision
15864
+ --body <markdown> Message body (send)
15865
+ --request-id <uuid> Idempotency key; generated when omitted
15866
+ --after <cursor> Opaque cursor from the previous page's nextCursor (pending)
15867
+ --since <RFC3339> First page only: lower bound on decision time (pending)
15868
+ --until <RFC3339> First page only: fixed upper bound of the Brief window; later pages inherit it through the cursor (pending)
15869
+ --first <n> Page size, 1-100 (pending)
15870
+ --digest-run-id <id> The request id echoed by the send that carried these deliveries (briefed)
15871
+
15872
+ Examples (terminal; the embedded Agent tool omits --inbox-path):
15873
+ alva steward decide --inbox-path /alva/home/alice/agents/steward-9/.pi/agent/sessions/main.inbox.jsonl --delivery-id 123 --decision immediate --reason "guidance cut 15%"
15874
+ alva steward forward --inbox-path <inbox> --delivery-id 123
15875
+ alva steward send --inbox-path <inbox> --delivery-ids 124,125 --body "Two related moves..."
15876
+ alva steward pending --inbox-path <inbox> --until 2026-09-15T13:00:00Z
15877
+ alva steward pending --inbox-path <inbox> --after <nextCursor from the previous page>
15878
+ alva steward briefed --inbox-path <inbox> --digest-run-id <request id echoed by send> --delivery-ids 124,125`,
15167
15879
  configure: `Usage: alva configure --api-key <key> [--base-url <url>] [--profile <name>]
15168
15880
 
15169
15881
  Save API credentials to ~/.config/alva/config.json (mode 0600).
@@ -15508,7 +16220,7 @@ Build-time verify (fire once, then poll up to 5 minutes):
15508
16220
  --run-id "$(echo "$STATUS_JSON" | jq -r .run.id)"`,
15509
16221
  schedule: `Usage: alva schedule <subcommand> [options]
15510
16222
 
15511
- Manage named future and recurring work for an Alva Channel Agent.
16223
+ Manage named future and recurring work for an Alva Channel Agent or Session Inbox.
15512
16224
 
15513
16225
  Subcommands:
15514
16226
  list List schedules
@@ -15519,6 +16231,7 @@ Subcommands:
15519
16231
 
15520
16232
  Common flags:
15521
16233
  --channel-id <id> Target Channel; omit for your Agent Channel
16234
+ --inbox-path <path> Existing Session Inbox; mutually exclusive with --channel-id
15522
16235
  --name <name> Stable schedule name
15523
16236
 
15524
16237
  Put flags:
@@ -15534,6 +16247,7 @@ Examples:
15534
16247
  alva schedule put --name review --message "Review status" --after PT30M
15535
16248
  alva schedule put --name market-open --message "Review the open" --cron "30 9 * * 1-5" --timezone America/New_York
15536
16249
  alva schedule list
16250
+ alva schedule put --inbox-path /alva/home/alice/session.inbox.jsonl --name review --message "Review status" --after PT30M
15537
16251
  alva schedule pause --name market-open`,
15538
16252
  "service-account": `Usage: alva service-account <subcommand> [options]
15539
16253
 
@@ -16403,7 +17117,59 @@ Subcommands:
16403
17117
 
16404
17118
  Examples:
16405
17119
  alva arrays token ensure
16406
- alva arrays token status`
17120
+ alva arrays token status`,
17121
+ thesis: `Usage: alva thesis <subcommand> [options]
17122
+
17123
+ Create, read, update, close, delete, or explicitly rewrite an authored thesis.
17124
+ Backend owns Signal/Alert setup; the CLI never starts them separately.
17125
+ Create and update never rewrite text automatically.
17126
+
17127
+ Subcommands:
17128
+ create Create a thesis
17129
+ get Get one thesis
17130
+ set-visibility Change current access without publishing a version
17131
+ update Replaces document fields: body, title, entities, visibility (all sent in full)
17132
+ close Close the current author version with an optional note
17133
+ delete Delete a thesis
17134
+ rewrite Explicitly request a candidate body rewrite; never called by another command
17135
+
17136
+ Body input (create, update, rewrite): choose exactly one:
17137
+ --body <text> Literal text
17138
+ --body-file <path> Local UTF-8 text file (terminal CLI only; malformed bytes fail)
17139
+ --body-stdin Read UTF-8 text from stdin (terminal CLI only; malformed bytes fail)
17140
+
17141
+ Create and update require --request-id: a caller-supplied non-zero UUID. The
17142
+ toolkit does not generate or retry request IDs. If a response is ambiguous
17143
+ after a write, reuse the same request ID only after resolving that ambiguity with
17144
+ the backend; do not send a fresh ID. Create defaults --visibility to public.
17145
+ Update requires --visibility explicitly so it cannot inadvertently publish.
17146
+
17147
+ Other flags:
17148
+ create --request-id <uuid> --body ... [--title <text>] [--tickers <ticker,ticker>] [--entity-ids <id,id>] [--visibility <value>]
17149
+ get --id <signed-int64-decimal>
17150
+ set-visibility --id <id> --visibility public|private
17151
+ update --id <id> --request-id <uuid> --expected-author-version-id <id> --body ... --visibility <value> [--title <text>] [--entity-ids <id,id>] [--editorial]
17152
+ close --id <id> --expected-author-version-id <id> [--note <text>]
17153
+ delete --id <id>
17154
+ rewrite --body ... [--mode reformat|shorten|enrich]
17155
+
17156
+ Rewrite mode defaults only when omitted, and the toolkit always sends the
17157
+ canonical default \`reformat\`. \`shorten\` removes redundancy while retaining the
17158
+ core view, reasons, and qualifiers. \`enrich\` only expands supplied reasoning;
17159
+ it must not invent factual evidence, numbers, or citations. Rewrite returns a
17160
+ candidate only: it never creates, updates, retries, or chooses a mode from body
17161
+ length or errors.
17162
+
17163
+ IDs are decimal strings, never JavaScript numbers; provide at most 20 entity
17164
+ IDs. Body text must be nonblank,
17165
+ valid Unicode, and at most 65536 UTF-8 bytes; title is optional and at most
17166
+ 500 UTF-8 bytes. Text is passed without trimming or newline conversion.
17167
+
17168
+ Examples:
17169
+ alva thesis create --request-id 123e4567-e89b-42d3-a456-426614174000 --body $'line one\\r\\nline two'
17170
+ alva thesis set-visibility --id 9223372036854775807 --visibility private
17171
+ alva thesis update --id 9223372036854775807 --request-id 123e4567-e89b-42d3-a456-426614174000 --expected-author-version-id 9223372036854775806 --body-file ./thesis.md --visibility private
17172
+ printf '%s' 'Draft body' | alva thesis rewrite --body-stdin --mode shorten`
16407
17173
  };
16408
17174
  function parseFlags(argv) {
16409
17175
  const flags = {};
@@ -16782,6 +17548,22 @@ function feedVisibility(val) {
16782
17548
  "feed"
16783
17549
  );
16784
17550
  }
17551
+ function thesisVisibility(value) {
17552
+ if (value === "public" || value === "private") return value;
17553
+ throw new CliUsageError(
17554
+ `--visibility must be public or private for 'thesis', got '${value}'`,
17555
+ "thesis"
17556
+ );
17557
+ }
17558
+ function thesisRewriteMode(value) {
17559
+ if (value === "reformat" || value === "shorten" || value === "enrich") {
17560
+ return value;
17561
+ }
17562
+ throw new CliUsageError(
17563
+ `--mode must be reformat, shorten, or enrich for 'thesis rewrite', got '${value}'`,
17564
+ "thesis"
17565
+ );
17566
+ }
16785
17567
  function parseCreditsTimestamp(value, flag, command2) {
16786
17568
  const trimmed = value.trim();
16787
17569
  if (/^\d+$/.test(trimmed)) {
@@ -16818,8 +17600,20 @@ function parseCreditsDurationMs(value) {
16818
17600
  }
16819
17601
  return durationMs;
16820
17602
  }
16821
- async function scheduleChannelId(client, flags) {
16822
- return flags["channel-id"] ?? client.schedules.agentChannelId();
17603
+ async function scheduleTarget(client, flags) {
17604
+ if (flags["inbox-path"] !== void 0) {
17605
+ if (flags["channel-id"] !== void 0)
17606
+ throw new CliUsageError(
17607
+ "--inbox-path and --channel-id are mutually exclusive",
17608
+ "schedule"
17609
+ );
17610
+ if (flags["inbox-path"] === "")
17611
+ throw new CliUsageError("--inbox-path must not be empty", "schedule");
17612
+ return { inboxPath: flags["inbox-path"] };
17613
+ }
17614
+ return {
17615
+ channelId: flags["channel-id"] ?? await client.schedules.agentChannelId()
17616
+ };
16823
17617
  }
16824
17618
  function scheduleRuleFromFlags(flags) {
16825
17619
  const selected = ["after", "at", "every", "cron"].filter(
@@ -17012,6 +17806,85 @@ function readLocalTextFile(path, command2, flag, deps) {
17012
17806
  }
17013
17807
  return deps.localFiles.readText(path);
17014
17808
  }
17809
+ async function thesisBodyFromFlags(flags, command2, deps) {
17810
+ const sources = [
17811
+ flags.body !== void 0 ? "body" : void 0,
17812
+ flags["body-file"] !== void 0 ? "body-file" : void 0,
17813
+ flags["body-stdin"] === "true" ? "body-stdin" : void 0
17814
+ ].filter((source) => source !== void 0);
17815
+ if (sources.length !== 1) {
17816
+ throw new CliUsageError(
17817
+ `${command2} requires exactly one of --body, --body-file, or --body-stdin`,
17818
+ "thesis"
17819
+ );
17820
+ }
17821
+ if (sources[0] === "body") return flags.body;
17822
+ if (sources[0] === "body-file") {
17823
+ assertLocalFileAvailable(command2, "--body-file", deps);
17824
+ if (!deps?.localFiles) {
17825
+ throw new Error("Local file access requires a Node.js runtime adapter.");
17826
+ }
17827
+ return strictThesisUTF8(
17828
+ deps.localFiles.readBytes(flags["body-file"]),
17829
+ command2,
17830
+ "--body-file"
17831
+ );
17832
+ }
17833
+ if (deps?.runtime === "jagent") {
17834
+ throw localFileUnsupported(command2, "--body-stdin");
17835
+ }
17836
+ if (!deps?.readStdinBytes) {
17837
+ throw new Error("Thesis stdin requires a Node.js byte-stdin adapter.");
17838
+ }
17839
+ return strictThesisUTF8(await deps.readStdinBytes(), command2, "--body-stdin");
17840
+ }
17841
+ function thesisEntityIDs(flags) {
17842
+ const raw = flags["entity-ids"];
17843
+ if (raw === void 0 || raw === "") return [];
17844
+ const entityIDs = raw.split(",").map((id) => id.trim());
17845
+ if (entityIDs.some((id) => id === "")) {
17846
+ throw new CliUsageError(
17847
+ "--entity-ids must not contain empty IDs",
17848
+ "thesis"
17849
+ );
17850
+ }
17851
+ return entityIDs;
17852
+ }
17853
+ function thesisTickers(flags) {
17854
+ const raw = flags.tickers;
17855
+ if (raw === void 0) return void 0;
17856
+ const tickers = raw.split(",").map((ticker) => ticker.trim());
17857
+ if (tickers.some((ticker) => ticker === "")) {
17858
+ throw new CliUsageError(
17859
+ "--tickers must not contain empty tickers",
17860
+ "thesis"
17861
+ );
17862
+ }
17863
+ return tickers;
17864
+ }
17865
+ function strictThesisUTF8(value, command2, flag) {
17866
+ const bytes = toByteView(value);
17867
+ if (bytes === void 0) {
17868
+ throw new Error(`${flag} requires a byte-capable Node.js runtime adapter.`);
17869
+ }
17870
+ try {
17871
+ return new TextDecoder("utf-8", { fatal: true, ignoreBOM: true }).decode(
17872
+ bytes
17873
+ );
17874
+ } catch {
17875
+ throw new CliUsageError(
17876
+ `${flag} must contain valid UTF-8 for '${command2}'`,
17877
+ "thesis"
17878
+ );
17879
+ }
17880
+ }
17881
+ function toByteView(value) {
17882
+ if (value instanceof ArrayBuffer) return new Uint8Array(value);
17883
+ if (ArrayBuffer.isView(value)) {
17884
+ return new Uint8Array(value.buffer, value.byteOffset, value.byteLength);
17885
+ }
17886
+ return void 0;
17887
+ }
17015
17888
  function readLocalFileBytes(path, command2, flag, deps) {
17016
17889
  assertLocalFileAvailable(command2, flag, deps);
17017
17890
  if (!deps?.localFiles) {
@@ -17458,8 +18331,7 @@ async function executeParsedCommand(client, parsedCommand, meta, deps) {
17458
18331
  }
17459
18332
  switch (subcommand) {
17460
18333
  case "list": {
17461
- const channelId = await scheduleChannelId(client, flags);
17462
- return client.schedules.list({ channelId });
18334
+ return client.schedules.list(await scheduleTarget(client, flags));
17463
18335
  }
17464
18336
  case "put": {
17465
18337
  const rule = scheduleRuleFromFlags(flags);
@@ -17472,9 +18344,9 @@ async function executeParsedCommand(client, parsedCommand, meta, deps) {
17472
18344
  }
17473
18345
  const name = requireFlag(flags, "name", "schedule put");
17474
18346
  const text = requireFlag(flags, "message", "schedule put");
17475
- const channelId = await scheduleChannelId(client, flags);
18347
+ const target = await scheduleTarget(client, flags);
17476
18348
  return client.schedules.put({
17477
- channelId,
18349
+ ...target,
17478
18350
  name,
17479
18351
  text,
17480
18352
  rule,
@@ -17483,25 +18355,25 @@ async function executeParsedCommand(client, parsedCommand, meta, deps) {
17483
18355
  }
17484
18356
  case "pause": {
17485
18357
  const name = requireFlag(flags, "name", "schedule pause");
17486
- const channelId = await scheduleChannelId(client, flags);
18358
+ const target = await scheduleTarget(client, flags);
17487
18359
  return client.schedules.pause({
17488
- channelId,
18360
+ ...target,
17489
18361
  name
17490
18362
  });
17491
18363
  }
17492
18364
  case "resume": {
17493
18365
  const name = requireFlag(flags, "name", "schedule resume");
17494
- const channelId = await scheduleChannelId(client, flags);
18366
+ const target = await scheduleTarget(client, flags);
17495
18367
  return client.schedules.resume({
17496
- channelId,
18368
+ ...target,
17497
18369
  name
17498
18370
  });
17499
18371
  }
17500
18372
  case "delete": {
17501
18373
  const name = requireFlag(flags, "name", "schedule delete");
17502
- const channelId = await scheduleChannelId(client, flags);
18374
+ const target = await scheduleTarget(client, flags);
17503
18375
  await client.schedules.delete({
17504
- channelId,
18376
+ ...target,
17505
18377
  name
17506
18378
  });
17507
18379
  return { deleted: true };
@@ -17513,6 +18385,143 @@ async function executeParsedCommand(client, parsedCommand, meta, deps) {
17513
18385
  );
17514
18386
  }
17515
18387
  }
18388
+ case "steward": {
18389
+ if (!subcommand) {
18390
+ throw new CliUsageError("Missing subcommand for steward", "steward");
18391
+ }
18392
+ const inboxPath = requireFlag(
18393
+ flags,
18394
+ "inbox-path",
18395
+ `steward ${subcommand}`
18396
+ );
18397
+ const ids = (name) => requireFlag(flags, name, `steward ${subcommand}`).split(",").map((value) => value.trim()).filter((value) => value !== "");
18398
+ switch (subcommand) {
18399
+ case "decide":
18400
+ return client.steward.decide({
18401
+ inboxPath,
18402
+ deliveryId: requireFlag(flags, "delivery-id", "steward decide"),
18403
+ decision: requireDecision(
18404
+ requireFlag(flags, "decision", "steward decide")
18405
+ ),
18406
+ reason: requireFlag(flags, "reason", "steward decide")
18407
+ });
18408
+ case "forward":
18409
+ return client.steward.forward({
18410
+ inboxPath,
18411
+ deliveryId: requireFlag(flags, "delivery-id", "steward forward"),
18412
+ requestId: flags["request-id"]
18413
+ });
18414
+ case "send":
18415
+ return client.steward.send({
18416
+ inboxPath,
18417
+ body: requireFlag(flags, "body", "steward send"),
18418
+ deliveryIds: ids("delivery-ids"),
18419
+ requestId: flags["request-id"]
18420
+ });
18421
+ case "pending": {
18422
+ const parseTime = (name) => {
18423
+ const value = flags[name];
18424
+ if (value === void 0) return void 0;
18425
+ try {
18426
+ return parseRfc3339Milliseconds(value);
18427
+ } catch {
18428
+ throw new CliUsageError(
18429
+ `--${name} must be an RFC3339 timestamp with a timezone`,
18430
+ "steward"
18431
+ );
18432
+ }
18433
+ };
18434
+ const first = flags.first === void 0 ? void 0 : Number(flags.first);
18435
+ return client.steward.pending({
18436
+ inboxPath,
18437
+ after: flags.after,
18438
+ sinceMs: parseTime("since"),
18439
+ untilMs: parseTime("until"),
18440
+ first
18441
+ });
18442
+ }
18443
+ case "briefed":
18444
+ return client.steward.briefed({
18445
+ inboxPath,
18446
+ deliveryIds: ids("delivery-ids"),
18447
+ digestRunId: requireFlag(flags, "digest-run-id", "steward briefed")
18448
+ });
18449
+ default:
18450
+ throw new CliUsageError(
18451
+ `Unknown subcommand: steward ${subcommand}`,
18452
+ "steward"
18453
+ );
18454
+ }
18455
+ }
18456
+ case "thesis": {
18457
+ if (!subcommand) {
18458
+ throw new CliUsageError("Missing subcommand for thesis", "thesis");
18459
+ }
18460
+ switch (subcommand) {
18461
+ case "create":
18462
+ return client.theses.create({
18463
+ request_id: requireFlag(flags, "request-id", "thesis create"),
18464
+ body: await thesisBodyFromFlags(flags, "thesis create", deps),
18465
+ title: flags.title ?? "",
18466
+ entity_ids: thesisEntityIDs(flags),
18467
+ tickers: thesisTickers(flags),
18468
+ visibility: flags.visibility === void 0 ? "public" : thesisVisibility(flags.visibility)
18469
+ });
18470
+ case "get":
18471
+ return client.theses.get(requireFlag(flags, "id", "thesis get"));
18472
+ case "set-visibility":
18473
+ return client.theses.setVisibility(
18474
+ requireFlag(flags, "id", "thesis set-visibility"),
18475
+ {
18476
+ visibility: thesisVisibility(
18477
+ requireFlag(flags, "visibility", "thesis set-visibility")
18478
+ )
18479
+ }
18480
+ );
18481
+ case "update":
18482
+ return client.theses.update(
18483
+ requireFlag(flags, "id", "thesis update"),
18484
+ {
18485
+ request_id: requireFlag(flags, "request-id", "thesis update"),
18486
+ expected_author_version_id: requireFlag(
18487
+ flags,
18488
+ "expected-author-version-id",
18489
+ "thesis update"
18490
+ ),
18491
+ body: await thesisBodyFromFlags(flags, "thesis update", deps),
18492
+ title: flags.title ?? "",
18493
+ entity_ids: thesisEntityIDs(flags),
18494
+ visibility: thesisVisibility(
18495
+ requireFlag(flags, "visibility", "thesis update")
18496
+ ),
18497
+ editorial: boolFlag(flags.editorial) ?? false
18498
+ }
18499
+ );
18500
+ case "close":
18501
+ return client.theses.close(requireFlag(flags, "id", "thesis close"), {
18502
+ expected_author_version_id: requireFlag(
18503
+ flags,
18504
+ "expected-author-version-id",
18505
+ "thesis close"
18506
+ ),
18507
+ note: flags.note
18508
+ });
18509
+ case "delete":
18510
+ return client.theses.delete(
18511
+ requireFlag(flags, "id", "thesis delete")
18512
+ );
18513
+ case "rewrite":
18514
+ return client.theses.rewrite({
18515
+ body: await thesisBodyFromFlags(flags, "thesis rewrite", deps),
18516
+ mode: flags.mode === void 0 ? "reformat" : thesisRewriteMode(flags.mode)
18517
+ });
18518
+ default:
18519
+ throw new CliUsageError(
18520
+ `Unknown subcommand: thesis ${subcommand}`,
18521
+ "thesis"
18522
+ );
18523
+ }
18524
+ }
17516
18525
  case "service-account": {
17517
18526
  if (!subcommand)
17518
18527
  throw new CliUsageError(
@@ -18948,9 +19957,12 @@ function configureFetchTimeout(timeoutMs) {
18948
19957
  configuredRunFetchTimeoutMs = timeoutMs;
18949
19958
  }
18950
19959
  async function readAllStdin() {
19960
+ return Buffer.from(await readAllStdinBytes()).toString("utf8");
19961
+ }
19962
+ async function readAllStdinBytes() {
18951
19963
  const chunks = [];
18952
19964
  for await (const chunk of process.stdin) chunks.push(chunk);
18953
- return Buffer.concat(chunks).toString("utf8");
19965
+ return Buffer.concat(chunks);
18954
19966
  }
18955
19967
  var nodeRuntimeDeps = {
18956
19968
  runtime: "nodejs",
@@ -18962,6 +19974,7 @@ var nodeRuntimeDeps = {
18962
19974
  writeBytes: (path, data) => fs.writeFileSync(path, data)
18963
19975
  },
18964
19976
  readStdin: readAllStdin,
19977
+ readStdinBytes: readAllStdinBytes,
18965
19978
  randomUUID: () => crypto3.randomUUID(),
18966
19979
  configureFetchTimeout,
18967
19980
  writeBrokerResult: async (envelope, exitCode) => {