@bobannomi/client 0.1.0 → 0.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -572,7 +572,7 @@ function assertPromptMetadataAllowed(input) {
572
572
  const field = `${namespace}.outputSchema`;
573
573
  throw new DomainValidationError(`${field} is a stored snapshot; use explicit outputSchema`, field);
574
574
  }
575
- for (const name of ["pluginUi", "uiAction", "pluginUiSubmission", "pluginAppAction", "pluginAppSubmission", "pluginAppSource", "consumedForkHistory", "executionBinding", "configurationBinding", "initialConfigurationBinding", "steeredRunId", "sessionObservationGrant", "sessionObservationAccess"]) {
575
+ for (const name of ["pluginUi", "uiAction", "pluginUiSubmission", "pluginAppAction", "pluginAppSubmission", "pluginAppSource", "consumedForkHistory", "executionBinding", "steeredRunId", "steerTargetRunId", "appliedInputState", "appliedFollowUpInputIds", "unappliedFollowUpInputIds", "unappliedPromotion", "steerDeliveryFailed", "sessionObservationGrant", "sessionObservationAccess", "promotion", "cancellation", "interruption"]) {
576
576
  if (Object.hasOwn(metadata, name)) {
577
577
  const field = `${namespace}.${name}`;
578
578
  throw new DomainValidationError(
@@ -2438,11 +2438,11 @@ function assertPositiveSafeInteger(value, field) {
2438
2438
  }
2439
2439
  }
2440
2440
  async function throwResponseError(response) {
2441
- let body;
2441
+ const text3 = await response.text().catch(() => "");
2442
+ let body = text3;
2442
2443
  try {
2443
- body = await response.json();
2444
+ body = JSON.parse(text3);
2444
2445
  } catch {
2445
- body = await response.text().catch(() => "");
2446
2446
  }
2447
2447
  const message = body && typeof body === "object" && "error" in body && typeof body.error === "string" ? body.error : body && typeof body === "object" && "message" in body && typeof body.message === "string" ? body.message : `BobanNomi API request failed with ${response.status}`;
2448
2448
  throw new BobanNomiApiError(message, response.status, body);
@@ -2525,42 +2525,26 @@ var HttpTransport = class {
2525
2525
  return `${this.baseUrl}${resolvedPath}`;
2526
2526
  }
2527
2527
  async request(path2, options = {}) {
2528
- const business = !this.isHandshakeExempt(path2);
2529
- if (business && !this.protocolVerified) await this.ensureProtocol(options.signal);
2530
- options.signal?.throwIfAborted();
2531
- const url = this.resolveUrl(path2, options.query);
2532
- const hasJsonBody = options.body !== void 0;
2533
- const headers2 = mergeHeaders(
2534
- this.headers(hasJsonBody, options.auth ?? true),
2535
- options.headers
2536
- );
2537
- if (business) headers2[PROTOCOL_VERSION_HEADER] = String(CURRENT_PROTOCOL_VERSION);
2538
- const response = await this.fetchImpl(url, {
2539
- method: options.method ?? "GET",
2540
- headers: headers2,
2541
- body: hasJsonBody ? JSON.stringify(options.body) : void 0,
2542
- signal: options.signal
2543
- });
2544
- if (!response.ok) {
2545
- await throwResponseError(response);
2546
- }
2528
+ const { body, method, headers: headers2, signal, auth, query } = options;
2529
+ const response = await this.#send(path2, { method: method ?? "GET", headers: headers2, signal, auth, query }, { body });
2547
2530
  return await response.json();
2548
2531
  }
2549
2532
  async requestUnknown(path2, options = {}) {
2550
2533
  return this.request(path2, options);
2551
2534
  }
2552
2535
  async requestResponse(path2, options = {}) {
2536
+ return this.#send(path2, options);
2537
+ }
2538
+ async #send(path2, options, json2) {
2553
2539
  const business = !this.isHandshakeExempt(path2);
2554
- if (business) await this.ensureProtocol(options.signal ?? void 0);
2540
+ if (business && (!json2 || !this.protocolVerified)) await this.ensureProtocol(options.signal ?? void 0);
2555
2541
  options.signal?.throwIfAborted();
2556
- const url = this.resolveUrl(path2, options.query);
2557
- const auth = options.auth ?? true;
2558
- const headers2 = mergeHeaders(this.headers(false, auth), options.headers);
2542
+ const { query, auth, ...request } = options;
2543
+ const url = this.resolveUrl(path2, query);
2544
+ const hasJsonBody = json2?.body !== void 0;
2545
+ const headers2 = mergeHeaders(this.headers(hasJsonBody, auth ?? true), options.headers);
2559
2546
  if (business) headers2[PROTOCOL_VERSION_HEADER] = String(CURRENT_PROTOCOL_VERSION);
2560
- const init = {
2561
- ...options,
2562
- headers: headers2
2563
- };
2547
+ const init = json2 ? { ...request, headers: headers2, body: hasJsonBody ? JSON.stringify(json2.body) : void 0 } : { ...options, headers: headers2 };
2564
2548
  if (isReadableStream(init.body) && !init.duplex) {
2565
2549
  init.duplex = "half";
2566
2550
  }
@@ -2628,28 +2612,9 @@ ${slice}` : slice;
2628
2612
  return JSON.parse(data);
2629
2613
  }
2630
2614
  async function* streamServerSentEvents(open, decode = (value) => value) {
2631
- const reader = (await open()).getReader();
2632
- const decoder = new TextDecoder();
2633
- let buffer = "";
2634
- try {
2635
- while (true) {
2636
- const chunk = await reader.read();
2637
- if (chunk.done) break;
2638
- buffer += decoder.decode(chunk.value, { stream: true });
2639
- const frames = buffer.split(/\r?\n\r?\n/);
2640
- buffer = frames.pop() ?? "";
2641
- for (const frame of frames) {
2642
- const event = parseSseFrame(frame);
2643
- if (event !== void 0) yield decode(event);
2644
- }
2645
- }
2646
- } finally {
2647
- try {
2648
- await reader.cancel();
2649
- } catch {
2650
- } finally {
2651
- reader.releaseLock();
2652
- }
2615
+ for await (const frame of readSseFrames(await open())) {
2616
+ const event = parseSseFrame(frame);
2617
+ if (event !== void 0) yield decode(event);
2653
2618
  }
2654
2619
  }
2655
2620
  var SseTransport = class {
@@ -2692,17 +2657,17 @@ var SseTransport = class {
2692
2657
  options.onOpen?.();
2693
2658
  resetIdleTimer();
2694
2659
  try {
2695
- for await (const frame of readRawSseFrames(
2696
- response.body,
2697
- resetIdleTimer
2698
- )) {
2660
+ for await (const value of readSseFrames(response.body)) {
2661
+ resetIdleTimer();
2662
+ const frame = parseRawSseFrame(value);
2663
+ if (!frame) continue;
2699
2664
  if (frame.retry !== void 0) reconnectDelayMs = frame.retry;
2700
2665
  if (frame.data !== void 0) {
2701
- const value = (options.decode ?? ((value2) => value2))(
2666
+ const value2 = (options.decode ?? ((value3) => value3))(
2702
2667
  JSON.parse(frame.data)
2703
2668
  );
2704
2669
  if (frame.id !== void 0) lastEventId = frame.id;
2705
- yield value;
2670
+ yield value2;
2706
2671
  }
2707
2672
  }
2708
2673
  } catch (error) {
@@ -2718,7 +2683,7 @@ var SseTransport = class {
2718
2683
  }
2719
2684
  }
2720
2685
  };
2721
- async function* readRawSseFrames(stream, onFrame) {
2686
+ async function* readSseFrames(stream) {
2722
2687
  const reader = stream.getReader();
2723
2688
  const decoder = new TextDecoder();
2724
2689
  let buffer = "";
@@ -2729,11 +2694,7 @@ async function* readRawSseFrames(stream, onFrame) {
2729
2694
  buffer += decoder.decode(chunk.value, { stream: true });
2730
2695
  const frames = buffer.split(/\r?\n\r?\n/);
2731
2696
  buffer = frames.pop() ?? "";
2732
- for (const value of frames) {
2733
- onFrame?.();
2734
- const frame = parseRawSseFrame(value);
2735
- if (frame) yield frame;
2736
- }
2697
+ yield* frames;
2737
2698
  }
2738
2699
  } finally {
2739
2700
  try {
@@ -2831,6 +2792,14 @@ var ScheduleResource = class {
2831
2792
  );
2832
2793
  return response.run;
2833
2794
  }
2795
+ /** Reads the exact manual request without starting work. A missing record does not authorize replay. */
2796
+ async getTriggerTaskResult(id2, requestId, options = {}) {
2797
+ const response = await this.transport.request(
2798
+ this.transport.path(`/schedules/tasks/${encodeURIComponent(id2)}/run`, { requestId }),
2799
+ { signal: options.signal }
2800
+ );
2801
+ return response.run;
2802
+ }
2834
2803
  async listRuns(options = {}) {
2835
2804
  const { signal, ...query } = options;
2836
2805
  const response = await this.transport.request(
@@ -2839,10 +2808,18 @@ var ScheduleResource = class {
2839
2808
  );
2840
2809
  return response.runs;
2841
2810
  }
2811
+ /** Reads one run belonging to this task, regardless of how it was triggered. */
2812
+ async getRun(taskId, runId, options = {}) {
2813
+ const response = await this.transport.request(
2814
+ `/schedules/tasks/${encodeURIComponent(taskId)}/runs/${encodeURIComponent(runId)}`,
2815
+ { signal: options.signal }
2816
+ );
2817
+ return response.run;
2818
+ }
2842
2819
  async setRunUnread(id2, unread, options = {}) {
2843
2820
  const response = await this.transport.request(
2844
2821
  `/schedules/runs/${encodeURIComponent(id2)}/read`,
2845
- { method: "PATCH", body: { unread }, signal: options.signal }
2822
+ { method: "PATCH", body: { unread, ...options.taskId === void 0 ? {} : { taskId: options.taskId } }, signal: options.signal }
2846
2823
  );
2847
2824
  return response.run;
2848
2825
  }
@@ -2882,6 +2859,185 @@ var RuntimeResource = class {
2882
2859
  }
2883
2860
  };
2884
2861
 
2862
+ // src/resources/session/session-request-id.ts
2863
+ var promptRequestCounter = 0;
2864
+ function createPromptRequestId() {
2865
+ if (typeof globalThis.crypto?.randomUUID === "function") {
2866
+ return globalThis.crypto.randomUUID();
2867
+ }
2868
+ promptRequestCounter += 1;
2869
+ return `prompt-${Date.now().toString(36)}-${promptRequestCounter.toString(36)}`;
2870
+ }
2871
+
2872
+ // src/resources/session/session-configuration-requests.ts
2873
+ async function getDraftComposerOptions(transport, input, options = {}) {
2874
+ if (!validSessionControlInput("sessions.getDraftComposerOptions", input))
2875
+ throw new ProtocolDataError("Invalid draft composer target");
2876
+ const { workspaceId, outsideProject, roleId } = input;
2877
+ const path2 = transport.path("/sessions/configuration-options", {
2878
+ kind: "draft",
2879
+ workspaceId,
2880
+ outsideProject,
2881
+ roleId: roleId ?? void 0
2882
+ });
2883
+ const result = await transport.request(path2, {
2884
+ signal: options.signal
2885
+ });
2886
+ if (!validSessionControlResult("sessions.getDraftComposerOptions", result) || result.source !== input.source) {
2887
+ throw new ProtocolDataError("Draft composer options do not match target");
2888
+ }
2889
+ return result;
2890
+ }
2891
+ async function create(transport, input, options = {}) {
2892
+ const response = await transport.request(
2893
+ "/sessions",
2894
+ {
2895
+ method: "POST",
2896
+ body: parseCreateSessionRequest({
2897
+ ...input,
2898
+ id: input.id ?? createPromptRequestId(),
2899
+ requestId: input.requestId ?? createPromptRequestId()
2900
+ }),
2901
+ signal: options.signal
2902
+ }
2903
+ );
2904
+ return response.session;
2905
+ }
2906
+ async function getConfigurationOptions(transport, input, options = {}) {
2907
+ return transport.request(
2908
+ transport.path("/sessions/configuration-options", input),
2909
+ { signal: options.signal }
2910
+ );
2911
+ }
2912
+ async function getCreationResult(transport, input, options = {}) {
2913
+ return transport.request("/sessions/creation-result", {
2914
+ method: "POST",
2915
+ body: input,
2916
+ signal: options.signal
2917
+ });
2918
+ }
2919
+ async function getConfiguration(transport, sessionId, options = {}) {
2920
+ const value = await transport.requestUnknown(
2921
+ `/sessions/${encodeURIComponent(sessionId)}/configuration`,
2922
+ { signal: options.signal }
2923
+ );
2924
+ return decodeSessionConfigurationSnapshot(value);
2925
+ }
2926
+ async function configure(transport, sessionId, input, options = {}) {
2927
+ const body = parseConfigureSessionRequest(input);
2928
+ const response = await transport.requestUnknown(
2929
+ `/sessions/${encodeURIComponent(sessionId)}/configure`,
2930
+ { method: "POST", body, signal: options.signal }
2931
+ );
2932
+ return decodeSessionConfigurationReceipt(response, {
2933
+ sessionId,
2934
+ requestId: body.requestId
2935
+ });
2936
+ }
2937
+ async function getConfigurationResult(transport, sessionId, input, options = {}) {
2938
+ const body = parseConfigurationResultRequest(input);
2939
+ const response = await transport.requestUnknown(
2940
+ `/sessions/${encodeURIComponent(sessionId)}/configuration-result`,
2941
+ { method: "POST", body, signal: options.signal }
2942
+ );
2943
+ return response === null ? null : decodeSessionConfigurationReceipt(response, {
2944
+ sessionId,
2945
+ requestId: body.requestId
2946
+ });
2947
+ }
2948
+
2949
+ // src/resources/session/session-run-requests.ts
2950
+ function checkOutputSchema(transport, input, signal) {
2951
+ assertPromptMetadataAllowed2(input);
2952
+ if (input.outputSchema === void 0) return;
2953
+ return transport.ensureProtocol(signal).then((capabilities) => {
2954
+ if ((capabilities.features.structuredDelivery ?? 0) < 1) {
2955
+ throw new Error(
2956
+ "Server does not support structured delivery (outputSchema)"
2957
+ );
2958
+ }
2959
+ });
2960
+ }
2961
+ async function admitPrompt(transport, sessionId, input, options = {}) {
2962
+ const schemaCheck = checkOutputSchema(transport, input, options.signal);
2963
+ if (schemaCheck) await schemaCheck;
2964
+ if (input.expectedActiveRunId !== void 0) {
2965
+ const capabilities = await transport.ensureProtocol(options.signal);
2966
+ if ((capabilities.features.steer ?? 0) < 2) {
2967
+ throw new IncompatibleProtocolError(capabilities, "\u540E\u53F0\u7248\u672C\u4E0D\u652F\u6301\u8FD0\u884C\u4E2D\u8865\u5145\uFF0C\u8BF7\u66F4\u65B0\u540E\u91CD\u8BD5\u3002");
2968
+ }
2969
+ }
2970
+ return await transport.request(
2971
+ `/sessions/${encodeURIComponent(sessionId)}/prompts`,
2972
+ {
2973
+ method: "POST",
2974
+ body: { ...input, id: input.id ?? createPromptRequestId() },
2975
+ signal: options.signal
2976
+ }
2977
+ );
2978
+ }
2979
+ async function editLatestPrompt(transport, sessionId, input, options = {}) {
2980
+ await checkOutputSchema(transport, input, options.signal);
2981
+ return await transport.request(
2982
+ `/sessions/${encodeURIComponent(sessionId)}/prompts/latest/edit`,
2983
+ {
2984
+ method: "POST",
2985
+ body: input,
2986
+ signal: options.signal
2987
+ }
2988
+ );
2989
+ }
2990
+ async function promoteQueuedPrompt(transport, sessionId, inputId, input, options = {}) {
2991
+ return await transport.request(
2992
+ `/sessions/${encodeURIComponent(sessionId)}/prompts/${encodeURIComponent(inputId)}/promote`,
2993
+ { method: "POST", body: input, signal: options.signal }
2994
+ );
2995
+ }
2996
+ async function cancelQueuedPrompt(transport, sessionId, inputId, input, options = {}) {
2997
+ const mode = parseCancelResponseMode(options.responseMode);
2998
+ const response = await transport.request(
2999
+ `/sessions/${encodeURIComponent(sessionId)}/prompts/${encodeURIComponent(inputId)}/cancel`,
3000
+ {
3001
+ method: "POST",
3002
+ body: {
3003
+ ...input,
3004
+ ...options.responseMode ? { responseMode: mode } : {}
3005
+ },
3006
+ signal: options.signal
3007
+ }
3008
+ );
3009
+ if (mode === "receipt") {
3010
+ const receipt2 = decodeQueuedPromptCancelReceipt(response);
3011
+ if (receipt2.inputId !== inputId || receipt2.queuedRunId !== input.queuedRunId)
3012
+ throw new ProtocolDataError(
3013
+ "Cancellation receipt does not match target"
3014
+ );
3015
+ return receipt2;
3016
+ }
3017
+ return response;
3018
+ }
3019
+ async function resumeInterruptedRun(transport, sessionId, runId, input = {}, options = {}) {
3020
+ await checkOutputSchema(transport, input, options.signal);
3021
+ return await transport.request(
3022
+ `/sessions/${encodeURIComponent(sessionId)}/runs/${encodeURIComponent(runId)}/resume`,
3023
+ {
3024
+ method: "POST",
3025
+ body: { ...input, id: input.id ?? createPromptRequestId() },
3026
+ signal: options.signal
3027
+ }
3028
+ );
3029
+ }
3030
+ async function interrupt(transport, sessionId, options = {}) {
3031
+ return await transport.request(
3032
+ `/sessions/${encodeURIComponent(sessionId)}/interrupt`,
3033
+ {
3034
+ method: "POST",
3035
+ body: options.expectedRunId === void 0 ? void 0 : { expectedRunId: options.expectedRunId },
3036
+ signal: options.signal
3037
+ }
3038
+ );
3039
+ }
3040
+
2885
3041
  // src/resources/session/session-terminal-resource.ts
2886
3042
  var SessionTerminalResource = class {
2887
3043
  constructor(transport) {
@@ -2961,14 +3117,6 @@ var SessionManagementResource = class {
2961
3117
  };
2962
3118
 
2963
3119
  // src/resources/session/session-resource.ts
2964
- var promptRequestCounter = 0;
2965
- function createPromptRequestId() {
2966
- if (typeof globalThis.crypto?.randomUUID === "function") {
2967
- return globalThis.crypto.randomUUID();
2968
- }
2969
- promptRequestCounter += 1;
2970
- return `prompt-${Date.now().toString(36)}-${promptRequestCounter.toString(36)}`;
2971
- }
2972
3120
  var SessionResource = class {
2973
3121
  constructor(transport) {
2974
3122
  this.transport = transport;
@@ -2978,17 +3126,6 @@ var SessionResource = class {
2978
3126
  transport;
2979
3127
  resources;
2980
3128
  terminals;
2981
- checkOutputSchema(input, signal) {
2982
- assertPromptMetadataAllowed2(input);
2983
- if (input.outputSchema === void 0) return;
2984
- return this.transport.ensureProtocol(signal).then((capabilities) => {
2985
- if ((capabilities.features.structuredDelivery ?? 0) < 1) {
2986
- throw new Error(
2987
- "Server does not support structured delivery (outputSchema)"
2988
- );
2989
- }
2990
- });
2991
- }
2992
3129
  /** `GET /sessions/search` - search saved conversation text without opening it. */
2993
3130
  async search(options) {
2994
3131
  const { signal, ...query } = options;
@@ -3013,23 +3150,8 @@ var SessionResource = class {
3013
3150
  signal: options.signal
3014
3151
  });
3015
3152
  }
3016
- async getDraftComposerOptions(input, options = {}) {
3017
- if (!validSessionControlInput("sessions.getDraftComposerOptions", input))
3018
- throw new ProtocolDataError("Invalid draft composer target");
3019
- const { workspaceId, outsideProject, roleId } = input;
3020
- const path2 = this.transport.path("/sessions/configuration-options", {
3021
- kind: "draft",
3022
- workspaceId,
3023
- outsideProject,
3024
- roleId: roleId ?? void 0
3025
- });
3026
- const result = await this.transport.request(path2, {
3027
- signal: options.signal
3028
- });
3029
- if (!validSessionControlResult("sessions.getDraftComposerOptions", result) || result.source !== input.source) {
3030
- throw new ProtocolDataError("Draft composer options do not match target");
3031
- }
3032
- return result;
3153
+ getDraftComposerOptions(input, options = {}) {
3154
+ return getDraftComposerOptions(this.transport, input, options);
3033
3155
  }
3034
3156
  async getControls(sessionId, options = {}) {
3035
3157
  const result = await this.transport.request(
@@ -3076,62 +3198,23 @@ var SessionResource = class {
3076
3198
  return response.session;
3077
3199
  }
3078
3200
  /** `POST /sessions` */
3079
- async create(input, options = {}) {
3080
- const response = await this.transport.request(
3081
- "/sessions",
3082
- {
3083
- method: "POST",
3084
- body: parseCreateSessionRequest({
3085
- ...input,
3086
- id: input.id ?? createPromptRequestId(),
3087
- requestId: input.requestId ?? createPromptRequestId()
3088
- }),
3089
- signal: options.signal
3090
- }
3091
- );
3092
- return response.session;
3201
+ create(input, options = {}) {
3202
+ return create(this.transport, input, options);
3093
3203
  }
3094
- async getConfigurationOptions(input, options = {}) {
3095
- return this.transport.request(
3096
- this.transport.path("/sessions/configuration-options", input),
3097
- { signal: options.signal }
3098
- );
3204
+ getConfigurationOptions(input, options = {}) {
3205
+ return getConfigurationOptions(this.transport, input, options);
3099
3206
  }
3100
- async getCreationResult(input, options = {}) {
3101
- return this.transport.request("/sessions/creation-result", {
3102
- method: "POST",
3103
- body: input,
3104
- signal: options.signal
3105
- });
3207
+ getCreationResult(input, options = {}) {
3208
+ return getCreationResult(this.transport, input, options);
3106
3209
  }
3107
- async getConfiguration(sessionId, options = {}) {
3108
- const value = await this.transport.requestUnknown(
3109
- `/sessions/${encodeURIComponent(sessionId)}/configuration`,
3110
- { signal: options.signal }
3111
- );
3112
- return decodeSessionConfigurationSnapshot(value);
3210
+ getConfiguration(sessionId, options = {}) {
3211
+ return getConfiguration(this.transport, sessionId, options);
3113
3212
  }
3114
- async configure(sessionId, input, options = {}) {
3115
- const body = parseConfigureSessionRequest(input);
3116
- const response = await this.transport.requestUnknown(
3117
- `/sessions/${encodeURIComponent(sessionId)}/configure`,
3118
- { method: "POST", body, signal: options.signal }
3119
- );
3120
- return decodeSessionConfigurationReceipt(response, {
3121
- sessionId,
3122
- requestId: body.requestId
3123
- });
3213
+ configure(sessionId, input, options = {}) {
3214
+ return configure(this.transport, sessionId, input, options);
3124
3215
  }
3125
- async getConfigurationResult(sessionId, input, options = {}) {
3126
- const body = parseConfigurationResultRequest(input);
3127
- const response = await this.transport.requestUnknown(
3128
- `/sessions/${encodeURIComponent(sessionId)}/configuration-result`,
3129
- { method: "POST", body, signal: options.signal }
3130
- );
3131
- return response === null ? null : decodeSessionConfigurationReceipt(response, {
3132
- sessionId,
3133
- requestId: body.requestId
3134
- });
3216
+ getConfigurationResult(sessionId, input, options = {}) {
3217
+ return getConfigurationResult(this.transport, sessionId, input, options);
3135
3218
  }
3136
3219
  /** `PATCH /sessions/:id` - update title or application metadata. */
3137
3220
  async update(sessionId, input, options = {}) {
@@ -3225,88 +3308,30 @@ var SessionResource = class {
3225
3308
  return response.part;
3226
3309
  }
3227
3310
  /** `POST /sessions/:id/prompts` — 提交用户输入并触发/排队一次 run。 */
3228
- async admitPrompt(sessionId, input, options = {}) {
3229
- const schemaCheck = this.checkOutputSchema(input, options.signal);
3230
- if (schemaCheck) await schemaCheck;
3231
- return await this.transport.request(
3232
- `/sessions/${encodeURIComponent(sessionId)}/prompts`,
3233
- {
3234
- method: "POST",
3235
- body: { ...input, id: input.id ?? createPromptRequestId() },
3236
- signal: options.signal
3237
- }
3238
- );
3311
+ admitPrompt(sessionId, input, options = {}) {
3312
+ return admitPrompt(this.transport, sessionId, input, options);
3239
3313
  }
3240
3314
  /** `POST /sessions/:id/prompts/latest/edit` */
3241
- async editLatestPrompt(sessionId, input, options = {}) {
3242
- await this.checkOutputSchema(input, options.signal);
3243
- return await this.transport.request(
3244
- `/sessions/${encodeURIComponent(sessionId)}/prompts/latest/edit`,
3245
- {
3246
- method: "POST",
3247
- body: input,
3248
- signal: options.signal
3249
- }
3250
- );
3315
+ editLatestPrompt(sessionId, input, options = {}) {
3316
+ return editLatestPrompt(this.transport, sessionId, input, options);
3251
3317
  }
3252
3318
  /** Promote one durable queued prompt into the exact active run. */
3253
- async promoteQueuedPrompt(sessionId, inputId, input, options = {}) {
3254
- return await this.transport.request(
3255
- `/sessions/${encodeURIComponent(sessionId)}/prompts/${encodeURIComponent(inputId)}/promote`,
3256
- { method: "POST", body: input, signal: options.signal }
3257
- );
3319
+ promoteQueuedPrompt(sessionId, inputId, input, options = {}) {
3320
+ return promoteQueuedPrompt(this.transport, sessionId, inputId, input, options);
3258
3321
  }
3259
- async cancelQueuedPrompt(sessionId, inputId, input, options = {}) {
3260
- const mode = parseCancelResponseMode(options.responseMode);
3261
- const response = await this.transport.request(
3262
- `/sessions/${encodeURIComponent(sessionId)}/prompts/${encodeURIComponent(inputId)}/cancel`,
3263
- {
3264
- method: "POST",
3265
- body: {
3266
- ...input,
3267
- ...options.responseMode ? { responseMode: mode } : {}
3268
- },
3269
- signal: options.signal
3270
- }
3271
- );
3272
- if (mode === "receipt") {
3273
- const receipt2 = decodeQueuedPromptCancelReceipt(response);
3274
- if (receipt2.inputId !== inputId || receipt2.queuedRunId !== input.queuedRunId)
3275
- throw new ProtocolDataError(
3276
- "Cancellation receipt does not match target"
3277
- );
3278
- return receipt2;
3279
- }
3280
- return response;
3322
+ cancelQueuedPrompt(sessionId, inputId, input, options = {}) {
3323
+ return cancelQueuedPrompt(this.transport, sessionId, inputId, input, options);
3281
3324
  }
3282
3325
  /**
3283
3326
  * `POST /sessions/:id/runs/:runId/resume` — 显式重放一次中断 run 的原始 prompt。
3284
- * 不会继续旧 provider stream;服务端会创建一个带恢复溯源的新 input/run。
3327
+ * 服务端复用原 Input,创建一个带恢复来源的新 Run。旧模型连接已经结束。
3285
3328
  */
3286
- async resumeInterruptedRun(sessionId, runId, input = {}, options = {}) {
3287
- await this.checkOutputSchema(input, options.signal);
3288
- return await this.transport.request(
3289
- `/sessions/${encodeURIComponent(sessionId)}/runs/${encodeURIComponent(runId)}/resume`,
3290
- {
3291
- method: "POST",
3292
- body: { ...input, id: input.id ?? createPromptRequestId() },
3293
- signal: options.signal
3294
- }
3295
- );
3329
+ resumeInterruptedRun(sessionId, runId, input = {}, options = {}) {
3330
+ return resumeInterruptedRun(this.transport, sessionId, runId, input, options);
3296
3331
  }
3297
3332
  /** `POST /sessions/:id/interrupt` — 中断当前/排队中的 run。 */
3298
- async interrupt(sessionId, options = {}) {
3299
- return await this.transport.request(
3300
- `/sessions/${encodeURIComponent(sessionId)}/interrupt`,
3301
- {
3302
- method: "POST",
3303
- body: options.expectedRunId || options.source ? {
3304
- ...options.expectedRunId ? { expectedRunId: options.expectedRunId } : {},
3305
- ...options.source ? { source: options.source } : {}
3306
- } : void 0,
3307
- signal: options.signal
3308
- }
3309
- );
3333
+ interrupt(sessionId, options = {}) {
3334
+ return interrupt(this.transport, sessionId, options);
3310
3335
  }
3311
3336
  /** `POST /sessions/:id/compact` */
3312
3337
  async compact(sessionId, options = {}) {
@@ -3734,6 +3759,7 @@ function applySessionSnapshot(state, snapshot) {
3734
3759
  ...state.buckets,
3735
3760
  [snapshot.session.id]: {
3736
3761
  goal: snapshot.goal,
3762
+ goalEventSeq: snapshot.cursor,
3737
3763
  session: snapshot.session,
3738
3764
  inputs: [...snapshot.inputs].sort((a, b) => a.seq - b.seq),
3739
3765
  messages: [...snapshot.messages].sort((a, b) => a.seq - b.seq),
@@ -3774,12 +3800,7 @@ function applyEvent(state, event) {
3774
3800
  switch (event.type) {
3775
3801
  case "session.goal.created":
3776
3802
  case "session.goal.updated": {
3777
- const goal = readPayloadRecord(event, "goal");
3778
- if (goal && goal.sessionId === event.sessionId) {
3779
- const bucket = cloneBucket(next.buckets[goal.sessionId]);
3780
- if (!bucket.goal || goal.revision >= bucket.goal.revision) bucket.goal = goal;
3781
- next = { ...next, buckets: { ...next.buckets, [goal.sessionId]: bucket } };
3782
- }
3803
+ next = upsertGoal(next, event);
3783
3804
  break;
3784
3805
  }
3785
3806
  case "session.goal.usage.updated": {
@@ -3838,6 +3859,24 @@ function readPayloadRecord(event, key) {
3838
3859
  const value = event.payload[key];
3839
3860
  return value && typeof value === "object" && !Array.isArray(value) ? value : void 0;
3840
3861
  }
3862
+ function upsertGoal(state, event) {
3863
+ const goal = readPayloadRecord(event, "goal");
3864
+ if (!goal || goal.sessionId !== event.sessionId) return state;
3865
+ const bucket = state.buckets[goal.sessionId];
3866
+ const current = bucket?.goal;
3867
+ const seq = bucket?.goalEventSeq ?? 0;
3868
+ const sameGoal = current?.id === goal.id;
3869
+ if (current && !sameGoal && (event.type !== "session.goal.created" || event.seq <= seq)) return state;
3870
+ const isNewer = !sameGoal || goal.revision > current.revision || goal.revision === current.revision && event.seq > seq;
3871
+ const record5 = isNewer ? goal : current;
3872
+ const usage = sameGoal && current.usage.seq >= goal.usage.seq ? current.usage : goal.usage;
3873
+ if (!isNewer && usage === current.usage) return state;
3874
+ return { ...state, buckets: { ...state.buckets, [goal.sessionId]: {
3875
+ ...bucket ?? cloneBucket(void 0),
3876
+ goal: usage === record5.usage ? record5 : { ...record5, usage },
3877
+ goalEventSeq: isNewer ? Math.max(seq, event.seq) : seq
3878
+ } } };
3879
+ }
3841
3880
  function upsertSession(state, session) {
3842
3881
  if (!session) return state;
3843
3882
  const bucket = cloneBucket(state.buckets[session.id]);
@@ -4016,6 +4055,7 @@ function upsertTask(state, task) {
4016
4055
  function cloneBucket(bucket) {
4017
4056
  return {
4018
4057
  ...bucket?.goal !== void 0 ? { goal: bucket.goal } : {},
4058
+ ...bucket?.goalEventSeq !== void 0 ? { goalEventSeq: bucket.goalEventSeq } : {},
4019
4059
  session: bucket?.session,
4020
4060
  inputs: bucket?.inputs ? [...bucket.inputs] : [],
4021
4061
  messages: bucket?.messages ? [...bucket.messages] : [],
@@ -4029,6 +4069,7 @@ function cloneBucket(bucket) {
4029
4069
  function cloneBucketForPartWrite(bucket) {
4030
4070
  return {
4031
4071
  ...bucket?.goal !== void 0 ? { goal: bucket.goal } : {},
4072
+ ...bucket?.goalEventSeq !== void 0 ? { goalEventSeq: bucket.goalEventSeq } : {},
4032
4073
  session: bucket?.session,
4033
4074
  inputs: bucket?.inputs ?? [],
4034
4075
  messages: bucket?.messages ?? [],
@@ -4157,7 +4198,7 @@ async function* runEventSync(client, options, initialState = createInitialClient
4157
4198
  state = Object.keys(next.eventsBySeq).length ? { ...next, eventsBySeq: {} } : next;
4158
4199
  cursor = Math.max(cursor, snapshot.cursor, state.lastSeq);
4159
4200
  };
4160
- const replayHistory = async function* (initial) {
4201
+ const replayHistory = async function* (initial, beforeSeq) {
4161
4202
  let pageCursor = cursor;
4162
4203
  while (!signal?.aborted) {
4163
4204
  const page = await client.events.list({
@@ -4168,7 +4209,7 @@ async function* runEventSync(client, options, initialState = createInitialClient
4168
4209
  });
4169
4210
  if (signal?.aborted) return;
4170
4211
  for (const event of page) {
4171
- if (signal?.aborted) return;
4212
+ if (signal?.aborted || beforeSeq !== void 0 && event.seq >= beforeSeq) return;
4172
4213
  const before = state;
4173
4214
  state = reduce(state, event);
4174
4215
  cursor = Math.max(cursor, event.seq, state.lastSeq);
@@ -4210,7 +4251,7 @@ async function* runEventSync(client, options, initialState = createInitialClient
4210
4251
  if (signal?.aborted) return;
4211
4252
  attempt = 0;
4212
4253
  if (event.seq > cursor + 1 && !options.sessionId) {
4213
- yield* replayHistory(false);
4254
+ yield* replayHistory(false, event.seq);
4214
4255
  }
4215
4256
  if (signal?.aborted) return;
4216
4257
  const before = state;