@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/index.cjs CHANGED
@@ -33,6 +33,8 @@ __export(src_exports, {
33
33
  SUBSCRIBE_PROPOSE_MESSAGE: () => SUBSCRIBE_PROPOSE_MESSAGE,
34
34
  SUBSCRIBE_RESULT_MESSAGE: () => SUBSCRIBE_RESULT_MESSAGE,
35
35
  SchedulesResource: () => SchedulesResource,
36
+ StewardResource: () => StewardResource,
37
+ ThesesResource: () => ThesesResource,
36
38
  TradingPairsResource: () => TradingPairsResource,
37
39
  UDF_AUTH_REQUIRED_MESSAGE: () => UDF_AUTH_REQUIRED_MESSAGE,
38
40
  UDF_CONSENT_REQUEST_MESSAGE: () => UDF_CONSENT_REQUEST_MESSAGE,
@@ -3309,7 +3311,6 @@ var MarketsResource = class {
3309
3311
  // src/resources/schedules.ts
3310
3312
  var SCHEDULE_FIELDS = `
3311
3313
  id
3312
- channel { id }
3313
3314
  name
3314
3315
  rule { kind atMs everyIntervalSeconds cronExpression cronTimezone }
3315
3316
  bounds { startsAtMs untilMs maxOccurrences }
@@ -3326,7 +3327,7 @@ var LIST_SCHEDULES = `
3326
3327
  query ToolkitListAgentSchedules($channelId: ID!, $after: String) {
3327
3328
  viewer { channel(id: $channelId) {
3328
3329
  schedules(input: { first: 64, after: $after }) {
3329
- edges { node { ${SCHEDULE_FIELDS} } }
3330
+ edges { node { channel { id } ${SCHEDULE_FIELDS} } }
3330
3331
  pageInfo { hasNextPage endCursor }
3331
3332
  }
3332
3333
  } }
@@ -3334,6 +3335,20 @@ query ToolkitListAgentSchedules($channelId: ID!, $after: String) {
3334
3335
  var UPDATE_SCHEDULE = `
3335
3336
  mutation ToolkitUpdateAgentSchedule($input: UpdateChannelScheduleInput!) {
3336
3337
  updateChannelSchedule(input: $input) {
3338
+ schedule { channel { id } ${SCHEDULE_FIELDS} }
3339
+ deleted
3340
+ }
3341
+ }`.trim();
3342
+ var LIST_SESSION_SCHEDULES = `
3343
+ query ToolkitListSessionSchedules($inboxPath: String!, $after: String) {
3344
+ viewer { sessionSchedules(inboxPath: $inboxPath, input: { first: 64, after: $after }) {
3345
+ edges { node { ${SCHEDULE_FIELDS} } }
3346
+ pageInfo { hasNextPage endCursor }
3347
+ } }
3348
+ }`.trim();
3349
+ var UPDATE_SESSION_SCHEDULE = `
3350
+ mutation ToolkitUpdateSessionSchedule($input: UpdateSessionScheduleInput!) {
3351
+ updateSessionSchedule(input: $input) {
3337
3352
  schedule { ${SCHEDULE_FIELDS} }
3338
3353
  deleted
3339
3354
  }
@@ -3344,6 +3359,7 @@ query ToolkitAgentChannel {
3344
3359
  }`.trim();
3345
3360
  var SCHEDULE_NAME = /^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/;
3346
3361
  var RFC3339 = /^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})(Z|[+-](\d{2}):(\d{2}))$/i;
3362
+ 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;
3347
3363
  var ISO_DURATION = /^P(?:(\d+)D)?(?:T(?:(\d+)H)?(?:(\d+)M)?(?:(\d+)S)?)?$/;
3348
3364
  var GRAPHQL_STATUS_BY_CODE = {
3349
3365
  INVALID_ARGUMENT: 400,
@@ -3367,16 +3383,17 @@ var SchedulesResource = class {
3367
3383
  client;
3368
3384
  async list(params) {
3369
3385
  this.client._requireAuth();
3370
- const id = channelID(params.channelId);
3386
+ const target = targetInput(params);
3387
+ const inbox = "inboxPath" in target;
3371
3388
  const schedules = [];
3372
3389
  let after = null;
3373
3390
  const seenCursors = /* @__PURE__ */ new Set();
3374
3391
  for (; ; ) {
3375
3392
  const data = await this.graphql(
3376
- LIST_SCHEDULES,
3377
- { channelId: id, after }
3393
+ inbox ? LIST_SESSION_SCHEDULES : LIST_SCHEDULES,
3394
+ { ...target, after }
3378
3395
  );
3379
- const connection2 = data.viewer?.channel?.schedules;
3396
+ const connection2 = inbox ? data.viewer?.sessionSchedules : data.viewer?.channel?.schedules;
3380
3397
  if (!connection2?.edges) throw scheduleNotFound();
3381
3398
  for (const edge of connection2.edges) {
3382
3399
  if (!edge?.node) throw scheduleEmptyResponse();
@@ -3392,15 +3409,14 @@ var SchedulesResource = class {
3392
3409
  async put(params) {
3393
3410
  this.client._requireAuth();
3394
3411
  const input = {
3395
- channelId: channelID(params.channelId),
3412
+ ...targetInput(params),
3396
3413
  name: requireName(params.name),
3397
3414
  definition: {
3398
3415
  ...ruleInput(params.rule, params.bounds),
3399
3416
  message: { text: requireText(params.text) }
3400
3417
  }
3401
3418
  };
3402
- const data = await this.graphql(UPDATE_SCHEDULE, { input });
3403
- const schedule = data.updateChannelSchedule?.schedule;
3419
+ const schedule = (await this.update(input))?.schedule;
3404
3420
  if (!schedule) throw scheduleEmptyResponse();
3405
3421
  return fromWireSchedule(schedule);
3406
3422
  }
@@ -3412,11 +3428,11 @@ var SchedulesResource = class {
3412
3428
  }
3413
3429
  async delete(params) {
3414
3430
  this.client._requireAuth();
3415
- const data = await this.graphql(UPDATE_SCHEDULE, {
3416
- input: { ...managementInput(params), lifecycle: "REMOVED" }
3431
+ const result = await this.update({
3432
+ ...managementInput(params),
3433
+ lifecycle: "REMOVED"
3417
3434
  });
3418
- if (data.updateChannelSchedule?.deleted !== true)
3419
- throw scheduleEmptyResponse();
3435
+ if (result?.deleted !== true) throw scheduleEmptyResponse();
3420
3436
  }
3421
3437
  /** Resolve the authenticated viewer's unique Agent Channel for CLI defaults. */
3422
3438
  async agentChannelId() {
@@ -3430,13 +3446,15 @@ var SchedulesResource = class {
3430
3446
  }
3431
3447
  async manage(lifecycle, params) {
3432
3448
  this.client._requireAuth();
3433
- const data = await this.graphql(UPDATE_SCHEDULE, {
3434
- input: { ...managementInput(params), lifecycle }
3435
- });
3436
- const schedule = data.updateChannelSchedule?.schedule;
3449
+ const schedule = (await this.update({ ...managementInput(params), lifecycle }))?.schedule;
3437
3450
  if (!schedule) throw scheduleEmptyResponse();
3438
3451
  return fromWireSchedule(schedule);
3439
3452
  }
3453
+ async update(input) {
3454
+ const inbox = "inboxPath" in input;
3455
+ const data = await this.graphql(inbox ? UPDATE_SESSION_SCHEDULE : UPDATE_SCHEDULE, { input });
3456
+ return inbox ? data.updateSessionSchedule : data.updateChannelSchedule;
3457
+ }
3440
3458
  async graphql(query, variables) {
3441
3459
  const response = await this.client._request("POST", "/query", {
3442
3460
  body: variables === void 0 ? { query } : { query, variables }
@@ -3587,10 +3605,24 @@ function fromWireRule(rule) {
3587
3605
  }
3588
3606
  function managementInput(params) {
3589
3607
  return {
3590
- channelId: channelID(params.channelId),
3608
+ ...targetInput(params),
3591
3609
  name: requireName(params.name)
3592
3610
  };
3593
3611
  }
3612
+ function targetInput(target) {
3613
+ if (target.channelId !== void 0 === (target.inboxPath !== void 0))
3614
+ throw invalid("exactly one of channelId or inboxPath is required");
3615
+ if (target.channelId !== void 0)
3616
+ return { channelId: channelID(target.channelId) };
3617
+ const path = target.inboxPath;
3618
+ const size = typeof path === "string" ? utf8Size(path) : void 0;
3619
+ if (typeof path !== "string" || size === void 0 || size > 2048 || !path.startsWith("/") || path.includes("\0") || path.slice(1).split("/").some((segment) => segment === "" || segment === "." || segment === ".."))
3620
+ throw invalid("inboxPath must be a canonical absolute ALFS Inbox path");
3621
+ 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;
3622
+ if (transcript === void 0 || /\.inbox(?:\.jsonl)?$/.test(transcript) || /\.lock(?:\.recovery|\.heartbeat-[^/]+|\.stale-[^/]+)?$/.test(transcript) || transcript.endsWith("/.jsonl"))
3623
+ throw invalid("inboxPath must identify a standard Session Inbox sidecar");
3624
+ return { inboxPath: path };
3625
+ }
3594
3626
  function channelID(value) {
3595
3627
  if (typeof value === "number" && (!Number.isSafeInteger(value) || value <= 0)) {
3596
3628
  throw invalid(
@@ -3635,8 +3667,8 @@ function durationMilliseconds(value, minimumSeconds) {
3635
3667
  if (!Number.isSafeInteger(result)) throw invalid("duration is out of range");
3636
3668
  return result;
3637
3669
  }
3638
- function timestampMilliseconds(value) {
3639
- const match = RFC3339.exec(value);
3670
+ function timestampMilliseconds(value, fractional = false) {
3671
+ const match = (fractional ? RFC3339_FRACTIONAL : RFC3339).exec(value);
3640
3672
  if (!match) throw invalid("timestamp must be RFC3339 with a timezone");
3641
3673
  const [year, month, day, hour, minute, second] = match.slice(1, 7).map(Number);
3642
3674
  const offsetHour = Number(match[8] ?? 0);
@@ -3679,6 +3711,243 @@ function scheduleEmptyResponse() {
3679
3711
  );
3680
3712
  }
3681
3713
 
3714
+ // src/resources/steward.ts
3715
+ var GRAPHQL_STATUS_BY_CODE2 = {
3716
+ INVALID_ARGUMENT: 400,
3717
+ UNAUTHENTICATED: 401,
3718
+ PERMISSION_DENIED: 403,
3719
+ NOT_FOUND: 404,
3720
+ ALREADY_EXISTS: 409,
3721
+ ABORTED: 409,
3722
+ FAILED_PRECONDITION: 412,
3723
+ RESOURCE_EXHAUSTED: 429,
3724
+ INTERNAL: 500,
3725
+ UNKNOWN: 500,
3726
+ DATA_LOSS: 500,
3727
+ UNAVAILABLE: 503,
3728
+ DEADLINE_EXCEEDED: 504
3729
+ };
3730
+ var DECIDE = `
3731
+ mutation ToolkitStewardDecide($input: UpdateStewardDeliveryInput!) {
3732
+ updateStewardDelivery(input: $input) { delivery { deliveryId state } }
3733
+ }`.trim();
3734
+ var FORWARD = `
3735
+ mutation ToolkitStewardForward($input: UpdateStewardDeliveryInput!) {
3736
+ updateStewardDelivery(input: $input) { delivery { deliveryId state channelMessageId } }
3737
+ }`.trim();
3738
+ var SEND = `
3739
+ mutation ToolkitStewardSend($input: PostStewardMessageInput!) {
3740
+ postStewardMessage(input: $input) { message { channelMessageId requestId } }
3741
+ }`.trim();
3742
+ var PENDING = `
3743
+ query ToolkitStewardPending($inboxPath: String!, $input: StewardDigestPendingInput) {
3744
+ viewer {
3745
+ stewardDigestPending(inboxPath: $inboxPath, input: $input) {
3746
+ edges {
3747
+ cursor
3748
+ node { deliveryId feedEntryId source { kind id } decisionReason consumedAtMs }
3749
+ }
3750
+ pageInfo { hasNextPage endCursor }
3751
+ windowSinceMs
3752
+ windowUntilMs
3753
+ }
3754
+ }
3755
+ }`.trim();
3756
+ var BRIEFED = `
3757
+ mutation ToolkitStewardBriefed($input: CompleteStewardBriefInput!) {
3758
+ completeStewardBrief(input: $input) { ok }
3759
+ }`.trim();
3760
+ var DECISIONS = /* @__PURE__ */ new Set([
3761
+ "immediate",
3762
+ "digest",
3763
+ "suppress"
3764
+ ]);
3765
+ var DELIVERY_ID = /^[1-9][0-9]{0,18}$/;
3766
+ function invalid2(message) {
3767
+ return new AlvaError("INVALID_ARGUMENT", message, 400);
3768
+ }
3769
+ function requireInboxPath(target) {
3770
+ if (!target || typeof target.inboxPath !== "string" || target.inboxPath === "")
3771
+ throw invalid2("steward commands require the steward Session Inbox path");
3772
+ return target.inboxPath;
3773
+ }
3774
+ function requireDeliveryId(value, label = "delivery id") {
3775
+ if (!DELIVERY_ID.test(value))
3776
+ throw invalid2(`${label} must be a positive integer`);
3777
+ return value;
3778
+ }
3779
+ function requireDeliveryIds(values) {
3780
+ if (values.length === 0)
3781
+ throw invalid2("at least one delivery id is required");
3782
+ const unique = /* @__PURE__ */ new Set();
3783
+ for (const value of values) {
3784
+ requireDeliveryId(value);
3785
+ if (unique.has(value)) throw invalid2(`duplicate delivery id ${value}`);
3786
+ unique.add(value);
3787
+ }
3788
+ return [...unique];
3789
+ }
3790
+ function requireDecision(value) {
3791
+ if (!DECISIONS.has(value))
3792
+ throw invalid2("decision must be one of immediate, digest, suppress");
3793
+ return value;
3794
+ }
3795
+ function generateRequestId() {
3796
+ const webcrypto = globalThis.crypto;
3797
+ if (typeof webcrypto?.randomUUID === "function")
3798
+ return webcrypto.randomUUID();
3799
+ const bytes = new Uint8Array(16);
3800
+ if (typeof webcrypto?.getRandomValues === "function") {
3801
+ webcrypto.getRandomValues(bytes);
3802
+ } else {
3803
+ for (let i = 0; i < bytes.length; i += 1)
3804
+ bytes[i] = Math.floor(Math.random() * 256);
3805
+ }
3806
+ bytes[6] = bytes[6] & 15 | 64;
3807
+ bytes[8] = bytes[8] & 63 | 128;
3808
+ const hex = Array.from(bytes, (b) => b.toString(16).padStart(2, "0")).join(
3809
+ ""
3810
+ );
3811
+ return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`;
3812
+ }
3813
+ function requireRequestId(value) {
3814
+ if (value === void 0) return generateRequestId();
3815
+ if (!/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(
3816
+ value
3817
+ ))
3818
+ throw invalid2("request id must be a UUID");
3819
+ return value;
3820
+ }
3821
+ function emptyResponse() {
3822
+ return new AlvaError("EMPTY_RESPONSE", "steward response was empty", 502);
3823
+ }
3824
+ var StewardResource = class {
3825
+ constructor(client) {
3826
+ this.client = client;
3827
+ }
3828
+ client;
3829
+ async decide(params) {
3830
+ this.client._requireAuth();
3831
+ const reason = params.reason?.trim();
3832
+ if (!reason) throw invalid2("a decision reason is required");
3833
+ const data = await this.graphql(DECIDE, {
3834
+ input: {
3835
+ inboxPath: requireInboxPath(params),
3836
+ deliveryId: requireDeliveryId(params.deliveryId),
3837
+ decision: {
3838
+ decision: requireDecision(params.decision).toUpperCase(),
3839
+ reason
3840
+ }
3841
+ }
3842
+ });
3843
+ const delivery = data.updateStewardDelivery?.delivery;
3844
+ if (!delivery) throw emptyResponse();
3845
+ return { state: delivery.state };
3846
+ }
3847
+ async forward(params) {
3848
+ this.client._requireAuth();
3849
+ const data = await this.graphql(FORWARD, {
3850
+ input: {
3851
+ inboxPath: requireInboxPath(params),
3852
+ deliveryId: requireDeliveryId(params.deliveryId),
3853
+ forward: { requestId: requireRequestId(params.requestId) }
3854
+ }
3855
+ });
3856
+ const delivery = data.updateStewardDelivery?.delivery;
3857
+ if (!delivery || !delivery.channelMessageId) throw emptyResponse();
3858
+ return {
3859
+ channelMessageId: delivery.channelMessageId,
3860
+ state: delivery.state
3861
+ };
3862
+ }
3863
+ async send(params) {
3864
+ this.client._requireAuth();
3865
+ if (typeof params.body !== "string" || params.body.trim() === "")
3866
+ throw invalid2("a message body is required");
3867
+ const data = await this.graphql(SEND, {
3868
+ input: {
3869
+ inboxPath: requireInboxPath(params),
3870
+ requestId: requireRequestId(params.requestId),
3871
+ body: params.body,
3872
+ deliveryIds: requireDeliveryIds(params.deliveryIds)
3873
+ }
3874
+ });
3875
+ const message = data.postStewardMessage?.message;
3876
+ if (!message) throw emptyResponse();
3877
+ return message;
3878
+ }
3879
+ async pending(params) {
3880
+ this.client._requireAuth();
3881
+ const first = params.first ?? 50;
3882
+ if (!Number.isInteger(first) || first < 1 || first > 100)
3883
+ throw invalid2("first must be an integer between 1 and 100");
3884
+ const input = { first };
3885
+ if (params.after !== void 0 && params.after !== "") {
3886
+ input.after = params.after;
3887
+ } else {
3888
+ for (const [label, value] of [
3889
+ ["sinceMs", params.sinceMs],
3890
+ ["untilMs", params.untilMs]
3891
+ ]) {
3892
+ if (value !== void 0 && (!Number.isSafeInteger(value) || value <= 0))
3893
+ throw invalid2(`${label} must be a positive safe integer timestamp`);
3894
+ }
3895
+ if (params.sinceMs !== void 0 && params.untilMs !== void 0 && params.untilMs <= params.sinceMs)
3896
+ throw invalid2("untilMs must be after sinceMs");
3897
+ if (params.sinceMs !== void 0) input.sinceMs = params.sinceMs;
3898
+ if (params.untilMs !== void 0) input.untilMs = params.untilMs;
3899
+ }
3900
+ const data = await this.graphql(PENDING, { inboxPath: requireInboxPath(params), input });
3901
+ const page = data.viewer?.stewardDigestPending;
3902
+ if (!page || !Array.isArray(page.edges)) throw emptyResponse();
3903
+ const windowSinceMs = page.windowSinceMs ?? 0;
3904
+ const windowUntilMs = page.windowUntilMs ?? 0;
3905
+ if (!Number.isSafeInteger(windowSinceMs) || !Number.isSafeInteger(windowUntilMs) || windowSinceMs <= 0 || windowUntilMs <= windowSinceMs)
3906
+ throw emptyResponse();
3907
+ const items = page.edges.map((edge) => edge.node);
3908
+ const nextCursor = page.pageInfo?.hasNextPage === true && page.pageInfo.endCursor ? page.pageInfo.endCursor : null;
3909
+ return {
3910
+ items,
3911
+ nextCursor,
3912
+ windowSinceMs,
3913
+ windowUntilMs
3914
+ };
3915
+ }
3916
+ async briefed(params) {
3917
+ this.client._requireAuth();
3918
+ const digestRunId = params.digestRunId?.trim();
3919
+ if (!digestRunId) throw invalid2("a digest run id is required");
3920
+ const data = await this.graphql(BRIEFED, {
3921
+ input: {
3922
+ inboxPath: requireInboxPath(params),
3923
+ deliveryIds: requireDeliveryIds(params.deliveryIds),
3924
+ digestRunId
3925
+ }
3926
+ });
3927
+ if (data.completeStewardBrief?.ok !== true) throw emptyResponse();
3928
+ return { ok: true };
3929
+ }
3930
+ async graphql(query, variables) {
3931
+ const response = await this.client._request("POST", "/query", {
3932
+ body: { query, variables }
3933
+ });
3934
+ if (!response || typeof response !== "object") throw emptyResponse();
3935
+ if (response.errors?.length) {
3936
+ const codes = response.errors.map((error) => error.extensions?.code);
3937
+ const canonicalCode = new Set(codes).size === 1 && typeof codes[0] === "string" ? codes[0] : void 0;
3938
+ const canonicalStatus = canonicalCode ? GRAPHQL_STATUS_BY_CODE2[canonicalCode] : void 0;
3939
+ throw new AlvaError(
3940
+ canonicalCode !== void 0 && canonicalStatus !== void 0 ? canonicalCode : "GRAPHQL_ERROR",
3941
+ response.errors.map((error) => error.message).filter((message) => typeof message === "string").join("; ") || "GraphQL request failed",
3942
+ canonicalStatus ?? 502,
3943
+ { errors: response.errors }
3944
+ );
3945
+ }
3946
+ if (!response.data) throw emptyResponse();
3947
+ return response.data;
3948
+ }
3949
+ };
3950
+
3682
3951
  // src/resources/tradingPairs.ts
3683
3952
  function isRecord(value) {
3684
3953
  return typeof value === "object" && value !== null && !Array.isArray(value);
@@ -3864,14 +4133,357 @@ var TradingPairsResource = class {
3864
4133
  }
3865
4134
  };
3866
4135
 
4136
+ // src/resources/theses.ts
4137
+ var MAX_SIGNED_INT64 = 9223372036854775807n;
4138
+ var UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
4139
+ var UNPAIRED_SURROGATE = /[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?<![\uD800-\uDBFF])[\uDC00-\uDFFF]/;
4140
+ var encoder = new TextEncoder();
4141
+ var ThesesResource = class {
4142
+ constructor(client) {
4143
+ this.client = client;
4144
+ }
4145
+ client;
4146
+ async create(params) {
4147
+ this.client._requireAuth();
4148
+ const body = createBody(params);
4149
+ return thesisResponse(
4150
+ await this.client._request("POST", "/api/v1/theses", { body })
4151
+ );
4152
+ }
4153
+ async get(id) {
4154
+ this.client._requireAuth();
4155
+ return thesisGetResponse(
4156
+ await this.client._request("GET", `/api/v1/theses/${requireID(id, "id")}`)
4157
+ );
4158
+ }
4159
+ async update(id, params) {
4160
+ this.client._requireAuth();
4161
+ const body = updateBody(params);
4162
+ return thesisResponse(
4163
+ await this.client._request(
4164
+ "PUT",
4165
+ `/api/v1/theses/${requireID(id, "id")}`,
4166
+ {
4167
+ body
4168
+ }
4169
+ )
4170
+ );
4171
+ }
4172
+ async setVisibility(id, params) {
4173
+ this.client._requireAuth();
4174
+ if (!params) {
4175
+ throw invalidArgument("params is required");
4176
+ }
4177
+ const thesisID = requireID(id, "id");
4178
+ const visibility = requireVisibility(params.visibility);
4179
+ const response = thesisResponse(
4180
+ await this.client._request(
4181
+ "POST",
4182
+ `/api/v1/theses/${thesisID}/visibility`,
4183
+ { body: { visibility } }
4184
+ )
4185
+ );
4186
+ if (response.thesis.id !== thesisID || response.thesis.visibility !== visibility) {
4187
+ throw invalidResponse2(
4188
+ "visibility response must match the requested thesis and visibility"
4189
+ );
4190
+ }
4191
+ return response;
4192
+ }
4193
+ async close(id, params) {
4194
+ this.client._requireAuth();
4195
+ const body = {
4196
+ expected_author_version_id: requireID(
4197
+ params.expected_author_version_id,
4198
+ "expected_author_version_id"
4199
+ )
4200
+ };
4201
+ if (params.note !== void 0) body.note = requireText2(params.note, "note");
4202
+ return thesisResponse(
4203
+ await this.client._request(
4204
+ "POST",
4205
+ `/api/v1/theses/${requireID(id, "id")}/close`,
4206
+ { body }
4207
+ )
4208
+ );
4209
+ }
4210
+ async delete(id) {
4211
+ this.client._requireAuth();
4212
+ const response = await this.client._request(
4213
+ "DELETE",
4214
+ `/api/v1/theses/${requireID(id, "id")}`
4215
+ );
4216
+ if (response === void 0) return {};
4217
+ if (!isRecord2(response) || Object.keys(response).length !== 0) {
4218
+ throw invalidResponse2("delete response must be {}");
4219
+ }
4220
+ return {};
4221
+ }
4222
+ async rewrite(params) {
4223
+ this.client._requireAuth();
4224
+ const body = requireBody(params.body);
4225
+ const mode = params.mode === void 0 ? "reformat" : requireRewriteMode(params.mode);
4226
+ const response = await this.client._request(
4227
+ "POST",
4228
+ "/api/v1/theses/rewrite",
4229
+ {
4230
+ body: { body, mode }
4231
+ }
4232
+ );
4233
+ if (!isRecord2(response) || typeof response.body !== "string") {
4234
+ throw invalidResponse2("rewrite response must contain a string body");
4235
+ }
4236
+ return { body: responseBody(response.body) };
4237
+ }
4238
+ };
4239
+ function createBody(params) {
4240
+ const body = {
4241
+ request_id: requireRequestID(params.request_id),
4242
+ body: requireBody(params.body),
4243
+ title: requireTitle(params.title ?? ""),
4244
+ entity_ids: requireIDs(params.entity_ids ?? [], "entity_ids"),
4245
+ visibility: requireVisibility(params.visibility ?? "public")
4246
+ };
4247
+ if (params.tickers !== void 0)
4248
+ body.tickers = requireTickers(params.tickers);
4249
+ return body;
4250
+ }
4251
+ function updateBody(params) {
4252
+ return {
4253
+ request_id: requireRequestID(params.request_id),
4254
+ expected_author_version_id: requireID(
4255
+ params.expected_author_version_id,
4256
+ "expected_author_version_id"
4257
+ ),
4258
+ body: requireBody(params.body),
4259
+ title: requireTitle(params.title ?? ""),
4260
+ entity_ids: requireIDs(params.entity_ids ?? [], "entity_ids"),
4261
+ visibility: requireVisibility(params.visibility),
4262
+ editorial: params.editorial ?? false
4263
+ };
4264
+ }
4265
+ function thesisResponse(response) {
4266
+ if (!isRecord2(response) || !isRecord2(response.thesis)) {
4267
+ throw invalidResponse2("response must contain thesis");
4268
+ }
4269
+ const thesis = response.thesis;
4270
+ const value = {
4271
+ id: responseID(thesis.id, "thesis.id"),
4272
+ author_version_id: responseID(
4273
+ thesis.author_version_id,
4274
+ "thesis.author_version_id"
4275
+ ),
4276
+ material_version_id: responseID(
4277
+ thesis.material_version_id,
4278
+ "thesis.material_version_id"
4279
+ ),
4280
+ title: responseTitle(thesis.title),
4281
+ body: responseBody(thesis.body),
4282
+ entity_ids: responseIDs(thesis.entity_ids, "thesis.entity_ids"),
4283
+ visibility: responseVisibility(thesis.visibility),
4284
+ closed: responseBoolean(thesis.closed, "thesis.closed"),
4285
+ closing_note: responseClosingNote(thesis.closing_note),
4286
+ author_kind: responseText(thesis.author_kind, "thesis.author_kind"),
4287
+ author_ref: responseText(thesis.author_ref, "thesis.author_ref")
4288
+ };
4289
+ return { thesis: value };
4290
+ }
4291
+ function thesisGetResponse(response) {
4292
+ const base = thesisResponse(response);
4293
+ if (!isRecord2(response) || !isRecord2(response.author)) {
4294
+ throw invalidResponse2("response must contain author");
4295
+ }
4296
+ const authorRecord = response.author;
4297
+ const author = {
4298
+ id: responseID(authorRecord.id, "author.id"),
4299
+ kind: responseText(authorRecord.kind, "author.kind"),
4300
+ display_name: responseText(
4301
+ authorRecord.display_name,
4302
+ "author.display_name"
4303
+ ),
4304
+ avatar_url: responseText(authorRecord.avatar_url, "author.avatar_url"),
4305
+ username: responseText(authorRecord.username, "author.username")
4306
+ };
4307
+ if (!Array.isArray(response.entities)) {
4308
+ throw invalidResponse2("response must contain entities");
4309
+ }
4310
+ if (response.entities.length !== base.thesis.entity_ids.length) {
4311
+ throw invalidResponse2("entities must match thesis.entity_ids");
4312
+ }
4313
+ const entities = response.entities.map((item, index) => {
4314
+ if (!isRecord2(item))
4315
+ throw invalidResponse2(`entities[${index}] must be an object`);
4316
+ const entity = {
4317
+ id: responseID(item.id, `entities[${index}].id`),
4318
+ ticker: responseText(item.ticker, `entities[${index}].ticker`),
4319
+ name: responseText(item.name, `entities[${index}].name`),
4320
+ icon_url: responseText(item.icon_url, `entities[${index}].icon_url`),
4321
+ kind: responseText(item.kind, `entities[${index}].kind`)
4322
+ };
4323
+ if (entity.id !== base.thesis.entity_ids[index]) {
4324
+ throw invalidResponse2("entities must preserve thesis.entity_ids order");
4325
+ }
4326
+ return entity;
4327
+ });
4328
+ return { thesis: base.thesis, author, entities };
4329
+ }
4330
+ function requireRequestID(value) {
4331
+ if (!UUID.test(value) || /^0{8}-0{4}-0{4}-0{4}-0{12}$/i.test(value)) {
4332
+ throw invalidArgument("request_id must be a non-zero RFC 4122 UUID");
4333
+ }
4334
+ return value;
4335
+ }
4336
+ function requireID(value, field) {
4337
+ if (typeof value !== "string" || !/^[1-9]\d*$/.test(value)) {
4338
+ throw invalidArgument(`${field} must be a positive int64 decimal string`);
4339
+ }
4340
+ const parsed = BigInt(value);
4341
+ if (parsed > MAX_SIGNED_INT64) {
4342
+ throw invalidArgument(`${field} must be a positive int64 decimal string`);
4343
+ }
4344
+ return value;
4345
+ }
4346
+ function requireIDs(value, field) {
4347
+ if (!Array.isArray(value)) throw invalidArgument(`${field} must be an array`);
4348
+ if (value.length > 20) {
4349
+ throw invalidArgument(`${field} must contain at most 20 IDs`);
4350
+ }
4351
+ return value.map((item, index) => requireID(item, `${field}[${index}]`));
4352
+ }
4353
+ function requireTickers(value) {
4354
+ if (!Array.isArray(value)) throw invalidArgument("tickers must be an array");
4355
+ if (value.length > 100) {
4356
+ throw invalidArgument("tickers must contain at most 100 values");
4357
+ }
4358
+ return value.map((item, index) => {
4359
+ const ticker = requireText2(item, `tickers[${index}]`);
4360
+ if (ticker.trim() === "" || ticker.includes("\0")) {
4361
+ throw invalidArgument(`tickers[${index}] must be non-empty`);
4362
+ }
4363
+ return ticker;
4364
+ });
4365
+ }
4366
+ function requireBody(value) {
4367
+ const body = requireText2(value, "body");
4368
+ if (body.trim().length === 0) throw invalidArgument("body must not be blank");
4369
+ if (encoder.encode(body).byteLength > 65536) {
4370
+ throw invalidArgument("body must be at most 65536 UTF-8 bytes");
4371
+ }
4372
+ return body;
4373
+ }
4374
+ function requireTitle(value) {
4375
+ const title = requireText2(value, "title");
4376
+ if (encoder.encode(title).byteLength > 500) {
4377
+ throw invalidArgument("title must be at most 500 UTF-8 bytes");
4378
+ }
4379
+ return title;
4380
+ }
4381
+ function requireVisibility(value) {
4382
+ const visibility = requireText2(value, "visibility");
4383
+ if (visibility !== "public" && visibility !== "private") {
4384
+ throw invalidArgument("visibility must be public or private");
4385
+ }
4386
+ return visibility;
4387
+ }
4388
+ function requireRewriteMode(value) {
4389
+ const mode = requireText2(value, "mode");
4390
+ if (mode === "reformat" || mode === "shorten" || mode === "enrich") {
4391
+ return mode;
4392
+ }
4393
+ throw invalidArgument("mode must be reformat, shorten, or enrich");
4394
+ }
4395
+ function requireText2(value, field) {
4396
+ if (typeof value !== "string")
4397
+ throw invalidArgument(`${field} must be a string`);
4398
+ if (UNPAIRED_SURROGATE.test(value)) {
4399
+ throw invalidArgument(`${field} contains invalid Unicode`);
4400
+ }
4401
+ if ((field === "body" || field === "title" || field === "note") && value.includes("\0")) {
4402
+ throw invalidArgument(`${field} must not contain NUL`);
4403
+ }
4404
+ return value;
4405
+ }
4406
+ function responseID(value, field) {
4407
+ if (typeof value === "number") {
4408
+ throw invalidResponse2(
4409
+ `${field} must be a decimal string; numeric IDs are unsafe`
4410
+ );
4411
+ }
4412
+ try {
4413
+ return requireID(value, field);
4414
+ } catch {
4415
+ throw invalidResponse2(`${field} must be a positive int64 decimal string`);
4416
+ }
4417
+ }
4418
+ function responseIDs(value, field) {
4419
+ if (!Array.isArray(value)) throw invalidResponse2(`${field} must be an array`);
4420
+ if (value.length > 20) {
4421
+ throw invalidResponse2(`${field} must contain at most 20 IDs`);
4422
+ }
4423
+ return value.map((item, index) => responseID(item, `${field}[${index}]`));
4424
+ }
4425
+ function responseText(value, field) {
4426
+ try {
4427
+ return requireText2(value, field);
4428
+ } catch {
4429
+ throw invalidResponse2(`${field} must be valid text`);
4430
+ }
4431
+ }
4432
+ function responseClosingNote(value) {
4433
+ try {
4434
+ return requireText2(value, "note");
4435
+ } catch {
4436
+ throw invalidResponse2("thesis.closing_note must be valid text");
4437
+ }
4438
+ }
4439
+ function responseBoolean(value, field) {
4440
+ if (typeof value !== "boolean")
4441
+ throw invalidResponse2(`${field} must be boolean`);
4442
+ return value;
4443
+ }
4444
+ function responseVisibility(value) {
4445
+ try {
4446
+ return requireVisibility(value);
4447
+ } catch {
4448
+ throw invalidResponse2("thesis.visibility must be public or private");
4449
+ }
4450
+ }
4451
+ function responseBody(value) {
4452
+ try {
4453
+ return requireBody(value);
4454
+ } catch {
4455
+ throw invalidResponse2(
4456
+ "response body must be nonblank valid text at most 65536 UTF-8 bytes"
4457
+ );
4458
+ }
4459
+ }
4460
+ function responseTitle(value) {
4461
+ try {
4462
+ return requireTitle(value);
4463
+ } catch {
4464
+ throw invalidResponse2(
4465
+ "response title must be valid text at most 500 UTF-8 bytes"
4466
+ );
4467
+ }
4468
+ }
4469
+ function isRecord2(value) {
4470
+ return typeof value === "object" && value !== null && !Array.isArray(value);
4471
+ }
4472
+ function invalidArgument(message) {
4473
+ return new AlvaError("INVALID_ARGUMENT", message, 400);
4474
+ }
4475
+ function invalidResponse2(message) {
4476
+ return new AlvaError("INVALID_RESPONSE", message, 502);
4477
+ }
4478
+
3867
4479
  // src/client.ts
3868
4480
  var DEFAULT_BASE_URL = "https://api-llm.prd.alva.ai";
3869
4481
  var DEFAULT_ARRAYS_BASE_URL = "https://data-tools.prd.space.id";
3870
- function isRecord2(value) {
4482
+ function isRecord3(value) {
3871
4483
  return typeof value === "object" && value !== null;
3872
4484
  }
3873
4485
  function stringField(value, field) {
3874
- if (!isRecord2(value)) return void 0;
4486
+ if (!isRecord3(value)) return void 0;
3875
4487
  const fieldValue = value[field];
3876
4488
  return typeof fieldValue === "string" && fieldValue ? fieldValue : void 0;
3877
4489
  }
@@ -3885,7 +4497,7 @@ function describeCause(cause) {
3885
4497
  if (cause.message) details.message = cause.message;
3886
4498
  const code = stringField(cause, "code");
3887
4499
  if (code) details.code = code;
3888
- } else if (isRecord2(cause)) {
4500
+ } else if (isRecord3(cause)) {
3889
4501
  const code = stringField(cause, "code");
3890
4502
  const name = stringField(cause, "name");
3891
4503
  const message = stringField(cause, "message");
@@ -3913,7 +4525,7 @@ function describeFetchFailure(err) {
3913
4525
  details.message = String(err);
3914
4526
  }
3915
4527
  const { message: causeMessage, details: causeDetails } = describeCause(
3916
- isRecord2(err) ? err.cause : void 0
4528
+ isRecord3(err) ? err.cause : void 0
3917
4529
  );
3918
4530
  if (causeDetails) {
3919
4531
  details.cause = causeDetails;
@@ -3944,6 +4556,8 @@ var AlvaClient = class {
3944
4556
  originSessionId;
3945
4557
  /** Session profile kind associated with originSessionId. */
3946
4558
  originSessionKind;
4559
+ /** Host-attached file Session target, distinct from the chat origin header. */
4560
+ originInboxPath;
3947
4561
  _fs;
3948
4562
  _run;
3949
4563
  _deploy;
@@ -3974,7 +4588,9 @@ var AlvaClient = class {
3974
4588
  _credits;
3975
4589
  _markets;
3976
4590
  _schedules;
4591
+ _steward;
3977
4592
  _tradingPairs;
4593
+ _theses;
3978
4594
  constructor(config) {
3979
4595
  this.baseUrl = config.baseUrl ?? DEFAULT_BASE_URL;
3980
4596
  this.arraysBaseUrl = config.arraysBaseUrl ?? DEFAULT_ARRAYS_BASE_URL;
@@ -3987,6 +4603,7 @@ var AlvaClient = class {
3987
4603
  this.signal = config.signal;
3988
4604
  this.originSessionId = config.originSessionId;
3989
4605
  this.originSessionKind = config.originSessionKind;
4606
+ this.originInboxPath = config.originInboxPath;
3990
4607
  }
3991
4608
  get fs() {
3992
4609
  return this._fs ??= new FsResource(this);
@@ -4078,6 +4695,12 @@ var AlvaClient = class {
4078
4695
  get schedules() {
4079
4696
  return this._schedules ??= new SchedulesResource(this);
4080
4697
  }
4698
+ get steward() {
4699
+ return this._steward ??= new StewardResource(this);
4700
+ }
4701
+ get theses() {
4702
+ return this._theses ??= new ThesesResource(this);
4703
+ }
4081
4704
  _requireAuth() {
4082
4705
  if (!this.pbsvToken && !this.viewer_token && !this.apiKey) {
4083
4706
  throw new AlvaError(
@@ -4694,7 +5317,7 @@ var installPlaybookRuntime = (targetWindow) => {
4694
5317
  };
4695
5318
 
4696
5319
  // src/index.ts
4697
- var VERSION = true ? "0.28.0" : "dev";
5320
+ var VERSION = true ? "0.28.1-beta.1" : "dev";
4698
5321
  // Annotate the CommonJS export names for ESM import in node:
4699
5322
  0 && (module.exports = {
4700
5323
  AlertsResource,
@@ -4710,6 +5333,8 @@ var VERSION = true ? "0.28.0" : "dev";
4710
5333
  SUBSCRIBE_PROPOSE_MESSAGE,
4711
5334
  SUBSCRIBE_RESULT_MESSAGE,
4712
5335
  SchedulesResource,
5336
+ StewardResource,
5337
+ ThesesResource,
4713
5338
  TradingPairsResource,
4714
5339
  UDF_AUTH_REQUIRED_MESSAGE,
4715
5340
  UDF_CONSENT_REQUEST_MESSAGE,