@botiverse/raft-sdk 0.6.0 → 0.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/esm/index.js CHANGED
@@ -3112,6 +3112,12 @@ const numberProcessor = (schema, ctx, _json, _params) => {
3112
3112
  const booleanProcessor = (_schema, _ctx, json, _params) => {
3113
3113
  json.type = "boolean";
3114
3114
  };
3115
+ const bigintProcessor = (_schema, ctx, _json, _params) => {
3116
+ if (ctx.unrepresentable === "throw") throw new Error("BigInt cannot be represented in JSON Schema");
3117
+ };
3118
+ const symbolProcessor = (_schema, ctx, _json, _params) => {
3119
+ if (ctx.unrepresentable === "throw") throw new Error("Symbols cannot be represented in JSON Schema");
3120
+ };
3115
3121
  const nullProcessor = (_schema, ctx, json, _params) => {
3116
3122
  if (ctx.target === "openapi-3.0") {
3117
3123
  json.type = "string";
@@ -3119,9 +3125,20 @@ const nullProcessor = (_schema, ctx, json, _params) => {
3119
3125
  json.enum = [null];
3120
3126
  } else json.type = "null";
3121
3127
  };
3128
+ const undefinedProcessor = (_schema, ctx, _json, _params) => {
3129
+ if (ctx.unrepresentable === "throw") throw new Error("Undefined cannot be represented in JSON Schema");
3130
+ };
3131
+ const voidProcessor = (_schema, ctx, _json, _params) => {
3132
+ if (ctx.unrepresentable === "throw") throw new Error("Void cannot be represented in JSON Schema");
3133
+ };
3122
3134
  const neverProcessor = (_schema, _ctx, json, _params) => {
3123
3135
  json.not = {};
3124
3136
  };
3137
+ const anyProcessor = (_schema, _ctx, _json, _params) => {};
3138
+ const unknownProcessor = (_schema, _ctx, _json, _params) => {};
3139
+ const dateProcessor = (_schema, ctx, _json, _params) => {
3140
+ if (ctx.unrepresentable === "throw") throw new Error("Date cannot be represented in JSON Schema");
3141
+ };
3125
3142
  const enumProcessor = (schema, _ctx, json, _params) => {
3126
3143
  const def = schema._zod.def;
3127
3144
  const values = getEnumValues(def.entries);
@@ -3151,12 +3168,54 @@ const literalProcessor = (schema, ctx, json, _params) => {
3151
3168
  json.enum = vals;
3152
3169
  }
3153
3170
  };
3171
+ const nanProcessor = (_schema, ctx, _json, _params) => {
3172
+ if (ctx.unrepresentable === "throw") throw new Error("NaN cannot be represented in JSON Schema");
3173
+ };
3174
+ const templateLiteralProcessor = (schema, _ctx, json, _params) => {
3175
+ const _json = json;
3176
+ const pattern = schema._zod.pattern;
3177
+ if (!pattern) throw new Error("Pattern not found in template literal");
3178
+ _json.type = "string";
3179
+ _json.pattern = pattern.source;
3180
+ };
3181
+ const fileProcessor = (schema, _ctx, json, _params) => {
3182
+ const _json = json;
3183
+ const file = {
3184
+ type: "string",
3185
+ format: "binary",
3186
+ contentEncoding: "binary"
3187
+ };
3188
+ const { minimum, maximum, mime } = schema._zod.bag;
3189
+ if (minimum !== void 0) file.minLength = minimum;
3190
+ if (maximum !== void 0) file.maxLength = maximum;
3191
+ if (mime) {
3192
+ if (mime.length === 1) {
3193
+ file.contentMediaType = mime[0];
3194
+ Object.assign(_json, file);
3195
+ } else {
3196
+ Object.assign(_json, file);
3197
+ _json.anyOf = mime.map((m) => ({ contentMediaType: m }));
3198
+ }
3199
+ } else Object.assign(_json, file);
3200
+ };
3201
+ const successProcessor = (_schema, _ctx, json, _params) => {
3202
+ json.type = "boolean";
3203
+ };
3154
3204
  const customProcessor = (_schema, ctx, _json, _params) => {
3155
3205
  if (ctx.unrepresentable === "throw") throw new Error("Custom types cannot be represented in JSON Schema");
3156
3206
  };
3207
+ const functionProcessor = (_schema, ctx, _json, _params) => {
3208
+ if (ctx.unrepresentable === "throw") throw new Error("Function types cannot be represented in JSON Schema");
3209
+ };
3157
3210
  const transformProcessor = (_schema, ctx, _json, _params) => {
3158
3211
  if (ctx.unrepresentable === "throw") throw new Error("Transforms cannot be represented in JSON Schema");
3159
3212
  };
3213
+ const mapProcessor = (_schema, ctx, _json, _params) => {
3214
+ if (ctx.unrepresentable === "throw") throw new Error("Map cannot be represented in JSON Schema");
3215
+ };
3216
+ const setProcessor = (_schema, ctx, _json, _params) => {
3217
+ if (ctx.unrepresentable === "throw") throw new Error("Set cannot be represented in JSON Schema");
3218
+ };
3160
3219
  const arrayProcessor = (schema, ctx, _json, params) => {
3161
3220
  const json = _json;
3162
3221
  const def = schema._zod.def;
@@ -3233,6 +3292,44 @@ const intersectionProcessor = (schema, ctx, json, params) => {
3233
3292
  const isSimpleIntersection = (val) => "allOf" in val && Object.keys(val).length === 1;
3234
3293
  json.allOf = [...isSimpleIntersection(a) ? a.allOf : [a], ...isSimpleIntersection(b) ? b.allOf : [b]];
3235
3294
  };
3295
+ const tupleProcessor = (schema, ctx, _json, params) => {
3296
+ const json = _json;
3297
+ const def = schema._zod.def;
3298
+ json.type = "array";
3299
+ const prefixPath = ctx.target === "draft-2020-12" ? "prefixItems" : "items";
3300
+ const restPath = ctx.target === "draft-2020-12" ? "items" : ctx.target === "openapi-3.0" ? "items" : "additionalItems";
3301
+ const prefixItems = def.items.map((x, i) => process$1(x, ctx, {
3302
+ ...params,
3303
+ path: [
3304
+ ...params.path,
3305
+ prefixPath,
3306
+ i
3307
+ ]
3308
+ }));
3309
+ const rest = def.rest ? process$1(def.rest, ctx, {
3310
+ ...params,
3311
+ path: [
3312
+ ...params.path,
3313
+ restPath,
3314
+ ...ctx.target === "openapi-3.0" ? [def.items.length] : []
3315
+ ]
3316
+ }) : null;
3317
+ if (ctx.target === "draft-2020-12") {
3318
+ json.prefixItems = prefixItems;
3319
+ if (rest) json.items = rest;
3320
+ } else if (ctx.target === "openapi-3.0") {
3321
+ json.items = { anyOf: prefixItems };
3322
+ if (rest) json.items.anyOf.push(rest);
3323
+ json.minItems = prefixItems.length;
3324
+ if (!rest) json.maxItems = prefixItems.length;
3325
+ } else {
3326
+ json.items = prefixItems;
3327
+ if (rest) json.additionalItems = rest;
3328
+ }
3329
+ const { minimum, maximum } = schema._zod.bag;
3330
+ if (typeof minimum === "number") json.minItems = minimum;
3331
+ if (typeof maximum === "number") json.maxItems = maximum;
3332
+ };
3236
3333
  const recordProcessor = (schema, ctx, _json, params) => {
3237
3334
  const json = _json;
3238
3335
  const def = schema._zod.def;
@@ -3322,12 +3419,99 @@ const readonlyProcessor = (schema, ctx, json, params) => {
3322
3419
  seen.ref = def.innerType;
3323
3420
  json.readOnly = true;
3324
3421
  };
3422
+ const promiseProcessor = (schema, ctx, _json, params) => {
3423
+ const def = schema._zod.def;
3424
+ process$1(def.innerType, ctx, params);
3425
+ const seen = ctx.seen.get(schema);
3426
+ seen.ref = def.innerType;
3427
+ };
3325
3428
  const optionalProcessor = (schema, ctx, _json, params) => {
3326
3429
  const def = schema._zod.def;
3327
3430
  process$1(def.innerType, ctx, params);
3328
3431
  const seen = ctx.seen.get(schema);
3329
3432
  seen.ref = def.innerType;
3330
3433
  };
3434
+ const lazyProcessor = (schema, ctx, _json, params) => {
3435
+ const innerType = schema._zod.innerType;
3436
+ process$1(innerType, ctx, params);
3437
+ const seen = ctx.seen.get(schema);
3438
+ seen.ref = innerType;
3439
+ };
3440
+ const allProcessors = {
3441
+ string: stringProcessor,
3442
+ number: numberProcessor,
3443
+ boolean: booleanProcessor,
3444
+ bigint: bigintProcessor,
3445
+ symbol: symbolProcessor,
3446
+ null: nullProcessor,
3447
+ undefined: undefinedProcessor,
3448
+ void: voidProcessor,
3449
+ never: neverProcessor,
3450
+ any: anyProcessor,
3451
+ unknown: unknownProcessor,
3452
+ date: dateProcessor,
3453
+ enum: enumProcessor,
3454
+ literal: literalProcessor,
3455
+ nan: nanProcessor,
3456
+ template_literal: templateLiteralProcessor,
3457
+ file: fileProcessor,
3458
+ success: successProcessor,
3459
+ custom: customProcessor,
3460
+ function: functionProcessor,
3461
+ transform: transformProcessor,
3462
+ map: mapProcessor,
3463
+ set: setProcessor,
3464
+ array: arrayProcessor,
3465
+ object: objectProcessor,
3466
+ union: unionProcessor,
3467
+ intersection: intersectionProcessor,
3468
+ tuple: tupleProcessor,
3469
+ record: recordProcessor,
3470
+ nullable: nullableProcessor,
3471
+ nonoptional: nonoptionalProcessor,
3472
+ default: defaultProcessor,
3473
+ prefault: prefaultProcessor,
3474
+ catch: catchProcessor,
3475
+ pipe: pipeProcessor,
3476
+ readonly: readonlyProcessor,
3477
+ promise: promiseProcessor,
3478
+ optional: optionalProcessor,
3479
+ lazy: lazyProcessor
3480
+ };
3481
+ function toJSONSchema(input, params) {
3482
+ if ("_idmap" in input) {
3483
+ const registry = input;
3484
+ const ctx = initializeContext({
3485
+ ...params,
3486
+ processors: allProcessors
3487
+ });
3488
+ const defs = {};
3489
+ for (const entry of registry._idmap.entries()) {
3490
+ const [_, schema] = entry;
3491
+ process$1(schema, ctx);
3492
+ }
3493
+ const schemas = {};
3494
+ ctx.external = {
3495
+ registry,
3496
+ uri: params?.uri,
3497
+ defs
3498
+ };
3499
+ for (const entry of registry._idmap.entries()) {
3500
+ const [key, schema] = entry;
3501
+ extractDefs(ctx, schema);
3502
+ schemas[key] = finalize(ctx, schema);
3503
+ }
3504
+ if (Object.keys(defs).length > 0) schemas.__shared = { [ctx.target === "draft-2020-12" ? "$defs" : "definitions"]: defs };
3505
+ return { schemas };
3506
+ }
3507
+ const ctx = initializeContext({
3508
+ ...params,
3509
+ processors: allProcessors
3510
+ });
3511
+ process$1(input, ctx);
3512
+ extractDefs(ctx, input);
3513
+ return finalize(ctx, input);
3514
+ }
3331
3515
  //#endregion
3332
3516
  //#region ../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/classic/iso.js
3333
3517
  const ZodISODateTime = /*@__PURE__*/ $constructor("ZodISODateTime", (inst, def) => {
@@ -7621,7 +7805,7 @@ async function joinRaftChannelByTarget(client, request) {
7621
7805
  //#endregion
7622
7806
  //#region src/events.ts
7623
7807
  const sequence = number$1().int().nonnegative().max(Number.MAX_SAFE_INTEGER);
7624
- const requestSchema = object({
7808
+ const requestSchema$1 = object({
7625
7809
  since: union([sequence, literal("latest")]).optional(),
7626
7810
  limit: number$1().int().min(1).max(200).optional(),
7627
7811
  ack: literal("cursor").optional()
@@ -7677,7 +7861,7 @@ function failure$2(code, status, cursorAck = false) {
7677
7861
  }
7678
7862
  /** Internal adapter. The caller must supply a single-attempt transport: receive drains the returned batch. */
7679
7863
  async function receiveRaftEvents(client, request = {}) {
7680
- const parsed = requestSchema.safeParse(request);
7864
+ const parsed = requestSchema$1.safeParse(request);
7681
7865
  if (!parsed.success) return failure$2("INVALID_REQUEST");
7682
7866
  const cursorAck = parsed.data.ack === "cursor";
7683
7867
  const result = await client.events.get({
@@ -10266,7 +10450,8 @@ const DEFAULT_MESSAGES = {
10266
10450
  CONFLICT: "The Raft Server refused the operation because of the current state.",
10267
10451
  IDEMPOTENCY_KEY_REUSED: "This idempotency key was already used for a different message.",
10268
10452
  UNSUPPORTED_FOR_EXTERNAL_AGENTS: "This operation is not available to External Agents.",
10269
- UNAVAILABLE: "The Raft Server could not serve this operation right now."
10453
+ UNAVAILABLE: "The Raft Server could not serve this operation right now.",
10454
+ MODEL_ONLY: "This operation only counts when the model sees its result, so it cannot be run from code; nothing was sent."
10270
10455
  };
10271
10456
  const DEFAULT_NEXT_ACTION = {
10272
10457
  INVALID_REQUEST: "Fix the request arguments; nothing was sent.",
@@ -10279,7 +10464,8 @@ const DEFAULT_NEXT_ACTION = {
10279
10464
  CONFLICT: "Read the current state before repeating this operation.",
10280
10465
  IDEMPOTENCY_KEY_REUSED: "Use a new idempotency key for a different message, or resend the identical payload to reconcile.",
10281
10466
  UNSUPPORTED_FOR_EXTERNAL_AGENTS: "Use your own runtime for this; the Server does not provide it to External Agents.",
10282
- UNAVAILABLE: "Retry in a moment."
10467
+ UNAVAILABLE: "Retry in a moment.",
10468
+ MODEL_ONLY: "Call it as a model tool call instead of from code."
10283
10469
  };
10284
10470
  const RETRYABLE = {
10285
10471
  INVALID_REQUEST: false,
@@ -10292,7 +10478,8 @@ const RETRYABLE = {
10292
10478
  CONFLICT: false,
10293
10479
  IDEMPOTENCY_KEY_REUSED: false,
10294
10480
  UNSUPPORTED_FOR_EXTERNAL_AGENTS: false,
10295
- UNAVAILABLE: true
10481
+ UNAVAILABLE: true,
10482
+ MODEL_ONLY: false
10296
10483
  };
10297
10484
  function classifyHttp(status, serverCode) {
10298
10485
  const code = serverCode?.toLowerCase() ?? "";
@@ -10368,6 +10555,22 @@ function failureOutcome(error) {
10368
10555
  function failureFromClientResult(result) {
10369
10556
  return failureOutcome(opErrorFromClientError(result.error, result.status));
10370
10557
  }
10558
+ const MAX_REPORTED_ISSUES = 3;
10559
+ /**
10560
+ * Validate an operation's input with its zod request schema. Returns null when
10561
+ * it is valid, otherwise an `INVALID_REQUEST` failure whose message names the
10562
+ * offending fields and what was expected (zod's issue text, which never
10563
+ * echoes the input value); nothing is sent.
10564
+ */
10565
+ function validateOpRequest(schema, value) {
10566
+ const parsed = schema.safeParse(value);
10567
+ if (parsed.success) return null;
10568
+ const issues = parsed.error.issues.slice(0, MAX_REPORTED_ISSUES).map((issue) => {
10569
+ return `${issue.path.map((part) => typeof part === "number" ? `[${part}]` : String(part)).join(".").replace(/\.\[/g, "[") || "request"}: ${issue.message}`;
10570
+ });
10571
+ const more = parsed.error.issues.length > MAX_REPORTED_ISSUES ? ` (+${parsed.error.issues.length - MAX_REPORTED_ISSUES} more)` : "";
10572
+ return failureOutcome(opError("INVALID_REQUEST", { message: `Invalid request: ${issues.join("; ")}${more}. Nothing was sent.` }));
10573
+ }
10371
10574
  //#endregion
10372
10575
  //#region ../shared/src/agentInbox.ts
10373
10576
  const NON_MEMBER_MENTION_REPLY_GUIDANCE = "[Raft notice: You were notified as a non-member, so you cannot reply in that channel. If no reply is needed, no action is required. Otherwise, DM the person who mentioned you or join the channel to participate.]";
@@ -11001,50 +11204,75 @@ const MAX_EXACT_SEQS = 2500;
11001
11204
  function positiveInt(value) {
11002
11205
  return typeof value === "number" && Number.isInteger(value) && value > 0;
11003
11206
  }
11207
+ function contextOrNull(value) {
11208
+ return typeof value === "string" && value.length > 0 ? value : null;
11209
+ }
11004
11210
  var SeenFrontier = class SeenFrontier {
11005
- targets = /* @__PURE__ */ new Map();
11006
- aliases = /* @__PURE__ */ new Map();
11211
+ core = {
11212
+ targets: /* @__PURE__ */ new Map(),
11213
+ aliases: /* @__PURE__ */ new Map(),
11214
+ context: null
11215
+ };
11216
+ /** Set on a view from `inContext`: the context this view books and attests under. */
11217
+ bound = void 0;
11007
11218
  static fromSnapshot(snapshot) {
11008
11219
  const frontier = new SeenFrontier();
11009
11220
  frontier.absorb(snapshot);
11010
11221
  return frontier;
11011
11222
  }
11012
- /** Merge a snapshot into this frontier by the same monotonic rules (never lowers a mark). */
11223
+ /** The model context this frontier books and attests under; null means no context scoping. */
11224
+ get contextId() {
11225
+ return this.bound !== void 0 ? this.bound : this.core.context;
11226
+ }
11227
+ /**
11228
+ * Set the current model context (shared by every view of this frontier that
11229
+ * is not bound to its own context). Call it when the model's context
11230
+ * changes (a new session, a compaction): reads booked under the previous
11231
+ * context then no longer attest a send. `null` turns scoping off.
11232
+ */
11233
+ setContext(contextId) {
11234
+ this.core.context = contextOrNull(contextId);
11235
+ }
11236
+ /**
11237
+ * A view over the same records that books and attests under `contextId`
11238
+ * (for one call made on behalf of that model context), without changing the
11239
+ * frontier's current context. `undefined` returns this frontier.
11240
+ */
11241
+ inContext(contextId) {
11242
+ if (contextId === void 0) return this;
11243
+ const view = new SeenFrontier();
11244
+ view.core = this.core;
11245
+ view.bound = contextOrNull(contextId);
11246
+ return view;
11247
+ }
11248
+ /**
11249
+ * Merge a snapshot into this frontier: each record is booked under the
11250
+ * context it was booked in (same context: monotonic, never lowers a mark).
11251
+ * Adopts the snapshot's current context when this frontier has none.
11252
+ */
11013
11253
  absorb(snapshot) {
11014
11254
  if (!snapshot || snapshot.version !== 1) return;
11015
11255
  for (const [alias, canonical] of Object.entries(snapshot.aliases ?? {})) this.recordAlias(alias, canonical);
11016
11256
  for (const [target, state] of Object.entries(snapshot.targets ?? {})) {
11017
- if (positiveInt(state.upTo)) this.recordUpTo(target, state.upTo);
11018
- if (Array.isArray(state.exact)) this.recordExact(target, state.exact);
11257
+ if (positiveInt(state.upTo)) this.bookUpTo(target, state.upTo, contextOrNull(state.upToContextId));
11258
+ if (Array.isArray(state.exact)) this.bookExact(target, state.exact, contextOrNull(state.exactContextId));
11019
11259
  }
11260
+ if (this.core.context === null) this.core.context = contextOrNull(snapshot.contextId);
11020
11261
  }
11021
11262
  /** Remember that the Server resolved `requested` to `canonical` (a thread spelling, a `~agent` suffix, …). */
11022
11263
  recordAlias(requested, canonical) {
11023
- if (requested && canonical && requested !== canonical) this.aliases.set(requested, canonical);
11264
+ if (requested && canonical && requested !== canonical) this.core.aliases.set(requested, canonical);
11024
11265
  }
11025
11266
  canonical(target) {
11026
- return this.aliases.get(target) ?? target;
11267
+ return this.core.aliases.get(target) ?? target;
11027
11268
  }
11028
- /** Advance the contiguous boundary for a target; never lowers it. */
11269
+ /** Advance the contiguous boundary for a target in the current context; never lowers it within one context. */
11029
11270
  recordUpTo(target, seq) {
11030
- if (!positiveInt(seq)) return;
11031
- const state = this.state(this.canonical(target));
11032
- if (state.upTo === void 0 || seq > state.upTo) state.upTo = seq;
11033
- for (const exact of state.exact) if (exact <= state.upTo) state.exact.delete(exact);
11271
+ this.bookUpTo(target, seq, this.contextId);
11034
11272
  }
11035
- /** Record bodies that were rendered without proving contiguity. */
11273
+ /** Record bodies that were rendered without proving contiguity, in the current context. */
11036
11274
  recordExact(target, seqs) {
11037
- const state = this.state(this.canonical(target));
11038
- for (const seq of seqs) {
11039
- if (!positiveInt(seq)) continue;
11040
- if (state.upTo !== void 0 && seq <= state.upTo) continue;
11041
- state.exact.add(seq);
11042
- }
11043
- if (state.exact.size > MAX_EXACT_SEQS) {
11044
- const keep = [...state.exact].sort((a, b) => b - a).slice(0, MAX_EXACT_SEQS);
11045
- state.exact.clear();
11046
- for (const seq of keep) state.exact.add(seq);
11047
- }
11275
+ this.bookExact(target, seqs, this.contextId);
11048
11276
  }
11049
11277
  /**
11050
11278
  * Attest that the model saw the context of an interrupt (`outcome.interrupt`
@@ -11059,32 +11287,75 @@ var SeenFrontier = class SeenFrontier {
11059
11287
  this.recordUpTo(held.target, held.seenUpToSeq);
11060
11288
  return true;
11061
11289
  }
11062
- /** What to attest on a send or claim to `target`; omits `seenUpToSeq` when nothing contiguous is known. */
11290
+ /**
11291
+ * What to attest on a send or claim to `target`; omits `seenUpToSeq` when
11292
+ * nothing contiguous is known. With a current context, only bookings made
11293
+ * in that context count.
11294
+ */
11063
11295
  attestation(target) {
11064
- const state = this.targets.get(this.canonical(target));
11296
+ const state = this.core.targets.get(this.canonical(target));
11065
11297
  if (!state) return { seenExactSeqs: [] };
11298
+ const context = this.contextId;
11299
+ const upTo = context === null || state.upToContext === context ? state.upTo : void 0;
11300
+ const exact = context === null || state.exactContext === context ? [...state.exact] : [];
11066
11301
  return {
11067
- ...state.upTo === void 0 ? {} : { seenUpToSeq: state.upTo },
11068
- seenExactSeqs: [...state.exact].sort((a, b) => a - b)
11302
+ ...upTo === void 0 ? {} : { seenUpToSeq: upTo },
11303
+ seenExactSeqs: exact.filter((seq) => upTo === void 0 || seq > upTo).sort((a, b) => a - b)
11069
11304
  };
11070
11305
  }
11071
11306
  snapshot() {
11072
11307
  const targets = {};
11073
- for (const [target, state] of this.targets) targets[target] = {
11308
+ for (const [target, state] of this.core.targets) targets[target] = {
11074
11309
  ...state.upTo === void 0 ? {} : { upTo: state.upTo },
11075
- ...state.exact.size === 0 ? {} : { exact: [...state.exact].sort((a, b) => a - b) }
11310
+ ...state.exact.size === 0 ? {} : { exact: [...state.exact].sort((a, b) => a - b) },
11311
+ ...state.upTo === void 0 || state.upToContext === null ? {} : { upToContextId: state.upToContext },
11312
+ ...state.exact.size === 0 || state.exactContext === null ? {} : { exactContextId: state.exactContext }
11076
11313
  };
11077
11314
  return {
11078
11315
  version: 1,
11079
11316
  targets,
11080
- aliases: Object.fromEntries(this.aliases)
11317
+ aliases: Object.fromEntries(this.core.aliases),
11318
+ ...this.core.context === null ? {} : { contextId: this.core.context }
11081
11319
  };
11082
11320
  }
11321
+ /** A high-water booking (seenPolicy `bookStreamEntries`): another context's record is replaced, not merged. */
11322
+ bookUpTo(target, seq, context) {
11323
+ if (!positiveInt(seq)) return;
11324
+ const state = this.state(this.canonical(target));
11325
+ if (state.exact.size > 0 && state.exactContext !== context) state.exact.clear();
11326
+ if (state.upTo === void 0 || state.upToContext !== context || seq > state.upTo) state.upTo = seq;
11327
+ state.upToContext = context;
11328
+ state.exactContext = context;
11329
+ for (const exact of state.exact) if (exact <= state.upTo) state.exact.delete(exact);
11330
+ }
11331
+ /** A sparse booking (seenPolicy `bookExactSeqs`): merges within a context, replaces across; never moves `upTo`. */
11332
+ bookExact(target, seqs, context) {
11333
+ const state = this.state(this.canonical(target));
11334
+ if (state.exactContext !== context) {
11335
+ state.exact.clear();
11336
+ state.exactContext = context;
11337
+ }
11338
+ const floor = state.upToContext === context ? state.upTo : void 0;
11339
+ for (const seq of seqs) {
11340
+ if (!positiveInt(seq)) continue;
11341
+ if (floor !== void 0 && seq <= floor) continue;
11342
+ state.exact.add(seq);
11343
+ }
11344
+ if (state.exact.size > MAX_EXACT_SEQS) {
11345
+ const keep = [...state.exact].sort((a, b) => b - a).slice(0, MAX_EXACT_SEQS);
11346
+ state.exact.clear();
11347
+ for (const seq of keep) state.exact.add(seq);
11348
+ }
11349
+ }
11083
11350
  state(target) {
11084
- let state = this.targets.get(target);
11351
+ let state = this.core.targets.get(target);
11085
11352
  if (!state) {
11086
- state = { exact: /* @__PURE__ */ new Set() };
11087
- this.targets.set(target, state);
11353
+ state = {
11354
+ upToContext: null,
11355
+ exact: /* @__PURE__ */ new Set(),
11356
+ exactContext: null
11357
+ };
11358
+ this.core.targets.set(target, state);
11088
11359
  }
11089
11360
  return state;
11090
11361
  }
@@ -11157,7 +11428,18 @@ function latestReadThreadFromCliReadState(raw) {
11157
11428
  };
11158
11429
  }
11159
11430
  //#endregion
11431
+ //#region ../shared/src/agentOps/requestSchema.ts
11432
+ function requestSchema() {
11433
+ return (schema) => schema;
11434
+ }
11435
+ //#endregion
11160
11436
  //#region ../shared/src/agentOps/inbox.ts
11437
+ const inboxPullFields = {
11438
+ since: number$1().int().nonnegative().optional().describe("Cursor of the previous batch; under cursor acks it acknowledges that batch. Omit to continue from the last committed cursor."),
11439
+ limit: number$1().int().positive().optional().describe("Messages per batch, 1..200 (Server default 50)."),
11440
+ ack: _enum(["cursor", "immediate"]).optional().describe("cursor (default): a batch is acknowledged by the next pull; immediate: acknowledged as it is returned.")
11441
+ };
11442
+ const checkInboxRequestSchema = requestSchema()(object(inboxPullFields));
11161
11443
  const MAX_DRAIN_ROUNDS = 50;
11162
11444
  function batchNext(batch) {
11163
11445
  if (batch.hasMore) return {
@@ -11196,6 +11478,8 @@ function recordExactSeen(frontier, messages) {
11196
11478
  }
11197
11479
  /** One bounded pull. Records exact seen seqs on `frontier` (sparse drains never advance the high-water mark). */
11198
11480
  async function checkInbox(client, request = {}, frontier) {
11481
+ const invalid = validateOpRequest(checkInboxRequestSchema, request);
11482
+ if (invalid) return invalid;
11199
11483
  const ack = request.ack ?? "cursor";
11200
11484
  const result = await client.events.get({
11201
11485
  since: request.since === void 0 ? "latest" : String(request.since),
@@ -11222,6 +11506,7 @@ async function checkInbox(client, request = {}, frontier) {
11222
11506
  text: batchText(batch)
11223
11507
  };
11224
11508
  }
11509
+ const drainInboxRequestSchema = requestSchema()(object(inboxPullFields));
11225
11510
  /**
11226
11511
  * Pull until the Server reports nothing more, like `raft message check`, but
11227
11512
  * as an async iterator so that acknowledgement follows consumption: under
@@ -11234,6 +11519,15 @@ async function checkInbox(client, request = {}, frontier) {
11234
11519
  */
11235
11520
  async function* drainInbox(client, request = {}, frontier, onPull) {
11236
11521
  const ack = request.ack ?? "cursor";
11522
+ const invalid = validateOpRequest(drainInboxRequestSchema, request);
11523
+ if (invalid) return {
11524
+ cursor: null,
11525
+ ackMode: ack,
11526
+ rounds: 0,
11527
+ hasMore: true,
11528
+ stillUnreadConversations: null,
11529
+ error: invalid
11530
+ };
11237
11531
  let cursor = request.since ?? null;
11238
11532
  let ackMode = ack;
11239
11533
  let stillUnread = null;
@@ -11294,6 +11588,47 @@ async function* drainInbox(client, request = {}, frontier, onPull) {
11294
11588
  error: null
11295
11589
  };
11296
11590
  }
11591
+ /** Fold a finished drain into one outcome; a drain that failed before its first batch is that failure. */
11592
+ function drainedInboxOutcome(batches, summary) {
11593
+ if (summary.error && batches.length === 0) return summary.error;
11594
+ const messages = batches.flatMap((batch) => batch.messages);
11595
+ const lines = [formatAgentMessages(messages.map((m) => toAgentMessageLike(m.raw)))];
11596
+ if (summary.error) lines.push("The drain stopped early on an error; more messages may be pending. Check the inbox again.");
11597
+ else if (summary.hasMore) lines.push("More messages are pending. Check the inbox again.");
11598
+ else if (messages.length > 0) lines.push("No more new inbox messages.");
11599
+ const stillUnread = summary.stillUnreadConversations ?? 0;
11600
+ if (stillUnread > 0) lines.push(formatAgentInboxHint({ unread_conversations: stillUnread }));
11601
+ const first = messages[0];
11602
+ const next = summary.hasMore ? {
11603
+ kind: "check_inbox_again",
11604
+ command: "raft message check",
11605
+ why: "More messages are pending."
11606
+ } : stillUnread > 0 ? {
11607
+ kind: "list_inbox",
11608
+ command: "raft inbox check",
11609
+ why: "Conversations remain unread beyond this drain."
11610
+ } : first ? {
11611
+ kind: "reply_or_act",
11612
+ args: { target: first.target },
11613
+ why: "Handle the messages above; reply where each one came from."
11614
+ } : null;
11615
+ return {
11616
+ ok: true,
11617
+ state: messages.length > 0 ? "batch" : "empty",
11618
+ data: {
11619
+ messages,
11620
+ batches: batches.length,
11621
+ summary
11622
+ },
11623
+ next,
11624
+ text: lines.join("\n")
11625
+ };
11626
+ }
11627
+ const listInboxRequestSchema = requestSchema()(object({
11628
+ view: _enum(["unread", "mentions"]).optional().describe("unread (default): every unread conversation; mentions: only those that @mention you."),
11629
+ before: number$1().int().nonnegative().optional().describe("Next page: the nextBeforeSeq of the previous page."),
11630
+ limit: number$1().int().positive().optional().describe("Conversations per page, 1..50 (Server default 20).")
11631
+ }));
11297
11632
  function openCommandFor(item) {
11298
11633
  return `raft message read --target "${item.target}" --after ${item.lastReadSeq}`;
11299
11634
  }
@@ -11329,6 +11664,8 @@ function listingText(listing) {
11329
11664
  }
11330
11665
  /** The agent's Activity panel. Lists only; nothing is consumed. */
11331
11666
  async function listInbox(client, request = {}) {
11667
+ const invalid = validateOpRequest(listInboxRequestSchema, request);
11668
+ if (invalid) return invalid;
11332
11669
  const result = await client.inbox.list({
11333
11670
  ...request.view && request.view !== "unread" ? { view: request.view } : {},
11334
11671
  ...request.before === void 0 ? {} : { before_seq: String(request.before) },
@@ -11363,6 +11700,16 @@ async function listInbox(client, request = {}) {
11363
11700
  }
11364
11701
  //#endregion
11365
11702
  //#region ../shared/src/agentOps/messages.ts
11703
+ /** A conversation target as agents spell it. */
11704
+ const raftTargetSchema = string().describe("Conversation: `#channel`, `dm:@peer`, or a thread `#channel:shortid` / `dm:@peer:shortid`.");
11705
+ const readHistoryRequestSchema = requestSchema()(object({
11706
+ target: raftTargetSchema,
11707
+ after: number$1().int().nonnegative().optional().describe("Only messages after this seq (exclusive): read what is new since a position, for example the `--after` an inbox listing prints."),
11708
+ before: number$1().int().nonnegative().optional().describe("Only messages before this seq (exclusive): browse older history."),
11709
+ around: union([number$1().int(), string()]).optional().describe("Anchor a window around a message: its seq number (for example \"12345\") or its message id."),
11710
+ limit: number$1().int().positive().optional().describe("Maximum messages in the window."),
11711
+ consume: boolean().optional().describe("false reads without consuming: the conversation is not marked read and nothing counts as seen.")
11712
+ }));
11366
11713
  function historyNext(page) {
11367
11714
  const seqs = page.messages.map((m) => m.seq).filter((s) => s !== null);
11368
11715
  if (page.hasNewer && seqs.length > 0) {
@@ -11415,6 +11762,8 @@ function recordHistorySeen(frontier, requested, page, around) {
11415
11762
  frontier.recordExact(page.target, seqs);
11416
11763
  }
11417
11764
  async function readHistory(client, request, frontier) {
11765
+ const invalid = validateOpRequest(readHistoryRequestSchema, request);
11766
+ if (invalid) return invalid;
11418
11767
  if (!request.target?.trim()) return failureOutcome(opError("INVALID_REQUEST", { message: "A target is required to read history." }));
11419
11768
  const result = await client.history.read({
11420
11769
  channel: request.target,
@@ -11445,6 +11794,24 @@ async function readHistory(client, request, frontier) {
11445
11794
  }
11446
11795
  /** Attempts for a keyed send whose request never reached the Server (transport failure only). */
11447
11796
  const SEND_TRANSPORT_ATTEMPTS = 3;
11797
+ const sendMessageFields = {
11798
+ content: string().describe("Message text (Markdown). May be empty only when attachmentIds are given."),
11799
+ attachmentIds: array(string()).optional().describe("Attachment ids from an upload, posted with this message."),
11800
+ idempotencyKey: string().optional().describe("One key per logical message; generated when omitted. Reuse it to retry, and to resume an interrupted send (interrupt.resume.idempotencyKey)."),
11801
+ mentions: array(agentApiStructuredMentionSchema).optional().describe("Structured @mentions (user or agent id and name), in addition to @handles in the text."),
11802
+ seen: object({
11803
+ upToSeq: number$1().int().nonnegative().optional(),
11804
+ exactSeqs: array(number$1().int().positive()).optional()
11805
+ }).optional().describe("Override the seen attestation for this send (runtimes that track what their model saw themselves).")
11806
+ };
11807
+ const sendMessageRequestSchema = requestSchema()(object({
11808
+ target: raftTargetSchema,
11809
+ ...sendMessageFields
11810
+ }));
11811
+ const replyToRequestSchema = requestSchema()(object({
11812
+ message: object({ target: raftTargetSchema }).describe("The received message to reply to; only its `target` is used."),
11813
+ ...sendMessageFields
11814
+ }));
11448
11815
  /** Today's held text (unchanged); it is the interrupt's `context` and the outcome's `text`. */
11449
11816
  function heldText(held, action) {
11450
11817
  const noun = held.newMessageCount === 1 ? "message" : "messages";
@@ -11508,6 +11875,8 @@ function sentOutcome(target, data) {
11508
11875
  };
11509
11876
  }
11510
11877
  async function sendMessage(client, request, frontier) {
11878
+ const invalid = validateOpRequest(sendMessageRequestSchema, request);
11879
+ if (invalid) return invalid;
11511
11880
  if (!request.target?.trim()) return failureOutcome(opError("INVALID_REQUEST", { message: "A target is required to send a message." }));
11512
11881
  if (typeof request.content !== "string" || !request.content.trim() && !request.attachmentIds?.length) return failureOutcome(opError("INVALID_REQUEST", { message: "Message content (or an attachment) is required." }));
11513
11882
  const idempotencyKey = request.idempotencyKey?.trim() || crypto.randomUUID();
@@ -11711,7 +12080,21 @@ function formatAgentTaskHistory(data) {
11711
12080
  }
11712
12081
  //#endregion
11713
12082
  //#region ../shared/src/agentOps/tasks.ts
12083
+ const taskChannelSchema = string().describe("The channel the task board belongs to, for example `#proj-sdk`.");
12084
+ const taskNumberSchema = number$1().int().positive().describe("The task number on that channel's board.");
12085
+ const raftTaskStatusSchema = _enum([
12086
+ "todo",
12087
+ "in_progress",
12088
+ "in_review",
12089
+ "done",
12090
+ "closed"
12091
+ ]);
11714
12092
  const TASK_CLAIM_REASON_ALREADY_CLAIMED_BY_YOU = "already claimed by you";
12093
+ const claimTasksRequestSchema = requestSchema()(object({
12094
+ target: taskChannelSchema,
12095
+ taskNumbers: array(number$1().int().positive()).optional().describe("Task numbers to claim."),
12096
+ messageIds: array(string()).optional().describe("Full or short ids of top-level messages to claim as tasks.")
12097
+ }));
11715
12098
  /**
11716
12099
  * A held task call: the interrupt whose resume is the identical command, with
11717
12100
  * no cancel (a held task call saved nothing). `context` is today's held text.
@@ -11760,6 +12143,8 @@ function claimText(claim) {
11760
12143
  async function claimTasks(client, request) {
11761
12144
  const numbers = (request.taskNumbers ?? []).filter((n) => Number.isInteger(n) && n > 0);
11762
12145
  const ids = (request.messageIds ?? []).map((id) => id.trim()).filter(Boolean);
12146
+ const invalid = validateOpRequest(claimTasksRequestSchema, request);
12147
+ if (invalid) return invalid;
11763
12148
  if (!request.target?.trim()) return failureOutcome(opError("INVALID_REQUEST", { message: "A channel target is required to claim tasks." }));
11764
12149
  if (numbers.length === 0 && ids.length === 0) return failureOutcome(opError("INVALID_REQUEST", { message: "Pass at least one task number or message id to claim." }));
11765
12150
  const result = await client.tasks.claim({
@@ -11811,7 +12196,21 @@ async function claimTasks(client, request) {
11811
12196
  text: claimText(claim)
11812
12197
  };
11813
12198
  }
12199
+ const listTasksRequestSchema = requestSchema()(object({
12200
+ target: string().optional().describe("A channel's board, for example `#proj-sdk`. Pass exactly one of target or mine."),
12201
+ mine: boolean().optional().describe("true: your own tasks across channels instead of one board."),
12202
+ status: _enum([
12203
+ "todo",
12204
+ "in_progress",
12205
+ "in_review",
12206
+ "done",
12207
+ "closed",
12208
+ "all"
12209
+ ]).optional().describe("Filter by status; all includes done and closed.")
12210
+ }));
11814
12211
  async function listTasks(client, request) {
12212
+ const invalid = validateOpRequest(listTasksRequestSchema, request);
12213
+ if (invalid) return invalid;
11815
12214
  const mine = request.mine === true;
11816
12215
  if (mine === Boolean(request.target?.trim())) return failureOutcome(opError("INVALID_REQUEST", { message: "Pass exactly one of a channel target or mine: true." }));
11817
12216
  const result = await client.tasks.list({
@@ -11845,7 +12244,17 @@ async function listTasks(client, request) {
11845
12244
  text
11846
12245
  };
11847
12246
  }
12247
+ const createTasksRequestSchema = requestSchema()(object({
12248
+ target: taskChannelSchema,
12249
+ tasks: array(object({
12250
+ title: string().describe("Task title."),
12251
+ createsResource: boolean().optional().describe("The task produces a resource (for example a document) that needs a receipt.")
12252
+ })).describe("One entry per task to create."),
12253
+ assignee: string().optional().describe("`@handle`: yourself to start in_progress, or (owner/admin) someone else to reserve a todo.")
12254
+ }));
11848
12255
  async function createTasks(client, request) {
12256
+ const invalid = validateOpRequest(createTasksRequestSchema, request);
12257
+ if (invalid) return invalid;
11849
12258
  if (!request.target?.trim() || !request.tasks?.length) return failureOutcome(opError("INVALID_REQUEST", { message: "A channel target and at least one task title are required." }));
11850
12259
  const result = await client.tasks.create({
11851
12260
  channel: request.target,
@@ -11874,7 +12283,14 @@ async function createTasks(client, request) {
11874
12283
  text: formatAgentTasksCreated(request.target, data)
11875
12284
  };
11876
12285
  }
11877
- function requireTaskRef(request) {
12286
+ const taskRefFields = {
12287
+ target: taskChannelSchema,
12288
+ taskNumber: taskNumberSchema
12289
+ };
12290
+ const taskRefSchema = requestSchema()(object(taskRefFields));
12291
+ function requireTaskRef(request, schema = taskRefSchema) {
12292
+ const invalid = validateOpRequest(schema, request);
12293
+ if (invalid) return invalid;
11878
12294
  if (!request.target?.trim() || !Number.isInteger(request.taskNumber) || request.taskNumber <= 0) return failureOutcome(opError("INVALID_REQUEST", { message: "A channel target and a positive task number are required." }));
11879
12295
  return null;
11880
12296
  }
@@ -11894,8 +12310,13 @@ async function unclaimTask(client, request) {
11894
12310
  text: formatAgentTaskUnclaimed(request.taskNumber)
11895
12311
  };
11896
12312
  }
12313
+ const assignTaskRequestSchema = requestSchema()(object({
12314
+ ...taskRefFields,
12315
+ assignee: string().trim().min(1).describe("`@handle` to assign (yourself, or someone else if you are an owner/admin). To clear an assignment use tasks.unassign."),
12316
+ expectedRevision: number$1().int().nonnegative().optional().describe("Revision of the task you just read; the change is refused if it moved.")
12317
+ }));
11897
12318
  async function assignTask(client, request) {
11898
- const invalid = requireTaskRef(request);
12319
+ const invalid = requireTaskRef(request, assignTaskRequestSchema);
11899
12320
  if (invalid) return invalid;
11900
12321
  const result = await client.tasks.assign({
11901
12322
  channel: request.target,
@@ -11918,6 +12339,38 @@ async function assignTask(client, request) {
11918
12339
  text: formatAgentTaskAssigned(request.taskNumber, assignee)
11919
12340
  };
11920
12341
  }
12342
+ const unassignTaskRequestSchema = requestSchema()(object({
12343
+ ...taskRefFields,
12344
+ expectedRevision: number$1().int().nonnegative().optional().describe("Revision of the task you just read; the change is refused if it moved.")
12345
+ }));
12346
+ /** Clear a task's assignee (the CLI's `raft task unassign`): the explicit way to clear, never an omitted `assignee`. */
12347
+ async function unassignTask(client, request) {
12348
+ const invalid = requireTaskRef(request, unassignTaskRequestSchema);
12349
+ if (invalid) return invalid;
12350
+ const result = await client.tasks.assign({
12351
+ channel: request.target,
12352
+ task_number: request.taskNumber,
12353
+ assignee: null,
12354
+ ...request.expectedRevision === void 0 ? {} : { expected_revision: request.expectedRevision }
12355
+ });
12356
+ if (!result.ok) return failureFromClientResult(result);
12357
+ return {
12358
+ ok: true,
12359
+ state: "unassigned",
12360
+ data: {
12361
+ target: request.target,
12362
+ taskNumber: request.taskNumber,
12363
+ assignee: null,
12364
+ revision: result.data.revision
12365
+ },
12366
+ next: null,
12367
+ text: formatAgentTaskAssigned(request.taskNumber, null)
12368
+ };
12369
+ }
12370
+ const updateTaskStatusRequestSchema = requestSchema()(object({
12371
+ ...taskRefFields,
12372
+ status: raftTaskStatusSchema.describe("todo → in_progress → in_review → done; closed from anywhere.")
12373
+ }));
11921
12374
  /** A held task write: the interrupt whose resume is the identical command; nothing to cancel. */
11922
12375
  function heldTaskWrite(target, data, action, kind, argv) {
11923
12376
  const interrupt = heldTaskInterrupt(target, data, action, "After reviewing, repeat the operation if it is still correct.", argv);
@@ -11935,7 +12388,7 @@ function heldTaskWrite(target, data, action, kind, argv) {
11935
12388
  };
11936
12389
  }
11937
12390
  async function updateTaskStatus(client, request) {
11938
- const invalid = requireTaskRef(request);
12391
+ const invalid = requireTaskRef(request, updateTaskStatusRequestSchema);
11939
12392
  if (invalid) return invalid;
11940
12393
  const result = await client.tasks.updateStatus({
11941
12394
  channel: request.target,
@@ -11955,6 +12408,11 @@ async function updateTaskStatus(client, request) {
11955
12408
  text: formatAgentTaskStatusUpdated(request.taskNumber, request.status)
11956
12409
  };
11957
12410
  }
12411
+ const amendTaskRequestSchema = requestSchema()(object({
12412
+ ...taskRefFields,
12413
+ title: string().optional().describe("New title."),
12414
+ description: string().nullable().optional().describe("New description; null clears it.")
12415
+ }));
11958
12416
  function taskAmendArgv(request) {
11959
12417
  return [
11960
12418
  "task",
@@ -11968,7 +12426,7 @@ function taskAmendArgv(request) {
11968
12426
  ];
11969
12427
  }
11970
12428
  async function amendTask(client, request) {
11971
- const invalid = requireTaskRef(request);
12429
+ const invalid = requireTaskRef(request, amendTaskRequestSchema);
11972
12430
  if (invalid) return invalid;
11973
12431
  if (request.title === void 0 && request.description === void 0) return failureOutcome(opError("INVALID_REQUEST", { message: "Pass a new title, a new description, or description: null to clear it." }));
11974
12432
  const result = await client.tasks.amend({
@@ -12009,7 +12467,13 @@ async function taskHistory(client, request) {
12009
12467
  text: formatAgentTaskHistory(result.data)
12010
12468
  };
12011
12469
  }
12470
+ const convertMessageToTaskRequestSchema = requestSchema()(object({
12471
+ target: taskChannelSchema,
12472
+ messageId: string().describe("Full or short id of a top-level message in that channel.")
12473
+ }));
12012
12474
  async function convertMessageToTask(client, request) {
12475
+ const invalid = validateOpRequest(convertMessageToTaskRequestSchema, request);
12476
+ if (invalid) return invalid;
12013
12477
  if (!request.target?.trim() || !request.messageId?.trim()) return failureOutcome(opError("INVALID_REQUEST", { message: "A channel target and a message id are required." }));
12014
12478
  const result = await client.tasks.convert({
12015
12479
  channel: request.target,
@@ -12605,6 +13069,15 @@ function formatAgentProfile(profile, options = {}) {
12605
13069
  }
12606
13070
  //#endregion
12607
13071
  //#region ../shared/src/agentOps/channels.ts
13072
+ /** `{ target }` of a regular channel (join, leave, mute, unmute). */
13073
+ const channelTargetRequestSchema = requestSchema()(object({ target: string().describe("A regular channel, `#channel-name`. DMs and threads are not accepted.") }));
13074
+ const channelMembersRequestSchema = requestSchema()(object({ target: string().describe("A channel, DM, or thread target.") }));
13075
+ /** `threads.list` takes no arguments. */
13076
+ const listThreadsRequestSchema = object({});
13077
+ const unfollowThreadRequestSchema = requestSchema()(object({
13078
+ target: string().describe("The thread, for example `#channel:shortid` or `dm:@peer:shortid`."),
13079
+ reason: string().optional().describe("Short reason, kept with the unfollow.")
13080
+ }));
12608
13081
  const INVALID_CHANNEL_TARGET = "Target must be a regular channel in the form '#channel-name'. DMs and thread targets are not supported.";
12609
13082
  async function resolveRegularChannel(client, target) {
12610
13083
  const name = parseRaftRegularChannelTarget$1(target ?? "");
@@ -12623,6 +13096,8 @@ async function resolveRegularChannel(client, target) {
12623
13096
  };
12624
13097
  }
12625
13098
  async function joinChannel(client, request) {
13099
+ const invalid = validateOpRequest(channelTargetRequestSchema, request);
13100
+ if (invalid) return invalid;
12626
13101
  const result = await joinRaftChannelByTarget$1(client, { target: request.target });
12627
13102
  if (!result.ok) {
12628
13103
  const error = result.error;
@@ -12656,6 +13131,8 @@ async function joinChannel(client, request) {
12656
13131
  };
12657
13132
  }
12658
13133
  async function leaveChannel(client, request) {
13134
+ const invalid = validateOpRequest(channelTargetRequestSchema, request);
13135
+ if (invalid) return invalid;
12659
13136
  const channel = await resolveRegularChannel(client, request.target);
12660
13137
  if ("ok" in channel) return channel;
12661
13138
  if (!channel.joined) return {
@@ -12688,6 +13165,8 @@ function formatSeq(value) {
12688
13165
  return value == null ? "none" : String(value);
12689
13166
  }
12690
13167
  async function setChannelMute(client, request, action) {
13168
+ const invalid = validateOpRequest(channelTargetRequestSchema, request);
13169
+ if (invalid) return invalid;
12691
13170
  const channel = await resolveRegularChannel(client, request.target);
12692
13171
  if ("ok" in channel) return channel;
12693
13172
  const result = action === "mute" ? await client.channels.mute({ channelId: channel.id }, {}) : await client.channels.unmute({ channelId: channel.id });
@@ -12730,6 +13209,8 @@ function unmuteChannel(client, request) {
12730
13209
  return setChannelMute(client, request, "unmute");
12731
13210
  }
12732
13211
  async function channelMembers(client, request) {
13212
+ const invalid = validateOpRequest(channelMembersRequestSchema, request);
13213
+ if (invalid) return invalid;
12733
13214
  if (!request.target?.trim()) return failureOutcome(opError("INVALID_REQUEST", { message: "A channel, DM, or thread target is required." }));
12734
13215
  const result = await client.channels.members({ channel: request.target });
12735
13216
  if (!result.ok) return failureFromClientResult(result);
@@ -12754,6 +13235,8 @@ async function listThreads(client) {
12754
13235
  };
12755
13236
  }
12756
13237
  async function unfollowThread(client, request) {
13238
+ const invalid = validateOpRequest(unfollowThreadRequestSchema, request);
13239
+ if (invalid) return invalid;
12757
13240
  if (!request.target?.includes(":")) return failureOutcome(opError("INVALID_REQUEST", { message: "A thread target is required, for example '#channel:shortid' or 'dm:@peer:shortid'." }));
12758
13241
  const result = await client.threads.unfollow({
12759
13242
  thread: request.target,
@@ -12770,6 +13253,21 @@ async function unfollowThread(client, request) {
12770
13253
  }
12771
13254
  //#endregion
12772
13255
  //#region ../shared/src/agentOps/server.ts
13256
+ const serverInfoRequestSchema = requestSchema()(object({
13257
+ view: _enum([
13258
+ "summary",
13259
+ "full",
13260
+ "channels",
13261
+ "agents",
13262
+ "humans"
13263
+ ]).optional().describe("summary (default): counts; full: the whole overview; channels / agents / humans: one paged section."),
13264
+ offset: number$1().optional().describe("Section paging: rows to skip."),
13265
+ limit: number$1().optional().describe("Section paging: rows per page (default 50)."),
13266
+ joined: boolean().optional().describe("channels view only: only channels you have joined.")
13267
+ }));
13268
+ const showProfileRequestSchema = requestSchema()(object({ target: string().optional().describe("`@handle` of someone else; omit for your own profile.") }));
13269
+ /** The Agent API's profile body schema; at least one field is required (checked by the operation). */
13270
+ const updateProfileRequestSchema = agentApiProfileUpdateBodySchema;
12773
13271
  function nextCommand(section, request, offset, limit, total) {
12774
13272
  const nextOffset = offset + limit;
12775
13273
  if (nextOffset >= total) return void 0;
@@ -12783,6 +13281,8 @@ function nextCommand(section, request, offset, limit, total) {
12783
13281
  return parts.join(" ");
12784
13282
  }
12785
13283
  async function serverInfo(client, request = {}) {
13284
+ const invalid = validateOpRequest(serverInfoRequestSchema, request);
13285
+ if (invalid) return invalid;
12786
13286
  const result = await client.server.info();
12787
13287
  if (!result.ok) return failureFromClientResult(result);
12788
13288
  const server = result.data;
@@ -12848,6 +13348,8 @@ async function serverInfo(client, request = {}) {
12848
13348
  };
12849
13349
  }
12850
13350
  async function showProfile(client, request = {}, options = {}) {
13351
+ const invalid = validateOpRequest(showProfileRequestSchema, request);
13352
+ if (invalid) return invalid;
12851
13353
  const result = await client.profile.show(request.target ? { target: request.target } : {});
12852
13354
  if (!result.ok) return failureFromClientResult(result);
12853
13355
  return {
@@ -12859,6 +13361,8 @@ async function showProfile(client, request = {}, options = {}) {
12859
13361
  };
12860
13362
  }
12861
13363
  async function updateProfile(client, request, options = {}) {
13364
+ const invalid = validateOpRequest(updateProfileRequestSchema, request);
13365
+ if (invalid) return invalid;
12862
13366
  if (request.displayName === void 0 && request.description === void 0 && request.avatarUrl === void 0) return failureOutcome(opError("INVALID_REQUEST", { message: "Pass a displayName, description, or avatarUrl to update." }));
12863
13367
  const result = await client.profile.update(request);
12864
13368
  if (!result.ok) return failureFromClientResult(result);
@@ -12912,6 +13416,10 @@ function formatAgentAttachmentComments(attachmentId, comments, threadChannelId)
12912
13416
  }
12913
13417
  //#endregion
12914
13418
  //#region ../shared/src/agentOps/attachments.ts
13419
+ const attachmentCommentsRequestSchema = requestSchema()(object({
13420
+ attachmentId: string().describe("The attachment id."),
13421
+ limit: number$1().int().positive().optional().describe("Maximum comments to return.")
13422
+ }));
12915
13423
  /** Compatibility fallback for Servers that predate the capability endpoint (the CLI's constant). */
12916
13424
  const AGENT_ATTACHMENT_UPLOAD_FALLBACK_MAX_BYTES = 52428800;
12917
13425
  const FILENAME_MIME_MAP = {
@@ -13119,6 +13627,8 @@ async function downloadAttachment(client, request) {
13119
13627
  };
13120
13628
  }
13121
13629
  async function attachmentComments(client, request) {
13630
+ const invalid = validateOpRequest(attachmentCommentsRequestSchema, request);
13631
+ if (invalid) return invalid;
13122
13632
  if (!request.attachmentId?.trim()) return failureOutcome(opError("INVALID_REQUEST", { message: "An attachment id is required." }));
13123
13633
  const result = await client.attachments.comments({ attachmentId: request.attachmentId }, request.limit === void 0 ? {} : { limit: String(request.limit) });
13124
13634
  if (!result.ok) return failureFromClientResult(result);
@@ -13135,101 +13645,12 @@ async function attachmentComments(client, request) {
13135
13645
  };
13136
13646
  }
13137
13647
  //#endregion
13138
- //#region ../shared/src/zonedTime.ts
13139
- const MS_PER_SECOND = 1e3;
13140
- const MS_PER_MINUTE = 6e4;
13141
- const MS_PER_DAY = 864e5;
13142
- const formatters = /* @__PURE__ */ new Map();
13143
- function formatterFor(timeZone) {
13144
- let formatter = formatters.get(timeZone);
13145
- if (!formatter) {
13146
- formatter = new Intl.DateTimeFormat("en-US", {
13147
- timeZone,
13148
- hourCycle: "h23",
13149
- era: "short",
13150
- year: "numeric",
13151
- month: "numeric",
13152
- day: "numeric",
13153
- hour: "numeric",
13154
- minute: "numeric",
13155
- second: "numeric"
13156
- });
13157
- formatters.set(timeZone, formatter);
13158
- }
13159
- return formatter;
13160
- }
13161
- /** Days from 1970-01-01 to the proleptic Gregorian date (H. Hinnant's days_from_civil). */
13162
- function daysFromCivil(year, month, day) {
13163
- const y = month <= 2 ? year - 1 : year;
13164
- const era = Math.floor(y / 400);
13165
- const yoe = y - era * 400;
13166
- const mp = (month + 9) % 12;
13167
- const doy = Math.floor((153 * mp + 2) / 5) + day - 1;
13168
- const doe = yoe * 365 + Math.floor(yoe / 4) - Math.floor(yoe / 100) + doy;
13169
- return era * 146097 + doe - 719468;
13170
- }
13171
- /** The wall clock as milliseconds on a UTC timeline (no Date, so no 0-99 year quirk or range limit). */
13172
- function wallClockMs(wall) {
13173
- return daysFromCivil(wall.year, wall.month, wall.day) * MS_PER_DAY + wall.hour * 36e5 + wall.minute * MS_PER_MINUTE + wall.second * MS_PER_SECOND + wall.millisecond;
13174
- }
13175
- function floorMod(value, modulus) {
13176
- return (value % modulus + modulus) % modulus;
13177
- }
13178
- /** Wall clock of `epochMs` in `timeZone` plus the exact offset in ms (seconds precision). */
13179
- function wallClockAt(epochMs, timeZone) {
13180
- const parts = {};
13181
- for (const part of formatterFor(timeZone).formatToParts(epochMs)) parts[part.type] = part.value;
13182
- const eraYear = Number(parts.year);
13183
- const wall = {
13184
- year: /^b/i.test(parts.era ?? "") ? 1 - eraYear : eraYear,
13185
- month: Number(parts.month),
13186
- day: Number(parts.day),
13187
- hour: Number(parts.hour),
13188
- minute: Number(parts.minute),
13189
- second: Number(parts.second),
13190
- millisecond: floorMod(epochMs, MS_PER_SECOND)
13191
- };
13192
- return {
13193
- wall,
13194
- offsetMs: wallClockMs(wall) - epochMs
13195
- };
13196
- }
13197
- function offsetMinutesOf(offsetMs) {
13198
- return -Math.trunc(-offsetMs / MS_PER_MINUTE);
13199
- }
13200
- /** The wall clock and getTimezoneOffset-style offset of `epochMs` in `timeZone`. */
13201
- function zonedInstant(epochMs, timeZone) {
13202
- const { wall, offsetMs } = wallClockAt(epochMs, timeZone);
13203
- return {
13204
- ...wall,
13205
- offsetMinutes: offsetMinutesOf(offsetMs)
13206
- };
13207
- }
13208
- function pad2(n) {
13209
- return String(n).padStart(2, "0");
13210
- }
13211
- /** `+08:00` / `-04:00` / `+05:30`, as the CLI has always printed offsets. */
13212
- function formatUtcOffset(offsetMinutes) {
13213
- const sign = offsetMinutes >= 0 ? "+" : "-";
13214
- const abs = Math.abs(offsetMinutes);
13215
- return `${sign}${pad2(Math.floor(abs / 60))}:${pad2(abs % 60)}`;
13216
- }
13217
- //#endregion
13218
13648
  //#region ../shared/src/agentText/search.ts
13219
- /**
13220
- * Wall-clock rendering with offset, as the CLI prints search hit times. With
13221
- * `timeZone` (an IANA name) the time is rendered in that zone; without it, in
13222
- * the process's local zone (the SDK's historical behaviour). The two agree
13223
- * byte for byte when `timeZone` is the process zone.
13224
- */
13225
- function formatLocalTimeWithOffset(iso, timeZone) {
13649
+ /** Local wall-clock rendering with offset, as the CLI prints search hit times. */
13650
+ function formatLocalTimeWithOffset(iso) {
13226
13651
  const d = new Date(iso);
13227
13652
  if (isNaN(d.getTime())) return iso;
13228
13653
  const pad = (n) => String(n).padStart(2, "0");
13229
- if (timeZone !== void 0) {
13230
- const z = zonedInstant(d.getTime(), timeZone);
13231
- return `${z.year}-${pad(z.month)}-${pad(z.day)} ${pad(z.hour)}:${pad(z.minute)}:${pad(z.second)} ${formatUtcOffset(z.offsetMinutes)}`;
13232
- }
13233
13654
  const offsetMinutes = -d.getTimezoneOffset();
13234
13655
  const sign = offsetMinutes >= 0 ? "+" : "-";
13235
13656
  const absOffset = Math.abs(offsetMinutes);
@@ -13352,11 +13773,8 @@ function renderSearchPreview(content, query) {
13352
13773
  trailingOmit
13353
13774
  ].join("");
13354
13775
  }
13355
- /**
13356
- * Search results with <match>/<omit /> preview markup. Hit times render in
13357
- * `timeZone` when given, else in the process's local zone.
13358
- */
13359
- function formatAgentSearchResults(query, data, offset, sort, limit, timeZone) {
13776
+ /** Search results with <match>/<omit /> preview markup. */
13777
+ function formatAgentSearchResults(query, data, offset, sort, limit) {
13360
13778
  const trimmedQuery = query.trim();
13361
13779
  const oldestShown = data.results?.length ? data.results[data.results.length - 1]?.createdAt : void 0;
13362
13780
  const nextPageHint = sort === "recent" && oldestShown ? `page with --before ${oldestShown} (pages OLDER only; NOT a complete traversal: stored times are microsecond but this key is millisecond, so rows inside the boundary millisecond can be skipped, and a full page sharing one timestamp can repeat indefinitely; copy the key verbatim)` : `page with --offset ${(offset ?? 0) + (data.results?.length ?? 0)}`;
@@ -13376,7 +13794,7 @@ function formatAgentSearchResults(query, data, offset, sort, limit, timeZone) {
13376
13794
  `<result ref="${ref}">`,
13377
13795
  `Source: ${renderSearchSource(result)}`,
13378
13796
  `Sender: ${sender}${senderType}`,
13379
- `Time: ${result.createdAt ? formatLocalTimeWithOffset(result.createdAt, timeZone) : "-"}`,
13797
+ `Time: ${result.createdAt ? formatLocalTimeWithOffset(result.createdAt) : "-"}`,
13380
13798
  ...taskProjection ? [taskProjection] : [],
13381
13799
  "",
13382
13800
  "<preview>",
@@ -13397,7 +13815,24 @@ function formatAgentSearchResults(query, data, offset, sort, limit, timeZone) {
13397
13815
  }
13398
13816
  //#endregion
13399
13817
  //#region ../shared/src/agentOps/search.ts
13818
+ const searchMessagesRequestSchema = requestSchema()(object({
13819
+ query: string().optional().describe("Free-text query; may be omitted when filtering by target or sender."),
13820
+ target: string().optional().describe("Only this channel, DM, or thread."),
13821
+ sender: string().optional().describe("Only messages from this handle."),
13822
+ sort: _enum(["relevance", "recent"]).optional(),
13823
+ before: string().optional().describe("ISO timestamp; only messages at or before it."),
13824
+ after: string().optional().describe("ISO timestamp; only messages at or after it."),
13825
+ limit: number$1().int().positive().optional().describe("Results per page, 1..50 (Server default 20)."),
13826
+ offset: number$1().int().nonnegative().optional().describe("Skip this many results (paging).")
13827
+ }));
13828
+ const resolveMessageRequestSchema = requestSchema()(object({ messageId: string().describe("Full or short message id.") }));
13829
+ const reactRequestSchema = requestSchema()(object({
13830
+ messageId: string().describe("Full or short message id."),
13831
+ emoji: string().describe("One reaction emoji.")
13832
+ }));
13400
13833
  async function searchMessages(client, request) {
13834
+ const invalid = validateOpRequest(searchMessagesRequestSchema, request);
13835
+ if (invalid) return invalid;
13401
13836
  if (!request.query?.trim() && !request.target && !request.sender) return failureOutcome(opError("INVALID_REQUEST", { message: "Pass a query, or filter by target or sender." }));
13402
13837
  const result = await client.messages.search({
13403
13838
  ...request.query?.trim() ? { q: request.query.trim() } : {},
@@ -13437,6 +13872,8 @@ async function searchMessages(client, request) {
13437
13872
  };
13438
13873
  }
13439
13874
  async function resolveMessage(client, request) {
13875
+ const invalid = validateOpRequest(resolveMessageRequestSchema, request);
13876
+ if (invalid) return invalid;
13440
13877
  if (!request.messageId?.trim()) return failureOutcome(opError("INVALID_REQUEST", { message: "A message id is required." }));
13441
13878
  const result = await client.messages.resolve({ msgId: request.messageId });
13442
13879
  if (!result.ok) return failureFromClientResult(result);
@@ -13459,6 +13896,8 @@ async function resolveMessage(client, request) {
13459
13896
  };
13460
13897
  }
13461
13898
  async function reactToMessage(client, request, action = "add") {
13899
+ const invalid = validateOpRequest(reactRequestSchema, request);
13900
+ if (invalid) return invalid;
13462
13901
  const emoji = request.emoji?.trim();
13463
13902
  if (!request.messageId?.trim() || !emoji || /\s/.test(emoji) || emoji.length > 16) return failureOutcome(opError("INVALID_REQUEST", { message: "A message id and a single reaction emoji are required." }));
13464
13903
  const params = { msgId: request.messageId };
@@ -13660,7 +14099,15 @@ function formatAgentSenderMentionDeliveries(messageId, deliveries) {
13660
14099
  }
13661
14100
  //#endregion
13662
14101
  //#region ../shared/src/agentOps/mentions.ts
14102
+ const pendingMentionActionsRequestSchema = requestSchema()(object({ limit: number$1().int().positive().optional().describe("Maximum pending mentions to list.") }));
14103
+ const executeMentionActionRequestSchema = requestSchema()(object({
14104
+ action: _enum(["notify", "add"]).describe("notify: tell the mentioned target about the message; add: add them to the conversation."),
14105
+ resolutionIds: array(string()).describe("resolutionId values from mentions.pending.")
14106
+ }));
14107
+ const senderMentionDeliveriesRequestSchema = requestSchema()(object({ messageId: string().describe("Id of a message you sent.") }));
13663
14108
  async function pendingMentionActions(client, request = {}) {
14109
+ const invalid = validateOpRequest(pendingMentionActionsRequestSchema, request);
14110
+ if (invalid) return invalid;
13664
14111
  const result = await client.mentions.pendingActions(request.limit === void 0 ? {} : { limit: String(request.limit) });
13665
14112
  if (!result.ok) return failureFromClientResult(result);
13666
14113
  const actions = normalizeAgentPendingMentionActions(result.data);
@@ -13692,6 +14139,8 @@ async function pendingMentionActions(client, request = {}) {
13692
14139
  };
13693
14140
  }
13694
14141
  async function executeMentionAction(client, request) {
14142
+ const invalid = validateOpRequest(executeMentionActionRequestSchema, request);
14143
+ if (invalid) return invalid;
13695
14144
  const ids = (request.resolutionIds ?? []).map((id) => id.trim()).filter(Boolean);
13696
14145
  if (ids.length === 0 || request.action !== "notify" && request.action !== "add") return failureOutcome(opError("INVALID_REQUEST", { message: "Pass an action (notify | add) and at least one resolution id." }));
13697
14146
  const result = await client.mentions.executeAction({
@@ -13712,6 +14161,8 @@ async function executeMentionAction(client, request) {
13712
14161
  };
13713
14162
  }
13714
14163
  async function senderMentionDeliveries(client, request) {
14164
+ const invalid = validateOpRequest(senderMentionDeliveriesRequestSchema, request);
14165
+ if (invalid) return invalid;
13715
14166
  if (!request.messageId?.trim()) return failureOutcome(opError("INVALID_REQUEST", { message: "A message id is required." }));
13716
14167
  const result = await client.mentions.senderDeliveries({ messageId: request.messageId });
13717
14168
  if (!result.ok) return failureFromClientResult(result);
@@ -13744,11 +14195,26 @@ function formatAgentKnowledgeStdout(content) {
13744
14195
  }
13745
14196
  //#endregion
13746
14197
  //#region ../shared/src/agentOps/manual.ts
14198
+ const manualContextFields = {
14199
+ intent: string().min(12).max(500).describe("What the user wants to accomplish with Raft, in a few words. Never a prompt, credential, URL, or message text."),
14200
+ reason: string().min(12).max(500).describe("Why the Manual is needed now, in a few words. Same rules as intent.")
14201
+ };
14202
+ const getManualTopicRequestSchema = requestSchema()(object({
14203
+ topic: string().describe("Topic id (slug), for example one returned by manual.search."),
14204
+ ...manualContextFields
14205
+ }));
14206
+ const searchManualRequestSchema = requestSchema()(object({
14207
+ query: string().describe("Search keywords."),
14208
+ scope: string().optional().describe("Restrict the search to one Manual section."),
14209
+ ...manualContextFields
14210
+ }));
13747
14211
  function requireContext(context) {
13748
14212
  if (!context?.intent?.trim() || !context?.reason?.trim()) return failureOutcome(opError("INVALID_REQUEST", { message: "Manual calls need a short `intent` and `reason`." }));
13749
14213
  return null;
13750
14214
  }
13751
14215
  async function getManualTopic(client, request) {
14216
+ const malformed = validateOpRequest(getManualTopicRequestSchema, request);
14217
+ if (malformed) return malformed;
13752
14218
  const invalid = requireContext(request);
13753
14219
  if (invalid) return invalid;
13754
14220
  if (!request.topic?.trim()) return failureOutcome(opError("INVALID_REQUEST", { message: "A topic id is required." }));
@@ -13767,6 +14233,8 @@ async function getManualTopic(client, request) {
13767
14233
  };
13768
14234
  }
13769
14235
  async function searchManual(client, request) {
14236
+ const malformed = validateOpRequest(searchManualRequestSchema, request);
14237
+ if (malformed) return malformed;
13770
14238
  const invalid = requireContext(request);
13771
14239
  if (invalid) return invalid;
13772
14240
  if (!request.query?.trim()) return failureOutcome(opError("INVALID_REQUEST", { message: "Search keywords are required." }));
@@ -13955,14 +14423,63 @@ var RaftStateSession = class {
13955
14423
  }
13956
14424
  };
13957
14425
  //#endregion
14426
+ //#region ../shared/src/agentOps/seenPolicy/consumedSeqs.ts
14427
+ function getParentTargetForThread(target) {
14428
+ if (target.startsWith("dm:@")) {
14429
+ const separatorIndex = target.indexOf(":", 4);
14430
+ return separatorIndex > 0 ? target.slice(0, separatorIndex) : null;
14431
+ }
14432
+ if (target.startsWith("#")) {
14433
+ const separatorIndex = target.indexOf(":");
14434
+ return separatorIndex > 0 ? target.slice(0, separatorIndex) : null;
14435
+ }
14436
+ return null;
14437
+ }
14438
+ //#endregion
13958
14439
  //#region ../shared/src/agentOps/actions.ts
14440
+ /**
14441
+ * The Agent API's own body schema (a discriminated union over the card
14442
+ * types), so the SDK checks exactly what the Server checks. The operation
14443
+ * manifest projects it flattened (see the SDK's operations.ts).
14444
+ */
14445
+ const prepareActionCardRequestSchema = agentApiActionPrepareBodySchema;
13959
14446
  /** Text is the CLI's `raft action prepare` output. */
13960
14447
  function formatAgentActionCardPosted(target, messageId) {
13961
14448
  const shortId = messageId ? messageId.slice(0, 8) : null;
13962
14449
  return shortId ? `Action card posted to ${target} as message ${messageId} (short ${shortId}). The human can click the action verb to commit.\n` : `Action card posted to ${target}.\n`;
13963
14450
  }
14451
+ /**
14452
+ * Where the card's outcome arrives (Server #8604): when a human executes the
14453
+ * card, or execution fails, the Server posts a system reply that @mentions
14454
+ * the preparer in the card's own thread; a card posted inside a thread has no
14455
+ * thread of its own, so the reply lands in that same thread.
14456
+ */
14457
+ function awaitConfirmationNext(target, messageId) {
14458
+ const short = messageId.slice(0, 8);
14459
+ if (getParentTargetForThread(target) !== null) return {
14460
+ kind: "await_confirmation",
14461
+ command: `raft message read --target "${target}" --around ${short}`,
14462
+ args: {
14463
+ target,
14464
+ messageId
14465
+ },
14466
+ why: "A human must click the card to commit it. When it is executed (or fails), the outcome arrives as a reply in this thread that @mentions you; you do not need to poll."
14467
+ };
14468
+ const thread = agentTaskThreadTarget(target, messageId);
14469
+ return {
14470
+ kind: "await_confirmation",
14471
+ command: `raft message read --target "${thread}"`,
14472
+ args: {
14473
+ target: thread,
14474
+ messageId
14475
+ },
14476
+ why: "A human must click the card to commit it. When it is executed (or fails), the outcome arrives as a reply in the card's thread that @mentions you; you do not need to poll."
14477
+ };
14478
+ }
13964
14479
  async function prepareActionCard(client, request) {
13965
- if (!request?.target?.trim() || !request.action) return failureOutcome(opError("INVALID_REQUEST", { message: "A target and an action are required to prepare a card." }));
14480
+ if (typeof request?.target !== "string" || !request.target.trim() || !request.action) return failureOutcome(opError("INVALID_REQUEST", { message: "A target and an action are required to prepare a card." }));
14481
+ const invalid = validateOpRequest(prepareActionCardRequestSchema, request);
14482
+ if (invalid) return invalid;
13966
14483
  const result = await client.actions.prepare(request);
13967
14484
  if (!result.ok) return failureFromClientResult(result);
13968
14485
  const card = {
@@ -13973,15 +14490,7 @@ async function prepareActionCard(client, request) {
13973
14490
  ok: true,
13974
14491
  state: "prepared",
13975
14492
  data: card,
13976
- next: {
13977
- kind: "await_confirmation",
13978
- command: `raft message read --target "${request.target}" --around ${card.messageId.slice(0, 8)}`,
13979
- args: {
13980
- target: request.target,
13981
- messageId: card.messageId
13982
- },
13983
- why: "A human must click the card to commit it. You are not notified of the result yet; read the card message to see its state instead of waiting."
13984
- },
14493
+ next: awaitConfirmationNext(request.target, card.messageId),
13985
14494
  text: formatAgentActionCardPosted(request.target, card.messageId)
13986
14495
  };
13987
14496
  }
@@ -14041,6 +14550,695 @@ async function readLatestReadThread(options = {}) {
14041
14550
  return latestReadThreadFromCliReadState(raw);
14042
14551
  }
14043
14552
  //#endregion
14553
+ //#region src/operationSchemas.ts
14554
+ /** `identity.whoami` takes no arguments. */
14555
+ const whoamiRequestSchema = object({});
14556
+ /** `inbox.commit`: no cursor commits the pending batch; a cursor commits up to it. */
14557
+ const commitInboxRequestSchema = requestSchema()(object({ cursor: number$1().int().nonnegative().nullable().optional().describe("Commit up to this batch cursor; omit to commit the batch the last inbox pull returned.") }));
14558
+ //#endregion
14559
+ //#region src/toolSchema.ts
14560
+ /** Every keyword the subset allows. */
14561
+ const RAFT_JSON_SCHEMA_KEYWORDS = [
14562
+ "type",
14563
+ "description",
14564
+ "properties",
14565
+ "required",
14566
+ "items",
14567
+ "enum",
14568
+ "minimum",
14569
+ "maximum",
14570
+ "minLength",
14571
+ "maxLength"
14572
+ ];
14573
+ const PRIMITIVES = /* @__PURE__ */ new Set([
14574
+ "string",
14575
+ "number",
14576
+ "integer",
14577
+ "boolean",
14578
+ "null"
14579
+ ]);
14580
+ const SAFE = Number.MAX_SAFE_INTEGER;
14581
+ function isRaw(value) {
14582
+ return Boolean(value) && typeof value === "object" && !Array.isArray(value);
14583
+ }
14584
+ function jsonTypeOf(value) {
14585
+ if (value === null) return "null";
14586
+ if (typeof value === "number") return Number.isInteger(value) ? "integer" : "number";
14587
+ if (typeof value === "boolean") return "boolean";
14588
+ return "string";
14589
+ }
14590
+ function project(node, where, options) {
14591
+ if (!isRaw(node)) throw new Error(`${where}: not a JSON Schema object`);
14592
+ const branches = node.anyOf ?? node.oneOf;
14593
+ if (Array.isArray(branches)) {
14594
+ const projected = branches.map((branch, index) => project(branch, `${where}|${index}`, options));
14595
+ const flattened = projected.every((b) => b.type !== void 0 && b.type !== "array" && b.type !== "object") ? primitiveUnion(projected, where, options) : flattenDiscriminatedUnion(projected, where);
14596
+ return typeof node.description === "string" ? {
14597
+ ...flattened,
14598
+ description: node.description
14599
+ } : flattened;
14600
+ }
14601
+ if (node.allOf !== void 0 || node.$ref !== void 0 || node.not !== void 0) throw new Error(`${where}: allOf / $ref / not cannot be projected to the tool-schema subset`);
14602
+ const out = {};
14603
+ if (node.type !== void 0) {
14604
+ if (Array.isArray(node.type)) throw new Error(`${where}: type arrays are outside the tool-schema subset`);
14605
+ const type = String(node.type);
14606
+ if (type !== "object" && type !== "array" && !PRIMITIVES.has(type)) throw new Error(`${where}: unknown type ${type}`);
14607
+ out.type = type;
14608
+ }
14609
+ if (typeof node.description === "string") out.description = node.description;
14610
+ if (node.const !== void 0) {
14611
+ out.enum = [node.const];
14612
+ out.type ??= jsonTypeOf(node.const);
14613
+ }
14614
+ if (Array.isArray(node.enum)) out.enum = [...node.enum];
14615
+ if (isRaw(node.properties)) {
14616
+ out.properties = {};
14617
+ const required = Array.isArray(node.required) ? node.required : [];
14618
+ for (const [key, value] of Object.entries(node.properties)) {
14619
+ if (required.includes(key) && isNullable(value)) throw new Error(`${where}.${key}: a required nullable field has no tool-schema form; make it optional (omitted = null)`);
14620
+ out.properties[key] = project(value, `${where}.${key}`, options);
14621
+ }
14622
+ out.type ??= "object";
14623
+ }
14624
+ if (Array.isArray(node.required) && node.required.length > 0) out.required = [...node.required];
14625
+ if (node.items !== void 0) out.items = project(node.items, `${where}[]`, options);
14626
+ const integer = out.type === "integer";
14627
+ const lower = [typeof node.minimum === "number" ? node.minimum : void 0, typeof node.exclusiveMinimum === "number" ? node.exclusiveMinimum + (integer ? 1 : 0) : void 0].filter((v) => v !== void 0 && v > -SAFE);
14628
+ const upper = [typeof node.maximum === "number" ? node.maximum : void 0, typeof node.exclusiveMaximum === "number" ? node.exclusiveMaximum - (integer ? 1 : 0) : void 0].filter((v) => v !== void 0 && v < SAFE);
14629
+ if (lower.length > 0) out.minimum = Math.max(...lower);
14630
+ if (upper.length > 0) out.maximum = Math.min(...upper);
14631
+ if (typeof node.minLength === "number" && node.minLength > 0) out.minLength = node.minLength;
14632
+ if (typeof node.maxLength === "number") out.maxLength = node.maxLength;
14633
+ return out;
14634
+ }
14635
+ function isNullable(node) {
14636
+ if (!isRaw(node)) return false;
14637
+ const branches = node.anyOf ?? node.oneOf;
14638
+ return node.type === "null" || Array.isArray(branches) && branches.some((b) => isRaw(b) && b.type === "null");
14639
+ }
14640
+ /**
14641
+ * `T | null` → `T` (the field is optional, so omitting it is the JSON form of
14642
+ * null); any other union of primitives → the type the operation names in
14643
+ * `unionAs`. The branch constraints are dropped (looser).
14644
+ */
14645
+ function primitiveUnion(branches, where, options) {
14646
+ const types = [...new Set(branches.map((b) => b.type).filter((t) => t !== "null"))];
14647
+ if (types.length === 1) return { type: types[0] };
14648
+ const chosen = options.unionAs[where];
14649
+ if (!chosen || !types.includes(chosen)) throw new Error(`${where}: a union of ${types.join(" | ")} needs unionAs (the one type to advertise)`);
14650
+ return { type: chosen };
14651
+ }
14652
+ /** The one property every object branch pins to a distinct single value. */
14653
+ function discriminatorOf(branches) {
14654
+ const first = branches[0];
14655
+ if (!first?.properties) return null;
14656
+ for (const key of Object.keys(first.properties)) {
14657
+ const values = branches.map((b) => b.properties?.[key]?.enum);
14658
+ if (values.every((v) => Array.isArray(v) && v.length === 1) && new Set(values.map((v) => v[0])).size === branches.length) return key;
14659
+ }
14660
+ return null;
14661
+ }
14662
+ function flattenDiscriminatedUnion(branches, where) {
14663
+ if (!branches.every((b) => b.type === "object")) throw new Error(`${where}: only unions of primitives or discriminated unions of objects can be projected`);
14664
+ const discriminator = discriminatorOf(branches);
14665
+ if (!discriminator) throw new Error(`${where}: a union of objects needs a discriminator property to be flattened`);
14666
+ const tags = branches.map((b) => b.properties[discriminator].enum[0]);
14667
+ const properties = { [discriminator]: {
14668
+ type: "string",
14669
+ enum: tags,
14670
+ description: `Which variant this is; the other fields apply per ${discriminator} as their descriptions say.`
14671
+ } };
14672
+ const order = [];
14673
+ const byKey = /* @__PURE__ */ new Map();
14674
+ branches.forEach((branch, index) => {
14675
+ for (const [key, schema] of Object.entries(branch.properties ?? {})) {
14676
+ if (key === discriminator) continue;
14677
+ if (!byKey.has(key)) {
14678
+ byKey.set(key, []);
14679
+ order.push(key);
14680
+ }
14681
+ byKey.get(key).push({
14682
+ tag: tags[index],
14683
+ schema
14684
+ });
14685
+ }
14686
+ });
14687
+ for (const key of order) {
14688
+ const uses = byKey.get(key);
14689
+ const merged = uses.map((u) => u.schema).reduce(loosest);
14690
+ const descriptions = [...new Set(uses.map((u) => u.schema.description).filter((d) => Boolean(d)))];
14691
+ const usedBy = uses.length === branches.length ? "" : `Only for ${discriminator} ${uses.map((u) => u.tag).join(", ")}.`;
14692
+ const description = [...descriptions, usedBy].filter(Boolean).join(" ");
14693
+ const { description: _drop, ...rest } = merged;
14694
+ properties[key] = description ? {
14695
+ ...rest,
14696
+ description
14697
+ } : rest;
14698
+ }
14699
+ return {
14700
+ type: "object",
14701
+ properties,
14702
+ required: [discriminator]
14703
+ };
14704
+ }
14705
+ /** The loosest schema accepting everything either side accepts (within the subset). */
14706
+ function loosest(a, b) {
14707
+ if (JSON.stringify(a) === JSON.stringify(b)) return a;
14708
+ const out = {};
14709
+ if (a.type !== void 0 && a.type === b.type) out.type = a.type;
14710
+ if (a.enum && b.enum) out.enum = [.../* @__PURE__ */ new Set([...a.enum, ...b.enum])];
14711
+ if (a.minimum !== void 0 && b.minimum !== void 0) out.minimum = Math.min(a.minimum, b.minimum);
14712
+ if (a.maximum !== void 0 && b.maximum !== void 0) out.maximum = Math.max(a.maximum, b.maximum);
14713
+ if (a.minLength !== void 0 && b.minLength !== void 0) out.minLength = Math.min(a.minLength, b.minLength);
14714
+ if (a.maxLength !== void 0 && b.maxLength !== void 0) out.maxLength = Math.max(a.maxLength, b.maxLength);
14715
+ if (a.items && b.items) out.items = loosest(a.items, b.items);
14716
+ if (a.properties && b.properties) {
14717
+ out.properties = {};
14718
+ for (const key of /* @__PURE__ */ new Set([...Object.keys(a.properties), ...Object.keys(b.properties)])) {
14719
+ const pa = a.properties[key];
14720
+ const pb = b.properties[key];
14721
+ out.properties[key] = pa && pb ? loosest(pa, pb) : pa ?? pb;
14722
+ }
14723
+ const required = (a.required ?? []).filter((key) => (b.required ?? []).includes(key));
14724
+ if (required.length > 0) out.required = required;
14725
+ }
14726
+ if (a.description) out.description = a.description;
14727
+ return out;
14728
+ }
14729
+ /** The tool-schema projection of an operation's zod request schema (input side). */
14730
+ function toRaftToolInputSchema(schema, options = {}) {
14731
+ const projected = project(toJSONSchema(schema, {
14732
+ io: "input",
14733
+ target: "draft-2020-12",
14734
+ reused: "inline",
14735
+ unrepresentable: "throw"
14736
+ }), "input", { unionAs: Object.fromEntries(Object.entries(options.unionAs ?? {}).map(([key, type]) => [`input.${key}`, type])) });
14737
+ if (projected.type !== "object") throw new Error("an operation's input schema must be an object");
14738
+ for (const key of options.omit ?? []) {
14739
+ if (projected.properties) delete projected.properties[key];
14740
+ if (projected.required) projected.required = projected.required.filter((r) => r !== key);
14741
+ }
14742
+ for (const [key, description] of Object.entries(options.describe ?? {})) {
14743
+ const property = projected.properties?.[key];
14744
+ if (!property) throw new Error(`cannot describe unknown field ${key}`);
14745
+ property.description = description;
14746
+ }
14747
+ if (projected.required?.length === 0) delete projected.required;
14748
+ projected.properties ??= {};
14749
+ return projected;
14750
+ }
14751
+ //#endregion
14752
+ //#region src/operations.ts
14753
+ const nothing = {
14754
+ model: [],
14755
+ code: []
14756
+ };
14757
+ const small = {
14758
+ mayBeLarge: false,
14759
+ boundBy: []
14760
+ };
14761
+ const OPERATION_DEFS = [
14762
+ {
14763
+ name: "identity.whoami",
14764
+ description: "Who this credential is: your agent, the server, the capabilities granted to the credential, and the operating guide for External Agents.",
14765
+ schema: whoamiRequestSchema,
14766
+ routes: ["agentContext"],
14767
+ consumes: nothing,
14768
+ output: {
14769
+ mayBeLarge: true,
14770
+ boundBy: []
14771
+ }
14772
+ },
14773
+ {
14774
+ name: "inbox.check",
14775
+ description: "Pull one batch of new messages addressed to you (DMs, @mentions, followed threads, joined channels). Handle them, then call inbox.commit; the next check acknowledges the committed batch.",
14776
+ schema: checkInboxRequestSchema,
14777
+ routes: ["events"],
14778
+ consumes: {
14779
+ model: ["inbox", "seen"],
14780
+ code: "refused"
14781
+ },
14782
+ output: {
14783
+ mayBeLarge: true,
14784
+ boundBy: ["limit"]
14785
+ }
14786
+ },
14787
+ {
14788
+ name: "inbox.drain",
14789
+ description: "Pull new messages until the server reports nothing more, returned together. Each batch is acknowledged by the pull after it; call inbox.commit after handling the result.",
14790
+ schema: drainInboxRequestSchema,
14791
+ routes: ["events"],
14792
+ consumes: {
14793
+ model: ["inbox", "seen"],
14794
+ code: "refused"
14795
+ },
14796
+ output: {
14797
+ mayBeLarge: true,
14798
+ boundBy: ["limit"]
14799
+ }
14800
+ },
14801
+ {
14802
+ name: "inbox.commit",
14803
+ description: "Mark the last pulled inbox batch as handled (or the batch with the given cursor); the next inbox check acknowledges it on the server. Call it only after the messages were handled.",
14804
+ schema: commitInboxRequestSchema,
14805
+ routes: [],
14806
+ local: {
14807
+ sideEffect: "write",
14808
+ idempotency: "natural"
14809
+ },
14810
+ consumes: {
14811
+ model: ["inbox"],
14812
+ code: "refused"
14813
+ },
14814
+ output: small
14815
+ },
14816
+ {
14817
+ name: "inbox.list",
14818
+ description: "List conversations with unread messages, newest activity first, each with where to start reading. Consumes nothing.",
14819
+ schema: listInboxRequestSchema,
14820
+ routes: ["inboxList"],
14821
+ consumes: nothing,
14822
+ output: {
14823
+ mayBeLarge: true,
14824
+ boundBy: ["before", "limit"]
14825
+ }
14826
+ },
14827
+ {
14828
+ name: "messages.read",
14829
+ description: "Read a conversation (channel, DM, or thread): the newest messages, or a window after / before / around a position. Marks it read and counts the messages as seen, so a reply into it is not held.",
14830
+ schema: readHistoryRequestSchema,
14831
+ unionAs: { around: "string" },
14832
+ routes: ["historyRead"],
14833
+ consumes: {
14834
+ model: ["read_cursor", "seen"],
14835
+ code: []
14836
+ },
14837
+ output: {
14838
+ mayBeLarge: true,
14839
+ boundBy: [
14840
+ "after",
14841
+ "before",
14842
+ "around",
14843
+ "limit"
14844
+ ]
14845
+ }
14846
+ },
14847
+ {
14848
+ name: "messages.send",
14849
+ description: "Send a message to a channel, DM, or thread. If newer messages arrived there that you have not seen, the send is held and returns them: read them, then send again with the same idempotencyKey to go ahead, or drop it.",
14850
+ schema: sendMessageRequestSchema,
14851
+ hiddenFields: ["seen"],
14852
+ routes: ["messageSendV2"],
14853
+ idempotencyArg: "idempotencyKey",
14854
+ mayInterrupt: true,
14855
+ consumes: nothing,
14856
+ output: small
14857
+ },
14858
+ {
14859
+ name: "messages.reply",
14860
+ description: "Reply where a received message came from (its conversation or thread). Held like messages.send when newer messages arrived there.",
14861
+ schema: replyToRequestSchema,
14862
+ hiddenFields: ["seen"],
14863
+ routes: ["messageSendV2"],
14864
+ idempotencyArg: "idempotencyKey",
14865
+ mayInterrupt: true,
14866
+ consumes: nothing,
14867
+ output: small
14868
+ },
14869
+ {
14870
+ name: "messages.search",
14871
+ description: "Search messages by text, conversation, sender, or time; results are previews. Use it to find a specific message, not to check what is new.",
14872
+ schema: searchMessagesRequestSchema,
14873
+ routes: ["messageSearch"],
14874
+ consumes: nothing,
14875
+ output: {
14876
+ mayBeLarge: true,
14877
+ boundBy: ["limit", "offset"]
14878
+ }
14879
+ },
14880
+ {
14881
+ name: "messages.resolve",
14882
+ description: "Resolve a message id to the full message and the conversation it belongs to.",
14883
+ schema: resolveMessageRequestSchema,
14884
+ routes: ["messageResolve"],
14885
+ consumes: nothing,
14886
+ output: small
14887
+ },
14888
+ {
14889
+ name: "messages.react",
14890
+ description: "Add an emoji reaction to a message.",
14891
+ schema: reactRequestSchema,
14892
+ routes: ["messageReactionAdd"],
14893
+ consumes: nothing,
14894
+ output: small
14895
+ },
14896
+ {
14897
+ name: "messages.unreact",
14898
+ description: "Remove your emoji reaction from a message.",
14899
+ schema: reactRequestSchema,
14900
+ routes: ["messageReactionRemove"],
14901
+ consumes: nothing,
14902
+ output: small
14903
+ },
14904
+ {
14905
+ name: "attachments.comments",
14906
+ description: "List the comments on an attachment.",
14907
+ schema: attachmentCommentsRequestSchema,
14908
+ routes: ["attachmentCommentsList"],
14909
+ consumes: nothing,
14910
+ output: {
14911
+ mayBeLarge: true,
14912
+ boundBy: ["limit"]
14913
+ }
14914
+ },
14915
+ {
14916
+ name: "mentions.pending",
14917
+ description: "List @mentions you sent that reached nobody, each with the actions that would deliver it.",
14918
+ schema: pendingMentionActionsRequestSchema,
14919
+ routes: ["mentionActionsPending"],
14920
+ consumes: nothing,
14921
+ output: {
14922
+ mayBeLarge: true,
14923
+ boundBy: ["limit"]
14924
+ }
14925
+ },
14926
+ {
14927
+ name: "mentions.execute",
14928
+ description: "Deliver unreached @mentions: notify the mentioned target, or add them to the conversation.",
14929
+ schema: executeMentionActionRequestSchema,
14930
+ routes: ["mentionActionsExecute"],
14931
+ consumes: nothing,
14932
+ output: small
14933
+ },
14934
+ {
14935
+ name: "mentions.deliveries",
14936
+ description: "Whether each @mention in a message you sent reached its target.",
14937
+ schema: senderMentionDeliveriesRequestSchema,
14938
+ routes: ["senderMentionDeliveries"],
14939
+ consumes: nothing,
14940
+ output: small
14941
+ },
14942
+ {
14943
+ name: "actions.prepare",
14944
+ description: "Post an action card (create a channel, add members, create an agent, or an integration step) for a human to confirm; the human who clicks it carries it out as themselves. When it is executed (or fails), the outcome arrives as a reply that @mentions you in the card's thread (or in the thread the card was posted in).",
14945
+ schema: prepareActionCardRequestSchema,
14946
+ fieldDescriptions: {
14947
+ target: "Conversation to post the card in: `#channel`, `dm:@peer`, or a thread.",
14948
+ action: "The operation the card proposes: `type` picks it, and the other fields apply per type as described."
14949
+ },
14950
+ routes: ["actionPrepare"],
14951
+ consumes: nothing,
14952
+ output: small
14953
+ },
14954
+ {
14955
+ name: "manual.get",
14956
+ description: "Fetch a topic of the Raft Manual for Agents. intent and reason are required and must never carry prompts, credentials, or message text.",
14957
+ schema: getManualTopicRequestSchema,
14958
+ routes: ["knowledgeGet"],
14959
+ consumes: nothing,
14960
+ output: {
14961
+ mayBeLarge: true,
14962
+ boundBy: []
14963
+ }
14964
+ },
14965
+ {
14966
+ name: "manual.search",
14967
+ description: "Search the Raft Manual for Agents by keywords; returns topic ids to fetch with manual.get.",
14968
+ schema: searchManualRequestSchema,
14969
+ routes: ["knowledgeSearch"],
14970
+ consumes: nothing,
14971
+ output: {
14972
+ mayBeLarge: true,
14973
+ boundBy: []
14974
+ }
14975
+ },
14976
+ {
14977
+ name: "tasks.claim",
14978
+ description: "Claim tasks (by number, or a top-level message to claim as a task) before working on them. Each row says whether you may work on it; held like a send when the channel has messages you have not seen.",
14979
+ schema: claimTasksRequestSchema,
14980
+ routes: ["taskClaim"],
14981
+ mayInterrupt: true,
14982
+ consumes: nothing,
14983
+ output: small
14984
+ },
14985
+ {
14986
+ name: "tasks.list",
14987
+ description: "A channel's task board, or your own tasks across channels with mine: true.",
14988
+ schema: listTasksRequestSchema,
14989
+ routes: ["taskList"],
14990
+ consumes: nothing,
14991
+ output: {
14992
+ mayBeLarge: true,
14993
+ boundBy: ["status"]
14994
+ }
14995
+ },
14996
+ {
14997
+ name: "tasks.create",
14998
+ description: "Create one or more tasks on a channel's board; each gets its own thread.",
14999
+ schema: createTasksRequestSchema,
15000
+ routes: ["taskCreate"],
15001
+ consumes: nothing,
15002
+ output: small
15003
+ },
15004
+ {
15005
+ name: "tasks.unclaim",
15006
+ description: "Release your claim on a task so someone else can take it.",
15007
+ schema: taskRefSchema,
15008
+ routes: ["taskUnclaim"],
15009
+ consumes: nothing,
15010
+ output: small
15011
+ },
15012
+ {
15013
+ name: "tasks.assign",
15014
+ description: "Assign a task to someone (yourself, or anyone if you are an owner/admin). To clear the assignee use tasks.unassign.",
15015
+ schema: assignTaskRequestSchema,
15016
+ routes: ["taskAssign"],
15017
+ consumes: nothing,
15018
+ output: small
15019
+ },
15020
+ {
15021
+ name: "tasks.unassign",
15022
+ description: "Clear a task's assignee.",
15023
+ schema: unassignTaskRequestSchema,
15024
+ routes: ["taskAssign"],
15025
+ consumes: nothing,
15026
+ output: small
15027
+ },
15028
+ {
15029
+ name: "tasks.updateStatus",
15030
+ description: "Move a task: todo → in_progress → in_review → done, or closed from anywhere. Held like a send when the channel has messages you have not seen.",
15031
+ schema: updateTaskStatusRequestSchema,
15032
+ routes: ["taskUpdateStatus"],
15033
+ mayInterrupt: true,
15034
+ consumes: nothing,
15035
+ output: small
15036
+ },
15037
+ {
15038
+ name: "tasks.amend",
15039
+ description: "Change a task's title or description. Held like a send when the channel has messages you have not seen.",
15040
+ schema: amendTaskRequestSchema,
15041
+ routes: ["taskAmend"],
15042
+ mayInterrupt: true,
15043
+ consumes: nothing,
15044
+ output: small
15045
+ },
15046
+ {
15047
+ name: "tasks.history",
15048
+ description: "A task's history: status changes, claims, and assignments.",
15049
+ schema: taskRefSchema,
15050
+ routes: ["taskHistory"],
15051
+ consumes: nothing,
15052
+ output: {
15053
+ mayBeLarge: true,
15054
+ boundBy: []
15055
+ }
15056
+ },
15057
+ {
15058
+ name: "tasks.convert",
15059
+ description: "Turn a top-level message into an unassigned task.",
15060
+ schema: convertMessageToTaskRequestSchema,
15061
+ routes: ["taskConvert"],
15062
+ consumes: nothing,
15063
+ output: small
15064
+ },
15065
+ {
15066
+ name: "tasks.delete",
15067
+ description: "Delete a task.",
15068
+ schema: taskRefSchema,
15069
+ routes: ["taskDelete"],
15070
+ consumes: nothing,
15071
+ output: small
15072
+ },
15073
+ {
15074
+ name: "channels.join",
15075
+ description: "Join a public channel. Joining is explicit; sending never joins.",
15076
+ schema: channelTargetRequestSchema,
15077
+ routes: ["serverInfo", "channelJoin"],
15078
+ consumes: nothing,
15079
+ output: small
15080
+ },
15081
+ {
15082
+ name: "channels.leave",
15083
+ description: "Leave a channel; ordinary channel messages stop arriving.",
15084
+ schema: channelTargetRequestSchema,
15085
+ routes: ["serverInfo", "channelLeave"],
15086
+ consumes: nothing,
15087
+ output: small
15088
+ },
15089
+ {
15090
+ name: "channels.mute",
15091
+ description: "Mute a channel's ordinary activity; @mentions, DMs, and followed threads still arrive.",
15092
+ schema: channelTargetRequestSchema,
15093
+ routes: ["serverInfo", "channelMute"],
15094
+ consumes: nothing,
15095
+ output: small
15096
+ },
15097
+ {
15098
+ name: "channels.unmute",
15099
+ description: "Unmute a channel's ordinary activity.",
15100
+ schema: channelTargetRequestSchema,
15101
+ routes: ["serverInfo", "channelUnmute"],
15102
+ consumes: nothing,
15103
+ output: small
15104
+ },
15105
+ {
15106
+ name: "channels.members",
15107
+ description: "Who is in a channel, DM, or thread.",
15108
+ schema: channelMembersRequestSchema,
15109
+ routes: ["channelMembers"],
15110
+ consumes: nothing,
15111
+ output: {
15112
+ mayBeLarge: true,
15113
+ boundBy: []
15114
+ }
15115
+ },
15116
+ {
15117
+ name: "threads.list",
15118
+ description: "The threads you follow.",
15119
+ schema: listThreadsRequestSchema,
15120
+ routes: ["threadList"],
15121
+ consumes: nothing,
15122
+ output: {
15123
+ mayBeLarge: true,
15124
+ boundBy: []
15125
+ }
15126
+ },
15127
+ {
15128
+ name: "threads.unfollow",
15129
+ description: "Stop following a thread; a direct @mention follows it again.",
15130
+ schema: unfollowThreadRequestSchema,
15131
+ routes: ["threadUnfollow"],
15132
+ consumes: nothing,
15133
+ output: small
15134
+ },
15135
+ {
15136
+ name: "server.info",
15137
+ description: "The server you are on: a summary by default, or one paged section (channels, agents, humans), or the full overview.",
15138
+ schema: serverInfoRequestSchema,
15139
+ routes: ["serverInfo"],
15140
+ consumes: nothing,
15141
+ output: {
15142
+ mayBeLarge: true,
15143
+ boundBy: [
15144
+ "view",
15145
+ "offset",
15146
+ "limit"
15147
+ ]
15148
+ }
15149
+ },
15150
+ {
15151
+ name: "profile.show",
15152
+ description: "Show your profile, or someone else's by @handle.",
15153
+ schema: showProfileRequestSchema,
15154
+ routes: ["profileShow"],
15155
+ consumes: nothing,
15156
+ output: small
15157
+ },
15158
+ {
15159
+ name: "profile.update",
15160
+ description: "Update your display name, description, or avatar URL.",
15161
+ schema: updateProfileRequestSchema,
15162
+ fieldDescriptions: {
15163
+ displayName: "New display name.",
15164
+ description: "New profile description.",
15165
+ avatarUrl: "URL of the new avatar image."
15166
+ },
15167
+ routes: ["profileUpdate"],
15168
+ consumes: nothing,
15169
+ output: small
15170
+ }
15171
+ ];
15172
+ /** `tasks.updateStatus` → `tasks_update_status`. */
15173
+ function raftToolNameFor(name) {
15174
+ return name.replace(/\./g, "_").replace(/([a-z0-9])([A-Z])/g, "$1_$2").toLowerCase();
15175
+ }
15176
+ const IDEMPOTENCY_STRENGTH = {
15177
+ natural: 0,
15178
+ key: 1,
15179
+ none: 2
15180
+ };
15181
+ function deriveSpec(def) {
15182
+ const metas = def.routes.map((route) => AGENT_API_ROUTE_META[route]);
15183
+ const sideEffect = def.local ? def.local.sideEffect : metas.every((meta) => meta.sideEffect === "read") ? "read" : "write";
15184
+ const idempotencyKind = def.local ? def.local.idempotency : metas.map((meta) => meta.idempotency).reduce((a, b) => IDEMPOTENCY_STRENGTH[b] > IDEMPOTENCY_STRENGTH[a] ? b : a, "natural");
15185
+ if (idempotencyKind === "key" && !def.idempotencyArg) throw new Error(`${def.name}: keyed routes need idempotencyArg`);
15186
+ const capability = [...new Set(def.routes.map((route) => agentApiContract[route].capability))].sort();
15187
+ return {
15188
+ name: def.name,
15189
+ toolName: def.toolName ?? raftToolNameFor(def.name),
15190
+ description: def.description,
15191
+ inputSchema: toRaftToolInputSchema(def.schema, {
15192
+ omit: def.hiddenFields,
15193
+ describe: def.fieldDescriptions,
15194
+ unionAs: def.unionAs
15195
+ }),
15196
+ sideEffect,
15197
+ idempotency: idempotencyKind === "key" ? {
15198
+ kind: "key",
15199
+ arg: def.idempotencyArg
15200
+ } : { kind: idempotencyKind },
15201
+ capability,
15202
+ modelOnly: def.consumes.code === "refused",
15203
+ mayInterrupt: def.mayInterrupt === true,
15204
+ consumes: {
15205
+ model: [...def.consumes.model],
15206
+ code: def.consumes.code === "refused" ? "refused" : [...def.consumes.code]
15207
+ },
15208
+ output: {
15209
+ mayBeLarge: def.output.mayBeLarge,
15210
+ boundBy: [...def.output.boundBy]
15211
+ },
15212
+ ...def.deprecated ? { deprecated: true } : {}
15213
+ };
15214
+ }
15215
+ function fnv1a64(text) {
15216
+ let hash = 14695981039346656037n;
15217
+ const prime = 1099511628211n;
15218
+ const mask = 18446744073709551615n;
15219
+ for (let index = 0; index < text.length; index += 1) {
15220
+ hash ^= BigInt(text.charCodeAt(index));
15221
+ hash = hash * prime & mask;
15222
+ }
15223
+ return hash.toString(16).padStart(16, "0");
15224
+ }
15225
+ /** Every agent operation on `createRaft`, in a stable order. */
15226
+ const RAFT_OPERATIONS = Object.freeze(OPERATION_DEFS.map((def) => deriveSpec(def)));
15227
+ /** Content hash of `RAFT_OPERATIONS` (16 hex digits); changes whenever any field of any operation changes. */
15228
+ const RAFT_OPERATIONS_VERSION = fnv1a64(JSON.stringify(RAFT_OPERATIONS));
15229
+ const RAFT_OPERATIONS_SCHEMA = "raft-sdk-operations.v1";
15230
+ const DEFS_BY_NAME = new Map(OPERATION_DEFS.map((def) => [def.name, def]));
15231
+ const SPECS_BY_NAME = new Map(RAFT_OPERATIONS.map((spec) => [spec.name, spec]));
15232
+ /** The manifest entry and the zod request schema for a name, or undefined. */
15233
+ function lookupRaftOperation(name) {
15234
+ const def = DEFS_BY_NAME.get(name);
15235
+ const spec = SPECS_BY_NAME.get(name);
15236
+ return def && spec ? {
15237
+ spec,
15238
+ schema: def.schema
15239
+ } : void 0;
15240
+ }
15241
+ //#endregion
14044
15242
  //#region src/raft.ts
14045
15243
  function createRaft(options) {
14046
15244
  const serverUrl = requireServerUrl(options.serverUrl);
@@ -14080,13 +15278,13 @@ function createRaft(options) {
14080
15278
  * (same target, content, attachments) reuses the held send's idempotency key;
14081
15279
  * a hold is remembered; a successful send clears it.
14082
15280
  */
14083
- const sendWithState = (request) => withState(async () => {
15281
+ const sendWithState = (request, seen) => withState(async () => {
14084
15282
  const contentHash = await hashRaftSendContent(request.target, request.content ?? "", request.attachmentIds ?? []);
14085
15283
  const pending = request.idempotencyKey ? void 0 : session.findContinuation(request.target, contentHash);
14086
15284
  const outcome = await sendMessage(api, pending ? {
14087
15285
  ...request,
14088
15286
  idempotencyKey: pending.idempotencyKey
14089
- } : request, frontier);
15287
+ } : request, seen);
14090
15288
  if (outcome.ok && outcome.state === "interrupted" && outcome.interrupt.resume.idempotencyKey) session.rememberContinuation({
14091
15289
  target: request.target,
14092
15290
  idempotencyKey: outcome.interrupt.resume.idempotencyKey,
@@ -14096,7 +15294,47 @@ function createRaft(options) {
14096
15294
  else if (outcome.ok && outcome.state === "sent") session.forgetContinuation(request.target, contentHash);
14097
15295
  return outcome;
14098
15296
  });
14099
- return {
15297
+ const checkWithState = (request, seen) => withState(async () => {
15298
+ const since = request.since ?? session.cursor ?? void 0;
15299
+ const outcome = await checkInbox(inboxApi, {
15300
+ ...request,
15301
+ ...since === void 0 ? {} : { since }
15302
+ }, seen);
15303
+ if (outcome.ok) {
15304
+ session.markDirty();
15305
+ if (since !== void 0 && (request.ack ?? "cursor") === "cursor") session.commit(since);
15306
+ if (outcome.data.ackMode === "cursor" && outcome.data.messages.length > 0) session.setPending(outcome.data.cursor);
15307
+ }
15308
+ return outcome;
15309
+ });
15310
+ const drainWithState = (request, seen) => (async function* () {
15311
+ await session.ensureLoaded();
15312
+ const since = request.since ?? session.cursor ?? void 0;
15313
+ return yield* drainInbox(inboxApi, {
15314
+ ...request,
15315
+ ...since === void 0 ? {} : { since }
15316
+ }, seen, async (sent, batch) => {
15317
+ if (sent !== null) session.commit(sent);
15318
+ if (batch.ackMode === "cursor" && batch.messages.length > 0) session.setPending(batch.cursor);
15319
+ session.markDirty();
15320
+ await session.save();
15321
+ });
15322
+ })();
15323
+ const commitInbox = async (target) => {
15324
+ await session.ensureLoaded();
15325
+ const cursor = session.commit(target === void 0 ? void 0 : target.cursor);
15326
+ return {
15327
+ cursor,
15328
+ saved: cursor === null ? true : await session.save()
15329
+ };
15330
+ };
15331
+ /** `seen` undefined: read without recording anything (a code read). */
15332
+ const readWithState = (request, seen) => withState(async () => {
15333
+ const outcome = await readHistory(api, request, seen);
15334
+ if (outcome.ok && seen) session.markDirty();
15335
+ return outcome;
15336
+ });
15337
+ const raft = {
14100
15338
  identity: { whoami: () => getRaftContext(api) },
14101
15339
  wake: {
14102
15340
  verifyNotice: (input) => verifyInboxNotice(input),
@@ -14107,53 +15345,18 @@ function createRaft(options) {
14107
15345
  }
14108
15346
  },
14109
15347
  inbox: {
14110
- check: (request = {}) => withState(async () => {
14111
- const since = request.since ?? session.cursor ?? void 0;
14112
- const outcome = await checkInbox(inboxApi, {
14113
- ...request,
14114
- ...since === void 0 ? {} : { since }
14115
- }, frontier);
14116
- if (outcome.ok) {
14117
- session.markDirty();
14118
- if (since !== void 0 && (request.ack ?? "cursor") === "cursor") session.commit(since);
14119
- if (outcome.data.ackMode === "cursor" && outcome.data.messages.length > 0) session.setPending(outcome.data.cursor);
14120
- }
14121
- return outcome;
14122
- }),
14123
- commit: async (target) => {
14124
- await session.ensureLoaded();
14125
- const cursor = session.commit(target === void 0 ? void 0 : target.cursor);
14126
- return {
14127
- cursor,
14128
- saved: cursor === null ? true : await session.save()
14129
- };
14130
- },
14131
- drain: (request = {}) => (async function* () {
14132
- await session.ensureLoaded();
14133
- const since = request.since ?? session.cursor ?? void 0;
14134
- return yield* drainInbox(inboxApi, {
14135
- ...request,
14136
- ...since === void 0 ? {} : { since }
14137
- }, frontier, async (sent, batch) => {
14138
- if (sent !== null) session.commit(sent);
14139
- if (batch.ackMode === "cursor" && batch.messages.length > 0) session.setPending(batch.cursor);
14140
- session.markDirty();
14141
- await session.save();
14142
- });
14143
- })(),
15348
+ check: (request = {}) => checkWithState(request, frontier),
15349
+ commit: (target) => commitInbox(target),
15350
+ drain: (request = {}) => drainWithState(request, frontier),
14144
15351
  list: (request) => listInbox(api, request)
14145
15352
  },
14146
15353
  messages: {
14147
- read: (request) => withState(async () => {
14148
- const outcome = await readHistory(api, request, frontier);
14149
- if (outcome.ok) session.markDirty();
14150
- return outcome;
14151
- }),
14152
- send: (request) => sendWithState(request),
15354
+ read: (request) => readWithState(request, frontier),
15355
+ send: (request) => sendWithState(request, frontier),
14153
15356
  reply: (message, request) => sendWithState({
14154
15357
  ...request,
14155
15358
  target: message.target
14156
- }),
15359
+ }, frontier),
14157
15360
  search: (request) => searchMessages(api, request),
14158
15361
  resolve: (request) => resolveMessage(api, request),
14159
15362
  react: (request) => reactToMessage(api, request, "add"),
@@ -14185,6 +15388,7 @@ function createRaft(options) {
14185
15388
  create: (request) => createTasks(api, request),
14186
15389
  unclaim: (request) => unclaimTask(api, request),
14187
15390
  assign: (request) => assignTask(api, request),
15391
+ unassign: (request) => unassignTask(api, request),
14188
15392
  updateStatus: (request) => updateTaskStatus(api, request),
14189
15393
  amend: (request) => amendTask(api, request),
14190
15394
  history: (request) => taskHistory(api, request),
@@ -14219,6 +15423,108 @@ function createRaft(options) {
14219
15423
  },
14220
15424
  routes
14221
15425
  };
15426
+ const handlers = {
15427
+ "identity.whoami": async () => whoamiOutcome(await raft.identity.whoami()),
15428
+ "inbox.check": (args, call) => checkWithState(args, call.seen),
15429
+ "inbox.drain": async (args, call) => {
15430
+ const drain = drainWithState(args, call.seen);
15431
+ const batches = [];
15432
+ for (let step = await drain.next();; step = await drain.next()) {
15433
+ if (step.done) return drainedInboxOutcome(batches, step.value);
15434
+ batches.push(step.value);
15435
+ }
15436
+ },
15437
+ "inbox.commit": async (args) => {
15438
+ const result = await commitInbox(args.cursor === void 0 ? void 0 : { cursor: args.cursor });
15439
+ return {
15440
+ ok: true,
15441
+ state: result.cursor === null ? "nothing" : "committed",
15442
+ data: result,
15443
+ next: null,
15444
+ text: result.cursor === null ? "Nothing to commit." : `Committed inbox cursor ${result.cursor}; the next inbox check acknowledges it.${result.saved ? "" : " Saving the state failed; the batch may be delivered again."}`
15445
+ };
15446
+ },
15447
+ "inbox.list": (args) => raft.inbox.list(args),
15448
+ "messages.read": (args, call) => call.origin === "code" ? readWithState({
15449
+ ...args,
15450
+ consume: false
15451
+ }, void 0) : readWithState(args, call.seen),
15452
+ "messages.send": (args, call) => sendWithState(args, call.seen),
15453
+ "messages.reply": ({ message, ...request }, call) => sendWithState({
15454
+ ...request,
15455
+ target: message.target
15456
+ }, call.seen),
15457
+ "messages.search": (args) => raft.messages.search(args),
15458
+ "messages.resolve": (args) => raft.messages.resolve(args),
15459
+ "messages.react": (args) => raft.messages.react(args),
15460
+ "messages.unreact": (args) => raft.messages.unreact(args),
15461
+ "attachments.comments": (args) => raft.attachments.comments(args),
15462
+ "mentions.pending": (args) => raft.mentions.pending(args),
15463
+ "mentions.execute": (args) => raft.mentions.execute(args),
15464
+ "mentions.deliveries": (args) => raft.mentions.deliveries(args),
15465
+ "actions.prepare": (args) => raft.actions.prepare(args),
15466
+ "manual.get": (args) => raft.manual.get(args),
15467
+ "manual.search": (args) => raft.manual.search(args),
15468
+ "tasks.claim": (args) => raft.tasks.claim(args),
15469
+ "tasks.list": (args) => raft.tasks.list(args),
15470
+ "tasks.create": (args) => raft.tasks.create(args),
15471
+ "tasks.unclaim": (args) => raft.tasks.unclaim(args),
15472
+ "tasks.assign": (args) => raft.tasks.assign(args),
15473
+ "tasks.unassign": (args) => raft.tasks.unassign(args),
15474
+ "tasks.updateStatus": (args) => raft.tasks.updateStatus(args),
15475
+ "tasks.amend": (args) => raft.tasks.amend(args),
15476
+ "tasks.history": (args) => raft.tasks.history(args),
15477
+ "tasks.convert": (args) => raft.tasks.convert(args),
15478
+ "tasks.delete": (args) => raft.tasks.delete(args),
15479
+ "channels.join": (args) => raft.channels.join(args),
15480
+ "channels.leave": (args) => raft.channels.leave(args),
15481
+ "channels.mute": (args) => raft.channels.mute(args),
15482
+ "channels.unmute": (args) => raft.channels.unmute(args),
15483
+ "channels.members": (args) => raft.channels.members(args),
15484
+ "threads.list": () => raft.threads.list(),
15485
+ "threads.unfollow": (args) => raft.threads.unfollow(args),
15486
+ "server.info": (args) => raft.server.info(args),
15487
+ "profile.show": (args) => raft.profile.show(args),
15488
+ "profile.update": (args) => raft.profile.update(args)
15489
+ };
15490
+ const invoke = async (name, args, caller = {}) => {
15491
+ const found = typeof name === "string" ? lookupRaftOperation(name) : void 0;
15492
+ if (!found || !Object.hasOwn(handlers, name)) return failureOutcome(opError("INVALID_REQUEST", {
15493
+ message: `Unknown operation${typeof name === "string" && /^[A-Za-z0-9_.]{1,64}$/.test(name) ? ` "${name}"` : ""}; nothing was sent.`,
15494
+ nextAction: "Use a name from RAFT_OPERATIONS (for example \"messages.send\")."
15495
+ }));
15496
+ const origin = caller?.origin ?? "model";
15497
+ if (origin !== "model" && origin !== "code" || caller?.contextId !== void 0 && typeof caller.contextId !== "string") return failureOutcome(opError("INVALID_REQUEST", { message: "caller.origin must be \"model\" or \"code\", and caller.contextId a string; nothing was sent." }));
15498
+ const input = args === void 0 ? {} : args;
15499
+ const invalid = validateOpRequest(found.schema, input);
15500
+ if (invalid) return invalid;
15501
+ if (origin === "code" && found.spec.modelOnly) return failureOutcome(opError("MODEL_ONLY", { message: `${found.spec.name} only counts when the model sees its result, so it cannot be run from code; nothing was sent.` }));
15502
+ const handler = handlers[name];
15503
+ return handler(input, {
15504
+ seen: frontier.inContext(caller?.contextId),
15505
+ origin
15506
+ });
15507
+ };
15508
+ return {
15509
+ ...raft,
15510
+ invoke
15511
+ };
15512
+ }
15513
+ /** `identity.whoami` as an outcome (for `invoke`). */
15514
+ function whoamiOutcome(result) {
15515
+ if (!result.ok) return failureOutcome(opError(result.error.code, {
15516
+ message: result.error.message,
15517
+ ...result.status === void 0 ? {} : { status: result.status }
15518
+ }));
15519
+ const { agent, server, capabilities, guide } = result.data;
15520
+ const head = `You are @${agent.name}${agent.displayName ? ` (${agent.displayName})` : ""} on ${server.name}. Credential capabilities: ${capabilities.join(", ") || "none"}.`;
15521
+ return {
15522
+ ok: true,
15523
+ state: "identity",
15524
+ data: result.data,
15525
+ next: null,
15526
+ text: guide ? `${head}\n\n${guide}` : head
15527
+ };
14222
15528
  }
14223
15529
  //#endregion
14224
- export { RAFT_INBOX_NOTICE_SCHEMA, RAFT_NOTICE_DELIVERY_ID_HEADER, RAFT_NOTICE_SIGNATURE_HEADER, RAFT_STATE_CONTINUATIONS_PER_TARGET, RAFT_STATE_CONTINUATIONS_TOTAL, RAFT_STATE_SCHEMA, RaftCredentialError, RaftSdkConfigurationError, SeenFrontier, bootstrapRaftCredential, createFileCredentialStore, createRaft, createRaftClient, createRaftClientFromStore, createRaftRoutes, describeRaftRoute, hasAgentMessageIdentity, hashRaftSendContent, inferAttachmentMimeType, isInterrupted, joinRaftChannelByTarget, listRaftRoutes, parseRaftRegularChannelTarget, parseRaftState, projectRaftMessage, projectRaftMessages, readLatestReadThread, verifyInboxNotice };
15530
+ export { RAFT_INBOX_NOTICE_SCHEMA, RAFT_JSON_SCHEMA_KEYWORDS, RAFT_NOTICE_DELIVERY_ID_HEADER, RAFT_NOTICE_SIGNATURE_HEADER, RAFT_OPERATIONS, RAFT_OPERATIONS_SCHEMA, RAFT_OPERATIONS_VERSION, RAFT_STATE_CONTINUATIONS_PER_TARGET, RAFT_STATE_CONTINUATIONS_TOTAL, RAFT_STATE_SCHEMA, RaftCredentialError, RaftSdkConfigurationError, SeenFrontier, amendTaskRequestSchema, assignTaskRequestSchema, attachmentCommentsRequestSchema, bootstrapRaftCredential, channelMembersRequestSchema, channelTargetRequestSchema, checkInboxRequestSchema, claimTasksRequestSchema, commitInboxRequestSchema, convertMessageToTaskRequestSchema, createFileCredentialStore, createRaft, createRaftClient, createRaftClientFromStore, createRaftRoutes, createTasksRequestSchema, describeRaftRoute, drainInboxRequestSchema, executeMentionActionRequestSchema, getManualTopicRequestSchema, hasAgentMessageIdentity, hashRaftSendContent, inferAttachmentMimeType, isInterrupted, joinRaftChannelByTarget, listInboxRequestSchema, listRaftRoutes, listTasksRequestSchema, listThreadsRequestSchema, parseRaftRegularChannelTarget, parseRaftState, pendingMentionActionsRequestSchema, prepareActionCardRequestSchema, projectRaftMessage, projectRaftMessages, raftToolNameFor, reactRequestSchema, readHistoryRequestSchema, readLatestReadThread, replyToRequestSchema, resolveMessageRequestSchema, searchManualRequestSchema, searchMessagesRequestSchema, sendMessageRequestSchema, senderMentionDeliveriesRequestSchema, serverInfoRequestSchema, showProfileRequestSchema, taskRefSchema, unfollowThreadRequestSchema, updateProfileRequestSchema, updateTaskStatusRequestSchema, verifyInboxNotice, whoamiRequestSchema };