You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@maka.apache.org by zh...@apache.org on 2026/08/31 17:51:11 UTC
(maka) 01/03: feat(runtime): withdraw producer-owned forms
This is an automated email from the ASF dual-hosted git repository.
me2seeks pushed a commit to branch feat/4364-client-capability-form-interactions
in repository https://gitbox.apache.org/repos/asf/maka.git
commit fc5de673439ce23531256819d03dfe7efd1602a2
Author: me2seeks <me...@gmail.com>
AuthorDate: Tue Sep 1 01:15:23 2026 +0800
feat(runtime): withdraw producer-owned forms
Let an exact hosted Run withdraw one form without closing its surrounding Turn. Commit producer cancellation through the existing InteractionStore authority, preserve an already-claimed Run closure, and compose provider-local cancellation with the Tool invocation signal.
Part of #4364.
Generated-by: OpenAI Codex
---
packages/core/src/backend-types.ts | 2 +
packages/core/src/interaction.ts | 1 +
.../src/__tests__/interaction-coordinator.test.ts | 20 +++-
.../src/server/interaction-coordinator.ts | 55 +++++++++++
.../runtime/src/__tests__/fake-backend.test.ts | 1 +
.../src/__tests__/interaction-authority.test.ts | 2 +
.../__tests__/runtime-kernel-interaction.test.ts | 2 +
.../session-manager-terminal-ledger.test.ts | 1 +
.../runtime/src/__tests__/session-manager.test.ts | 1 +
.../tool-runtime-form-interaction.test.ts | 108 ++++++++++++++++-----
.../tool-runtime-sandbox-boundary.test.ts | 3 +
packages/runtime/src/interaction-authority.ts | 5 +
packages/runtime/src/tool-runtime.ts | 45 +++++++--
13 files changed, 208 insertions(+), 38 deletions(-)
diff --git a/packages/core/src/backend-types.ts b/packages/core/src/backend-types.ts
index 2c491e7048..dc2fb74822 100644
--- a/packages/core/src/backend-types.ts
+++ b/packages/core/src/backend-types.ts
@@ -157,6 +157,8 @@ export interface HostedInteractionBridge {
request: FormRequestEvent;
settlement: HostedFormSettlement;
}): Promise<void>;
+ /** Withdraw one exact producer-owned form without closing the surrounding Run. */
+ withdrawFormRequest(requestId: string): Promise<void>;
admitSandboxBoundaryRequest(input: {
request: SandboxBoundaryRequestEvent;
settlement: HostedSandboxBoundarySettlement;
diff --git a/packages/core/src/interaction.ts b/packages/core/src/interaction.ts
index cbf2ce0af7..9866e957aa 100644
--- a/packages/core/src/interaction.ts
+++ b/packages/core/src/interaction.ts
@@ -68,6 +68,7 @@ export const INTERACTION_FORM_VALUE_MAX_BYTES = 2_048;
export const INTERACTION_CLOSURE_REASONS = [
'turn_stopped',
'turn_terminal',
+ 'producer_cancelled',
'timed_out',
'host_restarted',
] as const;
diff --git a/packages/runtime-host/src/__tests__/interaction-coordinator.test.ts b/packages/runtime-host/src/__tests__/interaction-coordinator.test.ts
index 7c8c86f9c5..745c4f8265 100644
--- a/packages/runtime-host/src/__tests__/interaction-coordinator.test.ts
+++ b/packages/runtime-host/src/__tests__/interaction-coordinator.test.ts
@@ -186,13 +186,27 @@ describe('HostInteractionCoordinator', () => {
closure: (reason) => closures.push(reason),
}),
});
- await owner.close('turn_terminal');
- assert.deepEqual(closures, ['turn_terminal']);
+ await owner.withdrawFormRequest('form_2');
+ assert.deepEqual(closures, ['producer_cancelled']);
assert.deepEqual((await store.readInteraction('form_2'))?.outcome?.outcome, {
kind: 'closure',
- reason: 'turn_terminal',
+ reason: 'producer_cancelled',
committedAt: 102,
});
+
+ await owner.acceptFormRequest({
+ request: formEvent('form_3', 12),
+ continuation: formContinuation('form_3', {
+ closure: (reason) => closures.push(reason),
+ }),
+ });
+ await owner.close('turn_terminal');
+ assert.deepEqual(closures, ['producer_cancelled', 'turn_terminal']);
+ assert.deepEqual((await store.readInteraction('form_3'))?.outcome?.outcome, {
+ kind: 'closure',
+ reason: 'turn_terminal',
+ committedAt: 103,
+ });
owner.release();
await coordinator.close();
});
diff --git a/packages/runtime-host/src/server/interaction-coordinator.ts b/packages/runtime-host/src/server/interaction-coordinator.ts
index c58e2b9631..42805b8071 100644
--- a/packages/runtime-host/src/server/interaction-coordinator.ts
+++ b/packages/runtime-host/src/server/interaction-coordinator.ts
@@ -217,6 +217,7 @@ export class HostInteractionCoordinator implements RuntimeInteractionAuthority {
) => this.#acceptUserQuestionRequest(run, input),
acceptFormRequest: (input: Parameters<RuntimeInteractionRunOwner['acceptFormRequest']>[0]) =>
this.#acceptFormRequest(run, input),
+ withdrawFormRequest: (requestId: string) => this.#withdrawFormRequest(run, requestId),
acceptSandboxBoundaryRequest: (
input: Parameters<RuntimeInteractionRunOwner['acceptSandboxBoundaryRequest']>[0],
) => this.#acceptSandboxBoundaryRequest(run, input),
@@ -832,6 +833,60 @@ export class HostInteractionCoordinator implements RuntimeInteractionAuthority {
}
}
+ #withdrawFormRequest(run: BoundRun, requestId: string): Promise<void> {
+ try {
+ this.#assertOwnedRun(run);
+ this.#throwIfPoisoned();
+ if (run.released) {
+ throw this.#poison(
+ new RuntimeInteractionInvariantError(
+ `Released Interaction Run ${run.runId} cannot withdraw a form`,
+ ),
+ );
+ }
+ return observed(
+ this.#sessionAdmission.run(run.sessionId, async (admission) => {
+ this.#throwIfPoisoned();
+ // A whole-Run stop/terminal closure that already claimed ownership
+ // remains the reason for every still-pending Interaction in that Run.
+ if (run.closure) return;
+ const record = await this.#readInteraction(requestId);
+ // Cancellation may win while admission is still proving publication.
+ // The producer will also observe its abort and must not publish afterward.
+ if (!record) return;
+ if (!sameRun(record.request, run) || record.request.request.kind !== 'form') {
+ throw this.#poison(
+ new RuntimeInteractionInvariantError(
+ `Interaction Run ${run.runId} cannot withdraw form ${requestId}`,
+ ),
+ );
+ }
+ // A canonical user answer or Run closure that won the Session admission
+ // race stays authoritative.
+ if (record.outcome) return;
+ const entry = this.#requireLiveStored(record.request);
+ if (entry.kind !== 'form' || entry.run !== run) {
+ throw this.#poison(
+ new RuntimeInteractionInvariantError(
+ `Form ${requestId} is not owned by Interaction Run ${run.runId}`,
+ ),
+ );
+ }
+ const outcome = await this.#commitOutcome(record.request, {
+ kind: 'closure',
+ reason: 'producer_cancelled',
+ committedAt: this.#now(),
+ });
+ await this.#refreshCanonicalContinuity(run.sessionId, admission);
+ this.#throwIfPoisoned();
+ await this.#applyAndDelete(entry, outcome);
+ }),
+ );
+ } catch (error) {
+ return rejected(error);
+ }
+ }
+
#claimRunClosure(run: BoundRun, reason: RuntimeInteractionRunClosureReason): RunClosure {
if (run.closure) return run.closure;
diff --git a/packages/runtime/src/__tests__/fake-backend.test.ts b/packages/runtime/src/__tests__/fake-backend.test.ts
index 0673427f59..c61f3447e5 100644
--- a/packages/runtime/src/__tests__/fake-backend.test.ts
+++ b/packages/runtime/src/__tests__/fake-backend.test.ts
@@ -45,6 +45,7 @@ test('Fake question publication waits for exact hosted admission', async () => {
await allowAdmission.promise;
},
acceptFormRequest: async () => {},
+ withdrawFormRequest: async () => {},
close: async () => {},
release: () => {},
}),
diff --git a/packages/runtime/src/__tests__/interaction-authority.test.ts b/packages/runtime/src/__tests__/interaction-authority.test.ts
index 25cbb72508..ebca8c44c3 100644
--- a/packages/runtime/src/__tests__/interaction-authority.test.ts
+++ b/packages/runtime/src/__tests__/interaction-authority.test.ts
@@ -91,6 +91,7 @@ describe('Runtime Interaction authority seam', () => {
acceptSandboxBoundaryRequest: async () => {},
acceptUserQuestionRequest: async () => {},
acceptFormRequest: async () => {},
+ withdrawFormRequest: async () => {},
close: async (reason) => {
log.push(`close:${reason}`);
},
@@ -603,6 +604,7 @@ function authority(
release: () => {},
...overrides,
acceptFormRequest: overrides.acceptFormRequest ?? (async () => {}),
+ withdrawFormRequest: overrides.withdrawFormRequest ?? (async () => {}),
}),
};
}
diff --git a/packages/runtime/src/__tests__/runtime-kernel-interaction.test.ts b/packages/runtime/src/__tests__/runtime-kernel-interaction.test.ts
index 8f3ce30567..2216a52160 100644
--- a/packages/runtime/src/__tests__/runtime-kernel-interaction.test.ts
+++ b/packages/runtime/src/__tests__/runtime-kernel-interaction.test.ts
@@ -101,6 +101,7 @@ describe('RuntimeKernel Interaction close cleanup', () => {
acceptSandboxBoundaryRequest: async () => {},
acceptUserQuestionRequest: async () => {},
acceptFormRequest: async () => {},
+ withdrawFormRequest: async () => {},
close: async () => {
closeCalls += 1;
closeStarted.resolve();
@@ -485,6 +486,7 @@ function runtimeFixture(options: RuntimeFixtureOptions = {}): {
acceptSandboxBoundaryRequest: async () => {},
acceptUserQuestionRequest: async () => {},
acceptFormRequest: async () => {},
+ withdrawFormRequest: async () => {},
close: async () => {
markCloseStarted();
if (options.deferredClose) await closeReleased;
diff --git a/packages/runtime/src/__tests__/session-manager-terminal-ledger.test.ts b/packages/runtime/src/__tests__/session-manager-terminal-ledger.test.ts
index 1d2fdc1c2f..710f063415 100644
--- a/packages/runtime/src/__tests__/session-manager-terminal-ledger.test.ts
+++ b/packages/runtime/src/__tests__/session-manager-terminal-ledger.test.ts
@@ -2673,6 +2673,7 @@ function hostedInteractionAuthority(): RuntimeInteractionAuthority {
acceptSandboxBoundaryRequest: async () => {},
acceptUserQuestionRequest: async () => {},
acceptFormRequest: async () => {},
+ withdrawFormRequest: async () => {},
close: async () => {},
release: () => {},
}),
diff --git a/packages/runtime/src/__tests__/session-manager.test.ts b/packages/runtime/src/__tests__/session-manager.test.ts
index 6a52ed4cd6..b77bfc2d71 100644
--- a/packages/runtime/src/__tests__/session-manager.test.ts
+++ b/packages/runtime/src/__tests__/session-manager.test.ts
@@ -14742,6 +14742,7 @@ function testInteractionAuthority(): RuntimeInteractionAuthority {
acceptSandboxBoundaryRequest: async () => {},
acceptUserQuestionRequest: async () => {},
acceptFormRequest: async () => {},
+ withdrawFormRequest: async () => {},
close: async () => {},
release: () => {},
}),
diff --git a/packages/runtime/src/__tests__/tool-runtime-form-interaction.test.ts b/packages/runtime/src/__tests__/tool-runtime-form-interaction.test.ts
index af70508124..72653b191a 100644
--- a/packages/runtime/src/__tests__/tool-runtime-form-interaction.test.ts
+++ b/packages/runtime/src/__tests__/tool-runtime-form-interaction.test.ts
@@ -19,6 +19,7 @@
import assert from 'node:assert/strict';
import { describe, test } from 'node:test';
+import type { HostedFormSettlement } from '@maka/core/backend-types';
import type { SessionEvent } from '@maka/core/events';
import type { SessionHeader } from '@maka/core/session';
import { z } from 'zod';
@@ -49,7 +50,7 @@ function header(): SessionHeader {
};
}
-function formTool(): MakaTool<Record<string, never>> {
+function formTool(cancellationSignal?: AbortSignal): MakaTool<Record<string, never>> {
return {
name: 'SyntheticForm',
description: 'Exercise the provider-neutral form seam.',
@@ -57,30 +58,33 @@ function formTool(): MakaTool<Record<string, never>> {
nesting: 'direct_only',
impl: (_input, context) => {
if (!context.requestUserForm) throw new Error('Form Interaction is unavailable');
- return context.requestUserForm({
- message: 'Choose deployment settings',
- requester: { name: 'deploy', source: 'Synthetic provider' },
- fields: [
- {
- kind: 'integer',
- name: 'replicas',
- label: 'Replicas',
- required: true,
- minimum: 1,
- maximum: 10,
- },
- {
- kind: 'multi_select',
- name: 'regions',
- label: 'Regions',
- required: false,
- options: [
- { value: 'us', label: 'US' },
- { value: 'eu', label: 'EU' },
- ],
- },
- ],
- });
+ return context.requestUserForm(
+ {
+ message: 'Choose deployment settings',
+ requester: { name: 'deploy', source: 'Synthetic provider' },
+ fields: [
+ {
+ kind: 'integer',
+ name: 'replicas',
+ label: 'Replicas',
+ required: true,
+ minimum: 1,
+ maximum: 10,
+ },
+ {
+ kind: 'multi_select',
+ name: 'regions',
+ label: 'Regions',
+ required: false,
+ options: [
+ { value: 'us', label: 'US' },
+ { value: 'eu', label: 'EU' },
+ ],
+ },
+ ],
+ },
+ cancellationSignal ? { cancellationSignal } : undefined,
+ );
},
};
}
@@ -197,4 +201,58 @@ describe('ToolRuntime form Interaction', () => {
false,
);
});
+
+ test('withdraws the exact hosted form when its producer is cancelled', async () => {
+ const events: SessionEvent[] = [];
+ const producer = new AbortController();
+ let admitted: { requestId: string; settlement: HostedFormSettlement } | undefined;
+ const withdrawals: string[] = [];
+ const toolRuntime = createTestToolRuntime({
+ sessionId: 'session-1',
+ header: header(),
+ connection: { providerType: 'openai', slug: 'c' } as never,
+ modelId: 'm',
+ appendMessage: async () => {},
+ newId: (() => {
+ let id = 0;
+ return () => `id-${++id}`;
+ })(),
+ now: () => 1,
+ getPermissionPauseTarget: () => null,
+ hostedInteraction: {
+ sessionId: 'session-1',
+ turnId: 'turn-1',
+ runId: 'run-1',
+ admitUserQuestionRequest: async () => {
+ throw new Error('Unexpected user question');
+ },
+ admitFormRequest: async (input) => {
+ admitted = { requestId: input.request.requestId, settlement: input.settlement };
+ },
+ withdrawFormRequest: async (requestId) => {
+ withdrawals.push(requestId);
+ await admitted?.settlement.applyClosure('producer_cancelled');
+ },
+ admitSandboxBoundaryRequest: async () => {
+ throw new Error('Unexpected sandbox boundary');
+ },
+ },
+ });
+ const pending = toolRuntime.settleToolCall({
+ tool: formTool(producer.signal),
+ turnId: 'turn-1',
+ toolCallId: 'tool-1',
+ input: {},
+ abortSignal: new AbortController().signal,
+ eventSink: sink(events),
+ });
+ while (!admitted) await new Promise<void>((resolve) => setImmediate(resolve));
+
+ producer.abort(new DOMException('Provider invocation ended', 'AbortError'));
+ await pending;
+
+ assert.deepEqual(withdrawals, [admitted.requestId]);
+ assert.equal(toolRuntime.pendingUserFormCount(), 0);
+ assert.equal(events.filter((event) => event.type === 'form_answer_ack').length, 0);
+ });
});
diff --git a/packages/runtime/src/__tests__/tool-runtime-sandbox-boundary.test.ts b/packages/runtime/src/__tests__/tool-runtime-sandbox-boundary.test.ts
index 24ed3e74ca..f3e464cb09 100644
--- a/packages/runtime/src/__tests__/tool-runtime-sandbox-boundary.test.ts
+++ b/packages/runtime/src/__tests__/tool-runtime-sandbox-boundary.test.ts
@@ -222,6 +222,9 @@ describe('ToolRuntime session sandbox boundary', () => {
admitFormRequest: async () => {
throw new Error('Unexpected user form');
},
+ withdrawFormRequest: async () => {
+ throw new Error('Unexpected user form withdrawal');
+ },
admitSandboxBoundaryRequest: async ({ request, settlement }) => {
admittedRequest = request;
captured = settlement;
diff --git a/packages/runtime/src/interaction-authority.ts b/packages/runtime/src/interaction-authority.ts
index 3594b34eaa..0863ba5519 100644
--- a/packages/runtime/src/interaction-authority.ts
+++ b/packages/runtime/src/interaction-authority.ts
@@ -119,6 +119,7 @@ export interface RuntimeInteractionRunFacet
RuntimeInteractionRunIdentity {}
export interface RuntimeInteractionRunOwner extends RuntimeInteractionRunFacet {
+ withdrawFormRequest(requestId: string): Promise<void>;
close(reason: RuntimeInteractionRunClosureReason): Promise<void>;
release(): void;
}
@@ -362,6 +363,10 @@ export class RuntimeInteractionRunBinding implements HostedInteractionBridge {
}
}
+ withdrawFormRequest(requestId: string): Promise<void> {
+ return this.owner.withdrawFormRequest(requestId);
+ }
+
async admitSandboxBoundaryRequest(input: {
request: SandboxBoundaryRequestEvent;
settlement: HostedSandboxBoundarySettlement;
diff --git a/packages/runtime/src/tool-runtime.ts b/packages/runtime/src/tool-runtime.ts
index 6363a6363e..7978b4bbdc 100644
--- a/packages/runtime/src/tool-runtime.ts
+++ b/packages/runtime/src/tool-runtime.ts
@@ -279,7 +279,10 @@ export interface MakaToolContext {
view?: 'result' | 'events' | 'runtime_events' | 'all';
}) => Promise<unknown>;
askUserQuestion?: (questions: UserQuestion[]) => Promise<UserQuestionResult>;
- requestUserForm?: (form: InteractionFormInput) => Promise<InteractionFormResult>;
+ requestUserForm?: (
+ form: InteractionFormInput,
+ options?: { readonly cancellationSignal?: AbortSignal },
+ ) => Promise<InteractionFormResult>;
requestSandboxBoundary?: (
expansion: SandboxBoundaryExpansion,
justification: string,
@@ -1652,8 +1655,15 @@ export class ToolRuntime {
}),
askUserQuestion: (questions) =>
this.askUserQuestion(turnId, toolUseId, questions, ctx.abortSignal, queue),
- requestUserForm: (form) =>
- this.requestUserForm(turnId, toolUseId, form, ctx.abortSignal, queue),
+ requestUserForm: (form, options) =>
+ this.requestUserForm(
+ turnId,
+ toolUseId,
+ form,
+ ctx.abortSignal,
+ queue,
+ options?.cancellationSignal,
+ ),
requestSandboxBoundary: (expansion, justification) =>
this.requestSandboxBoundary(
turnId,
@@ -2549,8 +2559,10 @@ export class ToolRuntime {
form: InteractionFormInput,
abortSignal: AbortSignal,
queue: DurableSessionEventSink,
+ producerCancellationSignal?: AbortSignal,
): Promise<InteractionFormResult> {
- throwIfAborted(abortSignal);
+ const interactionSignal = composeChildAbortSignal(abortSignal, producerCancellationSignal);
+ throwIfAborted(interactionSignal);
const hostedRun = this.interactionRun();
const requestId = this.input.newId();
const request = projectInteractionFormRequest({ toolUseId, ...form });
@@ -2564,7 +2576,18 @@ export class ToolRuntime {
this.userForms.reject(requestId, abortErrorFromSignal(abortSignal));
this.finishDeferredFormTurnClosure();
};
+ let producerWithdrawal: Promise<void> | undefined;
+ const onProducerCancellation = (): void => {
+ if (abortSignal.aborted) return;
+ if (hostedRun) {
+ producerWithdrawal ??= hostedRun.withdrawFormRequest(requestId);
+ } else if (producerCancellationSignal) {
+ this.userForms.reject(requestId, abortErrorFromSignal(producerCancellationSignal));
+ this.finishDeferredFormTurnClosure();
+ }
+ };
abortSignal.addEventListener('abort', onAbort, { once: true });
+ producerCancellationSignal?.addEventListener('abort', onProducerCancellation, { once: true });
if (hostedRun) void parked.catch(() => undefined);
try {
const requestEvent: FormRequestEvent = {
@@ -2582,9 +2605,9 @@ export class ToolRuntime {
const settlement = this.createFormSettlement(turnId, requestId);
const admission = hostedRun.admitFormRequest({ request: requestEvent, settlement });
try {
- await racePromiseWithAbort(admission, abortSignal);
+ await racePromiseWithAbort(admission, interactionSignal);
} catch (error) {
- if (abortSignal.aborted) {
+ if (interactionSignal.aborted) {
void admission.catch((admissionError) => {
this.userForms.reject(
requestId,
@@ -2597,7 +2620,7 @@ export class ToolRuntime {
);
this.finishDeferredFormTurnClosure();
});
- throw abortErrorFromSignal(abortSignal);
+ throw abortErrorFromSignal(interactionSignal);
}
this.userForms.reject(
requestId,
@@ -2616,10 +2639,10 @@ export class ToolRuntime {
);
}
}
- throwIfAborted(abortSignal);
+ throwIfAborted(interactionSignal);
queue.push(requestEvent);
- const response = await racePromiseWithAbort(parked, abortSignal);
- throwIfAborted(abortSignal);
+ const response = await racePromiseWithAbort(parked, interactionSignal);
+ throwIfAborted(interactionSignal);
const answerAck: FormAnswerAckEvent = {
type: 'form_answer_ack',
id: this.input.newId(),
@@ -2635,6 +2658,8 @@ export class ToolRuntime {
: { action: response.action };
} finally {
abortSignal.removeEventListener('abort', onAbort);
+ producerCancellationSignal?.removeEventListener('abort', onProducerCancellation);
+ if (producerWithdrawal) await producerWithdrawal;
}
}
---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@maka.apache.org
For additional commands, e-mail: commits-help@maka.apache.org