@botiverse/raft-sdk 0.6.0 → 0.8.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.
@@ -3113,6 +3113,12 @@ const numberProcessor = (schema, ctx, _json, _params) => {
3113
3113
  const booleanProcessor = (_schema, _ctx, json, _params) => {
3114
3114
  json.type = "boolean";
3115
3115
  };
3116
+ const bigintProcessor = (_schema, ctx, _json, _params) => {
3117
+ if (ctx.unrepresentable === "throw") throw new Error("BigInt cannot be represented in JSON Schema");
3118
+ };
3119
+ const symbolProcessor = (_schema, ctx, _json, _params) => {
3120
+ if (ctx.unrepresentable === "throw") throw new Error("Symbols cannot be represented in JSON Schema");
3121
+ };
3116
3122
  const nullProcessor = (_schema, ctx, json, _params) => {
3117
3123
  if (ctx.target === "openapi-3.0") {
3118
3124
  json.type = "string";
@@ -3120,9 +3126,20 @@ const nullProcessor = (_schema, ctx, json, _params) => {
3120
3126
  json.enum = [null];
3121
3127
  } else json.type = "null";
3122
3128
  };
3129
+ const undefinedProcessor = (_schema, ctx, _json, _params) => {
3130
+ if (ctx.unrepresentable === "throw") throw new Error("Undefined cannot be represented in JSON Schema");
3131
+ };
3132
+ const voidProcessor = (_schema, ctx, _json, _params) => {
3133
+ if (ctx.unrepresentable === "throw") throw new Error("Void cannot be represented in JSON Schema");
3134
+ };
3123
3135
  const neverProcessor = (_schema, _ctx, json, _params) => {
3124
3136
  json.not = {};
3125
3137
  };
3138
+ const anyProcessor = (_schema, _ctx, _json, _params) => {};
3139
+ const unknownProcessor = (_schema, _ctx, _json, _params) => {};
3140
+ const dateProcessor = (_schema, ctx, _json, _params) => {
3141
+ if (ctx.unrepresentable === "throw") throw new Error("Date cannot be represented in JSON Schema");
3142
+ };
3126
3143
  const enumProcessor = (schema, _ctx, json, _params) => {
3127
3144
  const def = schema._zod.def;
3128
3145
  const values = getEnumValues(def.entries);
@@ -3152,12 +3169,54 @@ const literalProcessor = (schema, ctx, json, _params) => {
3152
3169
  json.enum = vals;
3153
3170
  }
3154
3171
  };
3172
+ const nanProcessor = (_schema, ctx, _json, _params) => {
3173
+ if (ctx.unrepresentable === "throw") throw new Error("NaN cannot be represented in JSON Schema");
3174
+ };
3175
+ const templateLiteralProcessor = (schema, _ctx, json, _params) => {
3176
+ const _json = json;
3177
+ const pattern = schema._zod.pattern;
3178
+ if (!pattern) throw new Error("Pattern not found in template literal");
3179
+ _json.type = "string";
3180
+ _json.pattern = pattern.source;
3181
+ };
3182
+ const fileProcessor = (schema, _ctx, json, _params) => {
3183
+ const _json = json;
3184
+ const file = {
3185
+ type: "string",
3186
+ format: "binary",
3187
+ contentEncoding: "binary"
3188
+ };
3189
+ const { minimum, maximum, mime } = schema._zod.bag;
3190
+ if (minimum !== void 0) file.minLength = minimum;
3191
+ if (maximum !== void 0) file.maxLength = maximum;
3192
+ if (mime) {
3193
+ if (mime.length === 1) {
3194
+ file.contentMediaType = mime[0];
3195
+ Object.assign(_json, file);
3196
+ } else {
3197
+ Object.assign(_json, file);
3198
+ _json.anyOf = mime.map((m) => ({ contentMediaType: m }));
3199
+ }
3200
+ } else Object.assign(_json, file);
3201
+ };
3202
+ const successProcessor = (_schema, _ctx, json, _params) => {
3203
+ json.type = "boolean";
3204
+ };
3155
3205
  const customProcessor = (_schema, ctx, _json, _params) => {
3156
3206
  if (ctx.unrepresentable === "throw") throw new Error("Custom types cannot be represented in JSON Schema");
3157
3207
  };
3208
+ const functionProcessor = (_schema, ctx, _json, _params) => {
3209
+ if (ctx.unrepresentable === "throw") throw new Error("Function types cannot be represented in JSON Schema");
3210
+ };
3158
3211
  const transformProcessor = (_schema, ctx, _json, _params) => {
3159
3212
  if (ctx.unrepresentable === "throw") throw new Error("Transforms cannot be represented in JSON Schema");
3160
3213
  };
3214
+ const mapProcessor = (_schema, ctx, _json, _params) => {
3215
+ if (ctx.unrepresentable === "throw") throw new Error("Map cannot be represented in JSON Schema");
3216
+ };
3217
+ const setProcessor = (_schema, ctx, _json, _params) => {
3218
+ if (ctx.unrepresentable === "throw") throw new Error("Set cannot be represented in JSON Schema");
3219
+ };
3161
3220
  const arrayProcessor = (schema, ctx, _json, params) => {
3162
3221
  const json = _json;
3163
3222
  const def = schema._zod.def;
@@ -3234,6 +3293,44 @@ const intersectionProcessor = (schema, ctx, json, params) => {
3234
3293
  const isSimpleIntersection = (val) => "allOf" in val && Object.keys(val).length === 1;
3235
3294
  json.allOf = [...isSimpleIntersection(a) ? a.allOf : [a], ...isSimpleIntersection(b) ? b.allOf : [b]];
3236
3295
  };
3296
+ const tupleProcessor = (schema, ctx, _json, params) => {
3297
+ const json = _json;
3298
+ const def = schema._zod.def;
3299
+ json.type = "array";
3300
+ const prefixPath = ctx.target === "draft-2020-12" ? "prefixItems" : "items";
3301
+ const restPath = ctx.target === "draft-2020-12" ? "items" : ctx.target === "openapi-3.0" ? "items" : "additionalItems";
3302
+ const prefixItems = def.items.map((x, i) => process$1(x, ctx, {
3303
+ ...params,
3304
+ path: [
3305
+ ...params.path,
3306
+ prefixPath,
3307
+ i
3308
+ ]
3309
+ }));
3310
+ const rest = def.rest ? process$1(def.rest, ctx, {
3311
+ ...params,
3312
+ path: [
3313
+ ...params.path,
3314
+ restPath,
3315
+ ...ctx.target === "openapi-3.0" ? [def.items.length] : []
3316
+ ]
3317
+ }) : null;
3318
+ if (ctx.target === "draft-2020-12") {
3319
+ json.prefixItems = prefixItems;
3320
+ if (rest) json.items = rest;
3321
+ } else if (ctx.target === "openapi-3.0") {
3322
+ json.items = { anyOf: prefixItems };
3323
+ if (rest) json.items.anyOf.push(rest);
3324
+ json.minItems = prefixItems.length;
3325
+ if (!rest) json.maxItems = prefixItems.length;
3326
+ } else {
3327
+ json.items = prefixItems;
3328
+ if (rest) json.additionalItems = rest;
3329
+ }
3330
+ const { minimum, maximum } = schema._zod.bag;
3331
+ if (typeof minimum === "number") json.minItems = minimum;
3332
+ if (typeof maximum === "number") json.maxItems = maximum;
3333
+ };
3237
3334
  const recordProcessor = (schema, ctx, _json, params) => {
3238
3335
  const json = _json;
3239
3336
  const def = schema._zod.def;
@@ -3323,12 +3420,99 @@ const readonlyProcessor = (schema, ctx, json, params) => {
3323
3420
  seen.ref = def.innerType;
3324
3421
  json.readOnly = true;
3325
3422
  };
3423
+ const promiseProcessor = (schema, ctx, _json, params) => {
3424
+ const def = schema._zod.def;
3425
+ process$1(def.innerType, ctx, params);
3426
+ const seen = ctx.seen.get(schema);
3427
+ seen.ref = def.innerType;
3428
+ };
3326
3429
  const optionalProcessor = (schema, ctx, _json, params) => {
3327
3430
  const def = schema._zod.def;
3328
3431
  process$1(def.innerType, ctx, params);
3329
3432
  const seen = ctx.seen.get(schema);
3330
3433
  seen.ref = def.innerType;
3331
3434
  };
3435
+ const lazyProcessor = (schema, ctx, _json, params) => {
3436
+ const innerType = schema._zod.innerType;
3437
+ process$1(innerType, ctx, params);
3438
+ const seen = ctx.seen.get(schema);
3439
+ seen.ref = innerType;
3440
+ };
3441
+ const allProcessors = {
3442
+ string: stringProcessor,
3443
+ number: numberProcessor,
3444
+ boolean: booleanProcessor,
3445
+ bigint: bigintProcessor,
3446
+ symbol: symbolProcessor,
3447
+ null: nullProcessor,
3448
+ undefined: undefinedProcessor,
3449
+ void: voidProcessor,
3450
+ never: neverProcessor,
3451
+ any: anyProcessor,
3452
+ unknown: unknownProcessor,
3453
+ date: dateProcessor,
3454
+ enum: enumProcessor,
3455
+ literal: literalProcessor,
3456
+ nan: nanProcessor,
3457
+ template_literal: templateLiteralProcessor,
3458
+ file: fileProcessor,
3459
+ success: successProcessor,
3460
+ custom: customProcessor,
3461
+ function: functionProcessor,
3462
+ transform: transformProcessor,
3463
+ map: mapProcessor,
3464
+ set: setProcessor,
3465
+ array: arrayProcessor,
3466
+ object: objectProcessor,
3467
+ union: unionProcessor,
3468
+ intersection: intersectionProcessor,
3469
+ tuple: tupleProcessor,
3470
+ record: recordProcessor,
3471
+ nullable: nullableProcessor,
3472
+ nonoptional: nonoptionalProcessor,
3473
+ default: defaultProcessor,
3474
+ prefault: prefaultProcessor,
3475
+ catch: catchProcessor,
3476
+ pipe: pipeProcessor,
3477
+ readonly: readonlyProcessor,
3478
+ promise: promiseProcessor,
3479
+ optional: optionalProcessor,
3480
+ lazy: lazyProcessor
3481
+ };
3482
+ function toJSONSchema(input, params) {
3483
+ if ("_idmap" in input) {
3484
+ const registry = input;
3485
+ const ctx = initializeContext({
3486
+ ...params,
3487
+ processors: allProcessors
3488
+ });
3489
+ const defs = {};
3490
+ for (const entry of registry._idmap.entries()) {
3491
+ const [_, schema] = entry;
3492
+ process$1(schema, ctx);
3493
+ }
3494
+ const schemas = {};
3495
+ ctx.external = {
3496
+ registry,
3497
+ uri: params?.uri,
3498
+ defs
3499
+ };
3500
+ for (const entry of registry._idmap.entries()) {
3501
+ const [key, schema] = entry;
3502
+ extractDefs(ctx, schema);
3503
+ schemas[key] = finalize(ctx, schema);
3504
+ }
3505
+ if (Object.keys(defs).length > 0) schemas.__shared = { [ctx.target === "draft-2020-12" ? "$defs" : "definitions"]: defs };
3506
+ return { schemas };
3507
+ }
3508
+ const ctx = initializeContext({
3509
+ ...params,
3510
+ processors: allProcessors
3511
+ });
3512
+ process$1(input, ctx);
3513
+ extractDefs(ctx, input);
3514
+ return finalize(ctx, input);
3515
+ }
3332
3516
  //#endregion
3333
3517
  //#region ../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/classic/iso.js
3334
3518
  const ZodISODateTime = /*@__PURE__*/ $constructor("ZodISODateTime", (inst, def) => {
@@ -7622,7 +7806,7 @@ async function joinRaftChannelByTarget(client, request) {
7622
7806
  //#endregion
7623
7807
  //#region src/events.ts
7624
7808
  const sequence = number$1().int().nonnegative().max(Number.MAX_SAFE_INTEGER);
7625
- const requestSchema = object({
7809
+ const requestSchema$1 = object({
7626
7810
  since: union([sequence, literal("latest")]).optional(),
7627
7811
  limit: number$1().int().min(1).max(200).optional(),
7628
7812
  ack: literal("cursor").optional()
@@ -7678,7 +7862,7 @@ function failure$2(code, status, cursorAck = false) {
7678
7862
  }
7679
7863
  /** Internal adapter. The caller must supply a single-attempt transport: receive drains the returned batch. */
7680
7864
  async function receiveRaftEvents(client, request = {}) {
7681
- const parsed = requestSchema.safeParse(request);
7865
+ const parsed = requestSchema$1.safeParse(request);
7682
7866
  if (!parsed.success) return failure$2("INVALID_REQUEST");
7683
7867
  const cursorAck = parsed.data.ack === "cursor";
7684
7868
  const result = await client.events.get({
@@ -10267,7 +10451,8 @@ const DEFAULT_MESSAGES = {
10267
10451
  CONFLICT: "The Raft Server refused the operation because of the current state.",
10268
10452
  IDEMPOTENCY_KEY_REUSED: "This idempotency key was already used for a different message.",
10269
10453
  UNSUPPORTED_FOR_EXTERNAL_AGENTS: "This operation is not available to External Agents.",
10270
- UNAVAILABLE: "The Raft Server could not serve this operation right now."
10454
+ UNAVAILABLE: "The Raft Server could not serve this operation right now.",
10455
+ MODEL_ONLY: "This operation only counts when the model sees its result, so it cannot be run from code; nothing was sent."
10271
10456
  };
10272
10457
  const DEFAULT_NEXT_ACTION = {
10273
10458
  INVALID_REQUEST: "Fix the request arguments; nothing was sent.",
@@ -10280,7 +10465,8 @@ const DEFAULT_NEXT_ACTION = {
10280
10465
  CONFLICT: "Read the current state before repeating this operation.",
10281
10466
  IDEMPOTENCY_KEY_REUSED: "Use a new idempotency key for a different message, or resend the identical payload to reconcile.",
10282
10467
  UNSUPPORTED_FOR_EXTERNAL_AGENTS: "Use your own runtime for this; the Server does not provide it to External Agents.",
10283
- UNAVAILABLE: "Retry in a moment."
10468
+ UNAVAILABLE: "Retry in a moment.",
10469
+ MODEL_ONLY: "Call it as a model tool call instead of from code."
10284
10470
  };
10285
10471
  const RETRYABLE = {
10286
10472
  INVALID_REQUEST: false,
@@ -10293,7 +10479,8 @@ const RETRYABLE = {
10293
10479
  CONFLICT: false,
10294
10480
  IDEMPOTENCY_KEY_REUSED: false,
10295
10481
  UNSUPPORTED_FOR_EXTERNAL_AGENTS: false,
10296
- UNAVAILABLE: true
10482
+ UNAVAILABLE: true,
10483
+ MODEL_ONLY: false
10297
10484
  };
10298
10485
  function classifyHttp(status, serverCode) {
10299
10486
  const code = serverCode?.toLowerCase() ?? "";
@@ -10369,6 +10556,22 @@ function failureOutcome(error) {
10369
10556
  function failureFromClientResult(result) {
10370
10557
  return failureOutcome(opErrorFromClientError(result.error, result.status));
10371
10558
  }
10559
+ const MAX_REPORTED_ISSUES = 3;
10560
+ /**
10561
+ * Validate an operation's input with its zod request schema. Returns null when
10562
+ * it is valid, otherwise an `INVALID_REQUEST` failure whose message names the
10563
+ * offending fields and what was expected (zod's issue text, which never
10564
+ * echoes the input value); nothing is sent.
10565
+ */
10566
+ function validateOpRequest(schema, value) {
10567
+ const parsed = schema.safeParse(value);
10568
+ if (parsed.success) return null;
10569
+ const issues = parsed.error.issues.slice(0, MAX_REPORTED_ISSUES).map((issue) => {
10570
+ return `${issue.path.map((part) => typeof part === "number" ? `[${part}]` : String(part)).join(".").replace(/\.\[/g, "[") || "request"}: ${issue.message}`;
10571
+ });
10572
+ const more = parsed.error.issues.length > MAX_REPORTED_ISSUES ? ` (+${parsed.error.issues.length - MAX_REPORTED_ISSUES} more)` : "";
10573
+ return failureOutcome(opError("INVALID_REQUEST", { message: `Invalid request: ${issues.join("; ")}${more}. Nothing was sent.` }));
10574
+ }
10372
10575
  //#endregion
10373
10576
  //#region ../shared/src/agentInbox.ts
10374
10577
  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.]";
@@ -11002,50 +11205,75 @@ const MAX_EXACT_SEQS = 2500;
11002
11205
  function positiveInt(value) {
11003
11206
  return typeof value === "number" && Number.isInteger(value) && value > 0;
11004
11207
  }
11208
+ function contextOrNull(value) {
11209
+ return typeof value === "string" && value.length > 0 ? value : null;
11210
+ }
11005
11211
  var SeenFrontier = class SeenFrontier {
11006
- targets = /* @__PURE__ */ new Map();
11007
- aliases = /* @__PURE__ */ new Map();
11212
+ core = {
11213
+ targets: /* @__PURE__ */ new Map(),
11214
+ aliases: /* @__PURE__ */ new Map(),
11215
+ context: null
11216
+ };
11217
+ /** Set on a view from `inContext`: the context this view books and attests under. */
11218
+ bound = void 0;
11008
11219
  static fromSnapshot(snapshot) {
11009
11220
  const frontier = new SeenFrontier();
11010
11221
  frontier.absorb(snapshot);
11011
11222
  return frontier;
11012
11223
  }
11013
- /** Merge a snapshot into this frontier by the same monotonic rules (never lowers a mark). */
11224
+ /** The model context this frontier books and attests under; null means no context scoping. */
11225
+ get contextId() {
11226
+ return this.bound !== void 0 ? this.bound : this.core.context;
11227
+ }
11228
+ /**
11229
+ * Set the current model context (shared by every view of this frontier that
11230
+ * is not bound to its own context). Call it when the model's context
11231
+ * changes (a new session, a compaction): reads booked under the previous
11232
+ * context then no longer attest a send. `null` turns scoping off.
11233
+ */
11234
+ setContext(contextId) {
11235
+ this.core.context = contextOrNull(contextId);
11236
+ }
11237
+ /**
11238
+ * A view over the same records that books and attests under `contextId`
11239
+ * (for one call made on behalf of that model context), without changing the
11240
+ * frontier's current context. `undefined` returns this frontier.
11241
+ */
11242
+ inContext(contextId) {
11243
+ if (contextId === void 0) return this;
11244
+ const view = new SeenFrontier();
11245
+ view.core = this.core;
11246
+ view.bound = contextOrNull(contextId);
11247
+ return view;
11248
+ }
11249
+ /**
11250
+ * Merge a snapshot into this frontier: each record is booked under the
11251
+ * context it was booked in (same context: monotonic, never lowers a mark).
11252
+ * Adopts the snapshot's current context when this frontier has none.
11253
+ */
11014
11254
  absorb(snapshot) {
11015
11255
  if (!snapshot || snapshot.version !== 1) return;
11016
11256
  for (const [alias, canonical] of Object.entries(snapshot.aliases ?? {})) this.recordAlias(alias, canonical);
11017
11257
  for (const [target, state] of Object.entries(snapshot.targets ?? {})) {
11018
- if (positiveInt(state.upTo)) this.recordUpTo(target, state.upTo);
11019
- if (Array.isArray(state.exact)) this.recordExact(target, state.exact);
11258
+ if (positiveInt(state.upTo)) this.bookUpTo(target, state.upTo, contextOrNull(state.upToContextId));
11259
+ if (Array.isArray(state.exact)) this.bookExact(target, state.exact, contextOrNull(state.exactContextId));
11020
11260
  }
11261
+ if (this.core.context === null) this.core.context = contextOrNull(snapshot.contextId);
11021
11262
  }
11022
11263
  /** Remember that the Server resolved `requested` to `canonical` (a thread spelling, a `~agent` suffix, …). */
11023
11264
  recordAlias(requested, canonical) {
11024
- if (requested && canonical && requested !== canonical) this.aliases.set(requested, canonical);
11265
+ if (requested && canonical && requested !== canonical) this.core.aliases.set(requested, canonical);
11025
11266
  }
11026
11267
  canonical(target) {
11027
- return this.aliases.get(target) ?? target;
11268
+ return this.core.aliases.get(target) ?? target;
11028
11269
  }
11029
- /** Advance the contiguous boundary for a target; never lowers it. */
11270
+ /** Advance the contiguous boundary for a target in the current context; never lowers it within one context. */
11030
11271
  recordUpTo(target, seq) {
11031
- if (!positiveInt(seq)) return;
11032
- const state = this.state(this.canonical(target));
11033
- if (state.upTo === void 0 || seq > state.upTo) state.upTo = seq;
11034
- for (const exact of state.exact) if (exact <= state.upTo) state.exact.delete(exact);
11272
+ this.bookUpTo(target, seq, this.contextId);
11035
11273
  }
11036
- /** Record bodies that were rendered without proving contiguity. */
11274
+ /** Record bodies that were rendered without proving contiguity, in the current context. */
11037
11275
  recordExact(target, seqs) {
11038
- const state = this.state(this.canonical(target));
11039
- for (const seq of seqs) {
11040
- if (!positiveInt(seq)) continue;
11041
- if (state.upTo !== void 0 && seq <= state.upTo) continue;
11042
- state.exact.add(seq);
11043
- }
11044
- if (state.exact.size > MAX_EXACT_SEQS) {
11045
- const keep = [...state.exact].sort((a, b) => b - a).slice(0, MAX_EXACT_SEQS);
11046
- state.exact.clear();
11047
- for (const seq of keep) state.exact.add(seq);
11048
- }
11276
+ this.bookExact(target, seqs, this.contextId);
11049
11277
  }
11050
11278
  /**
11051
11279
  * Attest that the model saw the context of an interrupt (`outcome.interrupt`
@@ -11060,32 +11288,75 @@ var SeenFrontier = class SeenFrontier {
11060
11288
  this.recordUpTo(held.target, held.seenUpToSeq);
11061
11289
  return true;
11062
11290
  }
11063
- /** What to attest on a send or claim to `target`; omits `seenUpToSeq` when nothing contiguous is known. */
11291
+ /**
11292
+ * What to attest on a send or claim to `target`; omits `seenUpToSeq` when
11293
+ * nothing contiguous is known. With a current context, only bookings made
11294
+ * in that context count.
11295
+ */
11064
11296
  attestation(target) {
11065
- const state = this.targets.get(this.canonical(target));
11297
+ const state = this.core.targets.get(this.canonical(target));
11066
11298
  if (!state) return { seenExactSeqs: [] };
11299
+ const context = this.contextId;
11300
+ const upTo = context === null || state.upToContext === context ? state.upTo : void 0;
11301
+ const exact = context === null || state.exactContext === context ? [...state.exact] : [];
11067
11302
  return {
11068
- ...state.upTo === void 0 ? {} : { seenUpToSeq: state.upTo },
11069
- seenExactSeqs: [...state.exact].sort((a, b) => a - b)
11303
+ ...upTo === void 0 ? {} : { seenUpToSeq: upTo },
11304
+ seenExactSeqs: exact.filter((seq) => upTo === void 0 || seq > upTo).sort((a, b) => a - b)
11070
11305
  };
11071
11306
  }
11072
11307
  snapshot() {
11073
11308
  const targets = {};
11074
- for (const [target, state] of this.targets) targets[target] = {
11309
+ for (const [target, state] of this.core.targets) targets[target] = {
11075
11310
  ...state.upTo === void 0 ? {} : { upTo: state.upTo },
11076
- ...state.exact.size === 0 ? {} : { exact: [...state.exact].sort((a, b) => a - b) }
11311
+ ...state.exact.size === 0 ? {} : { exact: [...state.exact].sort((a, b) => a - b) },
11312
+ ...state.upTo === void 0 || state.upToContext === null ? {} : { upToContextId: state.upToContext },
11313
+ ...state.exact.size === 0 || state.exactContext === null ? {} : { exactContextId: state.exactContext }
11077
11314
  };
11078
11315
  return {
11079
11316
  version: 1,
11080
11317
  targets,
11081
- aliases: Object.fromEntries(this.aliases)
11318
+ aliases: Object.fromEntries(this.core.aliases),
11319
+ ...this.core.context === null ? {} : { contextId: this.core.context }
11082
11320
  };
11083
11321
  }
11322
+ /** A high-water booking (seenPolicy `bookStreamEntries`): another context's record is replaced, not merged. */
11323
+ bookUpTo(target, seq, context) {
11324
+ if (!positiveInt(seq)) return;
11325
+ const state = this.state(this.canonical(target));
11326
+ if (state.exact.size > 0 && state.exactContext !== context) state.exact.clear();
11327
+ if (state.upTo === void 0 || state.upToContext !== context || seq > state.upTo) state.upTo = seq;
11328
+ state.upToContext = context;
11329
+ state.exactContext = context;
11330
+ for (const exact of state.exact) if (exact <= state.upTo) state.exact.delete(exact);
11331
+ }
11332
+ /** A sparse booking (seenPolicy `bookExactSeqs`): merges within a context, replaces across; never moves `upTo`. */
11333
+ bookExact(target, seqs, context) {
11334
+ const state = this.state(this.canonical(target));
11335
+ if (state.exactContext !== context) {
11336
+ state.exact.clear();
11337
+ state.exactContext = context;
11338
+ }
11339
+ const floor = state.upToContext === context ? state.upTo : void 0;
11340
+ for (const seq of seqs) {
11341
+ if (!positiveInt(seq)) continue;
11342
+ if (floor !== void 0 && seq <= floor) continue;
11343
+ state.exact.add(seq);
11344
+ }
11345
+ if (state.exact.size > MAX_EXACT_SEQS) {
11346
+ const keep = [...state.exact].sort((a, b) => b - a).slice(0, MAX_EXACT_SEQS);
11347
+ state.exact.clear();
11348
+ for (const seq of keep) state.exact.add(seq);
11349
+ }
11350
+ }
11084
11351
  state(target) {
11085
- let state = this.targets.get(target);
11352
+ let state = this.core.targets.get(target);
11086
11353
  if (!state) {
11087
- state = { exact: /* @__PURE__ */ new Set() };
11088
- this.targets.set(target, state);
11354
+ state = {
11355
+ upToContext: null,
11356
+ exact: /* @__PURE__ */ new Set(),
11357
+ exactContext: null
11358
+ };
11359
+ this.core.targets.set(target, state);
11089
11360
  }
11090
11361
  return state;
11091
11362
  }
@@ -11158,7 +11429,18 @@ function latestReadThreadFromCliReadState(raw) {
11158
11429
  };
11159
11430
  }
11160
11431
  //#endregion
11432
+ //#region ../shared/src/agentOps/requestSchema.ts
11433
+ function requestSchema() {
11434
+ return (schema) => schema;
11435
+ }
11436
+ //#endregion
11161
11437
  //#region ../shared/src/agentOps/inbox.ts
11438
+ const inboxPullFields = {
11439
+ 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."),
11440
+ limit: number$1().int().positive().optional().describe("Messages per batch, 1..200 (Server default 50)."),
11441
+ ack: _enum(["cursor", "immediate"]).optional().describe("cursor (default): a batch is acknowledged by the next pull; immediate: acknowledged as it is returned.")
11442
+ };
11443
+ const checkInboxRequestSchema = requestSchema()(object(inboxPullFields));
11162
11444
  const MAX_DRAIN_ROUNDS = 50;
11163
11445
  function batchNext(batch) {
11164
11446
  if (batch.hasMore) return {
@@ -11197,6 +11479,8 @@ function recordExactSeen(frontier, messages) {
11197
11479
  }
11198
11480
  /** One bounded pull. Records exact seen seqs on `frontier` (sparse drains never advance the high-water mark). */
11199
11481
  async function checkInbox(client, request = {}, frontier) {
11482
+ const invalid = validateOpRequest(checkInboxRequestSchema, request);
11483
+ if (invalid) return invalid;
11200
11484
  const ack = request.ack ?? "cursor";
11201
11485
  const result = await client.events.get({
11202
11486
  since: request.since === void 0 ? "latest" : String(request.since),
@@ -11223,6 +11507,7 @@ async function checkInbox(client, request = {}, frontier) {
11223
11507
  text: batchText(batch)
11224
11508
  };
11225
11509
  }
11510
+ const drainInboxRequestSchema = requestSchema()(object(inboxPullFields));
11226
11511
  /**
11227
11512
  * Pull until the Server reports nothing more, like `raft message check`, but
11228
11513
  * as an async iterator so that acknowledgement follows consumption: under
@@ -11235,6 +11520,15 @@ async function checkInbox(client, request = {}, frontier) {
11235
11520
  */
11236
11521
  async function* drainInbox(client, request = {}, frontier, onPull) {
11237
11522
  const ack = request.ack ?? "cursor";
11523
+ const invalid = validateOpRequest(drainInboxRequestSchema, request);
11524
+ if (invalid) return {
11525
+ cursor: null,
11526
+ ackMode: ack,
11527
+ rounds: 0,
11528
+ hasMore: true,
11529
+ stillUnreadConversations: null,
11530
+ error: invalid
11531
+ };
11238
11532
  let cursor = request.since ?? null;
11239
11533
  let ackMode = ack;
11240
11534
  let stillUnread = null;
@@ -11295,6 +11589,47 @@ async function* drainInbox(client, request = {}, frontier, onPull) {
11295
11589
  error: null
11296
11590
  };
11297
11591
  }
11592
+ /** Fold a finished drain into one outcome; a drain that failed before its first batch is that failure. */
11593
+ function drainedInboxOutcome(batches, summary) {
11594
+ if (summary.error && batches.length === 0) return summary.error;
11595
+ const messages = batches.flatMap((batch) => batch.messages);
11596
+ const lines = [formatAgentMessages(messages.map((m) => toAgentMessageLike(m.raw)))];
11597
+ if (summary.error) lines.push("The drain stopped early on an error; more messages may be pending. Check the inbox again.");
11598
+ else if (summary.hasMore) lines.push("More messages are pending. Check the inbox again.");
11599
+ else if (messages.length > 0) lines.push("No more new inbox messages.");
11600
+ const stillUnread = summary.stillUnreadConversations ?? 0;
11601
+ if (stillUnread > 0) lines.push(formatAgentInboxHint({ unread_conversations: stillUnread }));
11602
+ const first = messages[0];
11603
+ const next = summary.hasMore ? {
11604
+ kind: "check_inbox_again",
11605
+ command: "raft message check",
11606
+ why: "More messages are pending."
11607
+ } : stillUnread > 0 ? {
11608
+ kind: "list_inbox",
11609
+ command: "raft inbox check",
11610
+ why: "Conversations remain unread beyond this drain."
11611
+ } : first ? {
11612
+ kind: "reply_or_act",
11613
+ args: { target: first.target },
11614
+ why: "Handle the messages above; reply where each one came from."
11615
+ } : null;
11616
+ return {
11617
+ ok: true,
11618
+ state: messages.length > 0 ? "batch" : "empty",
11619
+ data: {
11620
+ messages,
11621
+ batches: batches.length,
11622
+ summary
11623
+ },
11624
+ next,
11625
+ text: lines.join("\n")
11626
+ };
11627
+ }
11628
+ const listInboxRequestSchema = requestSchema()(object({
11629
+ view: _enum(["unread", "mentions"]).optional().describe("unread (default): every unread conversation; mentions: only those that @mention you."),
11630
+ before: number$1().int().nonnegative().optional().describe("Next page: the nextBeforeSeq of the previous page."),
11631
+ limit: number$1().int().positive().optional().describe("Conversations per page, 1..50 (Server default 20).")
11632
+ }));
11298
11633
  function openCommandFor(item) {
11299
11634
  return `raft message read --target "${item.target}" --after ${item.lastReadSeq}`;
11300
11635
  }
@@ -11330,6 +11665,8 @@ function listingText(listing) {
11330
11665
  }
11331
11666
  /** The agent's Activity panel. Lists only; nothing is consumed. */
11332
11667
  async function listInbox(client, request = {}) {
11668
+ const invalid = validateOpRequest(listInboxRequestSchema, request);
11669
+ if (invalid) return invalid;
11333
11670
  const result = await client.inbox.list({
11334
11671
  ...request.view && request.view !== "unread" ? { view: request.view } : {},
11335
11672
  ...request.before === void 0 ? {} : { before_seq: String(request.before) },
@@ -11364,6 +11701,16 @@ async function listInbox(client, request = {}) {
11364
11701
  }
11365
11702
  //#endregion
11366
11703
  //#region ../shared/src/agentOps/messages.ts
11704
+ /** A conversation target as agents spell it. */
11705
+ const raftTargetSchema = string().describe("Conversation: `#channel`, `dm:@peer`, or a thread `#channel:shortid` / `dm:@peer:shortid`.");
11706
+ const readHistoryRequestSchema = requestSchema()(object({
11707
+ target: raftTargetSchema,
11708
+ 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."),
11709
+ before: number$1().int().nonnegative().optional().describe("Only messages before this seq (exclusive): browse older history."),
11710
+ around: union([number$1().int(), string()]).optional().describe("Anchor a window around a message: its seq number (for example \"12345\") or its message id."),
11711
+ limit: number$1().int().positive().optional().describe("Maximum messages in the window."),
11712
+ consume: boolean().optional().describe("false reads without consuming: the conversation is not marked read and nothing counts as seen.")
11713
+ }));
11367
11714
  function historyNext(page) {
11368
11715
  const seqs = page.messages.map((m) => m.seq).filter((s) => s !== null);
11369
11716
  if (page.hasNewer && seqs.length > 0) {
@@ -11416,6 +11763,8 @@ function recordHistorySeen(frontier, requested, page, around) {
11416
11763
  frontier.recordExact(page.target, seqs);
11417
11764
  }
11418
11765
  async function readHistory(client, request, frontier) {
11766
+ const invalid = validateOpRequest(readHistoryRequestSchema, request);
11767
+ if (invalid) return invalid;
11419
11768
  if (!request.target?.trim()) return failureOutcome(opError("INVALID_REQUEST", { message: "A target is required to read history." }));
11420
11769
  const result = await client.history.read({
11421
11770
  channel: request.target,
@@ -11446,6 +11795,24 @@ async function readHistory(client, request, frontier) {
11446
11795
  }
11447
11796
  /** Attempts for a keyed send whose request never reached the Server (transport failure only). */
11448
11797
  const SEND_TRANSPORT_ATTEMPTS = 3;
11798
+ const sendMessageFields = {
11799
+ content: string().describe("Message text (Markdown). May be empty only when attachmentIds are given."),
11800
+ attachmentIds: array(string()).optional().describe("Attachment ids from an upload, posted with this message."),
11801
+ 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)."),
11802
+ mentions: array(agentApiStructuredMentionSchema).optional().describe("Structured @mentions (user or agent id and name), in addition to @handles in the text."),
11803
+ seen: object({
11804
+ upToSeq: number$1().int().nonnegative().optional(),
11805
+ exactSeqs: array(number$1().int().positive()).optional()
11806
+ }).optional().describe("Override the seen attestation for this send (runtimes that track what their model saw themselves).")
11807
+ };
11808
+ const sendMessageRequestSchema = requestSchema()(object({
11809
+ target: raftTargetSchema,
11810
+ ...sendMessageFields
11811
+ }));
11812
+ const replyToRequestSchema = requestSchema()(object({
11813
+ message: object({ target: raftTargetSchema }).describe("The received message to reply to; only its `target` is used."),
11814
+ ...sendMessageFields
11815
+ }));
11449
11816
  /** Today's held text (unchanged); it is the interrupt's `context` and the outcome's `text`. */
11450
11817
  function heldText(held, action) {
11451
11818
  const noun = held.newMessageCount === 1 ? "message" : "messages";
@@ -11509,6 +11876,8 @@ function sentOutcome(target, data) {
11509
11876
  };
11510
11877
  }
11511
11878
  async function sendMessage(client, request, frontier) {
11879
+ const invalid = validateOpRequest(sendMessageRequestSchema, request);
11880
+ if (invalid) return invalid;
11512
11881
  if (!request.target?.trim()) return failureOutcome(opError("INVALID_REQUEST", { message: "A target is required to send a message." }));
11513
11882
  if (typeof request.content !== "string" || !request.content.trim() && !request.attachmentIds?.length) return failureOutcome(opError("INVALID_REQUEST", { message: "Message content (or an attachment) is required." }));
11514
11883
  const idempotencyKey = request.idempotencyKey?.trim() || crypto.randomUUID();
@@ -11710,9 +12079,39 @@ function formatAgentTaskHistory(data) {
11710
12079
  return `seq=${event.seq} time=${event.createdAt} actor=${actor} type=${event.eventType}\n ${JSON.stringify(event.payload)}`;
11711
12080
  }).join("\n")}`;
11712
12081
  }
12082
+ /**
12083
+ * `raft task show`: one task's current title and description (moved verbatim
12084
+ * from the CLI's commands/task/show.ts). Labels match the agent delivery
12085
+ * surface (`Current title:` / `Current description:`). `description` has three
12086
+ * states that must not collapse: a string, an explicit null, and a field the
12087
+ * envelope omitted.
12088
+ */
12089
+ function formatAgentTaskShow(target, task) {
12090
+ const descriptionLine = typeof task.description === "string" ? `Current description: ${task.description}` : task.description === null ? "Current description: (none set)" : "Current description: (not returned by this surface)";
12091
+ return [
12092
+ `#${task.taskNumber} [${task.status ?? "unknown"}] in ${target}`,
12093
+ `Current title: ${task.title ?? "(none set)"}`,
12094
+ descriptionLine,
12095
+ ""
12096
+ ].join("\n");
12097
+ }
11713
12098
  //#endregion
11714
12099
  //#region ../shared/src/agentOps/tasks.ts
12100
+ const taskChannelSchema = string().describe("The channel the task board belongs to, for example `#proj-sdk`.");
12101
+ const taskNumberSchema = number$1().int().positive().describe("The task number on that channel's board.");
12102
+ const raftTaskStatusSchema = _enum([
12103
+ "todo",
12104
+ "in_progress",
12105
+ "in_review",
12106
+ "done",
12107
+ "closed"
12108
+ ]);
11715
12109
  const TASK_CLAIM_REASON_ALREADY_CLAIMED_BY_YOU = "already claimed by you";
12110
+ const claimTasksRequestSchema = requestSchema()(object({
12111
+ target: taskChannelSchema,
12112
+ taskNumbers: array(number$1().int().positive()).optional().describe("Task numbers to claim."),
12113
+ messageIds: array(string()).optional().describe("Full or short ids of top-level messages to claim as tasks.")
12114
+ }));
11716
12115
  /**
11717
12116
  * A held task call: the interrupt whose resume is the identical command, with
11718
12117
  * no cancel (a held task call saved nothing). `context` is today's held text.
@@ -11761,6 +12160,8 @@ function claimText(claim) {
11761
12160
  async function claimTasks(client, request) {
11762
12161
  const numbers = (request.taskNumbers ?? []).filter((n) => Number.isInteger(n) && n > 0);
11763
12162
  const ids = (request.messageIds ?? []).map((id) => id.trim()).filter(Boolean);
12163
+ const invalid = validateOpRequest(claimTasksRequestSchema, request);
12164
+ if (invalid) return invalid;
11764
12165
  if (!request.target?.trim()) return failureOutcome(opError("INVALID_REQUEST", { message: "A channel target is required to claim tasks." }));
11765
12166
  if (numbers.length === 0 && ids.length === 0) return failureOutcome(opError("INVALID_REQUEST", { message: "Pass at least one task number or message id to claim." }));
11766
12167
  const result = await client.tasks.claim({
@@ -11812,7 +12213,21 @@ async function claimTasks(client, request) {
11812
12213
  text: claimText(claim)
11813
12214
  };
11814
12215
  }
12216
+ const listTasksRequestSchema = requestSchema()(object({
12217
+ target: string().optional().describe("A channel's board, for example `#proj-sdk`. Pass exactly one of target or mine."),
12218
+ mine: boolean().optional().describe("true: your own tasks across channels instead of one board."),
12219
+ status: _enum([
12220
+ "todo",
12221
+ "in_progress",
12222
+ "in_review",
12223
+ "done",
12224
+ "closed",
12225
+ "all"
12226
+ ]).optional().describe("Filter by status; all includes done and closed.")
12227
+ }));
11815
12228
  async function listTasks(client, request) {
12229
+ const invalid = validateOpRequest(listTasksRequestSchema, request);
12230
+ if (invalid) return invalid;
11816
12231
  const mine = request.mine === true;
11817
12232
  if (mine === Boolean(request.target?.trim())) return failureOutcome(opError("INVALID_REQUEST", { message: "Pass exactly one of a channel target or mine: true." }));
11818
12233
  const result = await client.tasks.list({
@@ -11846,7 +12261,17 @@ async function listTasks(client, request) {
11846
12261
  text
11847
12262
  };
11848
12263
  }
12264
+ const createTasksRequestSchema = requestSchema()(object({
12265
+ target: taskChannelSchema,
12266
+ tasks: array(object({
12267
+ title: string().describe("Task title."),
12268
+ createsResource: boolean().optional().describe("The task produces a resource (for example a document) that needs a receipt.")
12269
+ })).describe("One entry per task to create."),
12270
+ assignee: string().optional().describe("`@handle`: yourself to start in_progress, or (owner/admin) someone else to reserve a todo.")
12271
+ }));
11849
12272
  async function createTasks(client, request) {
12273
+ const invalid = validateOpRequest(createTasksRequestSchema, request);
12274
+ if (invalid) return invalid;
11850
12275
  if (!request.target?.trim() || !request.tasks?.length) return failureOutcome(opError("INVALID_REQUEST", { message: "A channel target and at least one task title are required." }));
11851
12276
  const result = await client.tasks.create({
11852
12277
  channel: request.target,
@@ -11875,7 +12300,14 @@ async function createTasks(client, request) {
11875
12300
  text: formatAgentTasksCreated(request.target, data)
11876
12301
  };
11877
12302
  }
11878
- function requireTaskRef(request) {
12303
+ const taskRefFields = {
12304
+ target: taskChannelSchema,
12305
+ taskNumber: taskNumberSchema
12306
+ };
12307
+ const taskRefSchema = requestSchema()(object(taskRefFields));
12308
+ function requireTaskRef(request, schema = taskRefSchema) {
12309
+ const invalid = validateOpRequest(schema, request);
12310
+ if (invalid) return invalid;
11879
12311
  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." }));
11880
12312
  return null;
11881
12313
  }
@@ -11895,8 +12327,13 @@ async function unclaimTask(client, request) {
11895
12327
  text: formatAgentTaskUnclaimed(request.taskNumber)
11896
12328
  };
11897
12329
  }
12330
+ const assignTaskRequestSchema = requestSchema()(object({
12331
+ ...taskRefFields,
12332
+ 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."),
12333
+ expectedRevision: number$1().int().nonnegative().optional().describe("Revision of the task you just read; the change is refused if it moved.")
12334
+ }));
11898
12335
  async function assignTask(client, request) {
11899
- const invalid = requireTaskRef(request);
12336
+ const invalid = requireTaskRef(request, assignTaskRequestSchema);
11900
12337
  if (invalid) return invalid;
11901
12338
  const result = await client.tasks.assign({
11902
12339
  channel: request.target,
@@ -11919,6 +12356,38 @@ async function assignTask(client, request) {
11919
12356
  text: formatAgentTaskAssigned(request.taskNumber, assignee)
11920
12357
  };
11921
12358
  }
12359
+ const unassignTaskRequestSchema = requestSchema()(object({
12360
+ ...taskRefFields,
12361
+ expectedRevision: number$1().int().nonnegative().optional().describe("Revision of the task you just read; the change is refused if it moved.")
12362
+ }));
12363
+ /** Clear a task's assignee (the CLI's `raft task unassign`): the explicit way to clear, never an omitted `assignee`. */
12364
+ async function unassignTask(client, request) {
12365
+ const invalid = requireTaskRef(request, unassignTaskRequestSchema);
12366
+ if (invalid) return invalid;
12367
+ const result = await client.tasks.assign({
12368
+ channel: request.target,
12369
+ task_number: request.taskNumber,
12370
+ assignee: null,
12371
+ ...request.expectedRevision === void 0 ? {} : { expected_revision: request.expectedRevision }
12372
+ });
12373
+ if (!result.ok) return failureFromClientResult(result);
12374
+ return {
12375
+ ok: true,
12376
+ state: "unassigned",
12377
+ data: {
12378
+ target: request.target,
12379
+ taskNumber: request.taskNumber,
12380
+ assignee: null,
12381
+ revision: result.data.revision
12382
+ },
12383
+ next: null,
12384
+ text: formatAgentTaskAssigned(request.taskNumber, null)
12385
+ };
12386
+ }
12387
+ const updateTaskStatusRequestSchema = requestSchema()(object({
12388
+ ...taskRefFields,
12389
+ status: raftTaskStatusSchema.describe("todo → in_progress → in_review → done; closed from anywhere.")
12390
+ }));
11922
12391
  /** A held task write: the interrupt whose resume is the identical command; nothing to cancel. */
11923
12392
  function heldTaskWrite(target, data, action, kind, argv) {
11924
12393
  const interrupt = heldTaskInterrupt(target, data, action, "After reviewing, repeat the operation if it is still correct.", argv);
@@ -11936,7 +12405,7 @@ function heldTaskWrite(target, data, action, kind, argv) {
11936
12405
  };
11937
12406
  }
11938
12407
  async function updateTaskStatus(client, request) {
11939
- const invalid = requireTaskRef(request);
12408
+ const invalid = requireTaskRef(request, updateTaskStatusRequestSchema);
11940
12409
  if (invalid) return invalid;
11941
12410
  const result = await client.tasks.updateStatus({
11942
12411
  channel: request.target,
@@ -11956,6 +12425,11 @@ async function updateTaskStatus(client, request) {
11956
12425
  text: formatAgentTaskStatusUpdated(request.taskNumber, request.status)
11957
12426
  };
11958
12427
  }
12428
+ const amendTaskRequestSchema = requestSchema()(object({
12429
+ ...taskRefFields,
12430
+ title: string().optional().describe("New title."),
12431
+ description: string().nullable().optional().describe("New description; null clears it.")
12432
+ }));
11959
12433
  function taskAmendArgv(request) {
11960
12434
  return [
11961
12435
  "task",
@@ -11969,7 +12443,7 @@ function taskAmendArgv(request) {
11969
12443
  ];
11970
12444
  }
11971
12445
  async function amendTask(client, request) {
11972
- const invalid = requireTaskRef(request);
12446
+ const invalid = requireTaskRef(request, amendTaskRequestSchema);
11973
12447
  if (invalid) return invalid;
11974
12448
  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." }));
11975
12449
  const result = await client.tasks.amend({
@@ -12010,7 +12484,45 @@ async function taskHistory(client, request) {
12010
12484
  text: formatAgentTaskHistory(result.data)
12011
12485
  };
12012
12486
  }
12487
+ /**
12488
+ * `raft task show`: one task's current title and description. Reads the
12489
+ * channel's whole board (`status: "all"`, so done and closed tasks are found)
12490
+ * and picks the task; a miss says whether the Server asserted the list is
12491
+ * complete, exactly as the CLI does.
12492
+ */
12493
+ async function showTask(client, request) {
12494
+ const invalid = requireTaskRef(request);
12495
+ if (invalid) return invalid;
12496
+ const { target, taskNumber } = request;
12497
+ const result = await client.tasks.list({
12498
+ channel: target,
12499
+ status: "all"
12500
+ });
12501
+ if (!result.ok) return failureFromClientResult(result);
12502
+ const tasks = result.data.tasks ?? [];
12503
+ const task = tasks.find((candidate) => candidate.taskNumber === taskNumber);
12504
+ if (!task) return failureOutcome(opError("NOT_FOUND", {
12505
+ message: result.data.pagination?.mode === "complete" && result.data.pagination.truncated === false ? `task #${taskNumber} not found in ${target} (searched ${tasks.length} task(s), status=all; server asserts this list is complete)` : tasks.length === 0 ? `task #${taskNumber} not found in ${target}: the server returned 0 tasks and did not assert the list is complete. That can mean the channel has no tasks, or that the server failed to read them (it currently reports some read errors as an empty list), and this command cannot tell which — so this is not evidence that task #${taskNumber} does not exist` : `task #${taskNumber} not found in ${target} (searched ${tasks.length} task(s), status=all; this surface does NOT assert completeness — so this is "absent from what was returned", not "does not exist")`,
12506
+ nextAction: `Check the number with \`raft task list --target "${target}" --status all\`.`
12507
+ }));
12508
+ return {
12509
+ ok: true,
12510
+ state: "task",
12511
+ data: {
12512
+ target,
12513
+ task
12514
+ },
12515
+ next: null,
12516
+ text: formatAgentTaskShow(target, task)
12517
+ };
12518
+ }
12519
+ const convertMessageToTaskRequestSchema = requestSchema()(object({
12520
+ target: taskChannelSchema,
12521
+ messageId: string().describe("Full or short id of a top-level message in that channel.")
12522
+ }));
12013
12523
  async function convertMessageToTask(client, request) {
12524
+ const invalid = validateOpRequest(convertMessageToTaskRequestSchema, request);
12525
+ if (invalid) return invalid;
12014
12526
  if (!request.target?.trim() || !request.messageId?.trim()) return failureOutcome(opError("INVALID_REQUEST", { message: "A channel target and a message id are required." }));
12015
12527
  const result = await client.tasks.convert({
12016
12528
  channel: request.target,
@@ -12332,6 +12844,30 @@ function formatPageFooter(page) {
12332
12844
  if (page.nextCommand && end < page.total) lines.push(`More: ${page.nextCommand}`);
12333
12845
  return `${lines.join("\n")}\n`;
12334
12846
  }
12847
+ /** Single channel detail block. */
12848
+ function formatAgentChannelInfo(channel, memberCounts) {
12849
+ const lines = ["## Channel", ""];
12850
+ lines.push(`Channel: ${agentChannelRef(channel.name, channel.type)}`);
12851
+ if (channel.id) lines.push(`ID: ${channel.id}`);
12852
+ lines.push(`Visibility: ${channelVisibility(channel)}`);
12853
+ lines.push(`Joined: ${channel.joined ? "yes" : "no"}`);
12854
+ if (channel.channelRole) lines.push(`Channel role: ${channel.channelRole}`);
12855
+ if (channel.channelAdminBasis) lines.push(`Channel admin basis: ${channel.channelAdminBasis}`);
12856
+ const callableCapabilities = Object.entries(channel.channelCapabilities ?? {}).filter(([, allowed]) => allowed).map(([capability]) => capability);
12857
+ if (callableCapabilities.length > 0) lines.push(`Channel capabilities: ${callableCapabilities.join(", ")}`);
12858
+ const muted = channelMuted(channel);
12859
+ if (muted !== void 0) lines.push(`Muted: ${muted ? "yes" : "no"}`);
12860
+ if (typeof channel.archived === "boolean") lines.push(`Archived: ${channel.archived ? "yes" : "no"}`);
12861
+ lines.push(`Description: ${channel.description?.trim() || "(none)"}`);
12862
+ if (memberCounts) {
12863
+ const agents = memberCounts.agents ?? 0;
12864
+ const humans = memberCounts.humans ?? 0;
12865
+ lines.push(`Members: ${agents + humans} (${agents} agents, ${humans} humans)`);
12866
+ }
12867
+ lines.push("");
12868
+ lines.push(`More: raft channel members "${agentChannelRef(channel.name, channel.type)}"`);
12869
+ return `${lines.join("\n")}\n`;
12870
+ }
12335
12871
  /** Compact server summary. */
12336
12872
  function formatAgentServerSummary(data) {
12337
12873
  const channels = data.channels ?? [];
@@ -12398,6 +12934,23 @@ function formatAgentServerHumans(humans, page) {
12398
12934
  }
12399
12935
  return `${lines.join("\n")}${formatPageFooter(page)}`;
12400
12936
  }
12937
+ /** Narrow visible facts for one user/agent. */
12938
+ function formatAgentUserInfo(user, memberships, page, skippedChannels = 0) {
12939
+ const name = user.value.name;
12940
+ const role = roleLabel(user.value.role);
12941
+ const lines = ["## User", ""];
12942
+ lines.push(`User: @${name}`);
12943
+ lines.push(`Kind: ${user.kind}`);
12944
+ if (user.kind === "agent") lines.push(`Status: ${agentStatusLabel(user.value)}`);
12945
+ if (role) lines.push(`Role: ${role.slice(2, -1)}`);
12946
+ if (user.value.description) lines.push(`Description: ${user.value.description}`);
12947
+ lines.push("");
12948
+ lines.push("### Visible Channel Memberships");
12949
+ if (memberships.length === 0) lines.push("(none found in inspected visible channels)");
12950
+ else for (const channel of memberships) lines.push(`${agentChannelRef(channel.name, channel.type)} [${channelStatus(channel)}]`);
12951
+ if (skippedChannels > 0) lines.push(`Skipped ${skippedChannels} visible channel roster checks because the server rejected them.`);
12952
+ return `${lines.join("\n")}${formatPageFooter(page)}`;
12953
+ }
12401
12954
  /** Channel membership with server-role labels. */
12402
12955
  function formatAgentChannelMembers(data) {
12403
12956
  let text = "## Channel Members\n\n";
@@ -12606,6 +13159,15 @@ function formatAgentProfile(profile, options = {}) {
12606
13159
  }
12607
13160
  //#endregion
12608
13161
  //#region ../shared/src/agentOps/channels.ts
13162
+ /** `{ target }` of a regular channel (join, leave, mute, unmute). */
13163
+ const channelTargetRequestSchema = requestSchema()(object({ target: string().describe("A regular channel, `#channel-name`. DMs and threads are not accepted.") }));
13164
+ const channelMembersRequestSchema = requestSchema()(object({ target: string().describe("A channel, DM, or thread target.") }));
13165
+ /** `threads.list` takes no arguments. */
13166
+ const listThreadsRequestSchema = object({});
13167
+ const unfollowThreadRequestSchema = requestSchema()(object({
13168
+ target: string().describe("The thread, for example `#channel:shortid` or `dm:@peer:shortid`."),
13169
+ reason: string().optional().describe("Short reason, kept with the unfollow.")
13170
+ }));
12609
13171
  const INVALID_CHANNEL_TARGET = "Target must be a regular channel in the form '#channel-name'. DMs and thread targets are not supported.";
12610
13172
  async function resolveRegularChannel(client, target) {
12611
13173
  const name = parseRaftRegularChannelTarget$1(target ?? "");
@@ -12624,6 +13186,8 @@ async function resolveRegularChannel(client, target) {
12624
13186
  };
12625
13187
  }
12626
13188
  async function joinChannel(client, request) {
13189
+ const invalid = validateOpRequest(channelTargetRequestSchema, request);
13190
+ if (invalid) return invalid;
12627
13191
  const result = await joinRaftChannelByTarget$1(client, { target: request.target });
12628
13192
  if (!result.ok) {
12629
13193
  const error = result.error;
@@ -12657,6 +13221,8 @@ async function joinChannel(client, request) {
12657
13221
  };
12658
13222
  }
12659
13223
  async function leaveChannel(client, request) {
13224
+ const invalid = validateOpRequest(channelTargetRequestSchema, request);
13225
+ if (invalid) return invalid;
12660
13226
  const channel = await resolveRegularChannel(client, request.target);
12661
13227
  if ("ok" in channel) return channel;
12662
13228
  if (!channel.joined) return {
@@ -12689,6 +13255,8 @@ function formatSeq(value) {
12689
13255
  return value == null ? "none" : String(value);
12690
13256
  }
12691
13257
  async function setChannelMute(client, request, action) {
13258
+ const invalid = validateOpRequest(channelTargetRequestSchema, request);
13259
+ if (invalid) return invalid;
12692
13260
  const channel = await resolveRegularChannel(client, request.target);
12693
13261
  if ("ok" in channel) return channel;
12694
13262
  const result = action === "mute" ? await client.channels.mute({ channelId: channel.id }, {}) : await client.channels.unmute({ channelId: channel.id });
@@ -12731,6 +13299,8 @@ function unmuteChannel(client, request) {
12731
13299
  return setChannelMute(client, request, "unmute");
12732
13300
  }
12733
13301
  async function channelMembers(client, request) {
13302
+ const invalid = validateOpRequest(channelMembersRequestSchema, request);
13303
+ if (invalid) return invalid;
12734
13304
  if (!request.target?.trim()) return failureOutcome(opError("INVALID_REQUEST", { message: "A channel, DM, or thread target is required." }));
12735
13305
  const result = await client.channels.members({ channel: request.target });
12736
13306
  if (!result.ok) return failureFromClientResult(result);
@@ -12755,6 +13325,8 @@ async function listThreads(client) {
12755
13325
  };
12756
13326
  }
12757
13327
  async function unfollowThread(client, request) {
13328
+ const invalid = validateOpRequest(unfollowThreadRequestSchema, request);
13329
+ if (invalid) return invalid;
12758
13330
  if (!request.target?.includes(":")) return failureOutcome(opError("INVALID_REQUEST", { message: "A thread target is required, for example '#channel:shortid' or 'dm:@peer:shortid'." }));
12759
13331
  const result = await client.threads.unfollow({
12760
13332
  thread: request.target,
@@ -12769,8 +13341,58 @@ async function unfollowThread(client, request) {
12769
13341
  text: `Unfollowed ${request.target}. Ordinary delivery from this thread stops; a direct @mention reactivates the follow.`
12770
13342
  };
12771
13343
  }
13344
+ const channelInfoRequestSchema = requestSchema()(object({ target: string().describe("A regular channel, `#channel-name` (the `#` may be omitted). DMs and threads are not accepted.") }));
13345
+ /**
13346
+ * `raft channel info <target>`: the channel's facts from `server.info`, plus
13347
+ * member counts from its roster when the Server shows it.
13348
+ */
13349
+ async function channelInfo(client, request) {
13350
+ const invalid = validateOpRequest(channelInfoRequestSchema, request);
13351
+ if (invalid) return invalid;
13352
+ const trimmed = request.target.trim();
13353
+ const input = trimmed.startsWith("#") ? trimmed : `#${trimmed}`;
13354
+ const name = parseRaftRegularChannelTarget$1(input);
13355
+ if (!name) return failureOutcome(opError("INVALID_REQUEST", { message: "Target must be a regular channel name, e.g. '#engineering' or 'engineering'. DMs and thread targets are not supported." }));
13356
+ const info = await client.server.info();
13357
+ if (!info.ok) return failureFromClientResult(info);
13358
+ const channel = info.data.channels.find((candidate) => candidate.name === name);
13359
+ if (!channel) return failureOutcome(opError("NOT_FOUND", {
13360
+ message: `Channel not found or not visible: ${input}`,
13361
+ nextAction: "Run `raft server info --channels --query <name>` to inspect visible channels, or ask a channel member to add you if this is private."
13362
+ }));
13363
+ const members = await client.channels.members({ channel: `#${name}` });
13364
+ const memberCounts = members.ok ? {
13365
+ agents: members.data.agents?.length ?? 0,
13366
+ humans: members.data.humans?.length ?? 0
13367
+ } : null;
13368
+ return {
13369
+ ok: true,
13370
+ state: "info",
13371
+ data: {
13372
+ channel,
13373
+ memberCounts
13374
+ },
13375
+ next: null,
13376
+ text: formatAgentChannelInfo(channel, memberCounts)
13377
+ };
13378
+ }
12772
13379
  //#endregion
12773
13380
  //#region ../shared/src/agentOps/server.ts
13381
+ const serverInfoRequestSchema = requestSchema()(object({
13382
+ view: _enum([
13383
+ "summary",
13384
+ "full",
13385
+ "channels",
13386
+ "agents",
13387
+ "humans"
13388
+ ]).optional().describe("summary (default): counts; full: the whole overview; channels / agents / humans: one paged section."),
13389
+ offset: number$1().optional().describe("Section paging: rows to skip."),
13390
+ limit: number$1().optional().describe("Section paging: rows per page (default 50)."),
13391
+ joined: boolean().optional().describe("channels view only: only channels you have joined.")
13392
+ }));
13393
+ const showProfileRequestSchema = requestSchema()(object({ target: string().optional().describe("`@handle` of someone else; omit for your own profile.") }));
13394
+ /** The Agent API's profile body schema; at least one field is required (checked by the operation). */
13395
+ const updateProfileRequestSchema = agentApiProfileUpdateBodySchema;
12774
13396
  function nextCommand(section, request, offset, limit, total) {
12775
13397
  const nextOffset = offset + limit;
12776
13398
  if (nextOffset >= total) return void 0;
@@ -12784,6 +13406,8 @@ function nextCommand(section, request, offset, limit, total) {
12784
13406
  return parts.join(" ");
12785
13407
  }
12786
13408
  async function serverInfo(client, request = {}) {
13409
+ const invalid = validateOpRequest(serverInfoRequestSchema, request);
13410
+ if (invalid) return invalid;
12787
13411
  const result = await client.server.info();
12788
13412
  if (!result.ok) return failureFromClientResult(result);
12789
13413
  const server = result.data;
@@ -12849,6 +13473,8 @@ async function serverInfo(client, request = {}) {
12849
13473
  };
12850
13474
  }
12851
13475
  async function showProfile(client, request = {}, options = {}) {
13476
+ const invalid = validateOpRequest(showProfileRequestSchema, request);
13477
+ if (invalid) return invalid;
12852
13478
  const result = await client.profile.show(request.target ? { target: request.target } : {});
12853
13479
  if (!result.ok) return failureFromClientResult(result);
12854
13480
  return {
@@ -12860,6 +13486,8 @@ async function showProfile(client, request = {}, options = {}) {
12860
13486
  };
12861
13487
  }
12862
13488
  async function updateProfile(client, request, options = {}) {
13489
+ const invalid = validateOpRequest(updateProfileRequestSchema, request);
13490
+ if (invalid) return invalid;
12863
13491
  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." }));
12864
13492
  const result = await client.profile.update(request);
12865
13493
  if (!result.ok) return failureFromClientResult(result);
@@ -12871,6 +13499,85 @@ async function updateProfile(client, request, options = {}) {
12871
13499
  text: formatAgentProfile(result.data, options)
12872
13500
  };
12873
13501
  }
13502
+ const userInfoRequestSchema = requestSchema()(object({
13503
+ name: string().describe("The human or agent, `@handle` (or the bare handle)."),
13504
+ offset: number$1().int().nonnegative().optional().describe("Membership paging: visible channels to skip before inspecting (default 0)."),
13505
+ limit: number$1().int().positive().optional().describe("Membership paging: visible channels to inspect (default 50).")
13506
+ }));
13507
+ /**
13508
+ * `raft user info <name>`: the user's visible facts from `server.info`, and
13509
+ * their memberships among one page of the visible channels, checked one
13510
+ * channel roster at a time (a rejected roster is skipped and counted).
13511
+ */
13512
+ async function userInfo(client, request) {
13513
+ const invalid = validateOpRequest(userInfoRequestSchema, request);
13514
+ if (invalid) return invalid;
13515
+ const trimmed = request.name.trim();
13516
+ const name = trimmed.startsWith("@") ? trimmed.slice(1) : trimmed;
13517
+ if (!name) return failureOutcome(opError("INVALID_REQUEST", { message: "user name is required" }));
13518
+ const limit = request.limit ?? 50;
13519
+ const offset = request.offset ?? 0;
13520
+ const info = await client.server.info();
13521
+ if (!info.ok) return failureFromClientResult(info);
13522
+ const agent = info.data.agents.find((candidate) => candidate.name === name);
13523
+ const human = info.data.humans.find((candidate) => candidate.name === name);
13524
+ const user = agent ? {
13525
+ kind: "agent",
13526
+ value: agent
13527
+ } : human ? {
13528
+ kind: "human",
13529
+ value: human
13530
+ } : null;
13531
+ if (!user) return failureOutcome(opError("NOT_FOUND", {
13532
+ message: `User not found or not visible: @${name}`,
13533
+ nextAction: "Run `raft server info --agents --query <name>` or `raft server info --humans --query <name>` to inspect visible users."
13534
+ }));
13535
+ const visibleChannels = info.data.channels;
13536
+ const memberships = [];
13537
+ let skippedChannels = 0;
13538
+ for (const channel of visibleChannels.slice(offset, offset + limit)) {
13539
+ const members = await client.channels.members({ channel: `#${channel.name}` });
13540
+ if (!members.ok) {
13541
+ skippedChannels += 1;
13542
+ continue;
13543
+ }
13544
+ if ((user.kind === "agent" ? members.data.agents ?? [] : members.data.humans ?? []).some((candidate) => candidate.name === name)) memberships.push({
13545
+ ...channel,
13546
+ joined: true,
13547
+ muted: void 0,
13548
+ activityMuted: void 0
13549
+ });
13550
+ }
13551
+ const nextOffset = offset + limit;
13552
+ const page = {
13553
+ total: visibleChannels.length,
13554
+ offset,
13555
+ limit,
13556
+ nextCommand: nextOffset < visibleChannels.length ? `raft user info @${name} --offset ${nextOffset} --limit ${limit}` : void 0
13557
+ };
13558
+ const next = page.nextCommand ? {
13559
+ kind: "next_page",
13560
+ command: page.nextCommand,
13561
+ args: {
13562
+ name: `@${name}`,
13563
+ offset: nextOffset,
13564
+ limit
13565
+ },
13566
+ why: "Only one page of visible channels was inspected for memberships."
13567
+ } : null;
13568
+ return {
13569
+ ok: true,
13570
+ state: "info",
13571
+ data: {
13572
+ user,
13573
+ memberships,
13574
+ skippedChannels,
13575
+ page
13576
+ },
13577
+ next,
13578
+ text: formatAgentUserInfo(user, memberships, page, skippedChannels)
13579
+ };
13580
+ }
12874
13581
  //#endregion
12875
13582
  //#region ../shared/src/agentText/attachments.ts
12876
13583
  /** Upload receipt with attachment id and send-usage hint. */
@@ -12913,6 +13620,10 @@ function formatAgentAttachmentComments(attachmentId, comments, threadChannelId)
12913
13620
  }
12914
13621
  //#endregion
12915
13622
  //#region ../shared/src/agentOps/attachments.ts
13623
+ const attachmentCommentsRequestSchema = requestSchema()(object({
13624
+ attachmentId: string().describe("The attachment id."),
13625
+ limit: number$1().int().positive().optional().describe("Maximum comments to return.")
13626
+ }));
12916
13627
  /** Compatibility fallback for Servers that predate the capability endpoint (the CLI's constant). */
12917
13628
  const AGENT_ATTACHMENT_UPLOAD_FALLBACK_MAX_BYTES = 52428800;
12918
13629
  const FILENAME_MIME_MAP = {
@@ -13120,6 +13831,8 @@ async function downloadAttachment(client, request) {
13120
13831
  };
13121
13832
  }
13122
13833
  async function attachmentComments(client, request) {
13834
+ const invalid = validateOpRequest(attachmentCommentsRequestSchema, request);
13835
+ if (invalid) return invalid;
13123
13836
  if (!request.attachmentId?.trim()) return failureOutcome(opError("INVALID_REQUEST", { message: "An attachment id is required." }));
13124
13837
  const result = await client.attachments.comments({ attachmentId: request.attachmentId }, request.limit === void 0 ? {} : { limit: String(request.limit) });
13125
13838
  if (!result.ok) return failureFromClientResult(result);
@@ -13136,101 +13849,12 @@ async function attachmentComments(client, request) {
13136
13849
  };
13137
13850
  }
13138
13851
  //#endregion
13139
- //#region ../shared/src/zonedTime.ts
13140
- const MS_PER_SECOND = 1e3;
13141
- const MS_PER_MINUTE = 6e4;
13142
- const MS_PER_DAY = 864e5;
13143
- const formatters = /* @__PURE__ */ new Map();
13144
- function formatterFor(timeZone) {
13145
- let formatter = formatters.get(timeZone);
13146
- if (!formatter) {
13147
- formatter = new Intl.DateTimeFormat("en-US", {
13148
- timeZone,
13149
- hourCycle: "h23",
13150
- era: "short",
13151
- year: "numeric",
13152
- month: "numeric",
13153
- day: "numeric",
13154
- hour: "numeric",
13155
- minute: "numeric",
13156
- second: "numeric"
13157
- });
13158
- formatters.set(timeZone, formatter);
13159
- }
13160
- return formatter;
13161
- }
13162
- /** Days from 1970-01-01 to the proleptic Gregorian date (H. Hinnant's days_from_civil). */
13163
- function daysFromCivil(year, month, day) {
13164
- const y = month <= 2 ? year - 1 : year;
13165
- const era = Math.floor(y / 400);
13166
- const yoe = y - era * 400;
13167
- const mp = (month + 9) % 12;
13168
- const doy = Math.floor((153 * mp + 2) / 5) + day - 1;
13169
- const doe = yoe * 365 + Math.floor(yoe / 4) - Math.floor(yoe / 100) + doy;
13170
- return era * 146097 + doe - 719468;
13171
- }
13172
- /** The wall clock as milliseconds on a UTC timeline (no Date, so no 0-99 year quirk or range limit). */
13173
- function wallClockMs(wall) {
13174
- 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;
13175
- }
13176
- function floorMod(value, modulus) {
13177
- return (value % modulus + modulus) % modulus;
13178
- }
13179
- /** Wall clock of `epochMs` in `timeZone` plus the exact offset in ms (seconds precision). */
13180
- function wallClockAt(epochMs, timeZone) {
13181
- const parts = {};
13182
- for (const part of formatterFor(timeZone).formatToParts(epochMs)) parts[part.type] = part.value;
13183
- const eraYear = Number(parts.year);
13184
- const wall = {
13185
- year: /^b/i.test(parts.era ?? "") ? 1 - eraYear : eraYear,
13186
- month: Number(parts.month),
13187
- day: Number(parts.day),
13188
- hour: Number(parts.hour),
13189
- minute: Number(parts.minute),
13190
- second: Number(parts.second),
13191
- millisecond: floorMod(epochMs, MS_PER_SECOND)
13192
- };
13193
- return {
13194
- wall,
13195
- offsetMs: wallClockMs(wall) - epochMs
13196
- };
13197
- }
13198
- function offsetMinutesOf(offsetMs) {
13199
- return -Math.trunc(-offsetMs / MS_PER_MINUTE);
13200
- }
13201
- /** The wall clock and getTimezoneOffset-style offset of `epochMs` in `timeZone`. */
13202
- function zonedInstant(epochMs, timeZone) {
13203
- const { wall, offsetMs } = wallClockAt(epochMs, timeZone);
13204
- return {
13205
- ...wall,
13206
- offsetMinutes: offsetMinutesOf(offsetMs)
13207
- };
13208
- }
13209
- function pad2(n) {
13210
- return String(n).padStart(2, "0");
13211
- }
13212
- /** `+08:00` / `-04:00` / `+05:30`, as the CLI has always printed offsets. */
13213
- function formatUtcOffset(offsetMinutes) {
13214
- const sign = offsetMinutes >= 0 ? "+" : "-";
13215
- const abs = Math.abs(offsetMinutes);
13216
- return `${sign}${pad2(Math.floor(abs / 60))}:${pad2(abs % 60)}`;
13217
- }
13218
- //#endregion
13219
13852
  //#region ../shared/src/agentText/search.ts
13220
- /**
13221
- * Wall-clock rendering with offset, as the CLI prints search hit times. With
13222
- * `timeZone` (an IANA name) the time is rendered in that zone; without it, in
13223
- * the process's local zone (the SDK's historical behaviour). The two agree
13224
- * byte for byte when `timeZone` is the process zone.
13225
- */
13226
- function formatLocalTimeWithOffset(iso, timeZone) {
13853
+ /** Local wall-clock rendering with offset, as the CLI prints search hit times. */
13854
+ function formatLocalTimeWithOffset(iso) {
13227
13855
  const d = new Date(iso);
13228
13856
  if (isNaN(d.getTime())) return iso;
13229
13857
  const pad = (n) => String(n).padStart(2, "0");
13230
- if (timeZone !== void 0) {
13231
- const z = zonedInstant(d.getTime(), timeZone);
13232
- return `${z.year}-${pad(z.month)}-${pad(z.day)} ${pad(z.hour)}:${pad(z.minute)}:${pad(z.second)} ${formatUtcOffset(z.offsetMinutes)}`;
13233
- }
13234
13858
  const offsetMinutes = -d.getTimezoneOffset();
13235
13859
  const sign = offsetMinutes >= 0 ? "+" : "-";
13236
13860
  const absOffset = Math.abs(offsetMinutes);
@@ -13353,11 +13977,8 @@ function renderSearchPreview(content, query) {
13353
13977
  trailingOmit
13354
13978
  ].join("");
13355
13979
  }
13356
- /**
13357
- * Search results with <match>/<omit /> preview markup. Hit times render in
13358
- * `timeZone` when given, else in the process's local zone.
13359
- */
13360
- function formatAgentSearchResults(query, data, offset, sort, limit, timeZone) {
13980
+ /** Search results with <match>/<omit /> preview markup. */
13981
+ function formatAgentSearchResults(query, data, offset, sort, limit) {
13361
13982
  const trimmedQuery = query.trim();
13362
13983
  const oldestShown = data.results?.length ? data.results[data.results.length - 1]?.createdAt : void 0;
13363
13984
  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)}`;
@@ -13377,7 +13998,7 @@ function formatAgentSearchResults(query, data, offset, sort, limit, timeZone) {
13377
13998
  `<result ref="${ref}">`,
13378
13999
  `Source: ${renderSearchSource(result)}`,
13379
14000
  `Sender: ${sender}${senderType}`,
13380
- `Time: ${result.createdAt ? formatLocalTimeWithOffset(result.createdAt, timeZone) : "-"}`,
14001
+ `Time: ${result.createdAt ? formatLocalTimeWithOffset(result.createdAt) : "-"}`,
13381
14002
  ...taskProjection ? [taskProjection] : [],
13382
14003
  "",
13383
14004
  "<preview>",
@@ -13398,7 +14019,24 @@ function formatAgentSearchResults(query, data, offset, sort, limit, timeZone) {
13398
14019
  }
13399
14020
  //#endregion
13400
14021
  //#region ../shared/src/agentOps/search.ts
14022
+ const searchMessagesRequestSchema = requestSchema()(object({
14023
+ query: string().optional().describe("Free-text query; may be omitted when filtering by target or sender."),
14024
+ target: string().optional().describe("Only this channel, DM, or thread."),
14025
+ sender: string().optional().describe("Only messages from this handle."),
14026
+ sort: _enum(["relevance", "recent"]).optional(),
14027
+ before: string().optional().describe("ISO timestamp; only messages at or before it."),
14028
+ after: string().optional().describe("ISO timestamp; only messages at or after it."),
14029
+ limit: number$1().int().positive().optional().describe("Results per page, 1..50 (Server default 20)."),
14030
+ offset: number$1().int().nonnegative().optional().describe("Skip this many results (paging).")
14031
+ }));
14032
+ const resolveMessageRequestSchema = requestSchema()(object({ messageId: string().describe("Full or short message id.") }));
14033
+ const reactRequestSchema = requestSchema()(object({
14034
+ messageId: string().describe("Full or short message id."),
14035
+ emoji: string().describe("One reaction emoji.")
14036
+ }));
13401
14037
  async function searchMessages(client, request) {
14038
+ const invalid = validateOpRequest(searchMessagesRequestSchema, request);
14039
+ if (invalid) return invalid;
13402
14040
  if (!request.query?.trim() && !request.target && !request.sender) return failureOutcome(opError("INVALID_REQUEST", { message: "Pass a query, or filter by target or sender." }));
13403
14041
  const result = await client.messages.search({
13404
14042
  ...request.query?.trim() ? { q: request.query.trim() } : {},
@@ -13438,6 +14076,8 @@ async function searchMessages(client, request) {
13438
14076
  };
13439
14077
  }
13440
14078
  async function resolveMessage(client, request) {
14079
+ const invalid = validateOpRequest(resolveMessageRequestSchema, request);
14080
+ if (invalid) return invalid;
13441
14081
  if (!request.messageId?.trim()) return failureOutcome(opError("INVALID_REQUEST", { message: "A message id is required." }));
13442
14082
  const result = await client.messages.resolve({ msgId: request.messageId });
13443
14083
  if (!result.ok) return failureFromClientResult(result);
@@ -13460,6 +14100,8 @@ async function resolveMessage(client, request) {
13460
14100
  };
13461
14101
  }
13462
14102
  async function reactToMessage(client, request, action = "add") {
14103
+ const invalid = validateOpRequest(reactRequestSchema, request);
14104
+ if (invalid) return invalid;
13463
14105
  const emoji = request.emoji?.trim();
13464
14106
  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." }));
13465
14107
  const params = { msgId: request.messageId };
@@ -13661,7 +14303,15 @@ function formatAgentSenderMentionDeliveries(messageId, deliveries) {
13661
14303
  }
13662
14304
  //#endregion
13663
14305
  //#region ../shared/src/agentOps/mentions.ts
14306
+ const pendingMentionActionsRequestSchema = requestSchema()(object({ limit: number$1().int().positive().optional().describe("Maximum pending mentions to list.") }));
14307
+ const executeMentionActionRequestSchema = requestSchema()(object({
14308
+ action: _enum(["notify", "add"]).describe("notify: tell the mentioned target about the message; add: add them to the conversation."),
14309
+ resolutionIds: array(string()).describe("resolutionId values from mentions.pending.")
14310
+ }));
14311
+ const senderMentionDeliveriesRequestSchema = requestSchema()(object({ messageId: string().describe("Id of a message you sent.") }));
13664
14312
  async function pendingMentionActions(client, request = {}) {
14313
+ const invalid = validateOpRequest(pendingMentionActionsRequestSchema, request);
14314
+ if (invalid) return invalid;
13665
14315
  const result = await client.mentions.pendingActions(request.limit === void 0 ? {} : { limit: String(request.limit) });
13666
14316
  if (!result.ok) return failureFromClientResult(result);
13667
14317
  const actions = normalizeAgentPendingMentionActions(result.data);
@@ -13693,6 +14343,8 @@ async function pendingMentionActions(client, request = {}) {
13693
14343
  };
13694
14344
  }
13695
14345
  async function executeMentionAction(client, request) {
14346
+ const invalid = validateOpRequest(executeMentionActionRequestSchema, request);
14347
+ if (invalid) return invalid;
13696
14348
  const ids = (request.resolutionIds ?? []).map((id) => id.trim()).filter(Boolean);
13697
14349
  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." }));
13698
14350
  const result = await client.mentions.executeAction({
@@ -13713,6 +14365,8 @@ async function executeMentionAction(client, request) {
13713
14365
  };
13714
14366
  }
13715
14367
  async function senderMentionDeliveries(client, request) {
14368
+ const invalid = validateOpRequest(senderMentionDeliveriesRequestSchema, request);
14369
+ if (invalid) return invalid;
13716
14370
  if (!request.messageId?.trim()) return failureOutcome(opError("INVALID_REQUEST", { message: "A message id is required." }));
13717
14371
  const result = await client.mentions.senderDeliveries({ messageId: request.messageId });
13718
14372
  if (!result.ok) return failureFromClientResult(result);
@@ -13745,11 +14399,26 @@ function formatAgentKnowledgeStdout(content) {
13745
14399
  }
13746
14400
  //#endregion
13747
14401
  //#region ../shared/src/agentOps/manual.ts
14402
+ const manualContextFields = {
14403
+ 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."),
14404
+ reason: string().min(12).max(500).describe("Why the Manual is needed now, in a few words. Same rules as intent.")
14405
+ };
14406
+ const getManualTopicRequestSchema = requestSchema()(object({
14407
+ topic: string().describe("Topic id (slug), for example one returned by manual.search."),
14408
+ ...manualContextFields
14409
+ }));
14410
+ const searchManualRequestSchema = requestSchema()(object({
14411
+ query: string().describe("Search keywords."),
14412
+ scope: string().optional().describe("Restrict the search to one Manual section."),
14413
+ ...manualContextFields
14414
+ }));
13748
14415
  function requireContext(context) {
13749
14416
  if (!context?.intent?.trim() || !context?.reason?.trim()) return failureOutcome(opError("INVALID_REQUEST", { message: "Manual calls need a short `intent` and `reason`." }));
13750
14417
  return null;
13751
14418
  }
13752
14419
  async function getManualTopic(client, request) {
14420
+ const malformed = validateOpRequest(getManualTopicRequestSchema, request);
14421
+ if (malformed) return malformed;
13753
14422
  const invalid = requireContext(request);
13754
14423
  if (invalid) return invalid;
13755
14424
  if (!request.topic?.trim()) return failureOutcome(opError("INVALID_REQUEST", { message: "A topic id is required." }));
@@ -13768,6 +14437,8 @@ async function getManualTopic(client, request) {
13768
14437
  };
13769
14438
  }
13770
14439
  async function searchManual(client, request) {
14440
+ const malformed = validateOpRequest(searchManualRequestSchema, request);
14441
+ if (malformed) return malformed;
13771
14442
  const invalid = requireContext(request);
13772
14443
  if (invalid) return invalid;
13773
14444
  if (!request.query?.trim()) return failureOutcome(opError("INVALID_REQUEST", { message: "Search keywords are required." }));
@@ -13956,14 +14627,63 @@ var RaftStateSession = class {
13956
14627
  }
13957
14628
  };
13958
14629
  //#endregion
14630
+ //#region ../shared/src/agentOps/seenPolicy/consumedSeqs.ts
14631
+ function getParentTargetForThread(target) {
14632
+ if (target.startsWith("dm:@")) {
14633
+ const separatorIndex = target.indexOf(":", 4);
14634
+ return separatorIndex > 0 ? target.slice(0, separatorIndex) : null;
14635
+ }
14636
+ if (target.startsWith("#")) {
14637
+ const separatorIndex = target.indexOf(":");
14638
+ return separatorIndex > 0 ? target.slice(0, separatorIndex) : null;
14639
+ }
14640
+ return null;
14641
+ }
14642
+ //#endregion
13959
14643
  //#region ../shared/src/agentOps/actions.ts
14644
+ /**
14645
+ * The Agent API's own body schema (a discriminated union over the card
14646
+ * types), so the SDK checks exactly what the Server checks. The operation
14647
+ * manifest projects it flattened (see the SDK's operations.ts).
14648
+ */
14649
+ const prepareActionCardRequestSchema = agentApiActionPrepareBodySchema;
13960
14650
  /** Text is the CLI's `raft action prepare` output. */
13961
14651
  function formatAgentActionCardPosted(target, messageId) {
13962
14652
  const shortId = messageId ? messageId.slice(0, 8) : null;
13963
14653
  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`;
13964
14654
  }
14655
+ /**
14656
+ * Where the card's outcome arrives (Server #8604): when a human executes the
14657
+ * card, or execution fails, the Server posts a system reply that @mentions
14658
+ * the preparer in the card's own thread; a card posted inside a thread has no
14659
+ * thread of its own, so the reply lands in that same thread.
14660
+ */
14661
+ function awaitConfirmationNext(target, messageId) {
14662
+ const short = messageId.slice(0, 8);
14663
+ if (getParentTargetForThread(target) !== null) return {
14664
+ kind: "await_confirmation",
14665
+ command: `raft message read --target "${target}" --around ${short}`,
14666
+ args: {
14667
+ target,
14668
+ messageId
14669
+ },
14670
+ 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."
14671
+ };
14672
+ const thread = agentTaskThreadTarget(target, messageId);
14673
+ return {
14674
+ kind: "await_confirmation",
14675
+ command: `raft message read --target "${thread}"`,
14676
+ args: {
14677
+ target: thread,
14678
+ messageId
14679
+ },
14680
+ 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."
14681
+ };
14682
+ }
13965
14683
  async function prepareActionCard(client, request) {
13966
- if (!request?.target?.trim() || !request.action) return failureOutcome(opError("INVALID_REQUEST", { message: "A target and an action are required to prepare a card." }));
14684
+ 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." }));
14685
+ const invalid = validateOpRequest(prepareActionCardRequestSchema, request);
14686
+ if (invalid) return invalid;
13967
14687
  const result = await client.actions.prepare(request);
13968
14688
  if (!result.ok) return failureFromClientResult(result);
13969
14689
  const card = {
@@ -13974,15 +14694,7 @@ async function prepareActionCard(client, request) {
13974
14694
  ok: true,
13975
14695
  state: "prepared",
13976
14696
  data: card,
13977
- next: {
13978
- kind: "await_confirmation",
13979
- command: `raft message read --target "${request.target}" --around ${card.messageId.slice(0, 8)}`,
13980
- args: {
13981
- target: request.target,
13982
- messageId: card.messageId
13983
- },
13984
- 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."
13985
- },
14697
+ next: awaitConfirmationNext(request.target, card.messageId),
13986
14698
  text: formatAgentActionCardPosted(request.target, card.messageId)
13987
14699
  };
13988
14700
  }
@@ -14042,6 +14754,725 @@ async function readLatestReadThread(options = {}) {
14042
14754
  return latestReadThreadFromCliReadState(raw);
14043
14755
  }
14044
14756
  //#endregion
14757
+ //#region src/operationSchemas.ts
14758
+ /** `identity.whoami` takes no arguments. */
14759
+ const whoamiRequestSchema = object({});
14760
+ /** `inbox.commit`: no cursor commits the pending batch; a cursor commits up to it. */
14761
+ 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.") }));
14762
+ //#endregion
14763
+ //#region src/toolSchema.ts
14764
+ /** Every keyword the subset allows. */
14765
+ const RAFT_JSON_SCHEMA_KEYWORDS = [
14766
+ "type",
14767
+ "description",
14768
+ "properties",
14769
+ "required",
14770
+ "items",
14771
+ "enum",
14772
+ "minimum",
14773
+ "maximum",
14774
+ "minLength",
14775
+ "maxLength"
14776
+ ];
14777
+ const PRIMITIVES = /* @__PURE__ */ new Set([
14778
+ "string",
14779
+ "number",
14780
+ "integer",
14781
+ "boolean",
14782
+ "null"
14783
+ ]);
14784
+ const SAFE = Number.MAX_SAFE_INTEGER;
14785
+ function isRaw(value) {
14786
+ return Boolean(value) && typeof value === "object" && !Array.isArray(value);
14787
+ }
14788
+ function jsonTypeOf(value) {
14789
+ if (value === null) return "null";
14790
+ if (typeof value === "number") return Number.isInteger(value) ? "integer" : "number";
14791
+ if (typeof value === "boolean") return "boolean";
14792
+ return "string";
14793
+ }
14794
+ function project(node, where, options) {
14795
+ if (!isRaw(node)) throw new Error(`${where}: not a JSON Schema object`);
14796
+ const branches = node.anyOf ?? node.oneOf;
14797
+ if (Array.isArray(branches)) {
14798
+ const projected = branches.map((branch, index) => project(branch, `${where}|${index}`, options));
14799
+ const flattened = projected.every((b) => b.type !== void 0 && b.type !== "array" && b.type !== "object") ? primitiveUnion(projected, where, options) : flattenDiscriminatedUnion(projected, where);
14800
+ return typeof node.description === "string" ? {
14801
+ ...flattened,
14802
+ description: node.description
14803
+ } : flattened;
14804
+ }
14805
+ 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`);
14806
+ const out = {};
14807
+ if (node.type !== void 0) {
14808
+ if (Array.isArray(node.type)) throw new Error(`${where}: type arrays are outside the tool-schema subset`);
14809
+ const type = String(node.type);
14810
+ if (type !== "object" && type !== "array" && !PRIMITIVES.has(type)) throw new Error(`${where}: unknown type ${type}`);
14811
+ out.type = type;
14812
+ }
14813
+ if (typeof node.description === "string") out.description = node.description;
14814
+ if (node.const !== void 0) {
14815
+ out.enum = [node.const];
14816
+ out.type ??= jsonTypeOf(node.const);
14817
+ }
14818
+ if (Array.isArray(node.enum)) out.enum = [...node.enum];
14819
+ if (isRaw(node.properties)) {
14820
+ out.properties = {};
14821
+ const required = Array.isArray(node.required) ? node.required : [];
14822
+ for (const [key, value] of Object.entries(node.properties)) {
14823
+ 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)`);
14824
+ out.properties[key] = project(value, `${where}.${key}`, options);
14825
+ }
14826
+ out.type ??= "object";
14827
+ }
14828
+ if (Array.isArray(node.required) && node.required.length > 0) out.required = [...node.required];
14829
+ if (node.items !== void 0) out.items = project(node.items, `${where}[]`, options);
14830
+ const integer = out.type === "integer";
14831
+ 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);
14832
+ 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);
14833
+ if (lower.length > 0) out.minimum = Math.max(...lower);
14834
+ if (upper.length > 0) out.maximum = Math.min(...upper);
14835
+ if (typeof node.minLength === "number" && node.minLength > 0) out.minLength = node.minLength;
14836
+ if (typeof node.maxLength === "number") out.maxLength = node.maxLength;
14837
+ return out;
14838
+ }
14839
+ function isNullable(node) {
14840
+ if (!isRaw(node)) return false;
14841
+ const branches = node.anyOf ?? node.oneOf;
14842
+ return node.type === "null" || Array.isArray(branches) && branches.some((b) => isRaw(b) && b.type === "null");
14843
+ }
14844
+ /**
14845
+ * `T | null` → `T` (the field is optional, so omitting it is the JSON form of
14846
+ * null); any other union of primitives → the type the operation names in
14847
+ * `unionAs`. The branch constraints are dropped (looser).
14848
+ */
14849
+ function primitiveUnion(branches, where, options) {
14850
+ const types = [...new Set(branches.map((b) => b.type).filter((t) => t !== "null"))];
14851
+ if (types.length === 1) return { type: types[0] };
14852
+ const chosen = options.unionAs[where];
14853
+ if (!chosen || !types.includes(chosen)) throw new Error(`${where}: a union of ${types.join(" | ")} needs unionAs (the one type to advertise)`);
14854
+ return { type: chosen };
14855
+ }
14856
+ /** The one property every object branch pins to a distinct single value. */
14857
+ function discriminatorOf(branches) {
14858
+ const first = branches[0];
14859
+ if (!first?.properties) return null;
14860
+ for (const key of Object.keys(first.properties)) {
14861
+ const values = branches.map((b) => b.properties?.[key]?.enum);
14862
+ if (values.every((v) => Array.isArray(v) && v.length === 1) && new Set(values.map((v) => v[0])).size === branches.length) return key;
14863
+ }
14864
+ return null;
14865
+ }
14866
+ function flattenDiscriminatedUnion(branches, where) {
14867
+ if (!branches.every((b) => b.type === "object")) throw new Error(`${where}: only unions of primitives or discriminated unions of objects can be projected`);
14868
+ const discriminator = discriminatorOf(branches);
14869
+ if (!discriminator) throw new Error(`${where}: a union of objects needs a discriminator property to be flattened`);
14870
+ const tags = branches.map((b) => b.properties[discriminator].enum[0]);
14871
+ const properties = { [discriminator]: {
14872
+ type: "string",
14873
+ enum: tags,
14874
+ description: `Which variant this is; the other fields apply per ${discriminator} as their descriptions say.`
14875
+ } };
14876
+ const order = [];
14877
+ const byKey = /* @__PURE__ */ new Map();
14878
+ branches.forEach((branch, index) => {
14879
+ for (const [key, schema] of Object.entries(branch.properties ?? {})) {
14880
+ if (key === discriminator) continue;
14881
+ if (!byKey.has(key)) {
14882
+ byKey.set(key, []);
14883
+ order.push(key);
14884
+ }
14885
+ byKey.get(key).push({
14886
+ tag: tags[index],
14887
+ schema
14888
+ });
14889
+ }
14890
+ });
14891
+ for (const key of order) {
14892
+ const uses = byKey.get(key);
14893
+ const merged = uses.map((u) => u.schema).reduce(loosest);
14894
+ const descriptions = [...new Set(uses.map((u) => u.schema.description).filter((d) => Boolean(d)))];
14895
+ const usedBy = uses.length === branches.length ? "" : `Only for ${discriminator} ${uses.map((u) => u.tag).join(", ")}.`;
14896
+ const description = [...descriptions, usedBy].filter(Boolean).join(" ");
14897
+ const { description: _drop, ...rest } = merged;
14898
+ properties[key] = description ? {
14899
+ ...rest,
14900
+ description
14901
+ } : rest;
14902
+ }
14903
+ return {
14904
+ type: "object",
14905
+ properties,
14906
+ required: [discriminator]
14907
+ };
14908
+ }
14909
+ /** The loosest schema accepting everything either side accepts (within the subset). */
14910
+ function loosest(a, b) {
14911
+ if (JSON.stringify(a) === JSON.stringify(b)) return a;
14912
+ const out = {};
14913
+ if (a.type !== void 0 && a.type === b.type) out.type = a.type;
14914
+ if (a.enum && b.enum) out.enum = [.../* @__PURE__ */ new Set([...a.enum, ...b.enum])];
14915
+ if (a.minimum !== void 0 && b.minimum !== void 0) out.minimum = Math.min(a.minimum, b.minimum);
14916
+ if (a.maximum !== void 0 && b.maximum !== void 0) out.maximum = Math.max(a.maximum, b.maximum);
14917
+ if (a.minLength !== void 0 && b.minLength !== void 0) out.minLength = Math.min(a.minLength, b.minLength);
14918
+ if (a.maxLength !== void 0 && b.maxLength !== void 0) out.maxLength = Math.max(a.maxLength, b.maxLength);
14919
+ if (a.items && b.items) out.items = loosest(a.items, b.items);
14920
+ if (a.properties && b.properties) {
14921
+ out.properties = {};
14922
+ for (const key of /* @__PURE__ */ new Set([...Object.keys(a.properties), ...Object.keys(b.properties)])) {
14923
+ const pa = a.properties[key];
14924
+ const pb = b.properties[key];
14925
+ out.properties[key] = pa && pb ? loosest(pa, pb) : pa ?? pb;
14926
+ }
14927
+ const required = (a.required ?? []).filter((key) => (b.required ?? []).includes(key));
14928
+ if (required.length > 0) out.required = required;
14929
+ }
14930
+ if (a.description) out.description = a.description;
14931
+ return out;
14932
+ }
14933
+ /** The tool-schema projection of an operation's zod request schema (input side). */
14934
+ function toRaftToolInputSchema(schema, options = {}) {
14935
+ const projected = project(toJSONSchema(schema, {
14936
+ io: "input",
14937
+ target: "draft-2020-12",
14938
+ reused: "inline",
14939
+ unrepresentable: "throw"
14940
+ }), "input", { unionAs: Object.fromEntries(Object.entries(options.unionAs ?? {}).map(([key, type]) => [`input.${key}`, type])) });
14941
+ if (projected.type !== "object") throw new Error("an operation's input schema must be an object");
14942
+ for (const key of options.omit ?? []) {
14943
+ if (projected.properties) delete projected.properties[key];
14944
+ if (projected.required) projected.required = projected.required.filter((r) => r !== key);
14945
+ }
14946
+ for (const [key, description] of Object.entries(options.describe ?? {})) {
14947
+ const property = projected.properties?.[key];
14948
+ if (!property) throw new Error(`cannot describe unknown field ${key}`);
14949
+ property.description = description;
14950
+ }
14951
+ if (projected.required?.length === 0) delete projected.required;
14952
+ projected.properties ??= {};
14953
+ return projected;
14954
+ }
14955
+ //#endregion
14956
+ //#region src/operations.ts
14957
+ const nothing = {
14958
+ model: [],
14959
+ code: []
14960
+ };
14961
+ const small = {
14962
+ mayBeLarge: false,
14963
+ boundBy: []
14964
+ };
14965
+ const OPERATION_DEFS = [
14966
+ {
14967
+ name: "identity.whoami",
14968
+ description: "Who this credential is: your agent, the server, the capabilities granted to the credential, and the operating guide for External Agents.",
14969
+ schema: whoamiRequestSchema,
14970
+ routes: ["agentContext"],
14971
+ consumes: nothing,
14972
+ output: {
14973
+ mayBeLarge: true,
14974
+ boundBy: []
14975
+ }
14976
+ },
14977
+ {
14978
+ name: "inbox.check",
14979
+ 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.",
14980
+ schema: checkInboxRequestSchema,
14981
+ routes: ["events"],
14982
+ consumes: {
14983
+ model: ["inbox", "seen"],
14984
+ code: "refused"
14985
+ },
14986
+ output: {
14987
+ mayBeLarge: true,
14988
+ boundBy: ["limit"]
14989
+ }
14990
+ },
14991
+ {
14992
+ name: "inbox.drain",
14993
+ 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.",
14994
+ schema: drainInboxRequestSchema,
14995
+ routes: ["events"],
14996
+ consumes: {
14997
+ model: ["inbox", "seen"],
14998
+ code: "refused"
14999
+ },
15000
+ output: {
15001
+ mayBeLarge: true,
15002
+ boundBy: ["limit"]
15003
+ }
15004
+ },
15005
+ {
15006
+ name: "inbox.commit",
15007
+ 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.",
15008
+ schema: commitInboxRequestSchema,
15009
+ routes: [],
15010
+ local: {
15011
+ sideEffect: "write",
15012
+ idempotency: "natural"
15013
+ },
15014
+ consumes: {
15015
+ model: ["inbox"],
15016
+ code: "refused"
15017
+ },
15018
+ output: small
15019
+ },
15020
+ {
15021
+ name: "inbox.list",
15022
+ description: "List conversations with unread messages, newest activity first, each with where to start reading. Consumes nothing.",
15023
+ schema: listInboxRequestSchema,
15024
+ routes: ["inboxList"],
15025
+ consumes: nothing,
15026
+ output: {
15027
+ mayBeLarge: true,
15028
+ boundBy: ["before", "limit"]
15029
+ }
15030
+ },
15031
+ {
15032
+ name: "messages.read",
15033
+ 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.",
15034
+ schema: readHistoryRequestSchema,
15035
+ unionAs: { around: "string" },
15036
+ routes: ["historyRead"],
15037
+ consumes: {
15038
+ model: ["read_cursor", "seen"],
15039
+ code: []
15040
+ },
15041
+ output: {
15042
+ mayBeLarge: true,
15043
+ boundBy: [
15044
+ "after",
15045
+ "before",
15046
+ "around",
15047
+ "limit"
15048
+ ]
15049
+ }
15050
+ },
15051
+ {
15052
+ name: "messages.send",
15053
+ 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.",
15054
+ schema: sendMessageRequestSchema,
15055
+ hiddenFields: ["seen"],
15056
+ routes: ["messageSendV2"],
15057
+ idempotencyArg: "idempotencyKey",
15058
+ mayInterrupt: true,
15059
+ consumes: nothing,
15060
+ output: small
15061
+ },
15062
+ {
15063
+ name: "messages.reply",
15064
+ description: "Reply where a received message came from (its conversation or thread). Held like messages.send when newer messages arrived there.",
15065
+ schema: replyToRequestSchema,
15066
+ hiddenFields: ["seen"],
15067
+ routes: ["messageSendV2"],
15068
+ idempotencyArg: "idempotencyKey",
15069
+ mayInterrupt: true,
15070
+ consumes: nothing,
15071
+ output: small
15072
+ },
15073
+ {
15074
+ name: "messages.search",
15075
+ 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.",
15076
+ schema: searchMessagesRequestSchema,
15077
+ routes: ["messageSearch"],
15078
+ consumes: nothing,
15079
+ output: {
15080
+ mayBeLarge: true,
15081
+ boundBy: ["limit", "offset"]
15082
+ }
15083
+ },
15084
+ {
15085
+ name: "messages.resolve",
15086
+ description: "Resolve a message id to the full message and the conversation it belongs to.",
15087
+ schema: resolveMessageRequestSchema,
15088
+ routes: ["messageResolve"],
15089
+ consumes: nothing,
15090
+ output: small
15091
+ },
15092
+ {
15093
+ name: "messages.react",
15094
+ description: "Add an emoji reaction to a message.",
15095
+ schema: reactRequestSchema,
15096
+ routes: ["messageReactionAdd"],
15097
+ consumes: nothing,
15098
+ output: small
15099
+ },
15100
+ {
15101
+ name: "messages.unreact",
15102
+ description: "Remove your emoji reaction from a message.",
15103
+ schema: reactRequestSchema,
15104
+ routes: ["messageReactionRemove"],
15105
+ consumes: nothing,
15106
+ output: small
15107
+ },
15108
+ {
15109
+ name: "attachments.comments",
15110
+ description: "List the comments on an attachment.",
15111
+ schema: attachmentCommentsRequestSchema,
15112
+ routes: ["attachmentCommentsList"],
15113
+ consumes: nothing,
15114
+ output: {
15115
+ mayBeLarge: true,
15116
+ boundBy: ["limit"]
15117
+ }
15118
+ },
15119
+ {
15120
+ name: "mentions.pending",
15121
+ description: "List @mentions you sent that reached nobody, each with the actions that would deliver it.",
15122
+ schema: pendingMentionActionsRequestSchema,
15123
+ routes: ["mentionActionsPending"],
15124
+ consumes: nothing,
15125
+ output: {
15126
+ mayBeLarge: true,
15127
+ boundBy: ["limit"]
15128
+ }
15129
+ },
15130
+ {
15131
+ name: "mentions.execute",
15132
+ description: "Deliver unreached @mentions: notify the mentioned target, or add them to the conversation.",
15133
+ schema: executeMentionActionRequestSchema,
15134
+ routes: ["mentionActionsExecute"],
15135
+ consumes: nothing,
15136
+ output: small
15137
+ },
15138
+ {
15139
+ name: "mentions.deliveries",
15140
+ description: "Whether each @mention in a message you sent reached its target.",
15141
+ schema: senderMentionDeliveriesRequestSchema,
15142
+ routes: ["senderMentionDeliveries"],
15143
+ consumes: nothing,
15144
+ output: small
15145
+ },
15146
+ {
15147
+ name: "actions.prepare",
15148
+ 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).",
15149
+ schema: prepareActionCardRequestSchema,
15150
+ fieldDescriptions: {
15151
+ target: "Conversation to post the card in: `#channel`, `dm:@peer`, or a thread.",
15152
+ action: "The operation the card proposes: `type` picks it, and the other fields apply per type as described."
15153
+ },
15154
+ routes: ["actionPrepare"],
15155
+ consumes: nothing,
15156
+ output: small
15157
+ },
15158
+ {
15159
+ name: "manual.get",
15160
+ description: "Fetch a topic of the Raft Manual for Agents. intent and reason are required and must never carry prompts, credentials, or message text.",
15161
+ schema: getManualTopicRequestSchema,
15162
+ routes: ["knowledgeGet"],
15163
+ consumes: nothing,
15164
+ output: {
15165
+ mayBeLarge: true,
15166
+ boundBy: []
15167
+ }
15168
+ },
15169
+ {
15170
+ name: "manual.search",
15171
+ description: "Search the Raft Manual for Agents by keywords; returns topic ids to fetch with manual.get.",
15172
+ schema: searchManualRequestSchema,
15173
+ routes: ["knowledgeSearch"],
15174
+ consumes: nothing,
15175
+ output: {
15176
+ mayBeLarge: true,
15177
+ boundBy: []
15178
+ }
15179
+ },
15180
+ {
15181
+ name: "tasks.claim",
15182
+ 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.",
15183
+ schema: claimTasksRequestSchema,
15184
+ routes: ["taskClaim"],
15185
+ mayInterrupt: true,
15186
+ consumes: nothing,
15187
+ output: small
15188
+ },
15189
+ {
15190
+ name: "tasks.list",
15191
+ description: "A channel's task board, or your own tasks across channels with mine: true.",
15192
+ schema: listTasksRequestSchema,
15193
+ routes: ["taskList"],
15194
+ consumes: nothing,
15195
+ output: {
15196
+ mayBeLarge: true,
15197
+ boundBy: ["status"]
15198
+ }
15199
+ },
15200
+ {
15201
+ name: "tasks.create",
15202
+ description: "Create one or more tasks on a channel's board; each gets its own thread.",
15203
+ schema: createTasksRequestSchema,
15204
+ routes: ["taskCreate"],
15205
+ consumes: nothing,
15206
+ output: small
15207
+ },
15208
+ {
15209
+ name: "tasks.unclaim",
15210
+ description: "Release your claim on a task so someone else can take it.",
15211
+ schema: taskRefSchema,
15212
+ routes: ["taskUnclaim"],
15213
+ consumes: nothing,
15214
+ output: small
15215
+ },
15216
+ {
15217
+ name: "tasks.assign",
15218
+ description: "Assign a task to someone (yourself, or anyone if you are an owner/admin). To clear the assignee use tasks.unassign.",
15219
+ schema: assignTaskRequestSchema,
15220
+ routes: ["taskAssign"],
15221
+ consumes: nothing,
15222
+ output: small
15223
+ },
15224
+ {
15225
+ name: "tasks.unassign",
15226
+ description: "Clear a task's assignee.",
15227
+ schema: unassignTaskRequestSchema,
15228
+ routes: ["taskAssign"],
15229
+ consumes: nothing,
15230
+ output: small
15231
+ },
15232
+ {
15233
+ name: "tasks.updateStatus",
15234
+ 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.",
15235
+ schema: updateTaskStatusRequestSchema,
15236
+ routes: ["taskUpdateStatus"],
15237
+ mayInterrupt: true,
15238
+ consumes: nothing,
15239
+ output: small
15240
+ },
15241
+ {
15242
+ name: "tasks.amend",
15243
+ description: "Change a task's title or description. Held like a send when the channel has messages you have not seen.",
15244
+ schema: amendTaskRequestSchema,
15245
+ routes: ["taskAmend"],
15246
+ mayInterrupt: true,
15247
+ consumes: nothing,
15248
+ output: small
15249
+ },
15250
+ {
15251
+ name: "tasks.history",
15252
+ description: "A task's history: status changes, claims, and assignments.",
15253
+ schema: taskRefSchema,
15254
+ routes: ["taskHistory"],
15255
+ consumes: nothing,
15256
+ output: {
15257
+ mayBeLarge: true,
15258
+ boundBy: []
15259
+ }
15260
+ },
15261
+ {
15262
+ name: "tasks.show",
15263
+ description: "One task's current status, title, and description. Finds done and closed tasks too.",
15264
+ schema: taskRefSchema,
15265
+ routes: ["taskList"],
15266
+ consumes: nothing,
15267
+ output: {
15268
+ mayBeLarge: true,
15269
+ boundBy: []
15270
+ }
15271
+ },
15272
+ {
15273
+ name: "tasks.convert",
15274
+ description: "Turn a top-level message into an unassigned task.",
15275
+ schema: convertMessageToTaskRequestSchema,
15276
+ routes: ["taskConvert"],
15277
+ consumes: nothing,
15278
+ output: small
15279
+ },
15280
+ {
15281
+ name: "tasks.delete",
15282
+ description: "Delete a task.",
15283
+ schema: taskRefSchema,
15284
+ routes: ["taskDelete"],
15285
+ consumes: nothing,
15286
+ output: small
15287
+ },
15288
+ {
15289
+ name: "channels.join",
15290
+ description: "Join a public channel. Joining is explicit; sending never joins.",
15291
+ schema: channelTargetRequestSchema,
15292
+ routes: ["serverInfo", "channelJoin"],
15293
+ consumes: nothing,
15294
+ output: small
15295
+ },
15296
+ {
15297
+ name: "channels.leave",
15298
+ description: "Leave a channel; ordinary channel messages stop arriving.",
15299
+ schema: channelTargetRequestSchema,
15300
+ routes: ["serverInfo", "channelLeave"],
15301
+ consumes: nothing,
15302
+ output: small
15303
+ },
15304
+ {
15305
+ name: "channels.mute",
15306
+ description: "Mute a channel's ordinary activity; @mentions, DMs, and followed threads still arrive.",
15307
+ schema: channelTargetRequestSchema,
15308
+ routes: ["serverInfo", "channelMute"],
15309
+ consumes: nothing,
15310
+ output: small
15311
+ },
15312
+ {
15313
+ name: "channels.unmute",
15314
+ description: "Unmute a channel's ordinary activity.",
15315
+ schema: channelTargetRequestSchema,
15316
+ routes: ["serverInfo", "channelUnmute"],
15317
+ consumes: nothing,
15318
+ output: small
15319
+ },
15320
+ {
15321
+ name: "channels.members",
15322
+ description: "Who is in a channel, DM, or thread.",
15323
+ schema: channelMembersRequestSchema,
15324
+ routes: ["channelMembers"],
15325
+ consumes: nothing,
15326
+ output: {
15327
+ mayBeLarge: true,
15328
+ boundBy: []
15329
+ }
15330
+ },
15331
+ {
15332
+ name: "channels.info",
15333
+ description: "A regular channel's facts: visibility, whether you joined it, your role and mute state, description, and member counts.",
15334
+ schema: channelInfoRequestSchema,
15335
+ routes: ["serverInfo", "channelMembers"],
15336
+ consumes: nothing,
15337
+ output: small
15338
+ },
15339
+ {
15340
+ name: "threads.list",
15341
+ description: "The threads you follow.",
15342
+ schema: listThreadsRequestSchema,
15343
+ routes: ["threadList"],
15344
+ consumes: nothing,
15345
+ output: {
15346
+ mayBeLarge: true,
15347
+ boundBy: []
15348
+ }
15349
+ },
15350
+ {
15351
+ name: "threads.unfollow",
15352
+ description: "Stop following a thread; a direct @mention follows it again.",
15353
+ schema: unfollowThreadRequestSchema,
15354
+ routes: ["threadUnfollow"],
15355
+ consumes: nothing,
15356
+ output: small
15357
+ },
15358
+ {
15359
+ name: "server.info",
15360
+ description: "The server you are on: a summary by default, or one paged section (channels, agents, humans), or the full overview.",
15361
+ schema: serverInfoRequestSchema,
15362
+ routes: ["serverInfo"],
15363
+ consumes: nothing,
15364
+ output: {
15365
+ mayBeLarge: true,
15366
+ boundBy: [
15367
+ "view",
15368
+ "offset",
15369
+ "limit"
15370
+ ]
15371
+ }
15372
+ },
15373
+ {
15374
+ name: "users.info",
15375
+ description: "A human's or agent's visible facts (kind, status, role, description) and which visible channels they are in. Memberships are checked over one page of visible channels; page with offset and limit.",
15376
+ schema: userInfoRequestSchema,
15377
+ routes: ["serverInfo", "channelMembers"],
15378
+ consumes: nothing,
15379
+ output: {
15380
+ mayBeLarge: true,
15381
+ boundBy: ["offset", "limit"]
15382
+ }
15383
+ },
15384
+ {
15385
+ name: "profile.show",
15386
+ description: "Show your profile, or someone else's by @handle.",
15387
+ schema: showProfileRequestSchema,
15388
+ routes: ["profileShow"],
15389
+ consumes: nothing,
15390
+ output: small
15391
+ },
15392
+ {
15393
+ name: "profile.update",
15394
+ description: "Update your display name, description, or avatar URL.",
15395
+ schema: updateProfileRequestSchema,
15396
+ fieldDescriptions: {
15397
+ displayName: "New display name.",
15398
+ description: "New profile description.",
15399
+ avatarUrl: "URL of the new avatar image."
15400
+ },
15401
+ routes: ["profileUpdate"],
15402
+ consumes: nothing,
15403
+ output: small
15404
+ }
15405
+ ];
15406
+ /** `tasks.updateStatus` → `tasks_update_status`. */
15407
+ function raftToolNameFor(name) {
15408
+ return name.replace(/\./g, "_").replace(/([a-z0-9])([A-Z])/g, "$1_$2").toLowerCase();
15409
+ }
15410
+ const IDEMPOTENCY_STRENGTH = {
15411
+ natural: 0,
15412
+ key: 1,
15413
+ none: 2
15414
+ };
15415
+ function deriveSpec(def) {
15416
+ const metas = def.routes.map((route) => AGENT_API_ROUTE_META[route]);
15417
+ const sideEffect = def.local ? def.local.sideEffect : metas.every((meta) => meta.sideEffect === "read") ? "read" : "write";
15418
+ const idempotencyKind = def.local ? def.local.idempotency : metas.map((meta) => meta.idempotency).reduce((a, b) => IDEMPOTENCY_STRENGTH[b] > IDEMPOTENCY_STRENGTH[a] ? b : a, "natural");
15419
+ if (idempotencyKind === "key" && !def.idempotencyArg) throw new Error(`${def.name}: keyed routes need idempotencyArg`);
15420
+ const capability = [...new Set(def.routes.map((route) => agentApiContract[route].capability))].sort();
15421
+ return {
15422
+ name: def.name,
15423
+ toolName: def.toolName ?? raftToolNameFor(def.name),
15424
+ description: def.description,
15425
+ inputSchema: toRaftToolInputSchema(def.schema, {
15426
+ omit: def.hiddenFields,
15427
+ describe: def.fieldDescriptions,
15428
+ unionAs: def.unionAs
15429
+ }),
15430
+ sideEffect,
15431
+ idempotency: idempotencyKind === "key" ? {
15432
+ kind: "key",
15433
+ arg: def.idempotencyArg
15434
+ } : { kind: idempotencyKind },
15435
+ capability,
15436
+ modelOnly: def.consumes.code === "refused",
15437
+ mayInterrupt: def.mayInterrupt === true,
15438
+ consumes: {
15439
+ model: [...def.consumes.model],
15440
+ code: def.consumes.code === "refused" ? "refused" : [...def.consumes.code]
15441
+ },
15442
+ output: {
15443
+ mayBeLarge: def.output.mayBeLarge,
15444
+ boundBy: [...def.output.boundBy]
15445
+ },
15446
+ ...def.deprecated ? { deprecated: true } : {}
15447
+ };
15448
+ }
15449
+ function fnv1a64(text) {
15450
+ let hash = 14695981039346656037n;
15451
+ const prime = 1099511628211n;
15452
+ const mask = 18446744073709551615n;
15453
+ for (let index = 0; index < text.length; index += 1) {
15454
+ hash ^= BigInt(text.charCodeAt(index));
15455
+ hash = hash * prime & mask;
15456
+ }
15457
+ return hash.toString(16).padStart(16, "0");
15458
+ }
15459
+ /** Every agent operation on `createRaft`, in a stable order. */
15460
+ const RAFT_OPERATIONS = Object.freeze(OPERATION_DEFS.map((def) => deriveSpec(def)));
15461
+ /** Content hash of `RAFT_OPERATIONS` (16 hex digits); changes whenever any field of any operation changes. */
15462
+ const RAFT_OPERATIONS_VERSION = fnv1a64(JSON.stringify(RAFT_OPERATIONS));
15463
+ const RAFT_OPERATIONS_SCHEMA = "raft-sdk-operations.v1";
15464
+ const DEFS_BY_NAME = new Map(OPERATION_DEFS.map((def) => [def.name, def]));
15465
+ const SPECS_BY_NAME = new Map(RAFT_OPERATIONS.map((spec) => [spec.name, spec]));
15466
+ /** The manifest entry and the zod request schema for a name, or undefined. */
15467
+ function lookupRaftOperation(name) {
15468
+ const def = DEFS_BY_NAME.get(name);
15469
+ const spec = SPECS_BY_NAME.get(name);
15470
+ return def && spec ? {
15471
+ spec,
15472
+ schema: def.schema
15473
+ } : void 0;
15474
+ }
15475
+ //#endregion
14045
15476
  //#region src/raft.ts
14046
15477
  function createRaft(options) {
14047
15478
  const serverUrl = requireServerUrl(options.serverUrl);
@@ -14081,13 +15512,13 @@ function createRaft(options) {
14081
15512
  * (same target, content, attachments) reuses the held send's idempotency key;
14082
15513
  * a hold is remembered; a successful send clears it.
14083
15514
  */
14084
- const sendWithState = (request) => withState(async () => {
15515
+ const sendWithState = (request, seen) => withState(async () => {
14085
15516
  const contentHash = await hashRaftSendContent(request.target, request.content ?? "", request.attachmentIds ?? []);
14086
15517
  const pending = request.idempotencyKey ? void 0 : session.findContinuation(request.target, contentHash);
14087
15518
  const outcome = await sendMessage(api, pending ? {
14088
15519
  ...request,
14089
15520
  idempotencyKey: pending.idempotencyKey
14090
- } : request, frontier);
15521
+ } : request, seen);
14091
15522
  if (outcome.ok && outcome.state === "interrupted" && outcome.interrupt.resume.idempotencyKey) session.rememberContinuation({
14092
15523
  target: request.target,
14093
15524
  idempotencyKey: outcome.interrupt.resume.idempotencyKey,
@@ -14097,7 +15528,47 @@ function createRaft(options) {
14097
15528
  else if (outcome.ok && outcome.state === "sent") session.forgetContinuation(request.target, contentHash);
14098
15529
  return outcome;
14099
15530
  });
14100
- return {
15531
+ const checkWithState = (request, seen) => withState(async () => {
15532
+ const since = request.since ?? session.cursor ?? void 0;
15533
+ const outcome = await checkInbox(inboxApi, {
15534
+ ...request,
15535
+ ...since === void 0 ? {} : { since }
15536
+ }, seen);
15537
+ if (outcome.ok) {
15538
+ session.markDirty();
15539
+ if (since !== void 0 && (request.ack ?? "cursor") === "cursor") session.commit(since);
15540
+ if (outcome.data.ackMode === "cursor" && outcome.data.messages.length > 0) session.setPending(outcome.data.cursor);
15541
+ }
15542
+ return outcome;
15543
+ });
15544
+ const drainWithState = (request, seen) => (async function* () {
15545
+ await session.ensureLoaded();
15546
+ const since = request.since ?? session.cursor ?? void 0;
15547
+ return yield* drainInbox(inboxApi, {
15548
+ ...request,
15549
+ ...since === void 0 ? {} : { since }
15550
+ }, seen, async (sent, batch) => {
15551
+ if (sent !== null) session.commit(sent);
15552
+ if (batch.ackMode === "cursor" && batch.messages.length > 0) session.setPending(batch.cursor);
15553
+ session.markDirty();
15554
+ await session.save();
15555
+ });
15556
+ })();
15557
+ const commitInbox = async (target) => {
15558
+ await session.ensureLoaded();
15559
+ const cursor = session.commit(target === void 0 ? void 0 : target.cursor);
15560
+ return {
15561
+ cursor,
15562
+ saved: cursor === null ? true : await session.save()
15563
+ };
15564
+ };
15565
+ /** `seen` undefined: read without recording anything (a code read). */
15566
+ const readWithState = (request, seen) => withState(async () => {
15567
+ const outcome = await readHistory(api, request, seen);
15568
+ if (outcome.ok && seen) session.markDirty();
15569
+ return outcome;
15570
+ });
15571
+ const raft = {
14101
15572
  identity: { whoami: () => getRaftContext(api) },
14102
15573
  wake: {
14103
15574
  verifyNotice: (input) => verifyInboxNotice(input),
@@ -14108,53 +15579,18 @@ function createRaft(options) {
14108
15579
  }
14109
15580
  },
14110
15581
  inbox: {
14111
- check: (request = {}) => withState(async () => {
14112
- const since = request.since ?? session.cursor ?? void 0;
14113
- const outcome = await checkInbox(inboxApi, {
14114
- ...request,
14115
- ...since === void 0 ? {} : { since }
14116
- }, frontier);
14117
- if (outcome.ok) {
14118
- session.markDirty();
14119
- if (since !== void 0 && (request.ack ?? "cursor") === "cursor") session.commit(since);
14120
- if (outcome.data.ackMode === "cursor" && outcome.data.messages.length > 0) session.setPending(outcome.data.cursor);
14121
- }
14122
- return outcome;
14123
- }),
14124
- commit: async (target) => {
14125
- await session.ensureLoaded();
14126
- const cursor = session.commit(target === void 0 ? void 0 : target.cursor);
14127
- return {
14128
- cursor,
14129
- saved: cursor === null ? true : await session.save()
14130
- };
14131
- },
14132
- drain: (request = {}) => (async function* () {
14133
- await session.ensureLoaded();
14134
- const since = request.since ?? session.cursor ?? void 0;
14135
- return yield* drainInbox(inboxApi, {
14136
- ...request,
14137
- ...since === void 0 ? {} : { since }
14138
- }, frontier, async (sent, batch) => {
14139
- if (sent !== null) session.commit(sent);
14140
- if (batch.ackMode === "cursor" && batch.messages.length > 0) session.setPending(batch.cursor);
14141
- session.markDirty();
14142
- await session.save();
14143
- });
14144
- })(),
15582
+ check: (request = {}) => checkWithState(request, frontier),
15583
+ commit: (target) => commitInbox(target),
15584
+ drain: (request = {}) => drainWithState(request, frontier),
14145
15585
  list: (request) => listInbox(api, request)
14146
15586
  },
14147
15587
  messages: {
14148
- read: (request) => withState(async () => {
14149
- const outcome = await readHistory(api, request, frontier);
14150
- if (outcome.ok) session.markDirty();
14151
- return outcome;
14152
- }),
14153
- send: (request) => sendWithState(request),
15588
+ read: (request) => readWithState(request, frontier),
15589
+ send: (request) => sendWithState(request, frontier),
14154
15590
  reply: (message, request) => sendWithState({
14155
15591
  ...request,
14156
15592
  target: message.target
14157
- }),
15593
+ }, frontier),
14158
15594
  search: (request) => searchMessages(api, request),
14159
15595
  resolve: (request) => resolveMessage(api, request),
14160
15596
  react: (request) => reactToMessage(api, request, "add"),
@@ -14186,9 +15622,11 @@ function createRaft(options) {
14186
15622
  create: (request) => createTasks(api, request),
14187
15623
  unclaim: (request) => unclaimTask(api, request),
14188
15624
  assign: (request) => assignTask(api, request),
15625
+ unassign: (request) => unassignTask(api, request),
14189
15626
  updateStatus: (request) => updateTaskStatus(api, request),
14190
15627
  amend: (request) => amendTask(api, request),
14191
15628
  history: (request) => taskHistory(api, request),
15629
+ show: (request) => showTask(api, request),
14192
15630
  convert: (request) => convertMessageToTask(api, request),
14193
15631
  delete: (request) => deleteTask(api, request)
14194
15632
  },
@@ -14197,13 +15635,15 @@ function createRaft(options) {
14197
15635
  leave: (request) => leaveChannel(api, request),
14198
15636
  mute: (request) => muteChannel(api, request),
14199
15637
  unmute: (request) => unmuteChannel(api, request),
14200
- members: (request) => channelMembers(api, request)
15638
+ members: (request) => channelMembers(api, request),
15639
+ info: (request) => channelInfo(api, request)
14201
15640
  },
14202
15641
  threads: {
14203
15642
  list: () => listThreads(api),
14204
15643
  unfollow: (request) => unfollowThread(api, request)
14205
15644
  },
14206
15645
  server: { info: (request) => serverInfo(api, request) },
15646
+ users: { info: (request) => userInfo(api, request) },
14207
15647
  profile: {
14208
15648
  show: (request) => showProfile(api, request),
14209
15649
  update: (request) => updateProfile(api, request)
@@ -14220,33 +15660,178 @@ function createRaft(options) {
14220
15660
  },
14221
15661
  routes
14222
15662
  };
15663
+ const handlers = {
15664
+ "identity.whoami": async () => whoamiOutcome(await raft.identity.whoami()),
15665
+ "inbox.check": (args, call) => checkWithState(args, call.seen),
15666
+ "inbox.drain": async (args, call) => {
15667
+ const drain = drainWithState(args, call.seen);
15668
+ const batches = [];
15669
+ for (let step = await drain.next();; step = await drain.next()) {
15670
+ if (step.done) return drainedInboxOutcome(batches, step.value);
15671
+ batches.push(step.value);
15672
+ }
15673
+ },
15674
+ "inbox.commit": async (args) => {
15675
+ const result = await commitInbox(args.cursor === void 0 ? void 0 : { cursor: args.cursor });
15676
+ return {
15677
+ ok: true,
15678
+ state: result.cursor === null ? "nothing" : "committed",
15679
+ data: result,
15680
+ next: null,
15681
+ 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."}`
15682
+ };
15683
+ },
15684
+ "inbox.list": (args) => raft.inbox.list(args),
15685
+ "messages.read": (args, call) => call.origin === "code" ? readWithState({
15686
+ ...args,
15687
+ consume: false
15688
+ }, void 0) : readWithState(args, call.seen),
15689
+ "messages.send": (args, call) => sendWithState(args, call.seen),
15690
+ "messages.reply": ({ message, ...request }, call) => sendWithState({
15691
+ ...request,
15692
+ target: message.target
15693
+ }, call.seen),
15694
+ "messages.search": (args) => raft.messages.search(args),
15695
+ "messages.resolve": (args) => raft.messages.resolve(args),
15696
+ "messages.react": (args) => raft.messages.react(args),
15697
+ "messages.unreact": (args) => raft.messages.unreact(args),
15698
+ "attachments.comments": (args) => raft.attachments.comments(args),
15699
+ "mentions.pending": (args) => raft.mentions.pending(args),
15700
+ "mentions.execute": (args) => raft.mentions.execute(args),
15701
+ "mentions.deliveries": (args) => raft.mentions.deliveries(args),
15702
+ "actions.prepare": (args) => raft.actions.prepare(args),
15703
+ "manual.get": (args) => raft.manual.get(args),
15704
+ "manual.search": (args) => raft.manual.search(args),
15705
+ "tasks.claim": (args) => raft.tasks.claim(args),
15706
+ "tasks.list": (args) => raft.tasks.list(args),
15707
+ "tasks.create": (args) => raft.tasks.create(args),
15708
+ "tasks.unclaim": (args) => raft.tasks.unclaim(args),
15709
+ "tasks.assign": (args) => raft.tasks.assign(args),
15710
+ "tasks.unassign": (args) => raft.tasks.unassign(args),
15711
+ "tasks.updateStatus": (args) => raft.tasks.updateStatus(args),
15712
+ "tasks.amend": (args) => raft.tasks.amend(args),
15713
+ "tasks.history": (args) => raft.tasks.history(args),
15714
+ "tasks.show": (args) => raft.tasks.show(args),
15715
+ "tasks.convert": (args) => raft.tasks.convert(args),
15716
+ "tasks.delete": (args) => raft.tasks.delete(args),
15717
+ "channels.join": (args) => raft.channels.join(args),
15718
+ "channels.leave": (args) => raft.channels.leave(args),
15719
+ "channels.mute": (args) => raft.channels.mute(args),
15720
+ "channels.unmute": (args) => raft.channels.unmute(args),
15721
+ "channels.members": (args) => raft.channels.members(args),
15722
+ "channels.info": (args) => raft.channels.info(args),
15723
+ "threads.list": () => raft.threads.list(),
15724
+ "threads.unfollow": (args) => raft.threads.unfollow(args),
15725
+ "server.info": (args) => raft.server.info(args),
15726
+ "users.info": (args) => raft.users.info(args),
15727
+ "profile.show": (args) => raft.profile.show(args),
15728
+ "profile.update": (args) => raft.profile.update(args)
15729
+ };
15730
+ const invoke = async (name, args, caller = {}) => {
15731
+ const found = typeof name === "string" ? lookupRaftOperation(name) : void 0;
15732
+ if (!found || !Object.hasOwn(handlers, name)) return failureOutcome(opError("INVALID_REQUEST", {
15733
+ message: `Unknown operation${typeof name === "string" && /^[A-Za-z0-9_.]{1,64}$/.test(name) ? ` "${name}"` : ""}; nothing was sent.`,
15734
+ nextAction: "Use a name from RAFT_OPERATIONS (for example \"messages.send\")."
15735
+ }));
15736
+ const origin = caller?.origin ?? "model";
15737
+ 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." }));
15738
+ const input = args === void 0 ? {} : args;
15739
+ const invalid = validateOpRequest(found.schema, input);
15740
+ if (invalid) return invalid;
15741
+ 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.` }));
15742
+ const handler = handlers[name];
15743
+ return handler(input, {
15744
+ seen: frontier.inContext(caller?.contextId),
15745
+ origin
15746
+ });
15747
+ };
15748
+ return {
15749
+ ...raft,
15750
+ invoke
15751
+ };
15752
+ }
15753
+ /** `identity.whoami` as an outcome (for `invoke`). */
15754
+ function whoamiOutcome(result) {
15755
+ if (!result.ok) return failureOutcome(opError(result.error.code, {
15756
+ message: result.error.message,
15757
+ ...result.status === void 0 ? {} : { status: result.status }
15758
+ }));
15759
+ const { agent, server, capabilities, guide } = result.data;
15760
+ const head = `You are @${agent.name}${agent.displayName ? ` (${agent.displayName})` : ""} on ${server.name}. Credential capabilities: ${capabilities.join(", ") || "none"}.`;
15761
+ return {
15762
+ ok: true,
15763
+ state: "identity",
15764
+ data: result.data,
15765
+ next: null,
15766
+ text: guide ? `${head}\n\n${guide}` : head
15767
+ };
14223
15768
  }
14224
15769
  //#endregion
14225
15770
  exports.RAFT_INBOX_NOTICE_SCHEMA = RAFT_INBOX_NOTICE_SCHEMA;
15771
+ exports.RAFT_JSON_SCHEMA_KEYWORDS = RAFT_JSON_SCHEMA_KEYWORDS;
14226
15772
  exports.RAFT_NOTICE_DELIVERY_ID_HEADER = RAFT_NOTICE_DELIVERY_ID_HEADER;
14227
15773
  exports.RAFT_NOTICE_SIGNATURE_HEADER = RAFT_NOTICE_SIGNATURE_HEADER;
15774
+ exports.RAFT_OPERATIONS = RAFT_OPERATIONS;
15775
+ exports.RAFT_OPERATIONS_SCHEMA = RAFT_OPERATIONS_SCHEMA;
15776
+ exports.RAFT_OPERATIONS_VERSION = RAFT_OPERATIONS_VERSION;
14228
15777
  exports.RAFT_STATE_CONTINUATIONS_PER_TARGET = RAFT_STATE_CONTINUATIONS_PER_TARGET;
14229
15778
  exports.RAFT_STATE_CONTINUATIONS_TOTAL = RAFT_STATE_CONTINUATIONS_TOTAL;
14230
15779
  exports.RAFT_STATE_SCHEMA = RAFT_STATE_SCHEMA;
14231
15780
  exports.RaftCredentialError = RaftCredentialError;
14232
15781
  exports.RaftSdkConfigurationError = RaftSdkConfigurationError;
14233
15782
  exports.SeenFrontier = SeenFrontier;
15783
+ exports.amendTaskRequestSchema = amendTaskRequestSchema;
15784
+ exports.assignTaskRequestSchema = assignTaskRequestSchema;
15785
+ exports.attachmentCommentsRequestSchema = attachmentCommentsRequestSchema;
14234
15786
  exports.bootstrapRaftCredential = bootstrapRaftCredential;
15787
+ exports.channelInfoRequestSchema = channelInfoRequestSchema;
15788
+ exports.channelMembersRequestSchema = channelMembersRequestSchema;
15789
+ exports.channelTargetRequestSchema = channelTargetRequestSchema;
15790
+ exports.checkInboxRequestSchema = checkInboxRequestSchema;
15791
+ exports.claimTasksRequestSchema = claimTasksRequestSchema;
15792
+ exports.commitInboxRequestSchema = commitInboxRequestSchema;
15793
+ exports.convertMessageToTaskRequestSchema = convertMessageToTaskRequestSchema;
14235
15794
  exports.createFileCredentialStore = createFileCredentialStore;
14236
15795
  exports.createRaft = createRaft;
14237
15796
  exports.createRaftClient = createRaftClient;
14238
15797
  exports.createRaftClientFromStore = createRaftClientFromStore;
14239
15798
  exports.createRaftRoutes = createRaftRoutes;
15799
+ exports.createTasksRequestSchema = createTasksRequestSchema;
14240
15800
  exports.describeRaftRoute = describeRaftRoute;
15801
+ exports.drainInboxRequestSchema = drainInboxRequestSchema;
15802
+ exports.executeMentionActionRequestSchema = executeMentionActionRequestSchema;
15803
+ exports.getManualTopicRequestSchema = getManualTopicRequestSchema;
14241
15804
  exports.hasAgentMessageIdentity = hasAgentMessageIdentity;
14242
15805
  exports.hashRaftSendContent = hashRaftSendContent;
14243
15806
  exports.inferAttachmentMimeType = inferAttachmentMimeType;
14244
15807
  exports.isInterrupted = isInterrupted;
14245
15808
  exports.joinRaftChannelByTarget = joinRaftChannelByTarget;
15809
+ exports.listInboxRequestSchema = listInboxRequestSchema;
14246
15810
  exports.listRaftRoutes = listRaftRoutes;
15811
+ exports.listTasksRequestSchema = listTasksRequestSchema;
15812
+ exports.listThreadsRequestSchema = listThreadsRequestSchema;
14247
15813
  exports.parseRaftRegularChannelTarget = parseRaftRegularChannelTarget;
14248
15814
  exports.parseRaftState = parseRaftState;
15815
+ exports.pendingMentionActionsRequestSchema = pendingMentionActionsRequestSchema;
15816
+ exports.prepareActionCardRequestSchema = prepareActionCardRequestSchema;
14249
15817
  exports.projectRaftMessage = projectRaftMessage;
14250
15818
  exports.projectRaftMessages = projectRaftMessages;
15819
+ exports.raftToolNameFor = raftToolNameFor;
15820
+ exports.reactRequestSchema = reactRequestSchema;
15821
+ exports.readHistoryRequestSchema = readHistoryRequestSchema;
14251
15822
  exports.readLatestReadThread = readLatestReadThread;
15823
+ exports.replyToRequestSchema = replyToRequestSchema;
15824
+ exports.resolveMessageRequestSchema = resolveMessageRequestSchema;
15825
+ exports.searchManualRequestSchema = searchManualRequestSchema;
15826
+ exports.searchMessagesRequestSchema = searchMessagesRequestSchema;
15827
+ exports.sendMessageRequestSchema = sendMessageRequestSchema;
15828
+ exports.senderMentionDeliveriesRequestSchema = senderMentionDeliveriesRequestSchema;
15829
+ exports.serverInfoRequestSchema = serverInfoRequestSchema;
15830
+ exports.showProfileRequestSchema = showProfileRequestSchema;
15831
+ exports.taskRefSchema = taskRefSchema;
15832
+ exports.unfollowThreadRequestSchema = unfollowThreadRequestSchema;
15833
+ exports.updateProfileRequestSchema = updateProfileRequestSchema;
15834
+ exports.updateTaskStatusRequestSchema = updateTaskStatusRequestSchema;
15835
+ exports.userInfoRequestSchema = userInfoRequestSchema;
14252
15836
  exports.verifyInboxNotice = verifyInboxNotice;
15837
+ exports.whoamiRequestSchema = whoamiRequestSchema;