@rivus/gateway 0.22.0 → 0.22.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -14,9 +14,9 @@ import { createNodePlatform } from "@rivus/agent-kit/node";
14
14
  import { access, appendFile, chmod, constants, lstat, mkdir, open, readFile, readdir, realpath, rename, rm, stat, unlink, writeFile } from "node:fs/promises";
15
15
  import { isNodeErrorWithCode } from "@rivus/platform/filesystem";
16
16
  import { createConnection, createServer } from "node:net";
17
- import { acquireProcessLock } from "@rivus/agent-kit-collab/process-lock";
18
17
  import { createHash, randomBytes, randomUUID } from "node:crypto";
19
18
  import { createPiAgentLoop, createPiAssembly, createPiBashTool, createPiManagedRunBinding, createPiModelRuntime, createPiSessionRegistry, createPiSessionResources, createPiSkillReadTools, createPiSkillRuntime, createPiToolNameResolver, createPiToolProxyDefinitions, ensurePiModel, mergePiProviderBaseUrlOverride, resolvePiSessionToolNames, validatePiSkillCommand } from "@rivus/runtime/pi";
19
+ import { acquireProcessLock } from "@rivus/agent-kit-collab/process-lock";
20
20
  import { mkdtempSync, rmSync, statSync } from "node:fs";
21
21
  import { spawn, spawnSync } from "node:child_process";
22
22
  import { Lexer } from "marked";
@@ -2307,227 +2307,179 @@ function reserveModelChangeBudget(budget, input) {
2307
2307
  };
2308
2308
  }
2309
2309
  //#endregion
2310
- //#region src/model-management/infra/adapters/cli/rivus-model-management-socket-server.ts
2311
- const MAX_FRAME_BYTES = 65536;
2312
- async function handleMutation(request, options) {
2313
- if (!request.context || !options.resolveTrustedRun) return createRivusModelManagementFailure("trusted_context_required", "a trusted Run context is required for model changes");
2314
- let trustedRun;
2315
- try {
2316
- trustedRun = await options.resolveTrustedRun.resolve(request.context);
2317
- } catch {
2318
- trustedRun = void 0;
2319
- }
2320
- if (trustedRun === void 0 || trustedRun === null) return createRivusModelManagementFailure("trusted_context_invalid", "the trusted Run context is invalid or expired");
2321
- try {
2322
- return projectRivusModelCliResponse(await options.handlers.handle(toRivusModelManagementSubmission(request), trustedRun), request.operation);
2323
- } catch {
2324
- return createRivusModelManagementFailure("handler_failed", "the model management request could not be completed");
2325
- }
2326
- }
2327
- function writeResponse(socket, response) {
2328
- try {
2329
- socket.end(`${JSON.stringify(response)}\n`);
2330
- } catch {
2331
- socket.destroy();
2310
+ //#region src/model-management/infra/adapters/pi/pi-model-run-context.ts
2311
+ const RIVUS_MODEL_CONTEXT_ENV = "RIVUS_MODEL_CONTEXT";
2312
+ const RIVUS_MODEL_SOCKET_ENV = "RIVUS_MODEL_SOCKET";
2313
+ const RIVUS_MODEL_CHANGE_TOOL_ID = "rivus.model.change";
2314
+ var PiModelRunContextError = class extends Error {
2315
+ code;
2316
+ name = "PiModelRunContextError";
2317
+ constructor(code, message) {
2318
+ super(message);
2319
+ this.code = code;
2332
2320
  }
2321
+ };
2322
+ function createToolGrantSet(options) {
2323
+ const toolIds = new Set(options.toolGrantSet.toolIds);
2324
+ if (options.modelManagementEnabled === true) toolIds.add(RIVUS_MODEL_CHANGE_TOOL_ID);
2325
+ return {
2326
+ revision: options.toolGrantSet.revision,
2327
+ toolIds: [...toolIds]
2328
+ };
2333
2329
  }
2334
- async function handleFrame(frame, socket, options) {
2335
- let response;
2336
- let request;
2337
- try {
2338
- request = parseRivusModelManagementWireRequest(JSON.parse(frame));
2339
- } catch (error) {
2340
- response = createRivusModelManagementFailure("invalid_request", error instanceof Error ? error.message : "invalid model request");
2341
- writeResponse(socket, response);
2342
- return;
2343
- }
2344
- try {
2345
- if (request.operation === "status") response = projectRivusModelCliResponse(await options.handlers.status({
2346
- ...request.requestId ? { requestId: request.requestId } : {},
2347
- ...request.verbose ? { verbose: true } : {}
2348
- }), request.operation);
2349
- else response = await handleMutation(request, options);
2350
- } catch {
2351
- response = createRivusModelManagementFailure("handler_failed", "the model management request could not be completed");
2352
- }
2353
- writeResponse(socket, response);
2330
+ function isContextReference(value) {
2331
+ return /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(value);
2354
2332
  }
2355
- async function handleConnection(socket, options) {
2356
- let buffer = "";
2357
- let handled = false;
2358
- socket.setEncoding("utf8");
2359
- socket.on("data", (chunk) => {
2360
- if (handled) return;
2361
- buffer += chunk;
2362
- if (Buffer.byteLength(buffer, "utf8") > MAX_FRAME_BYTES) {
2363
- handled = true;
2364
- writeResponse(socket, createRivusModelManagementFailure("request_too_large", "model management request is too large"));
2365
- return;
2333
+ /**
2334
+ * Inject the private transport values at process spawn time. The SDK passes
2335
+ * this hook the command and environment separately, so the opaque reference
2336
+ * never becomes model prompt content, an argv item, or a JSON request field.
2337
+ */
2338
+ function createPiModelManagementBashSpawnHook(options) {
2339
+ if (!isAbsolute(options.socketPath)) throw new Error(`${RIVUS_MODEL_SOCKET_ENV} must be an absolute path`);
2340
+ if (!isContextReference(options.context.reference)) throw new Error(`${RIVUS_MODEL_CONTEXT_ENV} must be an issued opaque reference`);
2341
+ const socketPath = options.socketPath;
2342
+ const contextReference = options.context.reference;
2343
+ return ({ command, cwd, env }) => ({
2344
+ command,
2345
+ cwd,
2346
+ env: {
2347
+ ...env,
2348
+ [RIVUS_MODEL_CONTEXT_ENV]: contextReference,
2349
+ [RIVUS_MODEL_SOCKET_ENV]: socketPath
2366
2350
  }
2367
- const newline = buffer.indexOf("\n");
2368
- if (newline < 0) return;
2369
- handled = true;
2370
- handleFrame(buffer.slice(0, newline).trim(), socket, options);
2371
2351
  });
2372
- socket.on("end", () => {
2373
- if (handled || buffer.trim() === "") return;
2374
- handled = true;
2375
- handleFrame(buffer.trim(), socket, options);
2376
- });
2377
- socket.on("error", () => {
2378
- handled = true;
2379
- });
2380
- }
2381
- async function prepareSocketParentDirectory(socketPath) {
2382
- const parent = dirname(socketPath);
2383
- await mkdir(parent, {
2384
- mode: 448,
2385
- recursive: true
2386
- });
2387
- await chmod(parent, 448);
2388
2352
  }
2389
- async function socketIsLive(socketPath) {
2390
- return new Promise((resolve, reject) => {
2391
- const socket = createConnection(socketPath);
2392
- let settled = false;
2393
- const finish = (result, error) => {
2394
- if (settled) return;
2395
- settled = true;
2396
- socket.destroy();
2397
- if (error) reject(error);
2398
- else resolve(result);
2399
- };
2400
- socket.setTimeout(250, () => finish(false, /* @__PURE__ */ new Error("model management socket liveness could not be verified")));
2401
- socket.once("connect", () => finish(true));
2402
- socket.once("error", (error) => {
2403
- if (isNodeErrorWithCode(error, "ECONNREFUSED") || isNodeErrorWithCode(error, "ENOENT")) finish(false);
2404
- else finish(false, error);
2405
- });
2406
- });
2353
+ function isAbortSignal(value) {
2354
+ return value instanceof AbortSignal;
2407
2355
  }
2408
- async function prepareSocketPath(socketPath) {
2409
- try {
2410
- const metadata = await stat(socketPath);
2411
- if (!metadata.isSocket()) throw new Error(`refusing to replace non-socket model path: ${socketPath}`);
2412
- if (await socketIsLive(socketPath)) throw new Error(`model management socket is already active: ${socketPath}`);
2413
- const current = await stat(socketPath);
2414
- if (current.dev !== metadata.dev || current.ino !== metadata.ino) throw new Error(`model management socket changed while starting: ${socketPath}`);
2415
- await unlink(socketPath);
2416
- } catch (error) {
2417
- if (!isNodeErrorWithCode(error, "ENOENT")) throw error;
2418
- }
2356
+ function isNonEmptyString(value) {
2357
+ return typeof value === "string" && value.trim().length > 0;
2419
2358
  }
2420
- async function unlinkSocketIfPresent(socketPath) {
2421
- try {
2422
- if ((await stat(socketPath)).isSocket()) await unlink(socketPath);
2423
- } catch (error) {
2424
- if (!isNodeErrorWithCode(error, "ENOENT")) throw error;
2425
- }
2359
+ function validateRegistryOptions(options) {
2360
+ if (!isNonEmptyString(options.agentId) || !isNonEmptyString(options.instanceId)) throw new Error("model Run context registry requires a Host agentId and instanceId");
2361
+ if (!isNonEmptyString(options.toolGrantSet.revision)) throw new Error("model Run context registry requires a tool grant revision");
2362
+ if (options.toolGrantSet.toolIds.some((toolId) => !isNonEmptyString(toolId))) throw new Error("model Run context registry requires non-empty tool grant ids");
2426
2363
  }
2427
- async function readSocketIdentity(socketPath) {
2428
- const metadata = await stat(socketPath);
2429
- return {
2430
- dev: metadata.dev,
2431
- ino: metadata.ino
2432
- };
2364
+ function isHumanTrustedFeishuInvocation(value) {
2365
+ if (value === void 0 || value.kind !== "feishu" || !Array.isArray(value.allowedActorOpenIds) || value.allowedActorOpenIds.length !== 1) return false;
2366
+ return value.allowedActorOpenIds.every(isNonEmptyString) && isNonEmptyString(value.endpointId) && isNonEmptyString(value.sourceMessageId) && isNonEmptyString(value.tenantKey);
2433
2367
  }
2434
- async function unlinkOwnedSocket(socketPath, identity) {
2435
- try {
2436
- const current = await readSocketIdentity(socketPath);
2437
- if (current.dev !== identity.dev || current.ino !== identity.ino) return;
2438
- await unlink(socketPath);
2439
- } catch (error) {
2440
- if (!isNodeErrorWithCode(error, "ENOENT")) throw error;
2441
- }
2368
+ function validateAgentLoopInput(input) {
2369
+ if (!isAbortSignal(input.abortSignal) || !isNonEmptyString(input.runId) || !isNonEmptyString(input.sessionKey) || typeof input.text !== "string") throw new PiModelRunContextError("invalid-input", "model management requires a concrete AgentLoopInput from the active Host Run");
2370
+ if (input.abortSignal.aborted) throw new PiModelRunContextError("run-aborted", "model management cannot issue a context for an aborted Run");
2371
+ const invocation = input.invocation;
2372
+ if (!isHumanTrustedFeishuInvocation(invocation)) throw new PiModelRunContextError("untrusted-invocation", "model management requires one trusted human Feishu invocation actor");
2373
+ return invocation;
2442
2374
  }
2443
- function listen(server, socketPath) {
2444
- return new Promise((resolve, reject) => {
2445
- const onError = (error) => {
2446
- server.off("listening", onListening);
2447
- reject(error);
2375
+ /**
2376
+ * Keep the model-management capability bound to a concrete host-owned Run.
2377
+ * The reference is the only value that crosses into a child process; all
2378
+ * invocation identity stays in this process behind the authority WeakMap.
2379
+ */
2380
+ function createPiModelRunContextRegistry(options) {
2381
+ validateRegistryOptions(options);
2382
+ const entries = /* @__PURE__ */ new Map();
2383
+ const toolGrantSet = createToolGrantSet(options);
2384
+ const revoke = (reference) => {
2385
+ const normalizedReference = reference;
2386
+ const entry = entries.get(normalizedReference);
2387
+ if (!entry) return false;
2388
+ entries.delete(normalizedReference);
2389
+ entry.abortSignal.removeEventListener("abort", entry.revokeOnAbort);
2390
+ return true;
2391
+ };
2392
+ const issue = (input) => {
2393
+ const invocation = validateAgentLoopInput(input);
2394
+ const reference = randomUUID();
2395
+ const authority = createInvocationAuthority({
2396
+ agentId: options.agentId,
2397
+ allowedActorOpenIds: [...invocation.allowedActorOpenIds],
2398
+ endpointId: invocation.endpointId,
2399
+ instanceId: options.instanceId,
2400
+ runId: input.runId,
2401
+ sessionKey: input.sessionKey,
2402
+ sourceMessageId: invocation.sourceMessageId,
2403
+ tenantKey: invocation.tenantKey,
2404
+ toolGrantSet
2405
+ });
2406
+ const context = Object.freeze({
2407
+ reference,
2408
+ runId: input.runId
2409
+ });
2410
+ const trustedRun = Object.freeze({
2411
+ authority,
2412
+ kind: "human"
2413
+ });
2414
+ const entry = {
2415
+ abortSignal: input.abortSignal,
2416
+ context,
2417
+ revokeOnAbort: () => {
2418
+ revoke(reference);
2419
+ },
2420
+ trustedRun
2448
2421
  };
2449
- function onListening() {
2450
- server.off("error", onError);
2451
- resolve();
2452
- }
2453
- server.once("error", onError);
2454
- server.once("listening", onListening);
2455
- server.listen(socketPath);
2456
- });
2457
- }
2458
- function closeServer(server) {
2459
- return new Promise((resolve, reject) => {
2460
- server.close((error) => error ? reject(error) : resolve());
2422
+ entries.set(reference, entry);
2423
+ input.abortSignal.addEventListener("abort", entry.revokeOnAbort, { once: true });
2424
+ return context;
2425
+ };
2426
+ return Object.freeze({
2427
+ issue,
2428
+ resolveRun: (reference) => entries.get(reference)?.trustedRun,
2429
+ revoke
2461
2430
  });
2462
2431
  }
2432
+ //#endregion
2433
+ //#region src/model-management/infra/adapters/pi/pi-managed-run-gateway-provider.ts
2463
2434
  /**
2464
- * Holds the socket's process lock for the daemon's whole lifetime: the lock is an
2465
- * exclusive SQLite kernel lock on `${socketPath}.process-lock`, so a crashed holder
2466
- * is released by the kernel and the next opener recovers without reclamation. The
2467
- * socket liveness check below remains a second line of defense for a live socket
2468
- * left by a holder that never took the lock.
2435
+ * Gateway-side provider for the Runtime managed-run binding.
2436
+ *
2437
+ * The provider owns policy: it reads the private active Run from the Gateway
2438
+ * closure, verifies the Runtime binding's run/session/signal match that source,
2439
+ * decides whether the source is a single-actor human Feishu Run, and either
2440
+ * issues a model-management context or falls back to the base environment
2441
+ * policy. The Runtime binding never sees the registry, socket path, or
2442
+ * invocation provenance logic.
2469
2443
  */
2470
- async function startServer(options, onStarted) {
2471
- await prepareSocketParentDirectory(options.socketPath);
2472
- const lockPath = `${options.socketPath}.process-lock`;
2473
- const acquired = await acquireProcessLock(options.platform, lockPath);
2474
- if (!acquired.ok) throw new Error("model management socket is owned by another running process");
2475
- const lock = acquired.value;
2476
- const next = createServer((socket) => handleConnection(socket, options));
2477
- let bound = false;
2478
- try {
2479
- await prepareSocketPath(options.socketPath);
2480
- await listen(next, options.socketPath);
2481
- bound = true;
2482
- await chmod(options.socketPath, 384);
2483
- onStarted(next, await readSocketIdentity(options.socketPath));
2484
- } catch (error) {
2485
- await closeServer(next).catch(() => void 0);
2486
- if (bound) await unlinkSocketIfPresent(options.socketPath);
2487
- await lock.release();
2488
- throw error;
2489
- }
2490
- return lock;
2491
- }
2492
- function assertAbsoluteSocketPath(socketPath) {
2493
- if (!isAbsolute(socketPath)) throw new Error("model socket path must be absolute");
2494
- }
2495
- function createRivusModelManagementSocketServer(options) {
2496
- assertAbsoluteSocketPath(options.socketPath);
2497
- let server;
2498
- let socketIdentity;
2499
- let processLock;
2500
- let listening = false;
2501
- let startPromise;
2502
- return {
2503
- close: async () => {
2504
- if (startPromise) await startPromise.catch(() => void 0);
2505
- const current = server;
2506
- const identity = socketIdentity;
2507
- server = void 0;
2508
- socketIdentity = void 0;
2509
- if (current && listening) await closeServer(current);
2510
- listening = false;
2511
- if (identity) await unlinkOwnedSocket(options.socketPath, identity);
2512
- await processLock?.release();
2513
- processLock = void 0;
2514
- },
2515
- listening: () => listening,
2516
- start: async () => {
2517
- if (listening) return;
2518
- if (startPromise) return startPromise;
2519
- startPromise = startServer(options, (next, identity) => {
2520
- server = next;
2521
- socketIdentity = identity;
2522
- listening = true;
2523
- }).then((lock) => {
2524
- processLock = lock;
2525
- });
2526
- try {
2527
- await startPromise;
2528
- } finally {
2529
- startPromise = void 0;
2444
+ function createPiManagedRunGatewayProvider(options) {
2445
+ const baseSpawnHook = (spawn) => {
2446
+ const { RIVUS_MODEL_CONTEXT: _context, RIVUS_MODEL_SOCKET: _socket, ...baseEnv } = spawn.env;
2447
+ return {
2448
+ ...spawn,
2449
+ env: {
2450
+ ...baseEnv,
2451
+ PATH: [
2452
+ options.binDirectory,
2453
+ dirname(options.nodeExecutable),
2454
+ baseEnv.PATH
2455
+ ].filter(Boolean).join(delimiter),
2456
+ RIVUS_MODEL_MANAGEMENT_ENABLED: "true",
2457
+ RIVUS_MODEL_SOCKET: options.socketPath
2530
2458
  }
2459
+ };
2460
+ };
2461
+ return (run) => {
2462
+ const source = options.source();
2463
+ if (run.runId !== source.runId || run.sessionKey !== source.sessionKey || run.abortSignal !== source.abortSignal) throw new Error("managed run binding input does not match the active Gateway Run");
2464
+ if (!(source.invocation?.kind === "feishu" && source.invocation.allowedActorOpenIds.length === 1)) return {
2465
+ spawnHook: baseSpawnHook,
2466
+ cleanup: () => {}
2467
+ };
2468
+ const context = options.contexts.issue(source);
2469
+ try {
2470
+ const managementHook = createPiModelManagementBashSpawnHook({
2471
+ context,
2472
+ socketPath: options.socketPath
2473
+ });
2474
+ return {
2475
+ spawnHook: (spawn) => managementHook(baseSpawnHook(spawn)),
2476
+ cleanup: () => {
2477
+ options.contexts.revoke(context.reference);
2478
+ }
2479
+ };
2480
+ } catch (error) {
2481
+ options.contexts.revoke(context.reference);
2482
+ throw error;
2531
2483
  }
2532
2484
  };
2533
2485
  }
@@ -2662,255 +2614,78 @@ async function installRivusRuntimeManagementSkill(options) {
2662
2614
  };
2663
2615
  }
2664
2616
  //#endregion
2665
- //#region src/model-management/infra/adapters/pi/pi-model-run-context.ts
2666
- const RIVUS_MODEL_CONTEXT_ENV = "RIVUS_MODEL_CONTEXT";
2667
- const RIVUS_MODEL_SOCKET_ENV = "RIVUS_MODEL_SOCKET";
2668
- const RIVUS_MODEL_CHANGE_TOOL_ID = "rivus.model.change";
2669
- var PiModelRunContextError = class extends Error {
2670
- code;
2671
- name = "PiModelRunContextError";
2672
- constructor(code, message) {
2673
- super(message);
2674
- this.code = code;
2675
- }
2676
- };
2677
- function createToolGrantSet(options) {
2678
- const toolIds = new Set(options.toolGrantSet.toolIds);
2679
- if (options.modelManagementEnabled === true) toolIds.add(RIVUS_MODEL_CHANGE_TOOL_ID);
2617
+ //#region src/model-management/infra/adapters/pi/pi-model-management-grant.ts
2618
+ /** Read the Host's current grant and provider binding without exposing credentials. */
2619
+ async function readPiModelManagementGrant(options, homeId, baseline) {
2620
+ const env = options.envFilePath ? await loadMergedLocalEnvFile(options.envFilePath, options.environmentOverrides) : options.environmentOverrides;
2621
+ const configuration = parseRivusModelManagementHomeConfig(env);
2622
+ const keyFile = env.PI_API_KEY_FILE?.trim();
2623
+ const inlineKey = env.PI_API_KEY?.trim();
2624
+ if (keyFile && inlineKey) throw new Error("PI_API_KEY and PI_API_KEY_FILE cannot both be set.");
2625
+ const credential = keyFile ? (await readFile(keyFile, "utf8")).trim() : inlineKey || (options.modelAuthPath ? await readPersistenceFile(options.modelAuthPath) ?? "runtime-auth" : "runtime-auth");
2626
+ if (!credential) throw new Error("The model provider credential is empty.");
2680
2627
  return {
2681
- revision: options.toolGrantSet.revision,
2682
- toolIds: [...toolIds]
2628
+ bindingRevision: createToolInputDigest({
2629
+ adapter: "pi-model-management-v1",
2630
+ baseUrl: env.PI_BASE_URL?.trim() || "provider-default",
2631
+ credential,
2632
+ provider: baseline.provider,
2633
+ configuredThinkingLevel: env.PI_THINKING_LEVEL?.trim() || null,
2634
+ thinkingLevel: options.thinkingLevel
2635
+ }, createSha256Digest),
2636
+ budget: {
2637
+ maxOutputTokens: 40960,
2638
+ maxPaidRequests: 5,
2639
+ recoveryReserveOutputTokens: 8192,
2640
+ recoveryReservePaidRequests: 1
2641
+ },
2642
+ enabled: configuration.enabled,
2643
+ endpointId: options.endpointId,
2644
+ homeId,
2645
+ operations: ["set", "rollback"],
2646
+ ownerId: configuration.ownerOpenId ?? "disabled",
2647
+ provider: baseline.provider,
2648
+ revision: 1,
2649
+ requireApproval: configuration.requireApproval,
2650
+ tenantKey: configuration.tenantKey ?? "disabled",
2651
+ timeoutMs: 3e5
2683
2652
  };
2684
2653
  }
2685
- function isContextReference(value) {
2686
- return /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(value);
2687
- }
2688
- /**
2689
- * Inject the private transport values at process spawn time. The SDK passes
2690
- * this hook the command and environment separately, so the opaque reference
2691
- * never becomes model prompt content, an argv item, or a JSON request field.
2692
- */
2693
- function createPiModelManagementBashSpawnHook(options) {
2694
- if (!isAbsolute(options.socketPath)) throw new Error(`${RIVUS_MODEL_SOCKET_ENV} must be an absolute path`);
2695
- if (!isContextReference(options.context.reference)) throw new Error(`${RIVUS_MODEL_CONTEXT_ENV} must be an issued opaque reference`);
2696
- const socketPath = options.socketPath;
2697
- const contextReference = options.context.reference;
2698
- return ({ command, cwd, env }) => ({
2699
- command,
2700
- cwd,
2701
- env: {
2702
- ...env,
2703
- [RIVUS_MODEL_CONTEXT_ENV]: contextReference,
2704
- [RIVUS_MODEL_SOCKET_ENV]: socketPath
2705
- }
2706
- });
2707
- }
2708
- function isAbortSignal(value) {
2709
- return value instanceof AbortSignal;
2710
- }
2711
- function isNonEmptyString(value) {
2712
- return typeof value === "string" && value.trim().length > 0;
2713
- }
2714
- function validateRegistryOptions(options) {
2715
- if (!isNonEmptyString(options.agentId) || !isNonEmptyString(options.instanceId)) throw new Error("model Run context registry requires a Host agentId and instanceId");
2716
- if (!isNonEmptyString(options.toolGrantSet.revision)) throw new Error("model Run context registry requires a tool grant revision");
2717
- if (options.toolGrantSet.toolIds.some((toolId) => !isNonEmptyString(toolId))) throw new Error("model Run context registry requires non-empty tool grant ids");
2718
- }
2719
- function isHumanTrustedFeishuInvocation(value) {
2720
- if (value === void 0 || value.kind !== "feishu" || !Array.isArray(value.allowedActorOpenIds) || value.allowedActorOpenIds.length !== 1) return false;
2721
- return value.allowedActorOpenIds.every(isNonEmptyString) && isNonEmptyString(value.endpointId) && isNonEmptyString(value.sourceMessageId) && isNonEmptyString(value.tenantKey);
2722
- }
2723
- function validateAgentLoopInput(input) {
2724
- if (!isAbortSignal(input.abortSignal) || !isNonEmptyString(input.runId) || !isNonEmptyString(input.sessionKey) || typeof input.text !== "string") throw new PiModelRunContextError("invalid-input", "model management requires a concrete AgentLoopInput from the active Host Run");
2725
- if (input.abortSignal.aborted) throw new PiModelRunContextError("run-aborted", "model management cannot issue a context for an aborted Run");
2726
- const invocation = input.invocation;
2727
- if (!isHumanTrustedFeishuInvocation(invocation)) throw new PiModelRunContextError("untrusted-invocation", "model management requires one trusted human Feishu invocation actor");
2728
- return invocation;
2729
- }
2730
- /**
2731
- * Keep the model-management capability bound to a concrete host-owned Run.
2732
- * The reference is the only value that crosses into a child process; all
2733
- * invocation identity stays in this process behind the authority WeakMap.
2734
- */
2735
- function createPiModelRunContextRegistry(options) {
2736
- validateRegistryOptions(options);
2737
- const entries = /* @__PURE__ */ new Map();
2738
- const toolGrantSet = createToolGrantSet(options);
2739
- const revoke = (reference) => {
2740
- const normalizedReference = reference;
2741
- const entry = entries.get(normalizedReference);
2742
- if (!entry) return false;
2743
- entries.delete(normalizedReference);
2744
- entry.abortSignal.removeEventListener("abort", entry.revokeOnAbort);
2745
- return true;
2746
- };
2747
- const issue = (input) => {
2748
- const invocation = validateAgentLoopInput(input);
2749
- const reference = randomUUID();
2750
- const authority = createInvocationAuthority({
2751
- agentId: options.agentId,
2752
- allowedActorOpenIds: [...invocation.allowedActorOpenIds],
2753
- endpointId: invocation.endpointId,
2754
- instanceId: options.instanceId,
2755
- runId: input.runId,
2756
- sessionKey: input.sessionKey,
2757
- sourceMessageId: invocation.sourceMessageId,
2758
- tenantKey: invocation.tenantKey,
2759
- toolGrantSet
2760
- });
2761
- const context = Object.freeze({
2762
- reference,
2763
- runId: input.runId
2764
- });
2765
- const trustedRun = Object.freeze({
2766
- authority,
2767
- kind: "human"
2768
- });
2769
- const entry = {
2770
- abortSignal: input.abortSignal,
2771
- context,
2772
- revokeOnAbort: () => {
2773
- revoke(reference);
2774
- },
2775
- trustedRun
2776
- };
2777
- entries.set(reference, entry);
2778
- input.abortSignal.addEventListener("abort", entry.revokeOnAbort, { once: true });
2779
- return context;
2780
- };
2781
- return Object.freeze({
2782
- issue,
2783
- resolveRun: (reference) => entries.get(reference)?.trustedRun,
2784
- revoke
2785
- });
2786
- }
2787
- //#endregion
2788
- //#region src/model-management/infra/adapters/pi/pi-managed-run-gateway-provider.ts
2789
- /**
2790
- * Gateway-side provider for the Runtime managed-run binding.
2791
- *
2792
- * The provider owns policy: it reads the private active Run from the Gateway
2793
- * closure, verifies the Runtime binding's run/session/signal match that source,
2794
- * decides whether the source is a single-actor human Feishu Run, and either
2795
- * issues a model-management context or falls back to the base environment
2796
- * policy. The Runtime binding never sees the registry, socket path, or
2797
- * invocation provenance logic.
2798
- */
2799
- function createPiManagedRunGatewayProvider(options) {
2800
- const baseSpawnHook = (spawn) => {
2801
- const { RIVUS_MODEL_CONTEXT: _context, RIVUS_MODEL_SOCKET: _socket, ...baseEnv } = spawn.env;
2802
- return {
2803
- ...spawn,
2804
- env: {
2805
- ...baseEnv,
2806
- PATH: [
2807
- options.binDirectory,
2808
- dirname(options.nodeExecutable),
2809
- baseEnv.PATH
2810
- ].filter(Boolean).join(delimiter),
2811
- RIVUS_MODEL_MANAGEMENT_ENABLED: "true",
2812
- RIVUS_MODEL_SOCKET: options.socketPath
2813
- }
2814
- };
2815
- };
2816
- return (run) => {
2817
- const source = options.source();
2818
- if (run.runId !== source.runId || run.sessionKey !== source.sessionKey || run.abortSignal !== source.abortSignal) throw new Error("managed run binding input does not match the active Gateway Run");
2819
- if (!(source.invocation?.kind === "feishu" && source.invocation.allowedActorOpenIds.length === 1)) return {
2820
- spawnHook: baseSpawnHook,
2821
- cleanup: () => {}
2822
- };
2823
- const context = options.contexts.issue(source);
2824
- try {
2825
- const managementHook = createPiModelManagementBashSpawnHook({
2826
- context,
2827
- socketPath: options.socketPath
2828
- });
2829
- return {
2830
- spawnHook: (spawn) => managementHook(baseSpawnHook(spawn)),
2831
- cleanup: () => {
2832
- options.contexts.revoke(context.reference);
2833
- }
2834
- };
2835
- } catch (error) {
2836
- options.contexts.revoke(context.reference);
2837
- throw error;
2838
- }
2839
- };
2840
- }
2841
- //#endregion
2842
- //#region src/model-management/infra/adapters/pi/pi-model-management-grant.ts
2843
- /** Read the Host's current grant and provider binding without exposing credentials. */
2844
- async function readPiModelManagementGrant(options, homeId, baseline) {
2845
- const env = options.envFilePath ? await loadMergedLocalEnvFile(options.envFilePath, options.environmentOverrides) : options.environmentOverrides;
2846
- const configuration = parseRivusModelManagementHomeConfig(env);
2847
- const keyFile = env.PI_API_KEY_FILE?.trim();
2848
- const inlineKey = env.PI_API_KEY?.trim();
2849
- if (keyFile && inlineKey) throw new Error("PI_API_KEY and PI_API_KEY_FILE cannot both be set.");
2850
- const credential = keyFile ? (await readFile(keyFile, "utf8")).trim() : inlineKey || (options.modelAuthPath ? await readPersistenceFile(options.modelAuthPath) ?? "runtime-auth" : "runtime-auth");
2851
- if (!credential) throw new Error("The model provider credential is empty.");
2852
- return {
2853
- bindingRevision: createToolInputDigest({
2854
- adapter: "pi-model-management-v1",
2855
- baseUrl: env.PI_BASE_URL?.trim() || "provider-default",
2856
- credential,
2857
- provider: baseline.provider,
2858
- configuredThinkingLevel: env.PI_THINKING_LEVEL?.trim() || null,
2859
- thinkingLevel: options.thinkingLevel
2860
- }, createSha256Digest),
2861
- budget: {
2862
- maxOutputTokens: 40960,
2863
- maxPaidRequests: 5,
2864
- recoveryReserveOutputTokens: 8192,
2865
- recoveryReservePaidRequests: 1
2866
- },
2867
- enabled: configuration.enabled,
2868
- endpointId: options.endpointId,
2869
- homeId,
2870
- operations: ["set", "rollback"],
2871
- ownerId: configuration.ownerOpenId ?? "disabled",
2872
- provider: baseline.provider,
2873
- revision: 1,
2874
- requireApproval: configuration.requireApproval,
2875
- tenantKey: configuration.tenantKey ?? "disabled",
2876
- timeoutMs: 3e5
2877
- };
2878
- }
2879
- //#endregion
2880
- //#region src/model-management/application/ports.ts
2881
- var ModelChangeAuthorizationPort = class extends Context.Service()("@rivus/gateway/model-management/ModelChangeAuthorizationPort") {};
2882
- var ModelChangeBoundaryPort = class extends Context.Service()("@rivus/gateway/model-management/ModelChangeBoundaryPort") {};
2883
- /** Optional: without it, result receipts are not delivered to a human source. */
2884
- var ModelChangeNotificationPort = class extends Context.Service()("@rivus/gateway/model-management/ModelChangeNotificationPort") {};
2885
- var ModelChangeIdentityPort = class extends Context.Service()("@rivus/gateway/model-management/ModelChangeIdentityPort") {};
2886
- var ModelChangeRequestConflict = class extends Error {
2887
- name = "ModelChangeRequestConflict";
2888
- };
2889
- var ModelChangeRevisionConflict = class extends Error {
2890
- name = "ModelChangeRevisionConflict";
2891
- };
2892
- var ModelChangeBusy = class extends Error {
2893
- name = "ModelChangeBusy";
2894
- };
2895
- var ModelChangeNotFound = class extends Error {
2896
- name = "ModelChangeNotFound";
2897
- };
2898
- var ModelChangeAuthorizationRejected = class extends Error {
2899
- name = "ModelChangeAuthorizationRejected";
2900
- };
2901
- var ModelStateRepository = class extends Context.Service()("@rivus/gateway/model-management/ModelStateRepository") {};
2902
- /** Optional: without it, a grant that requires approval rejects the request. */
2903
- var ModelChangeApprovalPort = class extends Context.Service()("@rivus/gateway/model-management/ModelChangeApprovalPort") {};
2904
- var ModelManagementGrantPort = class extends Context.Service()("@rivus/gateway/model-management/ModelManagementGrantPort") {};
2905
- var ModelManagementTrustedRunPort = class extends Context.Service()("@rivus/gateway/model-management/ModelManagementTrustedRunPort") {};
2906
- //#endregion
2907
- //#region src/lib/decode-section.ts
2908
- function decodeSection(decode, value, message) {
2909
- try {
2910
- return decode(value);
2911
- } catch {
2912
- throw new Error(message);
2913
- }
2654
+ //#endregion
2655
+ //#region src/model-management/application/ports.ts
2656
+ var ModelChangeAuthorizationPort = class extends Context.Service()("@rivus/gateway/model-management/ModelChangeAuthorizationPort") {};
2657
+ var ModelChangeBoundaryPort = class extends Context.Service()("@rivus/gateway/model-management/ModelChangeBoundaryPort") {};
2658
+ /** Optional: without it, result receipts are not delivered to a human source. */
2659
+ var ModelChangeNotificationPort = class extends Context.Service()("@rivus/gateway/model-management/ModelChangeNotificationPort") {};
2660
+ var ModelChangeIdentityPort = class extends Context.Service()("@rivus/gateway/model-management/ModelChangeIdentityPort") {};
2661
+ var ModelChangeRequestConflict = class extends Error {
2662
+ name = "ModelChangeRequestConflict";
2663
+ };
2664
+ var ModelChangeRevisionConflict = class extends Error {
2665
+ name = "ModelChangeRevisionConflict";
2666
+ };
2667
+ var ModelChangeBusy = class extends Error {
2668
+ name = "ModelChangeBusy";
2669
+ };
2670
+ var ModelChangeNotFound = class extends Error {
2671
+ name = "ModelChangeNotFound";
2672
+ };
2673
+ var ModelChangeAuthorizationRejected = class extends Error {
2674
+ name = "ModelChangeAuthorizationRejected";
2675
+ };
2676
+ var ModelStateRepository = class extends Context.Service()("@rivus/gateway/model-management/ModelStateRepository") {};
2677
+ /** Optional: without it, a grant that requires approval rejects the request. */
2678
+ var ModelChangeApprovalPort = class extends Context.Service()("@rivus/gateway/model-management/ModelChangeApprovalPort") {};
2679
+ var ModelManagementGrantPort = class extends Context.Service()("@rivus/gateway/model-management/ModelManagementGrantPort") {};
2680
+ var ModelManagementTrustedRunPort = class extends Context.Service()("@rivus/gateway/model-management/ModelManagementTrustedRunPort") {};
2681
+ //#endregion
2682
+ //#region src/lib/decode-section.ts
2683
+ function decodeSection(decode, value, message) {
2684
+ try {
2685
+ return decode(value);
2686
+ } catch {
2687
+ throw new Error(message);
2688
+ }
2914
2689
  }
2915
2690
  //#endregion
2916
2691
  //#region src/model-management/infra/models/model-state-codec.ts
@@ -3686,58 +3461,283 @@ function makeModelChangeAuthorization(settings) {
3686
3461
  });
3687
3462
  }
3688
3463
  //#endregion
3689
- //#region src/model-management/application/services/model-change-recovery.ts
3690
- const recoveryPhases = /* @__PURE__ */ new Set([
3691
- "activating",
3692
- "committing",
3693
- "validation-unknown",
3694
- "recovery-required"
3695
- ]);
3696
- function pendingRequiresModelChangeRecovery(pending) {
3697
- return recoveryPhases.has(pending.phase) || pending.unknownPaidCallId !== void 0;
3464
+ //#region src/model-management/infra/adapters/cli/rivus-model-management-socket-server.ts
3465
+ const MAX_FRAME_BYTES = 65536;
3466
+ async function handleMutation(request, options) {
3467
+ if (!request.context || !options.resolveTrustedRun) return createRivusModelManagementFailure("trusted_context_required", "a trusted Run context is required for model changes");
3468
+ let trustedRun;
3469
+ try {
3470
+ trustedRun = await options.resolveTrustedRun.resolve(request.context);
3471
+ } catch {
3472
+ trustedRun = void 0;
3473
+ }
3474
+ if (trustedRun === void 0 || trustedRun === null) return createRivusModelManagementFailure("trusted_context_invalid", "the trusted Run context is invalid or expired");
3475
+ try {
3476
+ return projectRivusModelCliResponse(await options.handlers.handle(toRivusModelManagementSubmission(request), trustedRun), request.operation);
3477
+ } catch {
3478
+ return createRivusModelManagementFailure("handler_failed", "the model management request could not be completed");
3479
+ }
3698
3480
  }
3699
- //#endregion
3700
- //#region src/model-management/application/services/model-change-projection.ts
3701
- function stateWithPending(state, pending, receipt) {
3702
- return {
3703
- ...state,
3704
- pending,
3705
- requests: {
3706
- ...state.requests,
3707
- [receipt.requestId]: receipt
3708
- },
3709
- updatedAt: receipt.updatedAt
3710
- };
3481
+ function writeResponse(socket, response) {
3482
+ try {
3483
+ socket.end(`${JSON.stringify(response)}\n`);
3484
+ } catch {
3485
+ socket.destroy();
3486
+ }
3711
3487
  }
3712
- function stateWithReceipt(state, receipt, recovery) {
3713
- const { pending: _pending, recoveryRequired: _recoveryRequired, ...stateWithoutTransient } = state;
3714
- return {
3715
- ...stateWithoutTransient,
3716
- ...recovery ? { recoveryRequired: recovery } : {},
3717
- requests: {
3718
- ...state.requests,
3719
- [receipt.requestId]: receipt
3720
- },
3721
- updatedAt: receipt.updatedAt
3722
- };
3488
+ async function handleFrame(frame, socket, options) {
3489
+ let response;
3490
+ let request;
3491
+ try {
3492
+ request = parseRivusModelManagementWireRequest(JSON.parse(frame));
3493
+ } catch (error) {
3494
+ response = createRivusModelManagementFailure("invalid_request", error instanceof Error ? error.message : "invalid model request");
3495
+ writeResponse(socket, response);
3496
+ return;
3497
+ }
3498
+ try {
3499
+ if (request.operation === "status") response = projectRivusModelCliResponse(await options.handlers.status({
3500
+ ...request.requestId ? { requestId: request.requestId } : {},
3501
+ ...request.verbose ? { verbose: true } : {}
3502
+ }), request.operation);
3503
+ else response = await handleMutation(request, options);
3504
+ } catch {
3505
+ response = createRivusModelManagementFailure("handler_failed", "the model management request could not be completed");
3506
+ }
3507
+ writeResponse(socket, response);
3723
3508
  }
3724
- function pendingReceipt(state, pending, updatedAt) {
3725
- return {
3726
- acceptedAt: pending.acceptedAt,
3727
- ...pending.authorizationId ? { authorizationId: pending.authorizationId } : {},
3728
- bindingRevision: pending.bindingRevision,
3729
- budget: pending.budget,
3730
- budgetIdentity: pending.budgetIdentity,
3731
- current: state.current,
3732
- expectedRevision: pending.expectedRevision,
3733
- inputDigest: pending.inputDigest,
3734
- operation: pending.operation,
3735
- phase: pending.phase,
3736
- ...state.previous ? { previous: state.previous } : {},
3737
- ...pending.principal ? { principal: pending.principal } : {},
3738
- requestId: pending.request.requestId,
3739
- revision: state.revision,
3740
- status: "pending",
3509
+ async function handleConnection(socket, options) {
3510
+ let buffer = "";
3511
+ let handled = false;
3512
+ socket.setEncoding("utf8");
3513
+ socket.on("data", (chunk) => {
3514
+ if (handled) return;
3515
+ buffer += chunk;
3516
+ if (Buffer.byteLength(buffer, "utf8") > MAX_FRAME_BYTES) {
3517
+ handled = true;
3518
+ writeResponse(socket, createRivusModelManagementFailure("request_too_large", "model management request is too large"));
3519
+ return;
3520
+ }
3521
+ const newline = buffer.indexOf("\n");
3522
+ if (newline < 0) return;
3523
+ handled = true;
3524
+ handleFrame(buffer.slice(0, newline).trim(), socket, options);
3525
+ });
3526
+ socket.on("end", () => {
3527
+ if (handled || buffer.trim() === "") return;
3528
+ handled = true;
3529
+ handleFrame(buffer.trim(), socket, options);
3530
+ });
3531
+ socket.on("error", () => {
3532
+ handled = true;
3533
+ });
3534
+ }
3535
+ async function prepareSocketParentDirectory(socketPath) {
3536
+ const parent = dirname(socketPath);
3537
+ await mkdir(parent, {
3538
+ mode: 448,
3539
+ recursive: true
3540
+ });
3541
+ await chmod(parent, 448);
3542
+ }
3543
+ async function socketIsLive(socketPath) {
3544
+ return new Promise((resolve, reject) => {
3545
+ const socket = createConnection(socketPath);
3546
+ let settled = false;
3547
+ const finish = (result, error) => {
3548
+ if (settled) return;
3549
+ settled = true;
3550
+ socket.destroy();
3551
+ if (error) reject(error);
3552
+ else resolve(result);
3553
+ };
3554
+ socket.setTimeout(250, () => finish(false, /* @__PURE__ */ new Error("model management socket liveness could not be verified")));
3555
+ socket.once("connect", () => finish(true));
3556
+ socket.once("error", (error) => {
3557
+ if (isNodeErrorWithCode(error, "ECONNREFUSED") || isNodeErrorWithCode(error, "ENOENT")) finish(false);
3558
+ else finish(false, error);
3559
+ });
3560
+ });
3561
+ }
3562
+ async function prepareSocketPath(socketPath) {
3563
+ try {
3564
+ const metadata = await stat(socketPath);
3565
+ if (!metadata.isSocket()) throw new Error(`refusing to replace non-socket model path: ${socketPath}`);
3566
+ if (await socketIsLive(socketPath)) throw new Error(`model management socket is already active: ${socketPath}`);
3567
+ const current = await stat(socketPath);
3568
+ if (current.dev !== metadata.dev || current.ino !== metadata.ino) throw new Error(`model management socket changed while starting: ${socketPath}`);
3569
+ await unlink(socketPath);
3570
+ } catch (error) {
3571
+ if (!isNodeErrorWithCode(error, "ENOENT")) throw error;
3572
+ }
3573
+ }
3574
+ async function unlinkSocketIfPresent(socketPath) {
3575
+ try {
3576
+ if ((await stat(socketPath)).isSocket()) await unlink(socketPath);
3577
+ } catch (error) {
3578
+ if (!isNodeErrorWithCode(error, "ENOENT")) throw error;
3579
+ }
3580
+ }
3581
+ async function readSocketIdentity(socketPath) {
3582
+ const metadata = await stat(socketPath);
3583
+ return {
3584
+ dev: metadata.dev,
3585
+ ino: metadata.ino
3586
+ };
3587
+ }
3588
+ async function unlinkOwnedSocket(socketPath, identity) {
3589
+ try {
3590
+ const current = await readSocketIdentity(socketPath);
3591
+ if (current.dev !== identity.dev || current.ino !== identity.ino) return;
3592
+ await unlink(socketPath);
3593
+ } catch (error) {
3594
+ if (!isNodeErrorWithCode(error, "ENOENT")) throw error;
3595
+ }
3596
+ }
3597
+ function listen(server, socketPath) {
3598
+ return new Promise((resolve, reject) => {
3599
+ const onError = (error) => {
3600
+ server.off("listening", onListening);
3601
+ reject(error);
3602
+ };
3603
+ function onListening() {
3604
+ server.off("error", onError);
3605
+ resolve();
3606
+ }
3607
+ server.once("error", onError);
3608
+ server.once("listening", onListening);
3609
+ server.listen(socketPath);
3610
+ });
3611
+ }
3612
+ function closeServer(server) {
3613
+ return new Promise((resolve, reject) => {
3614
+ server.close((error) => error ? reject(error) : resolve());
3615
+ });
3616
+ }
3617
+ /**
3618
+ * Holds the socket's process lock for the daemon's whole lifetime: the lock is an
3619
+ * exclusive SQLite kernel lock on `${socketPath}.process-lock`, so a crashed holder
3620
+ * is released by the kernel and the next opener recovers without reclamation. The
3621
+ * socket liveness check below remains a second line of defense for a live socket
3622
+ * left by a holder that never took the lock.
3623
+ */
3624
+ async function startServer(options, onStarted) {
3625
+ await prepareSocketParentDirectory(options.socketPath);
3626
+ const lockPath = `${options.socketPath}.process-lock`;
3627
+ const acquired = await acquireProcessLock(options.platform, lockPath);
3628
+ if (!acquired.ok) throw new Error("model management socket is owned by another running process");
3629
+ const lock = acquired.value;
3630
+ const next = createServer((socket) => handleConnection(socket, options));
3631
+ let bound = false;
3632
+ try {
3633
+ await prepareSocketPath(options.socketPath);
3634
+ await listen(next, options.socketPath);
3635
+ bound = true;
3636
+ await chmod(options.socketPath, 384);
3637
+ onStarted(next, await readSocketIdentity(options.socketPath));
3638
+ } catch (error) {
3639
+ await closeServer(next).catch(() => void 0);
3640
+ if (bound) await unlinkSocketIfPresent(options.socketPath);
3641
+ await lock.release();
3642
+ throw error;
3643
+ }
3644
+ return lock;
3645
+ }
3646
+ function assertAbsoluteSocketPath(socketPath) {
3647
+ if (!isAbsolute(socketPath)) throw new Error("model socket path must be absolute");
3648
+ }
3649
+ function createRivusModelManagementSocketServer(options) {
3650
+ assertAbsoluteSocketPath(options.socketPath);
3651
+ let server;
3652
+ let socketIdentity;
3653
+ let processLock;
3654
+ let listening = false;
3655
+ let startPromise;
3656
+ return {
3657
+ close: async () => {
3658
+ if (startPromise) await startPromise.catch(() => void 0);
3659
+ const current = server;
3660
+ const identity = socketIdentity;
3661
+ server = void 0;
3662
+ socketIdentity = void 0;
3663
+ if (current && listening) await closeServer(current);
3664
+ listening = false;
3665
+ if (identity) await unlinkOwnedSocket(options.socketPath, identity);
3666
+ await processLock?.release();
3667
+ processLock = void 0;
3668
+ },
3669
+ listening: () => listening,
3670
+ start: async () => {
3671
+ if (listening) return;
3672
+ if (startPromise) return startPromise;
3673
+ startPromise = startServer(options, (next, identity) => {
3674
+ server = next;
3675
+ socketIdentity = identity;
3676
+ listening = true;
3677
+ }).then((lock) => {
3678
+ processLock = lock;
3679
+ });
3680
+ try {
3681
+ await startPromise;
3682
+ } finally {
3683
+ startPromise = void 0;
3684
+ }
3685
+ }
3686
+ };
3687
+ }
3688
+ //#endregion
3689
+ //#region src/model-management/application/services/model-change-recovery.ts
3690
+ const recoveryPhases = /* @__PURE__ */ new Set([
3691
+ "activating",
3692
+ "committing",
3693
+ "validation-unknown",
3694
+ "recovery-required"
3695
+ ]);
3696
+ function pendingRequiresModelChangeRecovery(pending) {
3697
+ return recoveryPhases.has(pending.phase) || pending.unknownPaidCallId !== void 0;
3698
+ }
3699
+ //#endregion
3700
+ //#region src/model-management/application/services/model-change-projection.ts
3701
+ function stateWithPending(state, pending, receipt) {
3702
+ return {
3703
+ ...state,
3704
+ pending,
3705
+ requests: {
3706
+ ...state.requests,
3707
+ [receipt.requestId]: receipt
3708
+ },
3709
+ updatedAt: receipt.updatedAt
3710
+ };
3711
+ }
3712
+ function stateWithReceipt(state, receipt, recovery) {
3713
+ const { pending: _pending, recoveryRequired: _recoveryRequired, ...stateWithoutTransient } = state;
3714
+ return {
3715
+ ...stateWithoutTransient,
3716
+ ...recovery ? { recoveryRequired: recovery } : {},
3717
+ requests: {
3718
+ ...state.requests,
3719
+ [receipt.requestId]: receipt
3720
+ },
3721
+ updatedAt: receipt.updatedAt
3722
+ };
3723
+ }
3724
+ function pendingReceipt(state, pending, updatedAt) {
3725
+ return {
3726
+ acceptedAt: pending.acceptedAt,
3727
+ ...pending.authorizationId ? { authorizationId: pending.authorizationId } : {},
3728
+ bindingRevision: pending.bindingRevision,
3729
+ budget: pending.budget,
3730
+ budgetIdentity: pending.budgetIdentity,
3731
+ current: state.current,
3732
+ expectedRevision: pending.expectedRevision,
3733
+ inputDigest: pending.inputDigest,
3734
+ operation: pending.operation,
3735
+ phase: pending.phase,
3736
+ ...state.previous ? { previous: state.previous } : {},
3737
+ ...pending.principal ? { principal: pending.principal } : {},
3738
+ requestId: pending.request.requestId,
3739
+ revision: state.revision,
3740
+ status: "pending",
3741
3741
  ...pending.target ? { target: pending.target } : {},
3742
3742
  updatedAt
3743
3743
  };
@@ -5099,1065 +5099,1065 @@ function createFeishuEndpointMessagePolicy(options) {
5099
5099
  };
5100
5100
  }
5101
5101
  //#endregion
5102
- //#region src/feishu/infra/adapters/attachments/feishu-workspace-path.ts
5103
- function isStrictRelativePath(path) {
5104
- return path !== "" && path !== ".." && !path.startsWith(".." + sep) && !isAbsolute(path);
5105
- }
5102
+ //#region src/feishu/infra/repository/feishu-preparation-ledger.ts
5103
+ var FeishuPreparationLedgerError = class extends Error {
5104
+ code;
5105
+ dimension;
5106
+ _tag = "FeishuPreparationLedgerError";
5107
+ constructor(code, message, dimension) {
5108
+ super(message);
5109
+ this.code = code;
5110
+ this.dimension = dimension;
5111
+ this.name = "FeishuPreparationLedgerError";
5112
+ }
5113
+ };
5114
+ const LEDGER_VERSION = 1;
5106
5115
  /**
5107
- * Resolve a strict descendant of a trusted, existing directory and reject
5108
- * symlinks in its descendants. The root is realpathed so OS path aliases work.
5109
- *
5110
- * Recheck immediately before each filesystem side effect. Node has no
5111
- * portable openat-style API here, so this does not prevent an attacker from
5112
- * racing a path change between validation and the operation.
5113
- */
5114
- async function resolveSafeWorkspacePath(workspaceDirectory, targetPath) {
5115
- const requestedRoot = resolve(workspaceDirectory);
5116
- const canonicalRoot = await realpath(requestedRoot);
5117
- const absoluteTarget = resolve(targetPath);
5118
- const relativeTarget = [requestedRoot, canonicalRoot].map((root) => relative(root, absoluteTarget)).find(isStrictRelativePath);
5119
- if (relativeTarget === void 0) throw new Error("workspace path must be a strict descendant of its trusted root");
5120
- if (!(await lstat(canonicalRoot)).isDirectory()) throw new Error("workspace root is not a directory");
5121
- const segments = relativeTarget.split(sep);
5122
- let currentPath = canonicalRoot;
5123
- for (let index = 0; index < segments.length; index += 1) {
5124
- const segment = segments[index];
5125
- if (segment === void 0 || segment === "") throw new Error("workspace path contains an invalid segment");
5126
- currentPath = join(currentPath, segment);
5127
- let info;
5128
- try {
5129
- info = await lstat(currentPath);
5130
- } catch (error) {
5131
- if (isNodeErrorWithCode(error, "ENOENT")) break;
5132
- throw error;
5133
- }
5134
- if (info.isSymbolicLink()) throw new Error("workspace path contains a symbolic link");
5135
- if (index < segments.length - 1 && !info.isDirectory()) throw new Error("workspace path has a non-directory ancestor");
5136
- }
5137
- return join(canonicalRoot, ...segments);
5138
- }
5139
- //#endregion
5140
- //#region src/feishu/infra/adapters/client/feishu-resource-reader.ts
5141
- /**
5142
- * A resource failure carries only protocol metadata. In particular, it never
5143
- * stores the access token, response body, or a URL containing message data.
5116
+ * The persisted ledger decodes once into typed fields; a field of the wrong
5117
+ * type is absent or INVALID, and validateState reports it in the original
5118
+ * order with its original text.
5144
5119
  */
5145
- var FeishuResourceReadError = class extends Error {
5146
- _tag = "FeishuResourceReadError";
5147
- name = "FeishuResourceReadError";
5148
- classification;
5149
- consumedBytes;
5150
- status;
5151
- code;
5152
- retryAfterMs;
5153
- constructor(options) {
5154
- super(options.message);
5155
- this.classification = options.classification;
5156
- this.consumedBytes = options.consumedBytes;
5157
- this.status = options.status;
5158
- this.code = options.code;
5159
- this.retryAfterMs = options.retryAfterMs;
5160
- Object.setPrototypeOf(this, new.target.prototype);
5161
- }
5162
- };
5163
- const ERROR_BODY_MAX_BYTES = 65536;
5164
- const nonBlankIdentifier = tolerant(Schema.String.check(Schema.makeFilter((value) => value.trim() !== "")));
5165
- const decodeIdentifiers = Schema.decodeUnknownSync(Schema.Struct({
5166
- messageId: nonBlankIdentifier,
5167
- resourceKey: nonBlankIdentifier
5120
+ const nonNegativeIntegerField = tolerant(Schema.Int.check(Schema.isGreaterThanOrEqualTo(0)));
5121
+ const positiveIntegerField = tolerant(Schema.Int.check(Schema.isGreaterThanOrEqualTo(1)));
5122
+ const scopeText = Schema.String.check(Schema.makeFilter((value) => value.trim() !== "" && value.length <= 512));
5123
+ /** A valid ledger scope; other records that carry a scope, such as input markers, check it with this. */
5124
+ const FeishuPreparationLedgerScopeSchema = Schema.Struct({
5125
+ deliveryId: scopeText,
5126
+ endpointId: scopeText,
5127
+ sessionGeneration: scopeText,
5128
+ tenantKey: scopeText
5129
+ });
5130
+ const scopeTextField = tolerant(scopeText);
5131
+ /** An array is an object without scope fields, so it reports the first missing field. */
5132
+ const ScopeContainer = Schema.Union([Schema.Struct({
5133
+ deliveryId: scopeTextField,
5134
+ endpointId: scopeTextField,
5135
+ sessionGeneration: scopeTextField,
5136
+ tenantKey: scopeTextField
5137
+ }), Schema.mutable(Schema.Array(Schema.Unknown))]);
5138
+ const InFlightState = Schema.Struct({
5139
+ attemptNumber: nonNegativeIntegerField,
5140
+ byteReservation: positiveIntegerField,
5141
+ id: tolerant(Schema.NonEmptyString),
5142
+ kind: tolerant(Schema.Literals(["download", "recovery"])),
5143
+ startedAtMs: nonNegativeIntegerField,
5144
+ timeReservationMs: positiveIntegerField
5145
+ });
5146
+ const ResourceState = Schema.Struct({
5147
+ activeTimeMs: nonNegativeIntegerField,
5148
+ attempts: nonNegativeIntegerField,
5149
+ bytes: nonNegativeIntegerField,
5150
+ inFlight: Schema.optionalKey(orInvalid(InFlightState)),
5151
+ recoveryAttempts: nonNegativeIntegerField,
5152
+ reservedActiveTimeMs: nonNegativeIntegerField,
5153
+ reservedBytes: nonNegativeIntegerField,
5154
+ resourceKey: tolerant(Schema.NonEmptyString),
5155
+ retryableFailure: Schema.optionalKey(orInvalid(Schema.Boolean)),
5156
+ status: tolerant(Schema.Literals([
5157
+ "pending",
5158
+ "in_flight",
5159
+ "stored",
5160
+ "failed",
5161
+ "cancelled"
5162
+ ]))
5163
+ });
5164
+ const decodeLedgerState = Schema.decodeUnknownOption(Schema.Struct({
5165
+ activeTimeMs: nonNegativeIntegerField,
5166
+ bytes: nonNegativeIntegerField,
5167
+ recoveryAttempts: nonNegativeIntegerField,
5168
+ reservedActiveTimeMs: nonNegativeIntegerField,
5169
+ reservedBytes: nonNegativeIntegerField,
5170
+ resources: tolerant(Schema.Array(orInvalid(ResourceState))),
5171
+ retryAttempts: nonNegativeIntegerField,
5172
+ scope: tolerant(ScopeContainer),
5173
+ terminalCancelled: tolerant(Schema.Boolean),
5174
+ version: tolerant(Schema.Literal(LEDGER_VERSION))
5168
5175
  }));
5169
- function buildResourceUrl(baseUrl, input) {
5170
- return baseUrl + "/open-apis/im/v1/messages/" + encodeURIComponent(input.messageId) + "/resources/" + encodeURIComponent(input.resourceKey) + "?type=" + input.resourceType;
5171
- }
5172
- function createProtocolError(classification, status, code, retryAfterMs) {
5173
- const options = {
5174
- classification,
5175
- status,
5176
- message: "Feishu resource request failed"
5177
- };
5178
- if (code !== void 0) Object.assign(options, { code });
5179
- if (retryAfterMs !== void 0) Object.assign(options, { retryAfterMs });
5180
- return new FeishuResourceReadError(options);
5181
- }
5182
- function containsExpiredText(message) {
5183
- return message !== void 0 && /expired|expire|过期|失效|已删除|deleted/i.test(message);
5176
+ const decodeScopeContainer = Schema.decodeUnknownOption(ScopeContainer);
5177
+ /** Completions come from preparation code, but a marker of the wrong type must not reach the ledger. */
5178
+ const hasValidCompletionMarker = Schema.is(Schema.Struct({ retryableFailure: Schema.optional(Schema.Boolean) }));
5179
+ const decodeRootDirectory = Schema.decodeUnknownOption(Schema.String.check(Schema.makeFilter((value) => value.trim() !== "")));
5180
+ const decodeLockOwner = Schema.decodeUnknownOption(Schema.Struct({
5181
+ createdAtMs: tolerant(Schema.Number),
5182
+ pid: Schema.Int,
5183
+ token: Schema.String
5184
+ }));
5185
+ const DEFAULT_LOCK_RETRY_MS = 5;
5186
+ const DEFAULT_LOCK_TIMEOUT_MS = 1e4;
5187
+ const DEFAULT_STALE_LOCK_MS = 3e4;
5188
+ function validateRootDirectory(value) {
5189
+ const rootDirectory = Option.getOrUndefined(decodeRootDirectory(value));
5190
+ if (rootDirectory === void 0) throw new FeishuPreparationLedgerError("invalid_scope", "root directory is required");
5191
+ return resolve(rootDirectory);
5184
5192
  }
5185
- function classifyError(status, code, message) {
5186
- if (code === 234043) return "unsupported";
5187
- if (code === 234005 || containsExpiredText(message)) return "expired";
5188
- if (status === 401) return "authentication";
5189
- if (status === 403) return "permission_denied";
5190
- if (status === 429) return "rate_limited";
5191
- if (status >= 500) return "unavailable";
5192
- if (status >= 400) return "invalid_request";
5193
- return "invalid_response";
5193
+ function validateOptions(options) {
5194
+ return validateRootDirectory(options.rootDirectory);
5194
5195
  }
5195
- /** Error bodies read `a ?? b` chains: a present value of the wrong type ends the chain without a value. */
5196
- const errorFields = {
5197
- code: chained(Schema.Union([Schema.Finite, Schema.String.check(Schema.isPattern(/^\d+$/))])),
5198
- message: chained(Schema.String),
5199
- msg: chained(Schema.String)
5200
- };
5201
- const decodeErrorBody = Schema.decodeUnknownOption(Schema.Struct({
5202
- ...errorFields,
5203
- data: tolerant(Schema.Struct(errorFields))
5204
- }));
5205
- function errorCode(value) {
5206
- if (typeof value === "number") return value;
5207
- const parsed = Number(value);
5208
- return Number.isSafeInteger(parsed) ? parsed : void 0;
5196
+ function invalidScopeField(field) {
5197
+ return new FeishuPreparationLedgerError("invalid_scope", `scope field ${field} is invalid`);
5209
5198
  }
5210
- function parseErrorDetails(body) {
5211
- if (body === void 0 || body === "") return {
5212
- code: void 0,
5213
- message: void 0
5199
+ function scopeFields(container) {
5200
+ const { tenantKey, endpointId, sessionGeneration, deliveryId } = Array.isArray(container) ? {} : container;
5201
+ if (tenantKey === void 0) throw invalidScopeField("tenantKey");
5202
+ if (endpointId === void 0) throw invalidScopeField("endpointId");
5203
+ if (sessionGeneration === void 0) throw invalidScopeField("sessionGeneration");
5204
+ if (deliveryId === void 0) throw invalidScopeField("deliveryId");
5205
+ return {
5206
+ tenantKey,
5207
+ endpointId,
5208
+ sessionGeneration,
5209
+ deliveryId
5214
5210
  };
5215
- let parsed;
5211
+ }
5212
+ function readFeishuPreparationLedgerScope(value) {
5213
+ const state = Option.getOrUndefined(decodeLedgerState(value));
5214
+ if (state?.version === void 0 || state.scope === void 0) return;
5216
5215
  try {
5217
- parsed = JSON.parse(body);
5216
+ return scopeFields(state.scope);
5218
5217
  } catch {
5219
- return {
5220
- code: void 0,
5221
- message: void 0
5222
- };
5218
+ return;
5223
5219
  }
5224
- const value = Option.getOrUndefined(decodeErrorBody(parsed));
5225
- const code = value?.code ?? value?.data?.code;
5226
- const message = value?.msg ?? value?.message ?? value?.data?.msg ?? value?.data?.message;
5220
+ }
5221
+ function normalizeScope(scope) {
5222
+ const container = Option.getOrUndefined(decodeScopeContainer(scope));
5223
+ if (container === void 0) throw new FeishuPreparationLedgerError("invalid_scope", "scope is required");
5224
+ return scopeFields(container);
5225
+ }
5226
+ function replaceResource(resources, replacement) {
5227
+ return resources.some((resource) => resource.resourceKey === replacement.resourceKey) ? resources.map((resource) => resource.resourceKey === replacement.resourceKey ? replacement : resource) : [...resources, replacement];
5228
+ }
5229
+ function initialState(scope) {
5227
5230
  return {
5228
- code: code === void 0 || code === null || code === INVALID ? void 0 : errorCode(code),
5229
- message: message === void 0 || message === null || message === INVALID ? void 0 : message.slice(0, 512)
5231
+ version: LEDGER_VERSION,
5232
+ scope: { ...scope },
5233
+ activeTimeMs: 0,
5234
+ reservedActiveTimeMs: 0,
5235
+ retryAttempts: 0,
5236
+ recoveryAttempts: 0,
5237
+ bytes: 0,
5238
+ reservedBytes: 0,
5239
+ resources: [],
5240
+ terminalCancelled: false
5230
5241
  };
5231
5242
  }
5232
- function errorFromJson(body, status) {
5233
- const details = parseErrorDetails(body);
5234
- return createProtocolError(classifyError(status, details.code, details.message), status, details.code, void 0);
5243
+ function snapshotState(state) {
5244
+ return {
5245
+ version: LEDGER_VERSION,
5246
+ scope: { ...state.scope },
5247
+ activeTimeMs: state.activeTimeMs,
5248
+ reservedActiveTimeMs: state.reservedActiveTimeMs,
5249
+ retryAttempts: state.retryAttempts,
5250
+ recoveryAttempts: state.recoveryAttempts,
5251
+ bytes: state.bytes,
5252
+ reservedBytes: state.reservedBytes,
5253
+ resources: [...state.resources].sort((left, right) => left.resourceKey.localeCompare(right.resourceKey)).map((resource) => ({
5254
+ resourceKey: resource.resourceKey,
5255
+ status: resource.status,
5256
+ attempts: resource.attempts,
5257
+ recoveryAttempts: resource.recoveryAttempts,
5258
+ activeTimeMs: resource.activeTimeMs,
5259
+ bytes: resource.bytes,
5260
+ reservedActiveTimeMs: resource.reservedActiveTimeMs,
5261
+ reservedBytes: resource.reservedBytes,
5262
+ ...resource.retryableFailure === void 0 ? {} : { retryableFailure: resource.retryableFailure },
5263
+ ...resource.inFlight === void 0 ? {} : { inFlight: { ...resource.inFlight } }
5264
+ })),
5265
+ terminalCancelled: state.terminalCancelled
5266
+ };
5235
5267
  }
5236
- async function cancelBody(body) {
5237
- if (body !== null) await body.cancel().catch(() => void 0);
5268
+ function cloneState(state) {
5269
+ return snapshotState(state);
5238
5270
  }
5239
- function normalizeMimeType(header) {
5240
- if (header === null) return;
5241
- const mimeType = header.split(";", 1)[0]?.trim().toLowerCase();
5242
- return mimeType === void 0 || mimeType === "" ? void 0 : mimeType;
5243
- }
5244
- function isJsonMimeType(mimeType) {
5245
- return mimeType === "application/json" || mimeType === "text/json" || mimeType?.endsWith("+json") === true;
5271
+ async function writeState(filePath, state) {
5272
+ await writeAtomicTextFile(filePath, `${JSON.stringify(snapshotState(state))}\n`, { mode: 384 });
5246
5273
  }
5247
- function isAttachmentResponse(response, resourceType) {
5248
- if (resourceType !== "file") return false;
5249
- const disposition = response.headers.get("content-disposition");
5250
- return disposition !== null && /(?:^|;)\s*attachment(?:;|$)/i.test(disposition);
5274
+ function feishuPreparationLedgerScopeDigest(scope) {
5275
+ return createHash("sha256").update(JSON.stringify([
5276
+ scope.tenantKey,
5277
+ scope.endpointId,
5278
+ scope.sessionGeneration,
5279
+ scope.deliveryId
5280
+ ])).digest("hex");
5251
5281
  }
5252
- function parseContentLength(header) {
5253
- if (header === null || !/^\d+$/.test(header.trim())) return;
5254
- const value = Number(header);
5255
- return Number.isSafeInteger(value) ? value : void 0;
5282
+ function pathFor(rootDirectory, scope) {
5283
+ return join(rootDirectory, "feishu-preparation-ledger", `${feishuPreparationLedgerScopeDigest(scope)}.json`);
5256
5284
  }
5257
- function parseRetryAfter(header) {
5258
- if (header === null) return;
5259
- const value = header.trim();
5260
- if (/^\d+$/.test(value)) {
5261
- const seconds = Number(value);
5262
- return Number.isSafeInteger(seconds) ? seconds * 1e3 : void 0;
5285
+ async function readLockOwner(lockPath) {
5286
+ try {
5287
+ const owner = Option.getOrUndefined(decodeLockOwner(JSON.parse(await readFile(lockPath, "utf8"))));
5288
+ if (owner === void 0) return;
5289
+ return {
5290
+ pid: owner.pid,
5291
+ token: owner.token,
5292
+ createdAtMs: owner.createdAtMs ?? 0
5293
+ };
5294
+ } catch (error) {
5295
+ if (isNodeErrorWithCode(error, "ENOENT")) return;
5296
+ throw error;
5263
5297
  }
5264
- const timestamp = Date.parse(value);
5265
- if (!Number.isFinite(timestamp)) return;
5266
- return Math.max(0, timestamp - Date.now());
5267
- }
5268
- function startsWith(bytes, expected) {
5269
- if (bytes.byteLength < expected.length) return false;
5270
- return expected.every((value, index) => bytes[index] === value);
5271
- }
5272
- function startsWithAscii(bytes, expected) {
5273
- if (bytes.byteLength < expected.length) return false;
5274
- return expected.split("").every((value, index) => bytes[index] === value.charCodeAt(0));
5275
5298
  }
5276
- function hasSupportedImageSignature(bytes, mimeType) {
5277
- if (startsWith(bytes, [
5278
- 137,
5279
- 80,
5280
- 78,
5281
- 71,
5282
- 13,
5283
- 10,
5284
- 26,
5285
- 10
5286
- ])) return mimeType === "image/png";
5287
- if (startsWith(bytes, [
5288
- 255,
5289
- 216,
5290
- 255
5291
- ])) return mimeType === "image/jpeg" || mimeType === "image/jpg";
5292
- if (startsWithAscii(bytes, "GIF87a") || startsWithAscii(bytes, "GIF89a")) return mimeType === "image/gif";
5293
- if (startsWithAscii(bytes, "RIFF") && startsWithAscii(bytes.slice(8), "WEBP")) return mimeType === "image/webp";
5294
- if (startsWithAscii(bytes, "BM")) return mimeType === "image/bmp" || mimeType === "image/x-ms-bmp";
5295
- if (startsWith(bytes, [
5296
- 73,
5297
- 73,
5298
- 42,
5299
- 0
5300
- ]) || startsWith(bytes, [
5301
- 77,
5302
- 77,
5303
- 0,
5304
- 42
5305
- ])) return mimeType === "image/tiff";
5306
- if (startsWithAscii(bytes.slice(4), "ftypavif")) return mimeType === "image/avif";
5307
- if (mimeType === "image/svg+xml") {
5308
- const prefix = new TextDecoder().decode(bytes.slice(0, Math.min(bytes.byteLength, 4096)));
5309
- return /^\uFEFF?\s*(?:<\?xml[^>]*>\s*)?<svg(?:\s|>)/i.test(prefix);
5299
+ async function releaseFileLock(lock) {
5300
+ try {
5301
+ if ((await readLockOwner(lock.path))?.token === lock.token) await unlink(lock.path).catch((error) => {
5302
+ if (!isNodeErrorWithCode(error, "ENOENT")) throw error;
5303
+ });
5304
+ } finally {
5305
+ await lock.handle.close();
5310
5306
  }
5311
- return false;
5312
5307
  }
5313
- function addAbortListener(signal, listener) {
5314
- if (signal === void 0) return () => void 0;
5315
- signal.addEventListener("abort", listener, { once: true });
5316
- return () => signal.removeEventListener("abort", listener);
5308
+ function isProcessAlive(pid) {
5309
+ try {
5310
+ process.kill(pid, 0);
5311
+ return true;
5312
+ } catch (error) {
5313
+ return isNodeErrorWithCode(error, "EPERM");
5314
+ }
5317
5315
  }
5318
- function isAbortError(error) {
5319
- return error instanceof Error && error.name === "AbortError";
5316
+ async function reclaimStaleLock(lockPath, staleLockMs) {
5317
+ let information;
5318
+ try {
5319
+ information = await stat(lockPath);
5320
+ } catch (error) {
5321
+ if (isNodeErrorWithCode(error, "ENOENT")) return true;
5322
+ throw error;
5323
+ }
5324
+ if (Date.now() - information.mtimeMs < staleLockMs) return false;
5325
+ const owner = await readLockOwner(lockPath);
5326
+ if (owner && isProcessAlive(owner.pid)) return false;
5327
+ try {
5328
+ await unlink(lockPath);
5329
+ return true;
5330
+ } catch (error) {
5331
+ if (isNodeErrorWithCode(error, "ENOENT")) return true;
5332
+ throw error;
5333
+ }
5320
5334
  }
5321
- function invalidRequestError(message) {
5322
- return new FeishuResourceReadError({
5323
- classification: "invalid_request",
5324
- message
5335
+ function delay(milliseconds, signal) {
5336
+ return new Promise((resolvePromise, reject) => {
5337
+ const timer = setTimeout(() => {
5338
+ signal?.removeEventListener("abort", onAbort);
5339
+ resolvePromise();
5340
+ }, milliseconds);
5341
+ function onAbort() {
5342
+ clearTimeout(timer);
5343
+ signal?.removeEventListener("abort", onAbort);
5344
+ reject(/* @__PURE__ */ new Error("ledger operation aborted"));
5345
+ }
5346
+ if (signal?.aborted) onAbort();
5347
+ else signal?.addEventListener("abort", onAbort, { once: true });
5325
5348
  });
5326
5349
  }
5327
- function validateBaseUrl(baseUrl) {
5328
- let parsed;
5329
- try {
5330
- parsed = new URL(baseUrl);
5331
- } catch {
5332
- throw invalidRequestError("Feishu base URL is invalid");
5350
+ async function acquireFileLock(lockPath, options) {
5351
+ await mkdir(dirname(lockPath), { recursive: true });
5352
+ const deadline = Date.now() + options.lockTimeoutMs;
5353
+ while (true) {
5354
+ if (options.signal?.aborted) throw new Error("ledger operation aborted");
5355
+ let handle;
5356
+ try {
5357
+ handle = await open(lockPath, "wx", 384);
5358
+ const owner = {
5359
+ pid: process.pid,
5360
+ token: randomUUID(),
5361
+ createdAtMs: Date.now()
5362
+ };
5363
+ await handle.writeFile(JSON.stringify(owner), "utf8");
5364
+ await handle.sync();
5365
+ return {
5366
+ handle,
5367
+ path: lockPath,
5368
+ token: owner.token
5369
+ };
5370
+ } catch (error) {
5371
+ await handle?.close().catch(() => void 0);
5372
+ if (!isNodeErrorWithCode(error, "EEXIST")) throw error;
5373
+ if (await reclaimStaleLock(lockPath, options.staleLockMs)) continue;
5374
+ if (Date.now() >= deadline) throw new FeishuPreparationLedgerError("lock_timeout", "ledger lock could not be acquired");
5375
+ await delay(options.lockRetryMs, options.signal);
5376
+ }
5333
5377
  }
5334
- if (parsed.protocol !== "http:" && parsed.protocol !== "https:") throw invalidRequestError("Feishu base URL must use HTTP or HTTPS");
5335
- if (parsed.username !== "" || parsed.password !== "") throw invalidRequestError("Feishu base URL must not contain credentials");
5336
- if (parsed.search !== "" || parsed.hash !== "" || parsed.pathname !== "" && parsed.pathname !== "/") throw invalidRequestError("Feishu base URL must not contain a path or query");
5337
- return parsed.origin;
5338
5378
  }
5339
- function validateInput$1(input) {
5340
- const identifiers = decodeIdentifiers(input);
5341
- if (identifiers.messageId === void 0) return invalidRequestError("Feishu message ID is required");
5342
- if (identifiers.resourceKey === void 0) return invalidRequestError("Feishu resource key is required");
5343
- if (input.messageId === "." || input.messageId === ".." || input.resourceKey === "." || input.resourceKey === "..") return invalidRequestError("Feishu resource identifier is invalid");
5344
- if (!Number.isSafeInteger(input.maxBytes) || input.maxBytes <= 0) return invalidRequestError("Feishu resource byte limit is invalid");
5379
+ async function withFileLock(statePath, options, operation) {
5380
+ const lock = await acquireFileLock(`${statePath}.lock`, options);
5381
+ let operationOutcome;
5382
+ try {
5383
+ operationOutcome = {
5384
+ ok: true,
5385
+ value: await operation()
5386
+ };
5387
+ } catch (error) {
5388
+ operationOutcome = {
5389
+ ok: false,
5390
+ error
5391
+ };
5392
+ }
5393
+ let releaseOutcome;
5394
+ try {
5395
+ await releaseFileLock(lock);
5396
+ releaseOutcome = { ok: true };
5397
+ } catch (error) {
5398
+ releaseOutcome = {
5399
+ ok: false,
5400
+ error
5401
+ };
5402
+ }
5403
+ if (!operationOutcome.ok) throw operationOutcome.error;
5404
+ if (!releaseOutcome.ok) throw releaseOutcome.error;
5405
+ return operationOutcome.value;
5345
5406
  }
5346
- function cancelledError$1(consumedBytes) {
5347
- return new FeishuResourceReadError({
5348
- classification: "cancelled",
5349
- message: "Feishu resource request was cancelled",
5350
- ...consumedBytes === void 0 ? {} : { consumedBytes }
5407
+ function withFeishuPreparationLedgerScopeLock(options, operation) {
5408
+ if (options.signal?.aborted) return Promise.reject(/* @__PURE__ */ new Error("ledger operation aborted"));
5409
+ const statePath = pathFor(validateRootDirectory(options.rootDirectory), normalizeScope(options.scope));
5410
+ return withFileLock(statePath, {
5411
+ lockRetryMs: DEFAULT_LOCK_RETRY_MS,
5412
+ lockTimeoutMs: DEFAULT_LOCK_TIMEOUT_MS,
5413
+ staleLockMs: DEFAULT_STALE_LOCK_MS,
5414
+ ...options.signal === void 0 ? {} : { signal: options.signal }
5415
+ }, async () => {
5416
+ if (options.signal?.aborted) throw new Error("ledger operation aborted");
5417
+ return operation(statePath);
5351
5418
  });
5352
5419
  }
5353
- function toResourceError(error, signal) {
5354
- if (error instanceof FeishuResourceReadError) return error;
5355
- if (signal?.aborted === true || isAbortError(error)) return cancelledError$1();
5356
- return new FeishuResourceReadError({
5357
- classification: "network",
5358
- message: "Feishu resource request failed"
5359
- });
5420
+ function safeFeishuPreparationClock(clock) {
5421
+ const value = clock();
5422
+ return Number.isSafeInteger(value) && value >= 0 ? value : Date.now();
5360
5423
  }
5361
- function tooLargeError(status, consumedBytes) {
5362
- const options = {
5363
- classification: "too_large",
5364
- message: "Feishu resource exceeded the configured byte limit"
5424
+ function positiveInteger$3(value, label) {
5425
+ if (value === void 0 || !Number.isSafeInteger(value) || value < 1) throw new FeishuPreparationLedgerError("invalid_request", `${label} must be a positive integer`);
5426
+ return value;
5427
+ }
5428
+ function normalizeLimits$1(limits) {
5429
+ return {
5430
+ totalBytes: positiveInteger$3(limits.totalBytes, "total bytes"),
5431
+ totalActiveTimeMs: positiveInteger$3(limits.totalActiveTimeMs, "total active time"),
5432
+ maxAttemptsPerResource: positiveInteger$3(limits.maxAttemptsPerResource, "attempt count")
5365
5433
  };
5366
- if (status !== void 0) Object.assign(options, { status });
5367
- if (consumedBytes !== void 0) Object.assign(options, { consumedBytes });
5368
- return new FeishuResourceReadError(options);
5369
5434
  }
5370
- function resourceErrorWithConsumedBytes(error, consumedBytes) {
5371
- return new FeishuResourceReadError({
5372
- classification: error.classification,
5373
- ...error.code === void 0 ? {} : { code: error.code },
5374
- ...error.retryAfterMs === void 0 ? {} : { retryAfterMs: error.retryAfterMs },
5375
- ...error.status === void 0 ? {} : { status: error.status },
5376
- consumedBytes,
5377
- message: error.message
5378
- });
5435
+ function validateReservationInput(input) {
5436
+ if (input.resourceKey.trim() === "" || input.resourceKey.length > 1024) throw new FeishuPreparationLedgerError("invalid_request", "resource key is invalid");
5437
+ positiveInteger$3(input.byteReservation, "byte reservation");
5438
+ positiveInteger$3(input.timeReservationMs, "time reservation");
5439
+ return input;
5379
5440
  }
5380
- async function readBoundedBytes(body, maxBytes, signal) {
5381
- if (body === null) throw new FeishuResourceReadError({
5382
- classification: "invalid_response",
5383
- message: "Feishu resource response did not contain a body"
5384
- });
5385
- const reader = body.getReader();
5386
- const chunks = [];
5387
- let total = 0;
5388
- let aborted = signal.aborted;
5389
- const onAbort = () => {
5390
- aborted = true;
5391
- reader.cancel().catch(() => void 0);
5441
+ function nonNegativeInteger$1(value, label) {
5442
+ if (value === void 0 || !Number.isSafeInteger(value) || value < 0) throw new FeishuPreparationLedgerError("corrupt", `${label} must be a non-negative integer`);
5443
+ return value;
5444
+ }
5445
+ function validateReservation(value) {
5446
+ if (value.id.length === 0) throw new FeishuPreparationLedgerError("invalid_request", "reservation is invalid");
5447
+ validateReservationInput(value);
5448
+ nonNegativeInteger$1(value.attemptNumber, "attempt number");
5449
+ if (!Number.isSafeInteger(value.startedAtMs) || value.startedAtMs < 0) throw new FeishuPreparationLedgerError("invalid_request", "reservation start time is invalid");
5450
+ return value;
5451
+ }
5452
+ function validateCompletion(value) {
5453
+ if (!hasValidCompletionMarker(value)) throw new FeishuPreparationLedgerError("invalid_request", "retryable failure marker is invalid");
5454
+ if (value.retryableFailure !== void 0 && value.status !== "failed") throw new FeishuPreparationLedgerError("invalid_request", "retryable failure marker requires a failed completion");
5455
+ nonNegativeInteger$1(value.bytes, "actual bytes");
5456
+ nonNegativeInteger$1(value.activeTimeMs, "actual active time");
5457
+ return value;
5458
+ }
5459
+ function validateInFlight(value) {
5460
+ if (value === INVALID || value.id === void 0) throw new FeishuPreparationLedgerError("corrupt", "ledger reservation marker is invalid");
5461
+ if (value.kind === void 0) throw new FeishuPreparationLedgerError("corrupt", "ledger reservation kind is invalid");
5462
+ return {
5463
+ id: value.id,
5464
+ kind: value.kind,
5465
+ byteReservation: positiveInteger$3(value.byteReservation, "reservation bytes"),
5466
+ timeReservationMs: positiveInteger$3(value.timeReservationMs, "reservation time"),
5467
+ startedAtMs: nonNegativeInteger$1(value.startedAtMs, "reservation start time"),
5468
+ attemptNumber: nonNegativeInteger$1(value.attemptNumber, "reservation attempt")
5392
5469
  };
5393
- signal.addEventListener("abort", onAbort, { once: true });
5394
- const isAborted = () => aborted || signal.aborted;
5395
- try {
5396
- while (true) {
5397
- if (isAborted()) throw cancelledError$1(total);
5398
- let readResult;
5399
- try {
5400
- readResult = await reader.read();
5401
- } catch (error) {
5402
- if (isAborted()) throw cancelledError$1(total);
5403
- throw error;
5404
- }
5405
- if (isAborted()) throw cancelledError$1(total);
5406
- if (readResult.done) break;
5407
- const chunk = readResult.value;
5408
- if (chunk.byteLength > maxBytes - total) {
5409
- await reader.cancel().catch(() => void 0);
5410
- throw tooLargeError(void 0, maxBytes);
5411
- }
5412
- if (chunk.byteLength > 0) {
5413
- chunks.push(chunk);
5414
- total += chunk.byteLength;
5415
- }
5416
- }
5417
- } catch (error) {
5418
- await reader.cancel().catch(() => void 0);
5419
- if (error instanceof FeishuResourceReadError) {
5420
- if (error.consumedBytes !== void 0) throw error;
5421
- throw resourceErrorWithConsumedBytes(error, total);
5422
- }
5423
- throw resourceErrorWithConsumedBytes(toResourceError(error, signal), maxBytes);
5424
- } finally {
5425
- signal.removeEventListener("abort", onAbort);
5426
- reader.releaseLock();
5427
- }
5428
- const bytes = new Uint8Array(total);
5429
- let offset = 0;
5430
- for (const chunk of chunks) {
5431
- bytes.set(chunk, offset);
5432
- offset += chunk.byteLength;
5433
- }
5434
- return bytes;
5435
5470
  }
5436
- async function readBoundedText(response, maxBytes, signal) {
5437
- try {
5438
- const bytes = await readBoundedBytes(response.body, maxBytes, signal);
5439
- return new TextDecoder().decode(bytes);
5440
- } catch (error) {
5441
- if (error instanceof FeishuResourceReadError && error.classification === "cancelled") throw error;
5442
- return;
5443
- }
5471
+ function validateResourceState(value, limits) {
5472
+ if (value === INVALID || value.resourceKey === void 0) throw new FeishuPreparationLedgerError("corrupt", "ledger resource is invalid");
5473
+ const status = value.status;
5474
+ if (status === void 0) throw new FeishuPreparationLedgerError("corrupt", "ledger resource status is invalid");
5475
+ const attempts = nonNegativeInteger$1(value.attempts, "resource attempts");
5476
+ const recoveryAttempts = nonNegativeInteger$1(value.recoveryAttempts, "resource recovery attempts");
5477
+ const activeTimeMs = nonNegativeInteger$1(value.activeTimeMs, "resource active time");
5478
+ const bytes = nonNegativeInteger$1(value.bytes, "resource bytes");
5479
+ const reservedActiveTimeMs = nonNegativeInteger$1(value.reservedActiveTimeMs, "resource reserved active time");
5480
+ const reservedBytes = nonNegativeInteger$1(value.reservedBytes, "resource reserved bytes");
5481
+ if (value.retryableFailure === INVALID) throw new FeishuPreparationLedgerError("corrupt", "ledger retryable failure marker is invalid");
5482
+ if (value.retryableFailure !== void 0 && status !== "failed") throw new FeishuPreparationLedgerError("corrupt", "ledger retryable failure marker requires a failed resource");
5483
+ if (attempts > limits.maxAttemptsPerResource || recoveryAttempts > 1) throw new FeishuPreparationLedgerError("corrupt", "ledger resource attempt budget is invalid");
5484
+ const inFlight = value.inFlight === void 0 ? void 0 : validateInFlight(value.inFlight);
5485
+ if (status === "in_flight" !== (inFlight !== void 0)) throw new FeishuPreparationLedgerError("corrupt", "ledger in-flight marker does not match status");
5486
+ if (inFlight === void 0 && (reservedActiveTimeMs !== 0 || reservedBytes !== 0)) throw new FeishuPreparationLedgerError("corrupt", "ledger has reservation credit without marker");
5487
+ if (inFlight && (reservedActiveTimeMs !== inFlight.timeReservationMs || reservedBytes !== inFlight.byteReservation)) throw new FeishuPreparationLedgerError("corrupt", "ledger reservation marker does not match credit");
5488
+ return {
5489
+ resourceKey: value.resourceKey,
5490
+ status,
5491
+ attempts,
5492
+ recoveryAttempts,
5493
+ activeTimeMs,
5494
+ bytes,
5495
+ reservedActiveTimeMs,
5496
+ reservedBytes,
5497
+ ...value.retryableFailure === void 0 ? {} : { retryableFailure: value.retryableFailure },
5498
+ ...inFlight === void 0 ? {} : { inFlight }
5499
+ };
5444
5500
  }
5445
- async function errorFromResponse(response, signal) {
5446
- const details = parseErrorDetails(await readBoundedText(response, ERROR_BODY_MAX_BYTES, signal));
5447
- const classification = classifyError(response.status, details.code, details.message);
5448
- const retryAfterMs = classification === "rate_limited" ? parseRetryAfter(response.headers.get("retry-after")) : void 0;
5449
- return createProtocolError(classification, response.status, details.code, retryAfterMs);
5501
+ function validateState$1(value, expectedScope, limits) {
5502
+ const state = Option.getOrUndefined(decodeLedgerState(value));
5503
+ if (state?.version === void 0 || state.scope === void 0) throw new FeishuPreparationLedgerError("corrupt", "ledger state version or scope is invalid");
5504
+ const scope = scopeFields(state.scope);
5505
+ if (scope.tenantKey !== expectedScope.tenantKey || scope.endpointId !== expectedScope.endpointId || scope.sessionGeneration !== expectedScope.sessionGeneration || scope.deliveryId !== expectedScope.deliveryId) throw new FeishuPreparationLedgerError("corrupt", "ledger scope does not match requested scope");
5506
+ const activeTimeMs = nonNegativeInteger$1(state.activeTimeMs, "active time");
5507
+ const reservedActiveTimeMs = nonNegativeInteger$1(state.reservedActiveTimeMs, "reserved active time");
5508
+ const retryAttempts = nonNegativeInteger$1(state.retryAttempts, "retry attempts");
5509
+ const recoveryAttempts = nonNegativeInteger$1(state.recoveryAttempts, "recovery attempts");
5510
+ const bytes = nonNegativeInteger$1(state.bytes, "bytes");
5511
+ const reservedBytes = nonNegativeInteger$1(state.reservedBytes, "reserved bytes");
5512
+ if (activeTimeMs + reservedActiveTimeMs > limits.totalActiveTimeMs) throw new FeishuPreparationLedgerError("corrupt", "ledger active-time budget is invalid");
5513
+ if (bytes + reservedBytes > limits.totalBytes) throw new FeishuPreparationLedgerError("corrupt", "ledger byte budget is invalid");
5514
+ if (state.terminalCancelled === void 0 || state.resources === void 0) throw new FeishuPreparationLedgerError("corrupt", "ledger state fields are invalid");
5515
+ const resources = state.resources.map((candidate) => validateResourceState(candidate, limits));
5516
+ if (new Set(resources.map((resource) => resource.resourceKey)).size !== resources.length) throw new FeishuPreparationLedgerError("corrupt", "ledger contains duplicate resources");
5517
+ const resourceReservedBytes = resources.reduce((total, resource) => total + resource.reservedBytes, 0);
5518
+ const resourceReservedTime = resources.reduce((total, resource) => total + resource.reservedActiveTimeMs, 0);
5519
+ if (resourceReservedBytes !== reservedBytes || resourceReservedTime !== reservedActiveTimeMs) throw new FeishuPreparationLedgerError("corrupt", "ledger reservation totals do not match resources");
5520
+ return snapshotState({
5521
+ version: LEDGER_VERSION,
5522
+ scope,
5523
+ activeTimeMs,
5524
+ reservedActiveTimeMs,
5525
+ retryAttempts,
5526
+ recoveryAttempts,
5527
+ bytes,
5528
+ reservedBytes,
5529
+ resources,
5530
+ terminalCancelled: state.terminalCancelled
5531
+ });
5450
5532
  }
5451
- async function fetchAndRead(fetchImpl, url, token, input, signal) {
5452
- let response;
5533
+ async function readFeishuPreparationLedgerState(filePath, scope, limits) {
5534
+ const raw = await readPersistenceFile(filePath);
5535
+ if (raw === void 0) return;
5536
+ let value;
5453
5537
  try {
5454
- response = await fetchImpl(url, {
5455
- method: "GET",
5456
- headers: { Authorization: "Bearer " + token },
5457
- redirect: "manual",
5458
- signal
5459
- });
5460
- } catch (error) {
5461
- throw toResourceError(error, signal);
5462
- }
5463
- if (response.status >= 300 && response.status < 400) {
5464
- await cancelBody(response.body);
5465
- throw new FeishuResourceReadError({
5466
- classification: "redirect",
5467
- status: response.status,
5468
- message: "Feishu resource endpoint returned a redirect"
5469
- });
5470
- }
5471
- if (response.type === "opaqueredirect") {
5472
- await cancelBody(response.body);
5473
- throw new FeishuResourceReadError({
5474
- classification: "redirect",
5475
- message: "Feishu resource endpoint returned a redirect"
5476
- });
5477
- }
5478
- if (response.status < 200 || response.status >= 300) throw await errorFromResponse(response, signal);
5479
- const mimeType = normalizeMimeType(response.headers.get("content-type"));
5480
- if (isJsonMimeType(mimeType) && !isAttachmentResponse(response, input.resourceType)) throw errorFromJson(await readBoundedText(response, ERROR_BODY_MAX_BYTES, signal), response.status);
5481
- const declaredLength = parseContentLength(response.headers.get("content-length"));
5482
- if (declaredLength !== void 0 && declaredLength > input.maxBytes) {
5483
- await cancelBody(response.body);
5484
- throw tooLargeError(response.status);
5485
- }
5486
- if (mimeType === void 0) {
5487
- await cancelBody(response.body);
5488
- throw new FeishuResourceReadError({
5489
- classification: "invalid_response",
5490
- status: response.status,
5491
- message: "Feishu resource response did not declare a MIME type"
5492
- });
5538
+ value = JSON.parse(raw);
5539
+ } catch {
5540
+ throw new FeishuPreparationLedgerError("corrupt", "ledger state is not valid JSON");
5493
5541
  }
5494
- const bytes = await readBoundedBytes(response.body, input.maxBytes, signal);
5495
- if (bytes.byteLength === 0) throw new FeishuResourceReadError({
5496
- classification: "invalid_response",
5497
- status: response.status,
5498
- message: "Feishu resource response was empty"
5499
- });
5500
- if (input.resourceType === "image" && (!mimeType.startsWith("image/") || !hasSupportedImageSignature(bytes, mimeType))) throw new FeishuResourceReadError({
5501
- classification: "invalid_response",
5502
- status: response.status,
5503
- message: "Feishu image response MIME type or bytes did not match"
5542
+ return validateState$1(value, scope, limits);
5543
+ }
5544
+ async function loadState(filePath, scope, limits) {
5545
+ return await readFeishuPreparationLedgerState(filePath, scope, limits) ?? initialState(scope);
5546
+ }
5547
+ function asLedgerError(error) {
5548
+ if (error instanceof FeishuPreparationLedgerError) return error;
5549
+ return new FeishuPreparationLedgerError("corrupt", "ledger persistence failed");
5550
+ }
5551
+ function createFeishuPreparationLedger(options) {
5552
+ const rootDirectory = validateOptions(options);
5553
+ const scope = normalizeScope(options.scope);
5554
+ const limits = normalizeLimits$1(options.limits);
5555
+ const clock = options.clock ?? Date.now;
5556
+ const lockRetryMs = positiveInteger$3(options.lockRetryMs ?? DEFAULT_LOCK_RETRY_MS, "lock retry");
5557
+ const lockTimeoutMs = positiveInteger$3(options.lockTimeoutMs ?? DEFAULT_LOCK_TIMEOUT_MS, "lock timeout");
5558
+ const staleLockMs = positiveInteger$3(options.staleLockMs ?? DEFAULT_STALE_LOCK_MS, "stale lock");
5559
+ const filePath = pathFor(rootDirectory, scope);
5560
+ const serial = createSerialExecutor();
5561
+ const runExclusive = (operation) => Effect.tryPromise({
5562
+ try: () => serial.run(() => withFileLock(filePath, {
5563
+ lockRetryMs,
5564
+ lockTimeoutMs,
5565
+ staleLockMs
5566
+ }, async () => {
5567
+ const mutation = await operation(await loadState(filePath, scope, limits));
5568
+ if (mutation.write) await writeState(filePath, mutation.state);
5569
+ return mutation.value;
5570
+ })),
5571
+ catch: asLedgerError
5504
5572
  });
5505
5573
  return {
5506
- bytes,
5507
- mimeType
5508
- };
5509
- }
5510
- function readResource(baseUrl, fetchImpl, getTenantAccessToken, input) {
5511
- const validationError = validateInput$1(input);
5512
- if (validationError !== void 0) return Effect.fail(validationError);
5513
- if (input.signal?.aborted === true) return Effect.fail(cancelledError$1());
5514
- return Effect.gen(function* () {
5515
- const token = yield* getTenantAccessToken().pipe(Effect.mapError(() => new FeishuResourceReadError({
5516
- classification: "authentication",
5517
- message: "Feishu tenant access token is unavailable"
5518
- })));
5519
- if (input.signal?.aborted === true) return yield* Effect.fail(cancelledError$1());
5520
- return yield* Effect.callback((resume, effectSignal) => {
5521
- const controller = new AbortController();
5522
- const onAbort = () => controller.abort();
5523
- const cleanupCaller = addAbortListener(input.signal, onAbort);
5524
- const cleanupEffect = addAbortListener(effectSignal, onAbort);
5525
- const cleanup = () => {
5526
- cleanupCaller();
5527
- cleanupEffect();
5574
+ read: () => runExclusive(async (state) => ({
5575
+ state,
5576
+ value: cloneState(state),
5577
+ write: false
5578
+ })),
5579
+ reserve: (input) => {
5580
+ const request = validateReservationInput(input);
5581
+ return runExclusive(async (state) => {
5582
+ if (state.terminalCancelled) throw new FeishuPreparationLedgerError("terminal_cancelled", "ledger is terminal");
5583
+ const current = state.resources.find((resource) => resource.resourceKey === request.resourceKey);
5584
+ if (current?.inFlight) throw new FeishuPreparationLedgerError("resource_unavailable", "resource already has an active reservation");
5585
+ if (current?.status === "stored") throw new FeishuPreparationLedgerError("resource_unavailable", "resource is already stored");
5586
+ if (current?.status === "cancelled") throw new FeishuPreparationLedgerError("resource_unavailable", "resource is cancelled");
5587
+ if (request.kind === "download" && (current?.attempts ?? 0) >= limits.maxAttemptsPerResource) throw new FeishuPreparationLedgerError("budget_exhausted", "resource attempt budget is exhausted", "attempts");
5588
+ if (request.kind === "recovery" && (current?.recoveryAttempts ?? 0) >= 1) throw new FeishuPreparationLedgerError("budget_exhausted", "resource recovery budget is exhausted", "recovery");
5589
+ if (state.bytes + state.reservedBytes + request.byteReservation > limits.totalBytes) throw new FeishuPreparationLedgerError("budget_exhausted", "delivery byte budget is exhausted", "bytes");
5590
+ if (state.activeTimeMs + state.reservedActiveTimeMs + request.timeReservationMs > limits.totalActiveTimeMs) throw new FeishuPreparationLedgerError("budget_exhausted", "delivery active-time budget is exhausted", "active_time");
5591
+ const attemptNumber = (current?.attempts ?? 0) + (request.kind === "download" ? 1 : 0);
5592
+ const recoveryAttempts = (current?.recoveryAttempts ?? 0) + (request.kind === "recovery" ? 1 : 0);
5593
+ const startedAtMs = safeFeishuPreparationClock(clock);
5594
+ const reservation = {
5595
+ id: randomUUID(),
5596
+ resourceKey: request.resourceKey,
5597
+ kind: request.kind,
5598
+ byteReservation: request.byteReservation,
5599
+ timeReservationMs: request.timeReservationMs,
5600
+ attemptNumber: request.kind === "download" ? attemptNumber : current?.attempts ?? 0,
5601
+ startedAtMs
5602
+ };
5603
+ const resource = {
5604
+ resourceKey: request.resourceKey,
5605
+ status: "in_flight",
5606
+ attempts: attemptNumber,
5607
+ recoveryAttempts,
5608
+ activeTimeMs: current?.activeTimeMs ?? 0,
5609
+ bytes: current?.bytes ?? 0,
5610
+ reservedActiveTimeMs: request.timeReservationMs,
5611
+ reservedBytes: request.byteReservation,
5612
+ inFlight: {
5613
+ id: reservation.id,
5614
+ kind: reservation.kind,
5615
+ byteReservation: reservation.byteReservation,
5616
+ timeReservationMs: reservation.timeReservationMs,
5617
+ startedAtMs: reservation.startedAtMs,
5618
+ attemptNumber: reservation.attemptNumber
5619
+ }
5620
+ };
5621
+ return {
5622
+ state: snapshotState({
5623
+ ...state,
5624
+ activeTimeMs: state.activeTimeMs,
5625
+ reservedActiveTimeMs: state.reservedActiveTimeMs + request.timeReservationMs,
5626
+ retryAttempts: state.retryAttempts + (request.kind === "download" ? 1 : 0),
5627
+ recoveryAttempts: state.recoveryAttempts + (request.kind === "recovery" ? 1 : 0),
5628
+ bytes: state.bytes,
5629
+ reservedBytes: state.reservedBytes + request.byteReservation,
5630
+ resources: replaceResource(state.resources, resource),
5631
+ terminalCancelled: false
5632
+ }),
5633
+ value: reservation,
5634
+ write: true
5635
+ };
5636
+ });
5637
+ },
5638
+ complete: (reservation, completion) => {
5639
+ const checkedReservation = validateReservation(reservation);
5640
+ const checkedCompletion = validateCompletion(completion);
5641
+ return runExclusive(async (state) => {
5642
+ const current = state.resources.find((resource) => resource.resourceKey === checkedReservation.resourceKey);
5643
+ if (!current?.inFlight || current.inFlight.id !== checkedReservation.id) throw new FeishuPreparationLedgerError("reservation_not_found", "reservation is no longer active");
5644
+ if (current.inFlight.kind !== checkedReservation.kind || current.inFlight.byteReservation !== checkedReservation.byteReservation || current.inFlight.timeReservationMs !== checkedReservation.timeReservationMs) throw new FeishuPreparationLedgerError("reservation_not_found", "reservation does not match persisted marker");
5645
+ if (checkedCompletion.bytes > checkedReservation.byteReservation) throw new FeishuPreparationLedgerError("invalid_completion", "actual bytes exceed reserved bytes", "bytes");
5646
+ if (checkedCompletion.activeTimeMs > checkedReservation.timeReservationMs) throw new FeishuPreparationLedgerError("invalid_completion", "active time exceeds reserved time", "active_time");
5647
+ const resource = {
5648
+ resourceKey: current.resourceKey,
5649
+ status: checkedCompletion.status,
5650
+ attempts: current.attempts,
5651
+ recoveryAttempts: current.recoveryAttempts,
5652
+ activeTimeMs: current.activeTimeMs + checkedCompletion.activeTimeMs,
5653
+ bytes: current.bytes + checkedCompletion.bytes,
5654
+ reservedActiveTimeMs: 0,
5655
+ reservedBytes: 0,
5656
+ ...checkedCompletion.status === "failed" && checkedCompletion.retryableFailure !== void 0 ? { retryableFailure: checkedCompletion.retryableFailure } : {}
5657
+ };
5658
+ const next = snapshotState({
5659
+ ...state,
5660
+ activeTimeMs: state.activeTimeMs + checkedCompletion.activeTimeMs,
5661
+ reservedActiveTimeMs: state.reservedActiveTimeMs - checkedReservation.timeReservationMs,
5662
+ bytes: state.bytes + checkedCompletion.bytes,
5663
+ reservedBytes: state.reservedBytes - checkedReservation.byteReservation,
5664
+ resources: replaceResource(state.resources, resource)
5665
+ });
5666
+ return {
5667
+ state: next,
5668
+ value: cloneState(next),
5669
+ write: true
5670
+ };
5671
+ });
5672
+ },
5673
+ cancel: () => runExclusive(async (state) => {
5674
+ if (state.terminalCancelled) return {
5675
+ state,
5676
+ value: cloneState(state),
5677
+ write: false
5528
5678
  };
5529
- if (input.signal?.aborted === true || effectSignal.aborted === true) controller.abort();
5530
- fetchAndRead(fetchImpl, buildResourceUrl(baseUrl, input), token, input, controller.signal).then((result) => resume(Effect.succeed(result)), (error) => resume(Effect.fail(toResourceError(error, controller.signal)))).finally(cleanup);
5531
- return Effect.sync(() => {
5532
- cleanup();
5533
- controller.abort();
5679
+ const cancelledReservations = state.resources.reduce((totals, resource) => ({
5680
+ activeTimeMs: totals.activeTimeMs + (resource.inFlight?.timeReservationMs ?? 0),
5681
+ bytes: totals.bytes + (resource.inFlight?.byteReservation ?? 0)
5682
+ }), {
5683
+ activeTimeMs: 0,
5684
+ bytes: 0
5534
5685
  });
5535
- });
5536
- });
5686
+ const resources = state.resources.map((resource) => {
5687
+ if (!resource.inFlight) return resource;
5688
+ return {
5689
+ resourceKey: resource.resourceKey,
5690
+ status: "cancelled",
5691
+ attempts: resource.attempts,
5692
+ recoveryAttempts: resource.recoveryAttempts,
5693
+ activeTimeMs: resource.activeTimeMs + resource.inFlight.timeReservationMs,
5694
+ bytes: resource.bytes + resource.inFlight.byteReservation,
5695
+ reservedActiveTimeMs: 0,
5696
+ reservedBytes: 0
5697
+ };
5698
+ });
5699
+ const next = snapshotState({
5700
+ ...state,
5701
+ activeTimeMs: state.activeTimeMs + cancelledReservations.activeTimeMs,
5702
+ bytes: state.bytes + cancelledReservations.bytes,
5703
+ reservedActiveTimeMs: 0,
5704
+ reservedBytes: 0,
5705
+ resources,
5706
+ terminalCancelled: true
5707
+ });
5708
+ return {
5709
+ state: next,
5710
+ value: cloneState(next),
5711
+ write: true
5712
+ };
5713
+ })
5714
+ };
5715
+ }
5716
+ //#endregion
5717
+ //#region src/feishu/infra/adapters/attachments/feishu-workspace-path.ts
5718
+ function isStrictRelativePath(path) {
5719
+ return path !== "" && path !== ".." && !path.startsWith(".." + sep) && !isAbsolute(path);
5720
+ }
5721
+ /**
5722
+ * Resolve a strict descendant of a trusted, existing directory and reject
5723
+ * symlinks in its descendants. The root is realpathed so OS path aliases work.
5724
+ *
5725
+ * Recheck immediately before each filesystem side effect. Node has no
5726
+ * portable openat-style API here, so this does not prevent an attacker from
5727
+ * racing a path change between validation and the operation.
5728
+ */
5729
+ async function resolveSafeWorkspacePath(workspaceDirectory, targetPath) {
5730
+ const requestedRoot = resolve(workspaceDirectory);
5731
+ const canonicalRoot = await realpath(requestedRoot);
5732
+ const absoluteTarget = resolve(targetPath);
5733
+ const relativeTarget = [requestedRoot, canonicalRoot].map((root) => relative(root, absoluteTarget)).find(isStrictRelativePath);
5734
+ if (relativeTarget === void 0) throw new Error("workspace path must be a strict descendant of its trusted root");
5735
+ if (!(await lstat(canonicalRoot)).isDirectory()) throw new Error("workspace root is not a directory");
5736
+ const segments = relativeTarget.split(sep);
5737
+ let currentPath = canonicalRoot;
5738
+ for (let index = 0; index < segments.length; index += 1) {
5739
+ const segment = segments[index];
5740
+ if (segment === void 0 || segment === "") throw new Error("workspace path contains an invalid segment");
5741
+ currentPath = join(currentPath, segment);
5742
+ let info;
5743
+ try {
5744
+ info = await lstat(currentPath);
5745
+ } catch (error) {
5746
+ if (isNodeErrorWithCode(error, "ENOENT")) break;
5747
+ throw error;
5748
+ }
5749
+ if (info.isSymbolicLink()) throw new Error("workspace path contains a symbolic link");
5750
+ if (index < segments.length - 1 && !info.isDirectory()) throw new Error("workspace path has a non-directory ancestor");
5751
+ }
5752
+ return join(canonicalRoot, ...segments);
5537
5753
  }
5754
+ //#endregion
5755
+ //#region src/feishu/infra/adapters/client/feishu-resource-reader.ts
5538
5756
  /**
5539
- * Creates the one-request reader used by the gateway's attachment preparation
5540
- * boundary. Retries, persistence, and attachment IDs belong to the caller.
5757
+ * A resource failure carries only protocol metadata. In particular, it never
5758
+ * stores the access token, response body, or a URL containing message data.
5541
5759
  */
5542
- function createFeishuMessageResourceReader(options) {
5543
- const baseUrl = validateBaseUrl(options.baseUrl);
5544
- const fetchImpl = options.fetch ?? globalThis.fetch;
5545
- return { read: (input) => readResource(baseUrl, fetchImpl, options.getTenantAccessToken, input) };
5546
- }
5547
- //#endregion
5548
- //#region src/feishu/infra/repository/feishu-preparation-ledger.ts
5549
- var FeishuPreparationLedgerError = class extends Error {
5760
+ var FeishuResourceReadError = class extends Error {
5761
+ _tag = "FeishuResourceReadError";
5762
+ name = "FeishuResourceReadError";
5763
+ classification;
5764
+ consumedBytes;
5765
+ status;
5550
5766
  code;
5551
- dimension;
5552
- _tag = "FeishuPreparationLedgerError";
5553
- constructor(code, message, dimension) {
5554
- super(message);
5555
- this.code = code;
5556
- this.dimension = dimension;
5557
- this.name = "FeishuPreparationLedgerError";
5767
+ retryAfterMs;
5768
+ constructor(options) {
5769
+ super(options.message);
5770
+ this.classification = options.classification;
5771
+ this.consumedBytes = options.consumedBytes;
5772
+ this.status = options.status;
5773
+ this.code = options.code;
5774
+ this.retryAfterMs = options.retryAfterMs;
5775
+ Object.setPrototypeOf(this, new.target.prototype);
5558
5776
  }
5559
5777
  };
5560
- const LEDGER_VERSION = 1;
5561
- /**
5562
- * The persisted ledger decodes once into typed fields; a field of the wrong
5563
- * type is absent or INVALID, and validateState reports it in the original
5564
- * order with its original text.
5565
- */
5566
- const nonNegativeIntegerField = tolerant(Schema.Int.check(Schema.isGreaterThanOrEqualTo(0)));
5567
- const positiveIntegerField = tolerant(Schema.Int.check(Schema.isGreaterThanOrEqualTo(1)));
5568
- const scopeText = Schema.String.check(Schema.makeFilter((value) => value.trim() !== "" && value.length <= 512));
5569
- /** A valid ledger scope; other records that carry a scope, such as input markers, check it with this. */
5570
- const FeishuPreparationLedgerScopeSchema = Schema.Struct({
5571
- deliveryId: scopeText,
5572
- endpointId: scopeText,
5573
- sessionGeneration: scopeText,
5574
- tenantKey: scopeText
5575
- });
5576
- const scopeTextField = tolerant(scopeText);
5577
- /** An array is an object without scope fields, so it reports the first missing field. */
5578
- const ScopeContainer = Schema.Union([Schema.Struct({
5579
- deliveryId: scopeTextField,
5580
- endpointId: scopeTextField,
5581
- sessionGeneration: scopeTextField,
5582
- tenantKey: scopeTextField
5583
- }), Schema.mutable(Schema.Array(Schema.Unknown))]);
5584
- const InFlightState = Schema.Struct({
5585
- attemptNumber: nonNegativeIntegerField,
5586
- byteReservation: positiveIntegerField,
5587
- id: tolerant(Schema.NonEmptyString),
5588
- kind: tolerant(Schema.Literals(["download", "recovery"])),
5589
- startedAtMs: nonNegativeIntegerField,
5590
- timeReservationMs: positiveIntegerField
5591
- });
5592
- const ResourceState = Schema.Struct({
5593
- activeTimeMs: nonNegativeIntegerField,
5594
- attempts: nonNegativeIntegerField,
5595
- bytes: nonNegativeIntegerField,
5596
- inFlight: Schema.optionalKey(orInvalid(InFlightState)),
5597
- recoveryAttempts: nonNegativeIntegerField,
5598
- reservedActiveTimeMs: nonNegativeIntegerField,
5599
- reservedBytes: nonNegativeIntegerField,
5600
- resourceKey: tolerant(Schema.NonEmptyString),
5601
- retryableFailure: Schema.optionalKey(orInvalid(Schema.Boolean)),
5602
- status: tolerant(Schema.Literals([
5603
- "pending",
5604
- "in_flight",
5605
- "stored",
5606
- "failed",
5607
- "cancelled"
5608
- ]))
5609
- });
5610
- const decodeLedgerState = Schema.decodeUnknownOption(Schema.Struct({
5611
- activeTimeMs: nonNegativeIntegerField,
5612
- bytes: nonNegativeIntegerField,
5613
- recoveryAttempts: nonNegativeIntegerField,
5614
- reservedActiveTimeMs: nonNegativeIntegerField,
5615
- reservedBytes: nonNegativeIntegerField,
5616
- resources: tolerant(Schema.Array(orInvalid(ResourceState))),
5617
- retryAttempts: nonNegativeIntegerField,
5618
- scope: tolerant(ScopeContainer),
5619
- terminalCancelled: tolerant(Schema.Boolean),
5620
- version: tolerant(Schema.Literal(LEDGER_VERSION))
5621
- }));
5622
- const decodeScopeContainer = Schema.decodeUnknownOption(ScopeContainer);
5623
- /** Completions come from preparation code, but a marker of the wrong type must not reach the ledger. */
5624
- const hasValidCompletionMarker = Schema.is(Schema.Struct({ retryableFailure: Schema.optional(Schema.Boolean) }));
5625
- const decodeRootDirectory = Schema.decodeUnknownOption(Schema.String.check(Schema.makeFilter((value) => value.trim() !== "")));
5626
- const decodeLockOwner = Schema.decodeUnknownOption(Schema.Struct({
5627
- createdAtMs: tolerant(Schema.Number),
5628
- pid: Schema.Int,
5629
- token: Schema.String
5778
+ const ERROR_BODY_MAX_BYTES = 65536;
5779
+ const nonBlankIdentifier = tolerant(Schema.String.check(Schema.makeFilter((value) => value.trim() !== "")));
5780
+ const decodeIdentifiers = Schema.decodeUnknownSync(Schema.Struct({
5781
+ messageId: nonBlankIdentifier,
5782
+ resourceKey: nonBlankIdentifier
5630
5783
  }));
5631
- const DEFAULT_LOCK_RETRY_MS = 5;
5632
- const DEFAULT_LOCK_TIMEOUT_MS = 1e4;
5633
- const DEFAULT_STALE_LOCK_MS = 3e4;
5634
- function validateRootDirectory(value) {
5635
- const rootDirectory = Option.getOrUndefined(decodeRootDirectory(value));
5636
- if (rootDirectory === void 0) throw new FeishuPreparationLedgerError("invalid_scope", "root directory is required");
5637
- return resolve(rootDirectory);
5638
- }
5639
- function validateOptions(options) {
5640
- return validateRootDirectory(options.rootDirectory);
5641
- }
5642
- function invalidScopeField(field) {
5643
- return new FeishuPreparationLedgerError("invalid_scope", `scope field ${field} is invalid`);
5784
+ function buildResourceUrl(baseUrl, input) {
5785
+ return baseUrl + "/open-apis/im/v1/messages/" + encodeURIComponent(input.messageId) + "/resources/" + encodeURIComponent(input.resourceKey) + "?type=" + input.resourceType;
5644
5786
  }
5645
- function scopeFields(container) {
5646
- const { tenantKey, endpointId, sessionGeneration, deliveryId } = Array.isArray(container) ? {} : container;
5647
- if (tenantKey === void 0) throw invalidScopeField("tenantKey");
5648
- if (endpointId === void 0) throw invalidScopeField("endpointId");
5649
- if (sessionGeneration === void 0) throw invalidScopeField("sessionGeneration");
5650
- if (deliveryId === void 0) throw invalidScopeField("deliveryId");
5651
- return {
5652
- tenantKey,
5653
- endpointId,
5654
- sessionGeneration,
5655
- deliveryId
5787
+ function createProtocolError(classification, status, code, retryAfterMs) {
5788
+ const options = {
5789
+ classification,
5790
+ status,
5791
+ message: "Feishu resource request failed"
5656
5792
  };
5793
+ if (code !== void 0) Object.assign(options, { code });
5794
+ if (retryAfterMs !== void 0) Object.assign(options, { retryAfterMs });
5795
+ return new FeishuResourceReadError(options);
5657
5796
  }
5658
- function readFeishuPreparationLedgerScope(value) {
5659
- const state = Option.getOrUndefined(decodeLedgerState(value));
5660
- if (state?.version === void 0 || state.scope === void 0) return;
5661
- try {
5662
- return scopeFields(state.scope);
5663
- } catch {
5664
- return;
5665
- }
5666
- }
5667
- function normalizeScope(scope) {
5668
- const container = Option.getOrUndefined(decodeScopeContainer(scope));
5669
- if (container === void 0) throw new FeishuPreparationLedgerError("invalid_scope", "scope is required");
5670
- return scopeFields(container);
5797
+ function containsExpiredText(message) {
5798
+ return message !== void 0 && /expired|expire|过期|失效|已删除|deleted/i.test(message);
5671
5799
  }
5672
- function replaceResource(resources, replacement) {
5673
- return resources.some((resource) => resource.resourceKey === replacement.resourceKey) ? resources.map((resource) => resource.resourceKey === replacement.resourceKey ? replacement : resource) : [...resources, replacement];
5800
+ function classifyError(status, code, message) {
5801
+ if (code === 234043) return "unsupported";
5802
+ if (code === 234005 || containsExpiredText(message)) return "expired";
5803
+ if (status === 401) return "authentication";
5804
+ if (status === 403) return "permission_denied";
5805
+ if (status === 429) return "rate_limited";
5806
+ if (status >= 500) return "unavailable";
5807
+ if (status >= 400) return "invalid_request";
5808
+ return "invalid_response";
5674
5809
  }
5675
- function initialState(scope) {
5676
- return {
5677
- version: LEDGER_VERSION,
5678
- scope: { ...scope },
5679
- activeTimeMs: 0,
5680
- reservedActiveTimeMs: 0,
5681
- retryAttempts: 0,
5682
- recoveryAttempts: 0,
5683
- bytes: 0,
5684
- reservedBytes: 0,
5685
- resources: [],
5686
- terminalCancelled: false
5687
- };
5810
+ /** Error bodies read `a ?? b` chains: a present value of the wrong type ends the chain without a value. */
5811
+ const errorFields = {
5812
+ code: chained(Schema.Union([Schema.Finite, Schema.String.check(Schema.isPattern(/^\d+$/))])),
5813
+ message: chained(Schema.String),
5814
+ msg: chained(Schema.String)
5815
+ };
5816
+ const decodeErrorBody = Schema.decodeUnknownOption(Schema.Struct({
5817
+ ...errorFields,
5818
+ data: tolerant(Schema.Struct(errorFields))
5819
+ }));
5820
+ function errorCode(value) {
5821
+ if (typeof value === "number") return value;
5822
+ const parsed = Number(value);
5823
+ return Number.isSafeInteger(parsed) ? parsed : void 0;
5688
5824
  }
5689
- function snapshotState(state) {
5690
- return {
5691
- version: LEDGER_VERSION,
5692
- scope: { ...state.scope },
5693
- activeTimeMs: state.activeTimeMs,
5694
- reservedActiveTimeMs: state.reservedActiveTimeMs,
5695
- retryAttempts: state.retryAttempts,
5696
- recoveryAttempts: state.recoveryAttempts,
5697
- bytes: state.bytes,
5698
- reservedBytes: state.reservedBytes,
5699
- resources: [...state.resources].sort((left, right) => left.resourceKey.localeCompare(right.resourceKey)).map((resource) => ({
5700
- resourceKey: resource.resourceKey,
5701
- status: resource.status,
5702
- attempts: resource.attempts,
5703
- recoveryAttempts: resource.recoveryAttempts,
5704
- activeTimeMs: resource.activeTimeMs,
5705
- bytes: resource.bytes,
5706
- reservedActiveTimeMs: resource.reservedActiveTimeMs,
5707
- reservedBytes: resource.reservedBytes,
5708
- ...resource.retryableFailure === void 0 ? {} : { retryableFailure: resource.retryableFailure },
5709
- ...resource.inFlight === void 0 ? {} : { inFlight: { ...resource.inFlight } }
5710
- })),
5711
- terminalCancelled: state.terminalCancelled
5825
+ function parseErrorDetails(body) {
5826
+ if (body === void 0 || body === "") return {
5827
+ code: void 0,
5828
+ message: void 0
5712
5829
  };
5713
- }
5714
- function cloneState(state) {
5715
- return snapshotState(state);
5716
- }
5717
- async function writeState(filePath, state) {
5718
- await writeAtomicTextFile(filePath, `${JSON.stringify(snapshotState(state))}\n`, { mode: 384 });
5719
- }
5720
- function feishuPreparationLedgerScopeDigest(scope) {
5721
- return createHash("sha256").update(JSON.stringify([
5722
- scope.tenantKey,
5723
- scope.endpointId,
5724
- scope.sessionGeneration,
5725
- scope.deliveryId
5726
- ])).digest("hex");
5727
- }
5728
- function pathFor(rootDirectory, scope) {
5729
- return join(rootDirectory, "feishu-preparation-ledger", `${feishuPreparationLedgerScopeDigest(scope)}.json`);
5730
- }
5731
- async function readLockOwner(lockPath) {
5830
+ let parsed;
5732
5831
  try {
5733
- const owner = Option.getOrUndefined(decodeLockOwner(JSON.parse(await readFile(lockPath, "utf8"))));
5734
- if (owner === void 0) return;
5832
+ parsed = JSON.parse(body);
5833
+ } catch {
5735
5834
  return {
5736
- pid: owner.pid,
5737
- token: owner.token,
5738
- createdAtMs: owner.createdAtMs ?? 0
5835
+ code: void 0,
5836
+ message: void 0
5739
5837
  };
5740
- } catch (error) {
5741
- if (isNodeErrorWithCode(error, "ENOENT")) return;
5742
- throw error;
5743
5838
  }
5839
+ const value = Option.getOrUndefined(decodeErrorBody(parsed));
5840
+ const code = value?.code ?? value?.data?.code;
5841
+ const message = value?.msg ?? value?.message ?? value?.data?.msg ?? value?.data?.message;
5842
+ return {
5843
+ code: code === void 0 || code === null || code === INVALID ? void 0 : errorCode(code),
5844
+ message: message === void 0 || message === null || message === INVALID ? void 0 : message.slice(0, 512)
5845
+ };
5744
5846
  }
5745
- async function releaseFileLock(lock) {
5746
- try {
5747
- if ((await readLockOwner(lock.path))?.token === lock.token) await unlink(lock.path).catch((error) => {
5748
- if (!isNodeErrorWithCode(error, "ENOENT")) throw error;
5749
- });
5750
- } finally {
5751
- await lock.handle.close();
5752
- }
5847
+ function errorFromJson(body, status) {
5848
+ const details = parseErrorDetails(body);
5849
+ return createProtocolError(classifyError(status, details.code, details.message), status, details.code, void 0);
5753
5850
  }
5754
- function isProcessAlive(pid) {
5755
- try {
5756
- process.kill(pid, 0);
5757
- return true;
5758
- } catch (error) {
5759
- return isNodeErrorWithCode(error, "EPERM");
5760
- }
5851
+ async function cancelBody(body) {
5852
+ if (body !== null) await body.cancel().catch(() => void 0);
5761
5853
  }
5762
- async function reclaimStaleLock(lockPath, staleLockMs) {
5763
- let information;
5764
- try {
5765
- information = await stat(lockPath);
5766
- } catch (error) {
5767
- if (isNodeErrorWithCode(error, "ENOENT")) return true;
5768
- throw error;
5769
- }
5770
- if (Date.now() - information.mtimeMs < staleLockMs) return false;
5771
- const owner = await readLockOwner(lockPath);
5772
- if (owner && isProcessAlive(owner.pid)) return false;
5773
- try {
5774
- await unlink(lockPath);
5775
- return true;
5776
- } catch (error) {
5777
- if (isNodeErrorWithCode(error, "ENOENT")) return true;
5778
- throw error;
5779
- }
5854
+ function normalizeMimeType(header) {
5855
+ if (header === null) return;
5856
+ const mimeType = header.split(";", 1)[0]?.trim().toLowerCase();
5857
+ return mimeType === void 0 || mimeType === "" ? void 0 : mimeType;
5780
5858
  }
5781
- function delay(milliseconds, signal) {
5782
- return new Promise((resolvePromise, reject) => {
5783
- const timer = setTimeout(() => {
5784
- signal?.removeEventListener("abort", onAbort);
5785
- resolvePromise();
5786
- }, milliseconds);
5787
- function onAbort() {
5788
- clearTimeout(timer);
5789
- signal?.removeEventListener("abort", onAbort);
5790
- reject(/* @__PURE__ */ new Error("ledger operation aborted"));
5791
- }
5792
- if (signal?.aborted) onAbort();
5793
- else signal?.addEventListener("abort", onAbort, { once: true });
5794
- });
5859
+ function isJsonMimeType(mimeType) {
5860
+ return mimeType === "application/json" || mimeType === "text/json" || mimeType?.endsWith("+json") === true;
5795
5861
  }
5796
- async function acquireFileLock(lockPath, options) {
5797
- await mkdir(dirname(lockPath), { recursive: true });
5798
- const deadline = Date.now() + options.lockTimeoutMs;
5799
- while (true) {
5800
- if (options.signal?.aborted) throw new Error("ledger operation aborted");
5801
- let handle;
5802
- try {
5803
- handle = await open(lockPath, "wx", 384);
5804
- const owner = {
5805
- pid: process.pid,
5806
- token: randomUUID(),
5807
- createdAtMs: Date.now()
5808
- };
5809
- await handle.writeFile(JSON.stringify(owner), "utf8");
5810
- await handle.sync();
5811
- return {
5812
- handle,
5813
- path: lockPath,
5814
- token: owner.token
5815
- };
5816
- } catch (error) {
5817
- await handle?.close().catch(() => void 0);
5818
- if (!isNodeErrorWithCode(error, "EEXIST")) throw error;
5819
- if (await reclaimStaleLock(lockPath, options.staleLockMs)) continue;
5820
- if (Date.now() >= deadline) throw new FeishuPreparationLedgerError("lock_timeout", "ledger lock could not be acquired");
5821
- await delay(options.lockRetryMs, options.signal);
5822
- }
5823
- }
5862
+ function isAttachmentResponse(response, resourceType) {
5863
+ if (resourceType !== "file") return false;
5864
+ const disposition = response.headers.get("content-disposition");
5865
+ return disposition !== null && /(?:^|;)\s*attachment(?:;|$)/i.test(disposition);
5824
5866
  }
5825
- async function withFileLock(statePath, options, operation) {
5826
- const lock = await acquireFileLock(`${statePath}.lock`, options);
5827
- let operationOutcome;
5828
- try {
5829
- operationOutcome = {
5830
- ok: true,
5831
- value: await operation()
5832
- };
5833
- } catch (error) {
5834
- operationOutcome = {
5835
- ok: false,
5836
- error
5837
- };
5838
- }
5839
- let releaseOutcome;
5840
- try {
5841
- await releaseFileLock(lock);
5842
- releaseOutcome = { ok: true };
5843
- } catch (error) {
5844
- releaseOutcome = {
5845
- ok: false,
5846
- error
5847
- };
5867
+ function parseContentLength(header) {
5868
+ if (header === null || !/^\d+$/.test(header.trim())) return;
5869
+ const value = Number(header);
5870
+ return Number.isSafeInteger(value) ? value : void 0;
5871
+ }
5872
+ function parseRetryAfter(header) {
5873
+ if (header === null) return;
5874
+ const value = header.trim();
5875
+ if (/^\d+$/.test(value)) {
5876
+ const seconds = Number(value);
5877
+ return Number.isSafeInteger(seconds) ? seconds * 1e3 : void 0;
5848
5878
  }
5849
- if (!operationOutcome.ok) throw operationOutcome.error;
5850
- if (!releaseOutcome.ok) throw releaseOutcome.error;
5851
- return operationOutcome.value;
5879
+ const timestamp = Date.parse(value);
5880
+ if (!Number.isFinite(timestamp)) return;
5881
+ return Math.max(0, timestamp - Date.now());
5852
5882
  }
5853
- function withFeishuPreparationLedgerScopeLock(options, operation) {
5854
- if (options.signal?.aborted) return Promise.reject(/* @__PURE__ */ new Error("ledger operation aborted"));
5855
- const statePath = pathFor(validateRootDirectory(options.rootDirectory), normalizeScope(options.scope));
5856
- return withFileLock(statePath, {
5857
- lockRetryMs: DEFAULT_LOCK_RETRY_MS,
5858
- lockTimeoutMs: DEFAULT_LOCK_TIMEOUT_MS,
5859
- staleLockMs: DEFAULT_STALE_LOCK_MS,
5860
- ...options.signal === void 0 ? {} : { signal: options.signal }
5861
- }, async () => {
5862
- if (options.signal?.aborted) throw new Error("ledger operation aborted");
5863
- return operation(statePath);
5864
- });
5883
+ function startsWith(bytes, expected) {
5884
+ if (bytes.byteLength < expected.length) return false;
5885
+ return expected.every((value, index) => bytes[index] === value);
5865
5886
  }
5866
- function safeFeishuPreparationClock(clock) {
5867
- const value = clock();
5868
- return Number.isSafeInteger(value) && value >= 0 ? value : Date.now();
5887
+ function startsWithAscii(bytes, expected) {
5888
+ if (bytes.byteLength < expected.length) return false;
5889
+ return expected.split("").every((value, index) => bytes[index] === value.charCodeAt(0));
5869
5890
  }
5870
- function positiveInteger$3(value, label) {
5871
- if (value === void 0 || !Number.isSafeInteger(value) || value < 1) throw new FeishuPreparationLedgerError("invalid_request", `${label} must be a positive integer`);
5872
- return value;
5891
+ function hasSupportedImageSignature(bytes, mimeType) {
5892
+ if (startsWith(bytes, [
5893
+ 137,
5894
+ 80,
5895
+ 78,
5896
+ 71,
5897
+ 13,
5898
+ 10,
5899
+ 26,
5900
+ 10
5901
+ ])) return mimeType === "image/png";
5902
+ if (startsWith(bytes, [
5903
+ 255,
5904
+ 216,
5905
+ 255
5906
+ ])) return mimeType === "image/jpeg" || mimeType === "image/jpg";
5907
+ if (startsWithAscii(bytes, "GIF87a") || startsWithAscii(bytes, "GIF89a")) return mimeType === "image/gif";
5908
+ if (startsWithAscii(bytes, "RIFF") && startsWithAscii(bytes.slice(8), "WEBP")) return mimeType === "image/webp";
5909
+ if (startsWithAscii(bytes, "BM")) return mimeType === "image/bmp" || mimeType === "image/x-ms-bmp";
5910
+ if (startsWith(bytes, [
5911
+ 73,
5912
+ 73,
5913
+ 42,
5914
+ 0
5915
+ ]) || startsWith(bytes, [
5916
+ 77,
5917
+ 77,
5918
+ 0,
5919
+ 42
5920
+ ])) return mimeType === "image/tiff";
5921
+ if (startsWithAscii(bytes.slice(4), "ftypavif")) return mimeType === "image/avif";
5922
+ if (mimeType === "image/svg+xml") {
5923
+ const prefix = new TextDecoder().decode(bytes.slice(0, Math.min(bytes.byteLength, 4096)));
5924
+ return /^\uFEFF?\s*(?:<\?xml[^>]*>\s*)?<svg(?:\s|>)/i.test(prefix);
5925
+ }
5926
+ return false;
5873
5927
  }
5874
- function normalizeLimits$1(limits) {
5875
- return {
5876
- totalBytes: positiveInteger$3(limits.totalBytes, "total bytes"),
5877
- totalActiveTimeMs: positiveInteger$3(limits.totalActiveTimeMs, "total active time"),
5878
- maxAttemptsPerResource: positiveInteger$3(limits.maxAttemptsPerResource, "attempt count")
5879
- };
5928
+ function addAbortListener(signal, listener) {
5929
+ if (signal === void 0) return () => void 0;
5930
+ signal.addEventListener("abort", listener, { once: true });
5931
+ return () => signal.removeEventListener("abort", listener);
5880
5932
  }
5881
- function validateReservationInput(input) {
5882
- if (input.resourceKey.trim() === "" || input.resourceKey.length > 1024) throw new FeishuPreparationLedgerError("invalid_request", "resource key is invalid");
5883
- positiveInteger$3(input.byteReservation, "byte reservation");
5884
- positiveInteger$3(input.timeReservationMs, "time reservation");
5885
- return input;
5933
+ function isAbortError(error) {
5934
+ return error instanceof Error && error.name === "AbortError";
5886
5935
  }
5887
- function nonNegativeInteger$1(value, label) {
5888
- if (value === void 0 || !Number.isSafeInteger(value) || value < 0) throw new FeishuPreparationLedgerError("corrupt", `${label} must be a non-negative integer`);
5889
- return value;
5936
+ function invalidRequestError(message) {
5937
+ return new FeishuResourceReadError({
5938
+ classification: "invalid_request",
5939
+ message
5940
+ });
5890
5941
  }
5891
- function validateReservation(value) {
5892
- if (value.id.length === 0) throw new FeishuPreparationLedgerError("invalid_request", "reservation is invalid");
5893
- validateReservationInput(value);
5894
- nonNegativeInteger$1(value.attemptNumber, "attempt number");
5895
- if (!Number.isSafeInteger(value.startedAtMs) || value.startedAtMs < 0) throw new FeishuPreparationLedgerError("invalid_request", "reservation start time is invalid");
5896
- return value;
5942
+ function validateBaseUrl(baseUrl) {
5943
+ let parsed;
5944
+ try {
5945
+ parsed = new URL(baseUrl);
5946
+ } catch {
5947
+ throw invalidRequestError("Feishu base URL is invalid");
5948
+ }
5949
+ if (parsed.protocol !== "http:" && parsed.protocol !== "https:") throw invalidRequestError("Feishu base URL must use HTTP or HTTPS");
5950
+ if (parsed.username !== "" || parsed.password !== "") throw invalidRequestError("Feishu base URL must not contain credentials");
5951
+ if (parsed.search !== "" || parsed.hash !== "" || parsed.pathname !== "" && parsed.pathname !== "/") throw invalidRequestError("Feishu base URL must not contain a path or query");
5952
+ return parsed.origin;
5953
+ }
5954
+ function validateInput$1(input) {
5955
+ const identifiers = decodeIdentifiers(input);
5956
+ if (identifiers.messageId === void 0) return invalidRequestError("Feishu message ID is required");
5957
+ if (identifiers.resourceKey === void 0) return invalidRequestError("Feishu resource key is required");
5958
+ if (input.messageId === "." || input.messageId === ".." || input.resourceKey === "." || input.resourceKey === "..") return invalidRequestError("Feishu resource identifier is invalid");
5959
+ if (!Number.isSafeInteger(input.maxBytes) || input.maxBytes <= 0) return invalidRequestError("Feishu resource byte limit is invalid");
5897
5960
  }
5898
- function validateCompletion(value) {
5899
- if (!hasValidCompletionMarker(value)) throw new FeishuPreparationLedgerError("invalid_request", "retryable failure marker is invalid");
5900
- if (value.retryableFailure !== void 0 && value.status !== "failed") throw new FeishuPreparationLedgerError("invalid_request", "retryable failure marker requires a failed completion");
5901
- nonNegativeInteger$1(value.bytes, "actual bytes");
5902
- nonNegativeInteger$1(value.activeTimeMs, "actual active time");
5903
- return value;
5961
+ function cancelledError$1(consumedBytes) {
5962
+ return new FeishuResourceReadError({
5963
+ classification: "cancelled",
5964
+ message: "Feishu resource request was cancelled",
5965
+ ...consumedBytes === void 0 ? {} : { consumedBytes }
5966
+ });
5904
5967
  }
5905
- function validateInFlight(value) {
5906
- if (value === INVALID || value.id === void 0) throw new FeishuPreparationLedgerError("corrupt", "ledger reservation marker is invalid");
5907
- if (value.kind === void 0) throw new FeishuPreparationLedgerError("corrupt", "ledger reservation kind is invalid");
5908
- return {
5909
- id: value.id,
5910
- kind: value.kind,
5911
- byteReservation: positiveInteger$3(value.byteReservation, "reservation bytes"),
5912
- timeReservationMs: positiveInteger$3(value.timeReservationMs, "reservation time"),
5913
- startedAtMs: nonNegativeInteger$1(value.startedAtMs, "reservation start time"),
5914
- attemptNumber: nonNegativeInteger$1(value.attemptNumber, "reservation attempt")
5915
- };
5968
+ function toResourceError(error, signal) {
5969
+ if (error instanceof FeishuResourceReadError) return error;
5970
+ if (signal?.aborted === true || isAbortError(error)) return cancelledError$1();
5971
+ return new FeishuResourceReadError({
5972
+ classification: "network",
5973
+ message: "Feishu resource request failed"
5974
+ });
5916
5975
  }
5917
- function validateResourceState(value, limits) {
5918
- if (value === INVALID || value.resourceKey === void 0) throw new FeishuPreparationLedgerError("corrupt", "ledger resource is invalid");
5919
- const status = value.status;
5920
- if (status === void 0) throw new FeishuPreparationLedgerError("corrupt", "ledger resource status is invalid");
5921
- const attempts = nonNegativeInteger$1(value.attempts, "resource attempts");
5922
- const recoveryAttempts = nonNegativeInteger$1(value.recoveryAttempts, "resource recovery attempts");
5923
- const activeTimeMs = nonNegativeInteger$1(value.activeTimeMs, "resource active time");
5924
- const bytes = nonNegativeInteger$1(value.bytes, "resource bytes");
5925
- const reservedActiveTimeMs = nonNegativeInteger$1(value.reservedActiveTimeMs, "resource reserved active time");
5926
- const reservedBytes = nonNegativeInteger$1(value.reservedBytes, "resource reserved bytes");
5927
- if (value.retryableFailure === INVALID) throw new FeishuPreparationLedgerError("corrupt", "ledger retryable failure marker is invalid");
5928
- if (value.retryableFailure !== void 0 && status !== "failed") throw new FeishuPreparationLedgerError("corrupt", "ledger retryable failure marker requires a failed resource");
5929
- if (attempts > limits.maxAttemptsPerResource || recoveryAttempts > 1) throw new FeishuPreparationLedgerError("corrupt", "ledger resource attempt budget is invalid");
5930
- const inFlight = value.inFlight === void 0 ? void 0 : validateInFlight(value.inFlight);
5931
- if (status === "in_flight" !== (inFlight !== void 0)) throw new FeishuPreparationLedgerError("corrupt", "ledger in-flight marker does not match status");
5932
- if (inFlight === void 0 && (reservedActiveTimeMs !== 0 || reservedBytes !== 0)) throw new FeishuPreparationLedgerError("corrupt", "ledger has reservation credit without marker");
5933
- if (inFlight && (reservedActiveTimeMs !== inFlight.timeReservationMs || reservedBytes !== inFlight.byteReservation)) throw new FeishuPreparationLedgerError("corrupt", "ledger reservation marker does not match credit");
5934
- return {
5935
- resourceKey: value.resourceKey,
5936
- status,
5937
- attempts,
5938
- recoveryAttempts,
5939
- activeTimeMs,
5940
- bytes,
5941
- reservedActiveTimeMs,
5942
- reservedBytes,
5943
- ...value.retryableFailure === void 0 ? {} : { retryableFailure: value.retryableFailure },
5944
- ...inFlight === void 0 ? {} : { inFlight }
5976
+ function tooLargeError(status, consumedBytes) {
5977
+ const options = {
5978
+ classification: "too_large",
5979
+ message: "Feishu resource exceeded the configured byte limit"
5945
5980
  };
5981
+ if (status !== void 0) Object.assign(options, { status });
5982
+ if (consumedBytes !== void 0) Object.assign(options, { consumedBytes });
5983
+ return new FeishuResourceReadError(options);
5946
5984
  }
5947
- function validateState$1(value, expectedScope, limits) {
5948
- const state = Option.getOrUndefined(decodeLedgerState(value));
5949
- if (state?.version === void 0 || state.scope === void 0) throw new FeishuPreparationLedgerError("corrupt", "ledger state version or scope is invalid");
5950
- const scope = scopeFields(state.scope);
5951
- if (scope.tenantKey !== expectedScope.tenantKey || scope.endpointId !== expectedScope.endpointId || scope.sessionGeneration !== expectedScope.sessionGeneration || scope.deliveryId !== expectedScope.deliveryId) throw new FeishuPreparationLedgerError("corrupt", "ledger scope does not match requested scope");
5952
- const activeTimeMs = nonNegativeInteger$1(state.activeTimeMs, "active time");
5953
- const reservedActiveTimeMs = nonNegativeInteger$1(state.reservedActiveTimeMs, "reserved active time");
5954
- const retryAttempts = nonNegativeInteger$1(state.retryAttempts, "retry attempts");
5955
- const recoveryAttempts = nonNegativeInteger$1(state.recoveryAttempts, "recovery attempts");
5956
- const bytes = nonNegativeInteger$1(state.bytes, "bytes");
5957
- const reservedBytes = nonNegativeInteger$1(state.reservedBytes, "reserved bytes");
5958
- if (activeTimeMs + reservedActiveTimeMs > limits.totalActiveTimeMs) throw new FeishuPreparationLedgerError("corrupt", "ledger active-time budget is invalid");
5959
- if (bytes + reservedBytes > limits.totalBytes) throw new FeishuPreparationLedgerError("corrupt", "ledger byte budget is invalid");
5960
- if (state.terminalCancelled === void 0 || state.resources === void 0) throw new FeishuPreparationLedgerError("corrupt", "ledger state fields are invalid");
5961
- const resources = state.resources.map((candidate) => validateResourceState(candidate, limits));
5962
- if (new Set(resources.map((resource) => resource.resourceKey)).size !== resources.length) throw new FeishuPreparationLedgerError("corrupt", "ledger contains duplicate resources");
5963
- const resourceReservedBytes = resources.reduce((total, resource) => total + resource.reservedBytes, 0);
5964
- const resourceReservedTime = resources.reduce((total, resource) => total + resource.reservedActiveTimeMs, 0);
5965
- if (resourceReservedBytes !== reservedBytes || resourceReservedTime !== reservedActiveTimeMs) throw new FeishuPreparationLedgerError("corrupt", "ledger reservation totals do not match resources");
5966
- return snapshotState({
5967
- version: LEDGER_VERSION,
5968
- scope,
5969
- activeTimeMs,
5970
- reservedActiveTimeMs,
5971
- retryAttempts,
5972
- recoveryAttempts,
5973
- bytes,
5974
- reservedBytes,
5975
- resources,
5976
- terminalCancelled: state.terminalCancelled
5985
+ function resourceErrorWithConsumedBytes(error, consumedBytes) {
5986
+ return new FeishuResourceReadError({
5987
+ classification: error.classification,
5988
+ ...error.code === void 0 ? {} : { code: error.code },
5989
+ ...error.retryAfterMs === void 0 ? {} : { retryAfterMs: error.retryAfterMs },
5990
+ ...error.status === void 0 ? {} : { status: error.status },
5991
+ consumedBytes,
5992
+ message: error.message
5977
5993
  });
5978
5994
  }
5979
- async function readFeishuPreparationLedgerState(filePath, scope, limits) {
5980
- const raw = await readPersistenceFile(filePath);
5981
- if (raw === void 0) return;
5982
- let value;
5995
+ async function readBoundedBytes(body, maxBytes, signal) {
5996
+ if (body === null) throw new FeishuResourceReadError({
5997
+ classification: "invalid_response",
5998
+ message: "Feishu resource response did not contain a body"
5999
+ });
6000
+ const reader = body.getReader();
6001
+ const chunks = [];
6002
+ let total = 0;
6003
+ let aborted = signal.aborted;
6004
+ const onAbort = () => {
6005
+ aborted = true;
6006
+ reader.cancel().catch(() => void 0);
6007
+ };
6008
+ signal.addEventListener("abort", onAbort, { once: true });
6009
+ const isAborted = () => aborted || signal.aborted;
5983
6010
  try {
5984
- value = JSON.parse(raw);
5985
- } catch {
5986
- throw new FeishuPreparationLedgerError("corrupt", "ledger state is not valid JSON");
6011
+ while (true) {
6012
+ if (isAborted()) throw cancelledError$1(total);
6013
+ let readResult;
6014
+ try {
6015
+ readResult = await reader.read();
6016
+ } catch (error) {
6017
+ if (isAborted()) throw cancelledError$1(total);
6018
+ throw error;
6019
+ }
6020
+ if (isAborted()) throw cancelledError$1(total);
6021
+ if (readResult.done) break;
6022
+ const chunk = readResult.value;
6023
+ if (chunk.byteLength > maxBytes - total) {
6024
+ await reader.cancel().catch(() => void 0);
6025
+ throw tooLargeError(void 0, maxBytes);
6026
+ }
6027
+ if (chunk.byteLength > 0) {
6028
+ chunks.push(chunk);
6029
+ total += chunk.byteLength;
6030
+ }
6031
+ }
6032
+ } catch (error) {
6033
+ await reader.cancel().catch(() => void 0);
6034
+ if (error instanceof FeishuResourceReadError) {
6035
+ if (error.consumedBytes !== void 0) throw error;
6036
+ throw resourceErrorWithConsumedBytes(error, total);
6037
+ }
6038
+ throw resourceErrorWithConsumedBytes(toResourceError(error, signal), maxBytes);
6039
+ } finally {
6040
+ signal.removeEventListener("abort", onAbort);
6041
+ reader.releaseLock();
5987
6042
  }
5988
- return validateState$1(value, scope, limits);
6043
+ const bytes = new Uint8Array(total);
6044
+ let offset = 0;
6045
+ for (const chunk of chunks) {
6046
+ bytes.set(chunk, offset);
6047
+ offset += chunk.byteLength;
6048
+ }
6049
+ return bytes;
5989
6050
  }
5990
- async function loadState(filePath, scope, limits) {
5991
- return await readFeishuPreparationLedgerState(filePath, scope, limits) ?? initialState(scope);
6051
+ async function readBoundedText(response, maxBytes, signal) {
6052
+ try {
6053
+ const bytes = await readBoundedBytes(response.body, maxBytes, signal);
6054
+ return new TextDecoder().decode(bytes);
6055
+ } catch (error) {
6056
+ if (error instanceof FeishuResourceReadError && error.classification === "cancelled") throw error;
6057
+ return;
6058
+ }
5992
6059
  }
5993
- function asLedgerError(error) {
5994
- if (error instanceof FeishuPreparationLedgerError) return error;
5995
- return new FeishuPreparationLedgerError("corrupt", "ledger persistence failed");
6060
+ async function errorFromResponse(response, signal) {
6061
+ const details = parseErrorDetails(await readBoundedText(response, ERROR_BODY_MAX_BYTES, signal));
6062
+ const classification = classifyError(response.status, details.code, details.message);
6063
+ const retryAfterMs = classification === "rate_limited" ? parseRetryAfter(response.headers.get("retry-after")) : void 0;
6064
+ return createProtocolError(classification, response.status, details.code, retryAfterMs);
5996
6065
  }
5997
- function createFeishuPreparationLedger(options) {
5998
- const rootDirectory = validateOptions(options);
5999
- const scope = normalizeScope(options.scope);
6000
- const limits = normalizeLimits$1(options.limits);
6001
- const clock = options.clock ?? Date.now;
6002
- const lockRetryMs = positiveInteger$3(options.lockRetryMs ?? DEFAULT_LOCK_RETRY_MS, "lock retry");
6003
- const lockTimeoutMs = positiveInteger$3(options.lockTimeoutMs ?? DEFAULT_LOCK_TIMEOUT_MS, "lock timeout");
6004
- const staleLockMs = positiveInteger$3(options.staleLockMs ?? DEFAULT_STALE_LOCK_MS, "stale lock");
6005
- const filePath = pathFor(rootDirectory, scope);
6006
- const serial = createSerialExecutor();
6007
- const runExclusive = (operation) => Effect.tryPromise({
6008
- try: () => serial.run(() => withFileLock(filePath, {
6009
- lockRetryMs,
6010
- lockTimeoutMs,
6011
- staleLockMs
6012
- }, async () => {
6013
- const mutation = await operation(await loadState(filePath, scope, limits));
6014
- if (mutation.write) await writeState(filePath, mutation.state);
6015
- return mutation.value;
6016
- })),
6017
- catch: asLedgerError
6066
+ async function fetchAndRead(fetchImpl, url, token, input, signal) {
6067
+ let response;
6068
+ try {
6069
+ response = await fetchImpl(url, {
6070
+ method: "GET",
6071
+ headers: { Authorization: "Bearer " + token },
6072
+ redirect: "manual",
6073
+ signal
6074
+ });
6075
+ } catch (error) {
6076
+ throw toResourceError(error, signal);
6077
+ }
6078
+ if (response.status >= 300 && response.status < 400) {
6079
+ await cancelBody(response.body);
6080
+ throw new FeishuResourceReadError({
6081
+ classification: "redirect",
6082
+ status: response.status,
6083
+ message: "Feishu resource endpoint returned a redirect"
6084
+ });
6085
+ }
6086
+ if (response.type === "opaqueredirect") {
6087
+ await cancelBody(response.body);
6088
+ throw new FeishuResourceReadError({
6089
+ classification: "redirect",
6090
+ message: "Feishu resource endpoint returned a redirect"
6091
+ });
6092
+ }
6093
+ if (response.status < 200 || response.status >= 300) throw await errorFromResponse(response, signal);
6094
+ const mimeType = normalizeMimeType(response.headers.get("content-type"));
6095
+ if (isJsonMimeType(mimeType) && !isAttachmentResponse(response, input.resourceType)) throw errorFromJson(await readBoundedText(response, ERROR_BODY_MAX_BYTES, signal), response.status);
6096
+ const declaredLength = parseContentLength(response.headers.get("content-length"));
6097
+ if (declaredLength !== void 0 && declaredLength > input.maxBytes) {
6098
+ await cancelBody(response.body);
6099
+ throw tooLargeError(response.status);
6100
+ }
6101
+ if (mimeType === void 0) {
6102
+ await cancelBody(response.body);
6103
+ throw new FeishuResourceReadError({
6104
+ classification: "invalid_response",
6105
+ status: response.status,
6106
+ message: "Feishu resource response did not declare a MIME type"
6107
+ });
6108
+ }
6109
+ const bytes = await readBoundedBytes(response.body, input.maxBytes, signal);
6110
+ if (bytes.byteLength === 0) throw new FeishuResourceReadError({
6111
+ classification: "invalid_response",
6112
+ status: response.status,
6113
+ message: "Feishu resource response was empty"
6114
+ });
6115
+ if (input.resourceType === "image" && (!mimeType.startsWith("image/") || !hasSupportedImageSignature(bytes, mimeType))) throw new FeishuResourceReadError({
6116
+ classification: "invalid_response",
6117
+ status: response.status,
6118
+ message: "Feishu image response MIME type or bytes did not match"
6018
6119
  });
6019
6120
  return {
6020
- read: () => runExclusive(async (state) => ({
6021
- state,
6022
- value: cloneState(state),
6023
- write: false
6024
- })),
6025
- reserve: (input) => {
6026
- const request = validateReservationInput(input);
6027
- return runExclusive(async (state) => {
6028
- if (state.terminalCancelled) throw new FeishuPreparationLedgerError("terminal_cancelled", "ledger is terminal");
6029
- const current = state.resources.find((resource) => resource.resourceKey === request.resourceKey);
6030
- if (current?.inFlight) throw new FeishuPreparationLedgerError("resource_unavailable", "resource already has an active reservation");
6031
- if (current?.status === "stored") throw new FeishuPreparationLedgerError("resource_unavailable", "resource is already stored");
6032
- if (current?.status === "cancelled") throw new FeishuPreparationLedgerError("resource_unavailable", "resource is cancelled");
6033
- if (request.kind === "download" && (current?.attempts ?? 0) >= limits.maxAttemptsPerResource) throw new FeishuPreparationLedgerError("budget_exhausted", "resource attempt budget is exhausted", "attempts");
6034
- if (request.kind === "recovery" && (current?.recoveryAttempts ?? 0) >= 1) throw new FeishuPreparationLedgerError("budget_exhausted", "resource recovery budget is exhausted", "recovery");
6035
- if (state.bytes + state.reservedBytes + request.byteReservation > limits.totalBytes) throw new FeishuPreparationLedgerError("budget_exhausted", "delivery byte budget is exhausted", "bytes");
6036
- if (state.activeTimeMs + state.reservedActiveTimeMs + request.timeReservationMs > limits.totalActiveTimeMs) throw new FeishuPreparationLedgerError("budget_exhausted", "delivery active-time budget is exhausted", "active_time");
6037
- const attemptNumber = (current?.attempts ?? 0) + (request.kind === "download" ? 1 : 0);
6038
- const recoveryAttempts = (current?.recoveryAttempts ?? 0) + (request.kind === "recovery" ? 1 : 0);
6039
- const startedAtMs = safeFeishuPreparationClock(clock);
6040
- const reservation = {
6041
- id: randomUUID(),
6042
- resourceKey: request.resourceKey,
6043
- kind: request.kind,
6044
- byteReservation: request.byteReservation,
6045
- timeReservationMs: request.timeReservationMs,
6046
- attemptNumber: request.kind === "download" ? attemptNumber : current?.attempts ?? 0,
6047
- startedAtMs
6048
- };
6049
- const resource = {
6050
- resourceKey: request.resourceKey,
6051
- status: "in_flight",
6052
- attempts: attemptNumber,
6053
- recoveryAttempts,
6054
- activeTimeMs: current?.activeTimeMs ?? 0,
6055
- bytes: current?.bytes ?? 0,
6056
- reservedActiveTimeMs: request.timeReservationMs,
6057
- reservedBytes: request.byteReservation,
6058
- inFlight: {
6059
- id: reservation.id,
6060
- kind: reservation.kind,
6061
- byteReservation: reservation.byteReservation,
6062
- timeReservationMs: reservation.timeReservationMs,
6063
- startedAtMs: reservation.startedAtMs,
6064
- attemptNumber: reservation.attemptNumber
6065
- }
6066
- };
6067
- return {
6068
- state: snapshotState({
6069
- ...state,
6070
- activeTimeMs: state.activeTimeMs,
6071
- reservedActiveTimeMs: state.reservedActiveTimeMs + request.timeReservationMs,
6072
- retryAttempts: state.retryAttempts + (request.kind === "download" ? 1 : 0),
6073
- recoveryAttempts: state.recoveryAttempts + (request.kind === "recovery" ? 1 : 0),
6074
- bytes: state.bytes,
6075
- reservedBytes: state.reservedBytes + request.byteReservation,
6076
- resources: replaceResource(state.resources, resource),
6077
- terminalCancelled: false
6078
- }),
6079
- value: reservation,
6080
- write: true
6081
- };
6082
- });
6083
- },
6084
- complete: (reservation, completion) => {
6085
- const checkedReservation = validateReservation(reservation);
6086
- const checkedCompletion = validateCompletion(completion);
6087
- return runExclusive(async (state) => {
6088
- const current = state.resources.find((resource) => resource.resourceKey === checkedReservation.resourceKey);
6089
- if (!current?.inFlight || current.inFlight.id !== checkedReservation.id) throw new FeishuPreparationLedgerError("reservation_not_found", "reservation is no longer active");
6090
- if (current.inFlight.kind !== checkedReservation.kind || current.inFlight.byteReservation !== checkedReservation.byteReservation || current.inFlight.timeReservationMs !== checkedReservation.timeReservationMs) throw new FeishuPreparationLedgerError("reservation_not_found", "reservation does not match persisted marker");
6091
- if (checkedCompletion.bytes > checkedReservation.byteReservation) throw new FeishuPreparationLedgerError("invalid_completion", "actual bytes exceed reserved bytes", "bytes");
6092
- if (checkedCompletion.activeTimeMs > checkedReservation.timeReservationMs) throw new FeishuPreparationLedgerError("invalid_completion", "active time exceeds reserved time", "active_time");
6093
- const resource = {
6094
- resourceKey: current.resourceKey,
6095
- status: checkedCompletion.status,
6096
- attempts: current.attempts,
6097
- recoveryAttempts: current.recoveryAttempts,
6098
- activeTimeMs: current.activeTimeMs + checkedCompletion.activeTimeMs,
6099
- bytes: current.bytes + checkedCompletion.bytes,
6100
- reservedActiveTimeMs: 0,
6101
- reservedBytes: 0,
6102
- ...checkedCompletion.status === "failed" && checkedCompletion.retryableFailure !== void 0 ? { retryableFailure: checkedCompletion.retryableFailure } : {}
6103
- };
6104
- const next = snapshotState({
6105
- ...state,
6106
- activeTimeMs: state.activeTimeMs + checkedCompletion.activeTimeMs,
6107
- reservedActiveTimeMs: state.reservedActiveTimeMs - checkedReservation.timeReservationMs,
6108
- bytes: state.bytes + checkedCompletion.bytes,
6109
- reservedBytes: state.reservedBytes - checkedReservation.byteReservation,
6110
- resources: replaceResource(state.resources, resource)
6111
- });
6112
- return {
6113
- state: next,
6114
- value: cloneState(next),
6115
- write: true
6116
- };
6117
- });
6118
- },
6119
- cancel: () => runExclusive(async (state) => {
6120
- if (state.terminalCancelled) return {
6121
- state,
6122
- value: cloneState(state),
6123
- write: false
6121
+ bytes,
6122
+ mimeType
6123
+ };
6124
+ }
6125
+ function readResource(baseUrl, fetchImpl, getTenantAccessToken, input) {
6126
+ const validationError = validateInput$1(input);
6127
+ if (validationError !== void 0) return Effect.fail(validationError);
6128
+ if (input.signal?.aborted === true) return Effect.fail(cancelledError$1());
6129
+ return Effect.gen(function* () {
6130
+ const token = yield* getTenantAccessToken().pipe(Effect.mapError(() => new FeishuResourceReadError({
6131
+ classification: "authentication",
6132
+ message: "Feishu tenant access token is unavailable"
6133
+ })));
6134
+ if (input.signal?.aborted === true) return yield* Effect.fail(cancelledError$1());
6135
+ return yield* Effect.callback((resume, effectSignal) => {
6136
+ const controller = new AbortController();
6137
+ const onAbort = () => controller.abort();
6138
+ const cleanupCaller = addAbortListener(input.signal, onAbort);
6139
+ const cleanupEffect = addAbortListener(effectSignal, onAbort);
6140
+ const cleanup = () => {
6141
+ cleanupCaller();
6142
+ cleanupEffect();
6124
6143
  };
6125
- const cancelledReservations = state.resources.reduce((totals, resource) => ({
6126
- activeTimeMs: totals.activeTimeMs + (resource.inFlight?.timeReservationMs ?? 0),
6127
- bytes: totals.bytes + (resource.inFlight?.byteReservation ?? 0)
6128
- }), {
6129
- activeTimeMs: 0,
6130
- bytes: 0
6131
- });
6132
- const resources = state.resources.map((resource) => {
6133
- if (!resource.inFlight) return resource;
6134
- return {
6135
- resourceKey: resource.resourceKey,
6136
- status: "cancelled",
6137
- attempts: resource.attempts,
6138
- recoveryAttempts: resource.recoveryAttempts,
6139
- activeTimeMs: resource.activeTimeMs + resource.inFlight.timeReservationMs,
6140
- bytes: resource.bytes + resource.inFlight.byteReservation,
6141
- reservedActiveTimeMs: 0,
6142
- reservedBytes: 0
6143
- };
6144
- });
6145
- const next = snapshotState({
6146
- ...state,
6147
- activeTimeMs: state.activeTimeMs + cancelledReservations.activeTimeMs,
6148
- bytes: state.bytes + cancelledReservations.bytes,
6149
- reservedActiveTimeMs: 0,
6150
- reservedBytes: 0,
6151
- resources,
6152
- terminalCancelled: true
6144
+ if (input.signal?.aborted === true || effectSignal.aborted === true) controller.abort();
6145
+ fetchAndRead(fetchImpl, buildResourceUrl(baseUrl, input), token, input, controller.signal).then((result) => resume(Effect.succeed(result)), (error) => resume(Effect.fail(toResourceError(error, controller.signal)))).finally(cleanup);
6146
+ return Effect.sync(() => {
6147
+ cleanup();
6148
+ controller.abort();
6153
6149
  });
6154
- return {
6155
- state: next,
6156
- value: cloneState(next),
6157
- write: true
6158
- };
6159
- })
6160
- };
6150
+ });
6151
+ });
6152
+ }
6153
+ /**
6154
+ * Creates the one-request reader used by the gateway's attachment preparation
6155
+ * boundary. Retries, persistence, and attachment IDs belong to the caller.
6156
+ */
6157
+ function createFeishuMessageResourceReader(options) {
6158
+ const baseUrl = validateBaseUrl(options.baseUrl);
6159
+ const fetchImpl = options.fetch ?? globalThis.fetch;
6160
+ return { read: (input) => readResource(baseUrl, fetchImpl, options.getTenantAccessToken, input) };
6161
6161
  }
6162
6162
  const FEISHU_MATERIALIZED_INPUT_MARKER_SUFFIX = ".rivus-input.json";
6163
6163
  function feishuMaterializedInputMarkerPath(path) {
@@ -10098,41 +10098,6 @@ function createJsonFetchRequest(options = {}) {
10098
10098
  });
10099
10099
  }
10100
10100
  //#endregion
10101
- //#region src/feishu/infra/adapters/conversation-session/feishu-session-key.ts
10102
- var InvalidFeishuSessionReference = class {
10103
- field;
10104
- message;
10105
- _tag = "InvalidFeishuSessionReference";
10106
- constructor(field, message) {
10107
- this.field = field;
10108
- this.message = message;
10109
- }
10110
- };
10111
- function requireField(fields, field) {
10112
- const value = fields[field];
10113
- if (value === void 0) return Effect.fail(new InvalidFeishuSessionReference(field, `${field} is required`));
10114
- return Effect.succeed(value);
10115
- }
10116
- function encodeSegment(value) {
10117
- return encodeURIComponent(value);
10118
- }
10119
- function conversationIdOf(fields) {
10120
- return Effect.gen(function* () {
10121
- const tenantKey = yield* requireField(fields, "tenantKey");
10122
- const chatId = yield* requireField(fields, "chatId");
10123
- const threadId = fields.threadId ?? "root";
10124
- return `feishu:${encodeSegment(tenantKey)}:${encodeSegment(chatId)}:${encodeSegment(threadId)}`;
10125
- });
10126
- }
10127
- function createFeishuSessionKey(fields) {
10128
- return Effect.gen(function* () {
10129
- return `${yield* conversationIdOf(fields)}:${encodeSegment(yield* requireField(fields, "agentId"))}`;
10130
- });
10131
- }
10132
- function createFeishuConversationId(fields) {
10133
- return conversationIdOf(fields);
10134
- }
10135
- //#endregion
10136
10101
  //#region src/feishu/infra/adapters/conversation-session/feishu-session-store.ts
10137
10102
  function asError$1(error) {
10138
10103
  return error instanceof Error ? error : new Error(String(error));
@@ -11438,38 +11403,6 @@ function createRunPresentationProjector() {
11438
11403
  };
11439
11404
  }
11440
11405
  //#endregion
11441
- //#region src/presentation/infra/repository/in-memory-card-delivery-repository.ts
11442
- function cloneRecord(record) {
11443
- return { ...requireTransitionResult(validateCardDeliveryRecord(record)) };
11444
- }
11445
- function cloneOptional(record) {
11446
- return record === void 0 ? void 0 : cloneRecord(record);
11447
- }
11448
- function createInMemoryCardDeliveryRepository(options = {}) {
11449
- const records = new Map(options.initial?.map((record) => [record.runId, cloneRecord(record)]) ?? []);
11450
- const semaphore = Semaphore.makeUnsafe(1);
11451
- return {
11452
- get: (runId) => cloneOptional(records.get(runId)),
11453
- transact: (runId, decide) => semaphore.withPermits(1)(Effect.uninterruptible(Effect.gen(function* () {
11454
- const current = cloneOptional(records.get(runId));
11455
- const decision = yield* Effect.try({
11456
- try: () => decide(current),
11457
- catch: (error) => error
11458
- });
11459
- if (!("next" in decision)) return decision.result;
11460
- const next = yield* Effect.try({
11461
- try: () => requireTransitionResult(validateCardDeliveryTransition(current, decision.next)),
11462
- catch: (error) => error
11463
- });
11464
- yield* options.persist?.(cloneRecord(next)) ?? Effect.void;
11465
- yield* Effect.sync(() => {
11466
- records.set(runId, cloneRecord(next));
11467
- });
11468
- return decision.result;
11469
- })))
11470
- };
11471
- }
11472
- //#endregion
11473
11406
  //#region src/presentation/infra/repository/in-memory-card-presentation-repository.ts
11474
11407
  function cloneAndValidate(chains) {
11475
11408
  const runIds = /* @__PURE__ */ new Set();
@@ -11630,6 +11563,38 @@ function openJsonCardPresentationRepository(options) {
11630
11563
  })));
11631
11564
  }
11632
11565
  //#endregion
11566
+ //#region src/presentation/infra/repository/in-memory-card-delivery-repository.ts
11567
+ function cloneRecord(record) {
11568
+ return { ...requireTransitionResult(validateCardDeliveryRecord(record)) };
11569
+ }
11570
+ function cloneOptional(record) {
11571
+ return record === void 0 ? void 0 : cloneRecord(record);
11572
+ }
11573
+ function createInMemoryCardDeliveryRepository(options = {}) {
11574
+ const records = new Map(options.initial?.map((record) => [record.runId, cloneRecord(record)]) ?? []);
11575
+ const semaphore = Semaphore.makeUnsafe(1);
11576
+ return {
11577
+ get: (runId) => cloneOptional(records.get(runId)),
11578
+ transact: (runId, decide) => semaphore.withPermits(1)(Effect.uninterruptible(Effect.gen(function* () {
11579
+ const current = cloneOptional(records.get(runId));
11580
+ const decision = yield* Effect.try({
11581
+ try: () => decide(current),
11582
+ catch: (error) => error
11583
+ });
11584
+ if (!("next" in decision)) return decision.result;
11585
+ const next = yield* Effect.try({
11586
+ try: () => requireTransitionResult(validateCardDeliveryTransition(current, decision.next)),
11587
+ catch: (error) => error
11588
+ });
11589
+ yield* options.persist?.(cloneRecord(next)) ?? Effect.void;
11590
+ yield* Effect.sync(() => {
11591
+ records.set(runId, cloneRecord(next));
11592
+ });
11593
+ return decision.result;
11594
+ })))
11595
+ };
11596
+ }
11597
+ //#endregion
11633
11598
  //#region src/presentation/infra/models/card-delivery-snapshot-codec.ts
11634
11599
  const cardDeliveryRecordSchema = Schema.Struct({
11635
11600
  revision: Schema.Int.check(Schema.isGreaterThan(0)),
@@ -12162,334 +12127,87 @@ function feishuActionsFromPresentation(input) {
12162
12127
  case "agent_run_completed": return [{
12163
12128
  ...hasProgress ? { presentation } : {},
12164
12129
  runId,
12165
- text: presentation?.answer.text.trim() || input.text || "",
12166
- type: "finish"
12167
- }];
12168
- case "agent_run_failed": return [{
12169
- errorMessage: input.errorMessage ?? "",
12170
- ...hasProgress ? { presentation } : {},
12171
- runId,
12172
- type: "fail"
12173
- }];
12174
- case "agent_run_cancelled": return [{
12175
- ...hasProgress ? { presentation } : {},
12176
- ...input.reason ? { reason: input.reason } : {},
12177
- runId,
12178
- type: "cancel"
12179
- }];
12180
- }
12181
- }
12182
- function createFeishuStreamProjector() {
12183
- const presentations = createRunPresentationProjector();
12184
- const applyEvent = (event, canonicalText) => {
12185
- const presentation = presentations.apply(event, canonicalText);
12186
- const text = event.type === "assistant_text_delta" ? event.delta : event.type === "agent_run_completed" ? canonicalText ?? event.finalText : void 0;
12187
- const errorMessage = event.type === "agent_run_failed" ? event.errorMessage : void 0;
12188
- const reason = event.type === "agent_run_cancelled" ? event.reason : void 0;
12189
- return feishuActionsFromPresentation({
12190
- eventType: event.type,
12191
- runId: event.runId,
12192
- ...presentation !== void 0 ? { presentation } : {},
12193
- ...text !== void 0 ? { text } : {},
12194
- ...errorMessage !== void 0 ? { errorMessage } : {},
12195
- ...reason !== void 0 ? { reason } : {}
12196
- });
12197
- };
12198
- return {
12199
- apply: (event) => applyEvent(event),
12200
- applyUpdate: ({ event, state }) => event.type === "agent_run_failed" ? applyEvent({
12201
- ...event,
12202
- errorMessage: state.errorMessage ?? event.errorMessage
12203
- }, state.finalText) : event.type === "agent_run_cancelled" ? applyEvent(state.cancellationReason ? {
12204
- ...event,
12205
- reason: state.cancellationReason
12206
- } : event, state.finalText) : applyEvent(event, state.finalText)
12207
- };
12208
- }
12209
- //#endregion
12210
- //#region src/feishu/infra/adapters/delivery/feishu-card-delivery-ledger.ts
12211
- function createFeishuCardDeliveryLedger(options = {}) {
12212
- const persist = options.persist;
12213
- return createInMemoryCardDeliveryLedger({
12214
- ...options.initial === void 0 ? {} : { initial: options.initial },
12215
- ...persist === void 0 ? {} : { persist: (record) => Effect.tryPromise({
12216
- try: () => persist(record),
12217
- catch: (error) => error
12218
- }) }
12219
- });
12220
- }
12221
- function createFeishuCardDeliveryReconciler(options) {
12222
- return { reconcile: () => Effect.gen(function* () {
12223
- const projector = createFeishuStreamProjector();
12224
- const terminalByRun = /* @__PURE__ */ new Map();
12225
- for (const event of options.events) for (const action of projector.apply(event)) if (action.type === "cancel" || action.type === "fail" || action.type === "finish") terminalByRun.set(action.runId, action);
12226
- let repaired = 0;
12227
- let skipped = 0;
12228
- for (const [runId, action] of terminalByRun) {
12229
- if (options.ledger.isTerminalPublished(runId)) continue;
12230
- yield* options.publish(action).pipe(Effect.catch((error) => {
12231
- if (error instanceof FeishuCardTargetNotFound) {
12232
- skipped += 1;
12233
- return Effect.void;
12234
- }
12235
- return Effect.fail(error);
12236
- }));
12237
- yield* options.ledger.markTerminal(runId);
12238
- repaired += 1;
12239
- }
12240
- return {
12241
- repaired,
12242
- skipped,
12243
- terminalRuns: terminalByRun.size
12244
- };
12245
- }) };
12246
- }
12247
- //#endregion
12248
- //#region src/feishu/infra/adapters/delivery/feishu-cardkit-openapi-client.ts
12249
- function isStreamingClosed(error) {
12250
- return error instanceof FeishuOpenApiError && (error.code === 200850 || error.code === 300309);
12251
- }
12252
- function replaceCard(baseUrl, cardId, sequence, card, call) {
12253
- return call({
12254
- body: {
12255
- card: {
12256
- data: JSON.stringify(card),
12257
- type: "card_json"
12258
- },
12259
- sequence
12260
- },
12261
- method: "PUT",
12262
- url: `${baseUrl}/open-apis/cardkit/v1/cards/${encodeURIComponent(cardId)}`
12263
- });
12264
- }
12265
- function updateRunningCard(baseUrl, agentName, request, call, progressDisplay, cancelButton) {
12266
- const card = createFeishuAgentRunCard({
12267
- agentName,
12268
- ...cancelButton === void 0 ? {} : { cancelButton },
12269
- ...request.presentation === void 0 ? {} : { presentation: request.presentation },
12270
- ...progressDisplay === void 0 ? {} : { progressDisplay },
12271
- runId: request.runId,
12272
- sessionKey: request.sessionKey,
12273
- status: "running",
12274
- ...request.text === void 0 ? {} : { text: request.text }
12275
- });
12276
- return replaceCard(baseUrl, request.cardId, request.sequence, card, call);
12277
- }
12278
- function updateWholeCard(baseUrl, agentName, request, status, call, progressDisplay) {
12279
- const requestText = "text" in request ? request.text : void 0;
12280
- const requestPresentation = "presentation" in request ? request.presentation : void 0;
12281
- const card = status === "completed" ? createFeishuAgentRunCard({
12282
- agentName,
12283
- ...requestPresentation === void 0 ? {} : { presentation: requestPresentation },
12284
- ...progressDisplay === void 0 ? {} : { progressDisplay },
12285
- status,
12286
- text: requestText ?? ""
12287
- }) : status === "cancelled" ? createFeishuAgentRunCard({
12288
- agentName,
12289
- ...requestPresentation === void 0 ? {} : { presentation: requestPresentation },
12290
- ...progressDisplay === void 0 ? {} : { progressDisplay },
12291
- ..."reason" in request && request.reason ? { reason: request.reason } : {},
12292
- status,
12293
- ...requestText === void 0 ? {} : { text: requestText }
12294
- }) : createFeishuAgentRunCard({
12295
- agentName,
12296
- ...requestPresentation === void 0 ? {} : { presentation: requestPresentation },
12297
- ...progressDisplay === void 0 ? {} : { progressDisplay },
12298
- status
12299
- });
12300
- return replaceCard(baseUrl, request.cardId, request.sequence, card, call);
12301
- }
12302
- function createFeishuCardKitOpenApiClient(options) {
12303
- const baseUrl = (options.baseUrl ?? "https://open.feishu.cn").replace(/\/$/, "");
12304
- const agentName = options.agentName ?? "Rivus Agent";
12305
- const streamingClosedCards = /* @__PURE__ */ new Set();
12306
- const call = (request) => options.client.request(request).pipe(Effect.asVoid);
12307
- const updateTerminal = (request, status) => updateWholeCard(baseUrl, agentName, request, status, call, options.progressDisplay).pipe(Effect.tap(() => Effect.sync(() => streamingClosedCards.delete(request.cardId))));
12308
- const publishStreamingUpdate = (cardId, update) => {
12309
- if (streamingClosedCards.has(cardId)) return Effect.void;
12310
- return update.pipe(Effect.catch((error) => {
12311
- if (!isStreamingClosed(error)) return Effect.fail(error);
12312
- return Effect.sync(() => {
12313
- streamingClosedCards.add(cardId);
12314
- options.onStreamingClosed?.(cardId);
12315
- });
12316
- }));
12317
- };
12318
- return {
12319
- cancel: (request) => updateTerminal(request, "cancelled"),
12320
- fail: (request) => updateTerminal(request, "failed"),
12321
- finish: (request) => updateTerminal(request, "completed"),
12322
- updatePresentation: (request) => publishStreamingUpdate(request.cardId, updateRunningCard(baseUrl, agentName, request, call, options.progressDisplay, options.cancelButton)),
12323
- updateText: (request) => publishStreamingUpdate(request.cardId, call({
12324
- body: {
12325
- content: request.content,
12326
- sequence: request.sequence
12327
- },
12328
- method: "PUT",
12329
- url: `${baseUrl}/open-apis/cardkit/v1/cards/${encodeURIComponent(request.cardId)}/elements/${encodeURIComponent(request.elementId)}/content`
12330
- }))
12331
- };
12332
- }
12333
- //#endregion
12334
- //#region src/feishu/infra/adapters/delivery/feishu-cardkit-publisher.ts
12335
- function createFeishuCardKitPublisher(options) {
12336
- const ledger = options.ledger ?? createFeishuCardDeliveryLedger();
12337
- return { publish: (action) => Effect.gen(function* () {
12338
- const target = yield* options.resolveTarget(action.runId);
12339
- if (action.type === "update_progress" && !target.progressElementId) return;
12340
- const sequence = yield* ledger.reserveSequence(action.runId);
12341
- switch (action.type) {
12342
- case "update_text": return yield* options.client.updateText({
12343
- cardId: target.cardId,
12344
- content: action.text,
12345
- elementId: target.elementId,
12346
- sequence
12347
- });
12348
- case "update_progress": return yield* options.client.updateText({
12349
- cardId: target.cardId,
12350
- content: renderFeishuRunProgress(action.presentation).markdown,
12351
- elementId: target.progressElementId,
12352
- sequence
12353
- });
12354
- case "update_presentation": return yield* options.client.updatePresentation({
12355
- cardId: target.cardId,
12356
- ...action.presentation === void 0 ? {} : { presentation: action.presentation },
12357
- runId: action.runId,
12358
- sequence,
12359
- sessionKey: action.sessionKey,
12360
- ...action.text === void 0 ? {} : { text: action.text }
12361
- });
12362
- case "finish":
12363
- yield* options.client.finish({
12364
- cardId: target.cardId,
12365
- ...action.presentation === void 0 ? {} : { presentation: action.presentation },
12366
- sequence,
12367
- text: action.text
12368
- });
12369
- return yield* ledger.markTerminal(action.runId);
12370
- case "fail":
12371
- yield* options.client.fail({
12372
- cardId: target.cardId,
12373
- errorMessage: action.errorMessage,
12374
- ...action.presentation === void 0 ? {} : { presentation: action.presentation },
12375
- sequence
12376
- });
12377
- return yield* ledger.markTerminal(action.runId);
12378
- case "cancel":
12379
- yield* options.client.cancel({
12380
- cardId: target.cardId,
12381
- ...action.presentation === void 0 ? {} : { presentation: action.presentation },
12382
- ...action.reason ? { reason: action.reason } : {},
12383
- sequence,
12384
- ...action.text === void 0 ? {} : { text: action.text }
12385
- });
12386
- return yield* ledger.markTerminal(action.runId);
12387
- }
12388
- }) };
12389
- }
12390
- //#endregion
12391
- //#region src/feishu/infra/adapters/streaming/feishu-coalescing-publisher.ts
12392
- function createCoalescingFeishuPublisher(options) {
12393
- const pendingTextByRun = /* @__PURE__ */ new Map();
12394
- const pendingProgressByRun = /* @__PURE__ */ new Map();
12395
- const pendingPresentationByRun = /* @__PURE__ */ new Map();
12396
- const flushText = (runId, text) => Effect.gen(function* () {
12397
- yield* options.publisher.publish({
12398
- runId,
12399
- text,
12400
- type: "update_text"
12401
- });
12402
- if (pendingTextByRun.get(runId) === text) pendingTextByRun.delete(runId);
12403
- });
12404
- const flushProgress = (runId, presentation) => Effect.gen(function* () {
12405
- yield* options.publisher.publish({
12406
- presentation,
12130
+ text: presentation?.answer.text.trim() || input.text || "",
12131
+ type: "finish"
12132
+ }];
12133
+ case "agent_run_failed": return [{
12134
+ errorMessage: input.errorMessage ?? "",
12135
+ ...hasProgress ? { presentation } : {},
12407
12136
  runId,
12408
- type: "update_progress"
12409
- });
12410
- if (pendingProgressByRun.get(runId) === presentation) pendingProgressByRun.delete(runId);
12411
- });
12412
- const flushRun = (runId) => {
12413
- const text = pendingTextByRun.get(runId);
12414
- const progress = pendingProgressByRun.get(runId);
12415
- const presentation = pendingPresentationByRun.get(runId);
12416
- return Effect.gen(function* () {
12417
- if (presentation !== void 0) {
12418
- yield* options.publisher.publish(presentation);
12419
- if (pendingPresentationByRun.get(runId) === presentation) pendingPresentationByRun.delete(runId);
12420
- if (pendingProgressByRun.get(runId) === progress) pendingProgressByRun.delete(runId);
12421
- if (pendingTextByRun.get(runId) === text) pendingTextByRun.delete(runId);
12422
- return;
12423
- }
12424
- if (progress !== void 0) yield* flushProgress(runId, progress);
12425
- if (text !== void 0) yield* flushText(runId, text);
12137
+ type: "fail"
12138
+ }];
12139
+ case "agent_run_cancelled": return [{
12140
+ ...hasProgress ? { presentation } : {},
12141
+ ...input.reason ? { reason: input.reason } : {},
12142
+ runId,
12143
+ type: "cancel"
12144
+ }];
12145
+ }
12146
+ }
12147
+ function createFeishuStreamProjector() {
12148
+ const presentations = createRunPresentationProjector();
12149
+ const applyEvent = (event, canonicalText) => {
12150
+ const presentation = presentations.apply(event, canonicalText);
12151
+ const text = event.type === "assistant_text_delta" ? event.delta : event.type === "agent_run_completed" ? canonicalText ?? event.finalText : void 0;
12152
+ const errorMessage = event.type === "agent_run_failed" ? event.errorMessage : void 0;
12153
+ const reason = event.type === "agent_run_cancelled" ? event.reason : void 0;
12154
+ return feishuActionsFromPresentation({
12155
+ eventType: event.type,
12156
+ runId: event.runId,
12157
+ ...presentation !== void 0 ? { presentation } : {},
12158
+ ...text !== void 0 ? { text } : {},
12159
+ ...errorMessage !== void 0 ? { errorMessage } : {},
12160
+ ...reason !== void 0 ? { reason } : {}
12426
12161
  });
12427
12162
  };
12428
12163
  return {
12429
- flush: (runId) => runId === void 0 ? Effect.gen(function* () {
12430
- const runIds = /* @__PURE__ */ new Set([
12431
- ...pendingPresentationByRun.keys(),
12432
- ...pendingProgressByRun.keys(),
12433
- ...pendingTextByRun.keys()
12434
- ]);
12435
- for (const pendingRunId of runIds) yield* flushRun(pendingRunId);
12436
- }) : flushRun(runId),
12437
- publish: (action) => {
12438
- switch (action.type) {
12439
- case "update_text": return Effect.sync(() => {
12440
- pendingTextByRun.set(action.runId, action.text);
12441
- });
12442
- case "update_progress": return Effect.sync(() => {
12443
- pendingProgressByRun.set(action.runId, action.presentation);
12444
- });
12445
- case "update_presentation": return Effect.sync(() => {
12446
- pendingPresentationByRun.set(action.runId, action);
12447
- });
12448
- case "finish":
12449
- case "fail":
12450
- case "cancel": return Effect.gen(function* () {
12451
- yield* Effect.sync(() => {
12452
- pendingProgressByRun.delete(action.runId);
12453
- pendingTextByRun.delete(action.runId);
12454
- pendingPresentationByRun.delete(action.runId);
12455
- });
12456
- yield* options.publisher.publish(action);
12457
- });
12458
- }
12459
- }
12164
+ apply: (event) => applyEvent(event),
12165
+ applyUpdate: ({ event, state }) => event.type === "agent_run_failed" ? applyEvent({
12166
+ ...event,
12167
+ errorMessage: state.errorMessage ?? event.errorMessage
12168
+ }, state.finalText) : event.type === "agent_run_cancelled" ? applyEvent(state.cancellationReason ? {
12169
+ ...event,
12170
+ reason: state.cancellationReason
12171
+ } : event, state.finalText) : applyEvent(event, state.finalText)
12460
12172
  };
12461
12173
  }
12462
12174
  //#endregion
12463
- //#region src/feishu/infra/adapters/streaming/feishu-rate-limited-publisher.ts
12464
- function createRateLimitedFeishuPublisher(options) {
12465
- let hasPublished = false;
12466
- const semaphore = Semaphore.makeUnsafe(1);
12467
- return { publish: (action) => semaphore.withPermits(1)(Effect.gen(function* () {
12468
- if (hasPublished) yield* options.sleep(options.minIntervalMs);
12469
- yield* options.publisher.publish(action);
12470
- hasPublished = true;
12471
- })) };
12472
- }
12473
- //#endregion
12474
- //#region src/feishu/infra/adapters/delivery/feishu-configured-cardkit-publisher.ts
12475
- function createConfiguredFeishuCardKitPublisher(options) {
12476
- const publisher = createFeishuCardKitPublisher({
12477
- client: createFeishuCardKitOpenApiClient({
12478
- ...options.agentName === void 0 ? {} : { agentName: options.agentName },
12479
- baseUrl: options.config.feishu.baseUrl,
12480
- ...options.cancelButton === void 0 ? {} : { cancelButton: options.cancelButton },
12481
- client: options.client,
12482
- ...options.onStreamingClosed === void 0 ? {} : { onStreamingClosed: options.onStreamingClosed },
12483
- ...options.progressDisplay === void 0 ? {} : { progressDisplay: options.progressDisplay }
12484
- }),
12485
- ...options.ledger ? { ledger: options.ledger } : {},
12486
- resolveTarget: options.resolveTarget
12175
+ //#region src/feishu/infra/adapters/delivery/feishu-card-delivery-ledger.ts
12176
+ function createFeishuCardDeliveryLedger(options = {}) {
12177
+ const persist = options.persist;
12178
+ return createInMemoryCardDeliveryLedger({
12179
+ ...options.initial === void 0 ? {} : { initial: options.initial },
12180
+ ...persist === void 0 ? {} : { persist: (record) => Effect.tryPromise({
12181
+ try: () => persist(record),
12182
+ catch: (error) => error
12183
+ }) }
12487
12184
  });
12488
- return createCoalescingFeishuPublisher({ publisher: createRateLimitedFeishuPublisher({
12489
- minIntervalMs: options.config.feishu.streamMinIntervalMs,
12490
- publisher,
12491
- sleep: options.sleep
12492
- }) });
12185
+ }
12186
+ function createFeishuCardDeliveryReconciler(options) {
12187
+ return { reconcile: () => Effect.gen(function* () {
12188
+ const projector = createFeishuStreamProjector();
12189
+ const terminalByRun = /* @__PURE__ */ new Map();
12190
+ for (const event of options.events) for (const action of projector.apply(event)) if (action.type === "cancel" || action.type === "fail" || action.type === "finish") terminalByRun.set(action.runId, action);
12191
+ let repaired = 0;
12192
+ let skipped = 0;
12193
+ for (const [runId, action] of terminalByRun) {
12194
+ if (options.ledger.isTerminalPublished(runId)) continue;
12195
+ yield* options.publish(action).pipe(Effect.catch((error) => {
12196
+ if (error instanceof FeishuCardTargetNotFound) {
12197
+ skipped += 1;
12198
+ return Effect.void;
12199
+ }
12200
+ return Effect.fail(error);
12201
+ }));
12202
+ yield* options.ledger.markTerminal(runId);
12203
+ repaired += 1;
12204
+ }
12205
+ return {
12206
+ repaired,
12207
+ skipped,
12208
+ terminalRuns: terminalByRun.size
12209
+ };
12210
+ }) };
12493
12211
  }
12494
12212
  //#endregion
12495
12213
  //#region src/feishu/infra/adapters/delivery/feishu-message-reaction.ts
@@ -13689,6 +13407,41 @@ function createAgentCommandFromFeishuCardAction(callback) {
13689
13407
  });
13690
13408
  }
13691
13409
  //#endregion
13410
+ //#region src/feishu/infra/adapters/conversation-session/feishu-session-key.ts
13411
+ var InvalidFeishuSessionReference = class {
13412
+ field;
13413
+ message;
13414
+ _tag = "InvalidFeishuSessionReference";
13415
+ constructor(field, message) {
13416
+ this.field = field;
13417
+ this.message = message;
13418
+ }
13419
+ };
13420
+ function requireField(fields, field) {
13421
+ const value = fields[field];
13422
+ if (value === void 0) return Effect.fail(new InvalidFeishuSessionReference(field, `${field} is required`));
13423
+ return Effect.succeed(value);
13424
+ }
13425
+ function encodeSegment(value) {
13426
+ return encodeURIComponent(value);
13427
+ }
13428
+ function conversationIdOf(fields) {
13429
+ return Effect.gen(function* () {
13430
+ const tenantKey = yield* requireField(fields, "tenantKey");
13431
+ const chatId = yield* requireField(fields, "chatId");
13432
+ const threadId = fields.threadId ?? "root";
13433
+ return `feishu:${encodeSegment(tenantKey)}:${encodeSegment(chatId)}:${encodeSegment(threadId)}`;
13434
+ });
13435
+ }
13436
+ function createFeishuSessionKey(fields) {
13437
+ return Effect.gen(function* () {
13438
+ return `${yield* conversationIdOf(fields)}:${encodeSegment(yield* requireField(fields, "agentId"))}`;
13439
+ });
13440
+ }
13441
+ function createFeishuConversationId(fields) {
13442
+ return conversationIdOf(fields);
13443
+ }
13444
+ //#endregion
13692
13445
  //#region src/feishu/infra/adapters/intake/feishu-inbound-inputs.ts
13693
13446
  /**
13694
13447
  * Historical inbox compatibility: the durable codec accepts only the four required message fields, so a stored
@@ -14371,11 +14124,6 @@ function createFeishuAgentInvocation(input) {
14371
14124
  };
14372
14125
  }
14373
14126
  //#endregion
14374
- //#region src/feishu/infra/adapters/intake/feishu-prompt-context.ts
14375
- function composeFeishuTopicPrompt(currentText, rootText) {
14376
- return `${currentText.trim()}\n\n<feishu_topic_context>\n话题原消息:\n${rootText.trim()}\n</feishu_topic_context>`;
14377
- }
14378
- //#endregion
14379
14127
  //#region src/feishu/infra/adapters/client/feishu-topic-root-reader.ts
14380
14128
  var InvalidFeishuTopicContext = class extends Error {
14381
14129
  name = "InvalidFeishuTopicContext";
@@ -14411,6 +14159,11 @@ function createFeishuTopicRootReader(options) {
14411
14159
  }) };
14412
14160
  }
14413
14161
  //#endregion
14162
+ //#region src/feishu/infra/adapters/intake/feishu-prompt-context.ts
14163
+ function composeFeishuTopicPrompt(currentText, rootText) {
14164
+ return `${currentText.trim()}\n\n<feishu_topic_context>\n话题原消息:\n${rootText.trim()}\n</feishu_topic_context>`;
14165
+ }
14166
+ //#endregion
14414
14167
  //#region src/feishu/infra/adapters/intake/feishu-topic-context-resolver.ts
14415
14168
  function createFeishuTopicContextResolver(options) {
14416
14169
  const rootReader = createFeishuTopicRootReader({
@@ -14537,33 +14290,280 @@ function createFeishuHumanInteractionCard(snapshot) {
14537
14290
  content: `${presentation.prefix} · ${snapshot.title}`,
14538
14291
  tag: "plain_text"
14539
14292
  }
14540
- },
14541
- schema: "2.0"
14293
+ },
14294
+ schema: "2.0"
14295
+ };
14296
+ }
14297
+ //#endregion
14298
+ //#region src/feishu/infra/adapters/interaction/human-interaction-presenter.ts
14299
+ function createFeishuHumanInteractionPresenter(options) {
14300
+ const baseUrl = (options.baseUrl ?? "https://open.feishu.cn").replace(/\/$/, "");
14301
+ return { present: (interaction) => Effect.gen(function* () {
14302
+ yield* options.client.request({
14303
+ body: {
14304
+ content: JSON.stringify(createFeishuHumanInteractionCard(interaction)),
14305
+ msg_type: "interactive",
14306
+ uuid: createHash("sha256").update(interaction.id).digest("hex").slice(0, 32)
14307
+ },
14308
+ method: "POST",
14309
+ url: `${baseUrl}/open-apis/im/v1/messages/${encodeURIComponent(interaction.sourceMessageId)}/reply`
14310
+ });
14311
+ }) };
14312
+ }
14313
+ //#endregion
14314
+ //#region src/feishu/infra/adapters/interaction/configured-human-interaction-presenter.ts
14315
+ function createConfiguredFeishuHumanInteractionPresenter(options) {
14316
+ return createFeishuHumanInteractionPresenter({
14317
+ baseUrl: options.config.feishu.baseUrl,
14318
+ client: options.client
14319
+ });
14320
+ }
14321
+ //#endregion
14322
+ //#region src/feishu/infra/adapters/streaming/feishu-coalescing-publisher.ts
14323
+ function createCoalescingFeishuPublisher(options) {
14324
+ const pendingTextByRun = /* @__PURE__ */ new Map();
14325
+ const pendingProgressByRun = /* @__PURE__ */ new Map();
14326
+ const pendingPresentationByRun = /* @__PURE__ */ new Map();
14327
+ const flushText = (runId, text) => Effect.gen(function* () {
14328
+ yield* options.publisher.publish({
14329
+ runId,
14330
+ text,
14331
+ type: "update_text"
14332
+ });
14333
+ if (pendingTextByRun.get(runId) === text) pendingTextByRun.delete(runId);
14334
+ });
14335
+ const flushProgress = (runId, presentation) => Effect.gen(function* () {
14336
+ yield* options.publisher.publish({
14337
+ presentation,
14338
+ runId,
14339
+ type: "update_progress"
14340
+ });
14341
+ if (pendingProgressByRun.get(runId) === presentation) pendingProgressByRun.delete(runId);
14342
+ });
14343
+ const flushRun = (runId) => {
14344
+ const text = pendingTextByRun.get(runId);
14345
+ const progress = pendingProgressByRun.get(runId);
14346
+ const presentation = pendingPresentationByRun.get(runId);
14347
+ return Effect.gen(function* () {
14348
+ if (presentation !== void 0) {
14349
+ yield* options.publisher.publish(presentation);
14350
+ if (pendingPresentationByRun.get(runId) === presentation) pendingPresentationByRun.delete(runId);
14351
+ if (pendingProgressByRun.get(runId) === progress) pendingProgressByRun.delete(runId);
14352
+ if (pendingTextByRun.get(runId) === text) pendingTextByRun.delete(runId);
14353
+ return;
14354
+ }
14355
+ if (progress !== void 0) yield* flushProgress(runId, progress);
14356
+ if (text !== void 0) yield* flushText(runId, text);
14357
+ });
14358
+ };
14359
+ return {
14360
+ flush: (runId) => runId === void 0 ? Effect.gen(function* () {
14361
+ const runIds = /* @__PURE__ */ new Set([
14362
+ ...pendingPresentationByRun.keys(),
14363
+ ...pendingProgressByRun.keys(),
14364
+ ...pendingTextByRun.keys()
14365
+ ]);
14366
+ for (const pendingRunId of runIds) yield* flushRun(pendingRunId);
14367
+ }) : flushRun(runId),
14368
+ publish: (action) => {
14369
+ switch (action.type) {
14370
+ case "update_text": return Effect.sync(() => {
14371
+ pendingTextByRun.set(action.runId, action.text);
14372
+ });
14373
+ case "update_progress": return Effect.sync(() => {
14374
+ pendingProgressByRun.set(action.runId, action.presentation);
14375
+ });
14376
+ case "update_presentation": return Effect.sync(() => {
14377
+ pendingPresentationByRun.set(action.runId, action);
14378
+ });
14379
+ case "finish":
14380
+ case "fail":
14381
+ case "cancel": return Effect.gen(function* () {
14382
+ yield* Effect.sync(() => {
14383
+ pendingProgressByRun.delete(action.runId);
14384
+ pendingTextByRun.delete(action.runId);
14385
+ pendingPresentationByRun.delete(action.runId);
14386
+ });
14387
+ yield* options.publisher.publish(action);
14388
+ });
14389
+ }
14390
+ }
14542
14391
  };
14543
14392
  }
14544
14393
  //#endregion
14545
- //#region src/feishu/infra/adapters/interaction/human-interaction-presenter.ts
14546
- function createFeishuHumanInteractionPresenter(options) {
14394
+ //#region src/feishu/infra/adapters/streaming/feishu-rate-limited-publisher.ts
14395
+ function createRateLimitedFeishuPublisher(options) {
14396
+ let hasPublished = false;
14397
+ const semaphore = Semaphore.makeUnsafe(1);
14398
+ return { publish: (action) => semaphore.withPermits(1)(Effect.gen(function* () {
14399
+ if (hasPublished) yield* options.sleep(options.minIntervalMs);
14400
+ yield* options.publisher.publish(action);
14401
+ hasPublished = true;
14402
+ })) };
14403
+ }
14404
+ //#endregion
14405
+ //#region src/feishu/infra/adapters/delivery/feishu-cardkit-openapi-client.ts
14406
+ function isStreamingClosed(error) {
14407
+ return error instanceof FeishuOpenApiError && (error.code === 200850 || error.code === 300309);
14408
+ }
14409
+ function replaceCard(baseUrl, cardId, sequence, card, call) {
14410
+ return call({
14411
+ body: {
14412
+ card: {
14413
+ data: JSON.stringify(card),
14414
+ type: "card_json"
14415
+ },
14416
+ sequence
14417
+ },
14418
+ method: "PUT",
14419
+ url: `${baseUrl}/open-apis/cardkit/v1/cards/${encodeURIComponent(cardId)}`
14420
+ });
14421
+ }
14422
+ function updateRunningCard(baseUrl, agentName, request, call, progressDisplay, cancelButton) {
14423
+ const card = createFeishuAgentRunCard({
14424
+ agentName,
14425
+ ...cancelButton === void 0 ? {} : { cancelButton },
14426
+ ...request.presentation === void 0 ? {} : { presentation: request.presentation },
14427
+ ...progressDisplay === void 0 ? {} : { progressDisplay },
14428
+ runId: request.runId,
14429
+ sessionKey: request.sessionKey,
14430
+ status: "running",
14431
+ ...request.text === void 0 ? {} : { text: request.text }
14432
+ });
14433
+ return replaceCard(baseUrl, request.cardId, request.sequence, card, call);
14434
+ }
14435
+ function updateWholeCard(baseUrl, agentName, request, status, call, progressDisplay) {
14436
+ const requestText = "text" in request ? request.text : void 0;
14437
+ const requestPresentation = "presentation" in request ? request.presentation : void 0;
14438
+ const card = status === "completed" ? createFeishuAgentRunCard({
14439
+ agentName,
14440
+ ...requestPresentation === void 0 ? {} : { presentation: requestPresentation },
14441
+ ...progressDisplay === void 0 ? {} : { progressDisplay },
14442
+ status,
14443
+ text: requestText ?? ""
14444
+ }) : status === "cancelled" ? createFeishuAgentRunCard({
14445
+ agentName,
14446
+ ...requestPresentation === void 0 ? {} : { presentation: requestPresentation },
14447
+ ...progressDisplay === void 0 ? {} : { progressDisplay },
14448
+ ..."reason" in request && request.reason ? { reason: request.reason } : {},
14449
+ status,
14450
+ ...requestText === void 0 ? {} : { text: requestText }
14451
+ }) : createFeishuAgentRunCard({
14452
+ agentName,
14453
+ ...requestPresentation === void 0 ? {} : { presentation: requestPresentation },
14454
+ ...progressDisplay === void 0 ? {} : { progressDisplay },
14455
+ status
14456
+ });
14457
+ return replaceCard(baseUrl, request.cardId, request.sequence, card, call);
14458
+ }
14459
+ function createFeishuCardKitOpenApiClient(options) {
14547
14460
  const baseUrl = (options.baseUrl ?? "https://open.feishu.cn").replace(/\/$/, "");
14548
- return { present: (interaction) => Effect.gen(function* () {
14549
- yield* options.client.request({
14461
+ const agentName = options.agentName ?? "Rivus Agent";
14462
+ const streamingClosedCards = /* @__PURE__ */ new Set();
14463
+ const call = (request) => options.client.request(request).pipe(Effect.asVoid);
14464
+ const updateTerminal = (request, status) => updateWholeCard(baseUrl, agentName, request, status, call, options.progressDisplay).pipe(Effect.tap(() => Effect.sync(() => streamingClosedCards.delete(request.cardId))));
14465
+ const publishStreamingUpdate = (cardId, update) => {
14466
+ if (streamingClosedCards.has(cardId)) return Effect.void;
14467
+ return update.pipe(Effect.catch((error) => {
14468
+ if (!isStreamingClosed(error)) return Effect.fail(error);
14469
+ return Effect.sync(() => {
14470
+ streamingClosedCards.add(cardId);
14471
+ options.onStreamingClosed?.(cardId);
14472
+ });
14473
+ }));
14474
+ };
14475
+ return {
14476
+ cancel: (request) => updateTerminal(request, "cancelled"),
14477
+ fail: (request) => updateTerminal(request, "failed"),
14478
+ finish: (request) => updateTerminal(request, "completed"),
14479
+ updatePresentation: (request) => publishStreamingUpdate(request.cardId, updateRunningCard(baseUrl, agentName, request, call, options.progressDisplay, options.cancelButton)),
14480
+ updateText: (request) => publishStreamingUpdate(request.cardId, call({
14550
14481
  body: {
14551
- content: JSON.stringify(createFeishuHumanInteractionCard(interaction)),
14552
- msg_type: "interactive",
14553
- uuid: createHash("sha256").update(interaction.id).digest("hex").slice(0, 32)
14482
+ content: request.content,
14483
+ sequence: request.sequence
14554
14484
  },
14555
- method: "POST",
14556
- url: `${baseUrl}/open-apis/im/v1/messages/${encodeURIComponent(interaction.sourceMessageId)}/reply`
14557
- });
14485
+ method: "PUT",
14486
+ url: `${baseUrl}/open-apis/cardkit/v1/cards/${encodeURIComponent(request.cardId)}/elements/${encodeURIComponent(request.elementId)}/content`
14487
+ }))
14488
+ };
14489
+ }
14490
+ //#endregion
14491
+ //#region src/feishu/infra/adapters/delivery/feishu-cardkit-publisher.ts
14492
+ function createFeishuCardKitPublisher(options) {
14493
+ const ledger = options.ledger ?? createFeishuCardDeliveryLedger();
14494
+ return { publish: (action) => Effect.gen(function* () {
14495
+ const target = yield* options.resolveTarget(action.runId);
14496
+ if (action.type === "update_progress" && !target.progressElementId) return;
14497
+ const sequence = yield* ledger.reserveSequence(action.runId);
14498
+ switch (action.type) {
14499
+ case "update_text": return yield* options.client.updateText({
14500
+ cardId: target.cardId,
14501
+ content: action.text,
14502
+ elementId: target.elementId,
14503
+ sequence
14504
+ });
14505
+ case "update_progress": return yield* options.client.updateText({
14506
+ cardId: target.cardId,
14507
+ content: renderFeishuRunProgress(action.presentation).markdown,
14508
+ elementId: target.progressElementId,
14509
+ sequence
14510
+ });
14511
+ case "update_presentation": return yield* options.client.updatePresentation({
14512
+ cardId: target.cardId,
14513
+ ...action.presentation === void 0 ? {} : { presentation: action.presentation },
14514
+ runId: action.runId,
14515
+ sequence,
14516
+ sessionKey: action.sessionKey,
14517
+ ...action.text === void 0 ? {} : { text: action.text }
14518
+ });
14519
+ case "finish":
14520
+ yield* options.client.finish({
14521
+ cardId: target.cardId,
14522
+ ...action.presentation === void 0 ? {} : { presentation: action.presentation },
14523
+ sequence,
14524
+ text: action.text
14525
+ });
14526
+ return yield* ledger.markTerminal(action.runId);
14527
+ case "fail":
14528
+ yield* options.client.fail({
14529
+ cardId: target.cardId,
14530
+ errorMessage: action.errorMessage,
14531
+ ...action.presentation === void 0 ? {} : { presentation: action.presentation },
14532
+ sequence
14533
+ });
14534
+ return yield* ledger.markTerminal(action.runId);
14535
+ case "cancel":
14536
+ yield* options.client.cancel({
14537
+ cardId: target.cardId,
14538
+ ...action.presentation === void 0 ? {} : { presentation: action.presentation },
14539
+ ...action.reason ? { reason: action.reason } : {},
14540
+ sequence,
14541
+ ...action.text === void 0 ? {} : { text: action.text }
14542
+ });
14543
+ return yield* ledger.markTerminal(action.runId);
14544
+ }
14558
14545
  }) };
14559
14546
  }
14560
14547
  //#endregion
14561
- //#region src/feishu/infra/adapters/interaction/configured-human-interaction-presenter.ts
14562
- function createConfiguredFeishuHumanInteractionPresenter(options) {
14563
- return createFeishuHumanInteractionPresenter({
14564
- baseUrl: options.config.feishu.baseUrl,
14565
- client: options.client
14548
+ //#region src/feishu/infra/adapters/delivery/feishu-configured-cardkit-publisher.ts
14549
+ function createConfiguredFeishuCardKitPublisher(options) {
14550
+ const publisher = createFeishuCardKitPublisher({
14551
+ client: createFeishuCardKitOpenApiClient({
14552
+ ...options.agentName === void 0 ? {} : { agentName: options.agentName },
14553
+ baseUrl: options.config.feishu.baseUrl,
14554
+ ...options.cancelButton === void 0 ? {} : { cancelButton: options.cancelButton },
14555
+ client: options.client,
14556
+ ...options.onStreamingClosed === void 0 ? {} : { onStreamingClosed: options.onStreamingClosed },
14557
+ ...options.progressDisplay === void 0 ? {} : { progressDisplay: options.progressDisplay }
14558
+ }),
14559
+ ...options.ledger ? { ledger: options.ledger } : {},
14560
+ resolveTarget: options.resolveTarget
14566
14561
  });
14562
+ return createCoalescingFeishuPublisher({ publisher: createRateLimitedFeishuPublisher({
14563
+ minIntervalMs: options.config.feishu.streamMinIntervalMs,
14564
+ publisher,
14565
+ sleep: options.sleep
14566
+ }) });
14567
14567
  }
14568
14568
  //#endregion
14569
14569
  //#region src/feishu/infra/adapters/rollover/feishu-card-rollover.ts
@@ -18092,7 +18092,8 @@ function resolveRivusDeploymentStateDirectory(STATE_DIR) {
18092
18092
  acpSessionStorePath: (agentId) => join(STATE_DIR, "acp", agentId, "provider-sessions.json"),
18093
18093
  automationOccurrencesPath: (automationId) => join(STATE_DIR, "automations", createHash("sha256").update(automationId).digest("hex").slice(0, 16), "ticks.json"),
18094
18094
  endpointStatePath: (endpointId) => join(STATE_DIR, "endpoints", endpointId),
18095
- instanceStatePath: (instanceId) => join(STATE_DIR, "instances", instanceId)
18095
+ instanceStatePath: (instanceId) => join(STATE_DIR, "instances", instanceId),
18096
+ instanceEventLogPath: (instanceId) => join(STATE_DIR, "instances", instanceId, "agent-events.jsonl")
18096
18097
  };
18097
18098
  }
18098
18099
  //#endregion
@@ -19720,11 +19721,11 @@ function assertNewHumanInteraction(interaction) {
19720
19721
  function isSameHumanInteractionSnapshot(left, right) {
19721
19722
  return JSON.stringify(left) === JSON.stringify(right);
19722
19723
  }
19723
- function toRoot$2(value) {
19724
+ function toRoot$1(value) {
19724
19725
  return typeof value.toSnapshot === "function" ? value : restoreStoredHumanInteraction(value);
19725
19726
  }
19726
19727
  function resolveHumanInteractionUpdate(current, next) {
19727
- const nextRoot = toRoot$2(next);
19728
+ const nextRoot = toRoot$1(next);
19728
19729
  if (nextRoot === current || isSameHumanInteractionSnapshot(nextRoot, current)) return current;
19729
19730
  if (nextRoot.id !== current.id || nextRoot.revision !== current.revision + 1) throw new Error("human interaction update must preserve id and advance exactly one revision");
19730
19731
  if (!current.validateTransitionTo(nextRoot)) throw new Error("invalid human interaction state transition");
@@ -19737,38 +19738,6 @@ function applyHumanInteractionTransition(current, id, transition) {
19737
19738
  return resolveHumanInteractionUpdate(current, transitioned.value);
19738
19739
  }
19739
19740
  //#endregion
19740
- //#region src/human-interaction/infra/repository/in-memory-human-interaction-repository.ts
19741
- function toRoot$1(value) {
19742
- return typeof value.toSnapshot === "function" ? value : restoreStoredHumanInteraction(value);
19743
- }
19744
- function clone(interaction) {
19745
- return interaction === void 0 ? void 0 : restoreStoredHumanInteraction(structuredClone(toRoot$1(interaction).toSnapshot()));
19746
- }
19747
- function createInMemoryHumanInteractionRepository() {
19748
- const interactions = /* @__PURE__ */ new Map();
19749
- return {
19750
- create: (interaction) => Effect.try({
19751
- try: () => {
19752
- const root = toRoot$1(interaction);
19753
- if (interactions.has(root.id)) throw new Error(`human interaction already exists: ${root.id}`);
19754
- assertNewHumanInteraction(root);
19755
- interactions.set(root.id, restoreStoredHumanInteraction(structuredClone(root.toSnapshot())));
19756
- },
19757
- catch: (error) => new HumanInteractionRepositoryError("create", "failed to create human interaction", error)
19758
- }),
19759
- get: (id) => Effect.sync(() => clone(interactions.get(id))),
19760
- update: (id, transition) => Effect.try({
19761
- try: () => {
19762
- const next = applyHumanInteractionTransition(interactions.get(id), id, transition);
19763
- const snapshot = restoreStoredHumanInteraction(structuredClone(next.toSnapshot()));
19764
- interactions.set(id, snapshot);
19765
- return snapshot;
19766
- },
19767
- catch: (error) => new HumanInteractionRepositoryError("update", "failed to update human interaction", error)
19768
- })
19769
- };
19770
- }
19771
- //#endregion
19772
19741
  //#region src/human-interaction/infra/models/human-interaction-snapshot-codec.ts
19773
19742
  const actorSchema = Schema.Struct({
19774
19743
  openId: Schema.String,
@@ -19968,7 +19937,6 @@ const SystemHumanInteractionClockLive = Layer.succeed(HumanInteractionClock, {
19968
19937
  function jsonlHumanInteractionRepository(options) {
19969
19938
  return Layer.sync(HumanInteractionRepository, () => createJsonlHumanInteractionRepository(options));
19970
19939
  }
19971
- Layer.sync(HumanInteractionRepository, createInMemoryHumanInteractionRepository);
19972
19940
  //#endregion
19973
19941
  //#region src/bootstrap/human-interaction/endpoint-human-interaction-service.ts
19974
19942
  /**
@@ -20181,12 +20149,6 @@ function createFeishuDeploymentEndpoint(options) {
20181
20149
  };
20182
20150
  }
20183
20151
  //#endregion
20184
- //#region src/bootstrap/deployment/effect-sleep.ts
20185
- /** Timeout-free sleep used by the deployment compositions that poll or roll over. */
20186
- function sleep(ms) {
20187
- return Effect.promise(() => new Promise((resolve) => setTimeout(resolve, ms)));
20188
- }
20189
- //#endregion
20190
20152
  //#region src/bootstrap/feishu/endpoint-port.ts
20191
20153
  function optional(value) {
20192
20154
  return value?.trim() || void 0;
@@ -20292,6 +20254,9 @@ function createFeishuEndpointPort(deps) {
20292
20254
  config
20293
20255
  })
20294
20256
  });
20257
+ const reportCardRolloverError = (error) => {
20258
+ console.error(`Feishu card rollover failed for endpoint ${input.endpointId}`, error);
20259
+ };
20295
20260
  const cardRollover = createConfiguredFeishuCardRolloverRuntime({
20296
20261
  agentName: input.agentId,
20297
20262
  cardTargets,
@@ -20299,15 +20264,13 @@ function createFeishuEndpointPort(deps) {
20299
20264
  clock: { now: Effect.sync(() => /* @__PURE__ */ new Date()) },
20300
20265
  config,
20301
20266
  ledger: cardLedger,
20302
- onError: (error) => {
20303
- console.error(`Feishu card rollover failed for endpoint ${input.endpointId}`, error);
20304
- },
20267
+ onError: reportCardRolloverError,
20305
20268
  ...input.definition.progressDisplay === void 0 ? {} : { progressDisplay: input.definition.progressDisplay },
20306
- sleep,
20269
+ sleep: (ms) => Effect.sleep(ms),
20307
20270
  title: input.agentId
20308
20271
  });
20309
20272
  const publisher = cardRollover.rollover;
20310
- const endpointInitialEvents = yield* createJsonlAgentEventLog({ filePath: join(deps.state.instanceStatePath(input.instanceId), "agent-events.jsonl") }).readAll();
20273
+ const endpointInitialEvents = yield* createJsonlAgentEventLog({ filePath: deps.state.instanceEventLogPath(input.instanceId) }).readAll();
20311
20274
  yield* createFeishuCardDeliveryReconciler({
20312
20275
  events: endpointInitialEvents,
20313
20276
  ledger: cardLedger,
@@ -20334,9 +20297,7 @@ function createFeishuEndpointPort(deps) {
20334
20297
  attachmentPreparation,
20335
20298
  attachmentRetention,
20336
20299
  botOpenId,
20337
- cardRollover: composeFeishuCardRolloverTransport(cardRollover, (error) => {
20338
- console.error(`Feishu card rollover failed for endpoint ${input.endpointId}`, error);
20339
- }),
20300
+ cardRollover: composeFeishuCardRolloverTransport(cardRollover, reportCardRolloverError),
20340
20301
  finalizeRun: (runId) => cardRollover.rollover.releaseRun(runId),
20341
20302
  cancel: input.cancel,
20342
20303
  endpointId: input.endpointId,
@@ -20364,7 +20325,7 @@ function createFeishuEndpointPort(deps) {
20364
20325
  steer: input.steer,
20365
20326
  ...cotPublisher ? { publishRunUpdate: (update) => cotPublisher.publish(update).pipe(Effect.catch((error) => reportCotError(input.endpointId, "update", error))) } : {},
20366
20327
  sessionNamespace: input.definition.sessionNamespace,
20367
- sleep,
20328
+ sleep: (ms) => Effect.sleep(ms),
20368
20329
  websocketClient: createLazyFeishuWebSocketClient(credentials, input.definition.baseUrl),
20369
20330
  workerConcurrency: 4
20370
20331
  });
@@ -20694,7 +20655,7 @@ function createRivusDeploymentRuntimePort(deps) {
20694
20655
  try: () => mkdir(instanceState, { recursive: true }),
20695
20656
  catch: (error) => error
20696
20657
  });
20697
- const eventLog = createJsonlAgentEventLog({ filePath: join(instanceState, "agent-events.jsonl") });
20658
+ const eventLog = createJsonlAgentEventLog({ filePath: deps.state.instanceEventLogPath(input.instanceId) });
20698
20659
  const initialEvents = yield* eventLog.readAll();
20699
20660
  const broker = createRivusToolBroker({
20700
20661
  approvals: createRoutedHumanInteractionToolApprovalService(() => deps.interactionRegistry.services()),
@@ -20770,10 +20731,7 @@ function createRivusDeploymentRuntimePort(deps) {
20770
20731
  }
20771
20732
  //#endregion
20772
20733
  //#region src/bootstrap/feishu.ts
20773
- /** Assemble the deployment adapters for a manifest-driven daemon. The top level only runs the assembly steps in
20774
- * order and connects the ports; each step's composition lives beside its concern — the state layout in
20775
- * `deployment/state-directory.ts`, the per-context factories in the contexts' `infra/factories/`, and the
20776
- * cross-context compositions in `deployment/` and `feishu/`. */
20734
+ /** Assemble the deployment adapters for a manifest-driven daemon. */
20777
20735
  async function createRivusDeploymentAdapters(context) {
20778
20736
  const state = resolveRivusDeploymentStateDirectory(context.env.RIVUS_DEPLOYMENT_STATE_DIR?.trim() || ".rivus/deployment");
20779
20737
  const { memory, manifest } = unwrapExit(await Effect.runPromiseExit(Effect.gen(function* () {