Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "@withone/cli",
"version": "2.16.1",
"version": "2.16.2",
"description": "CLI for managing One",
"type": "module",
"files": [
Expand Down
4 changes: 3 additions & 1 deletion skills/one/references/flows.md
Original file line number Diff line number Diff line change
Expand Up @@ -290,7 +290,7 @@ The `if`, `unless`, `condition.expression`, `while.condition`, `transform.expres

## Step Types

Every step needs `id`, `name` and `type`, plus the config object for its type. Common optional fields on any step: `if` / `unless` (JS conditions), `onError`, `timeoutMs` (the step fails with `status: "timeout"` and `errorCode: "TIMEOUT"`; the underlying API call or command is not cancelled), `requires` and `outputSchema` (below).
Every step needs `id`, `name` and `type`, plus the config object for its type. Common optional fields on any step: `if` / `unless` (JS conditions), `onError`, `timeoutMs` (the step fails with `status: "timeout"` and `errorCode: "TIMEOUT"`; an `action` or `paginate` step aborts its request, but any other step type keeps running in the background, including the steps inside a timed-out `loop`, `parallel`, `while` or `flow` step), `requires` and `outputSchema` (below).

### `action` — Execute a One API action

Expand Down Expand Up @@ -690,6 +690,8 @@ Scoped per-flow: a sub-flow uses its own `defaultOnError`, not the parent's.

Match rules: number entries are compared against any 3-digit token in the error message (covers `HTTP 429`, `status 502`, etc.); string entries match `error.errorCode` exactly OR appear as a case-insensitive substring of the message (covers Node error codes like `ETIMEDOUT` and our own `TIMEOUT`).

For an `action` or `paginate` step with `timeoutMs`, the CLI aborts its local preflight and request on timeout, and a `paginate` step fetches no further pages. A configured retry follows the existing `retryDelayMs` and backoff policy; the earlier operation may still be active when the retry begins, especially with `retryDelayMs: 0`. Aborting locally does not guarantee a remote write was rolled back: a write cancelled mid-request may or may not have reached the destination. Use the destination's idempotency support for stronger protection against duplicate writes.

**Inspecting retry outcomes.** A step that succeeded after retrying carries `$.steps.<id>.retries`, the number of retries it took (absent when the first attempt succeeded). A `retry` step that runs out of retries fails the flow, so it never lands as `status: "failed"`. `$.steps.<id>.error` is set on steps that failed under `continue` or `fallback`.

A successful-after-retry step also emits a `step:retry-success` event with the retry count, so you can distinguish a clean first-attempt success from a recovered one in logs.
Expand Down
14 changes: 14 additions & 0 deletions src/lib/action-details.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -129,6 +129,20 @@ describe('resolveActionDetails', () => {
assert.deepEqual(result.details, FULL_DETAILS);
});

it('does not serve stale action details after preflight is aborted', async () => {
writeEntry(makeEntry(FULL_DETAILS, { ageSeconds: 7200, ttl: 3600 }));
const controller = new AbortController();
const api = {
getActionDetailsWithMeta: async (_id: string, _etag?: string, signal?: AbortSignal) =>
new Promise<never>((_resolve, reject) => {
signal?.addEventListener('abort', () => reject(signal.reason), { once: true });
}),
};
const pending = resolveActionDetails(api, ACTION_ID, { signal: controller.signal });
controller.abort(new Error('cancelled'));
await assert.rejects(pending, /cancelled/);
});

it('routes the stale-fallback warning to a custom warn sink instead of stderr', async () => {
writeEntry(makeEntry(FULL_DETAILS, { ageSeconds: 7200, ttl: 3600 }));
const api = stubApi(() => { throw new Error('network down'); });
Expand Down
9 changes: 7 additions & 2 deletions src/lib/action-details.ts
Original file line number Diff line number Diff line change
Expand Up @@ -57,8 +57,9 @@ export function isActionDetailsEntry(
export async function resolveActionDetails(
api: Pick<OneApi, 'getActionDetailsWithMeta'>,
actionId: string,
opts: { useCache?: boolean; warn?: (msg: string) => void } = {}
opts: { useCache?: boolean; warn?: (msg: string) => void; signal?: AbortSignal } = {}
): Promise<ResolvedActionDetails> {
opts.signal?.throwIfAborted();
const useCache = opts.useCache !== false;
// Default warning sink is stderr; callers that resolve many actions (e.g.
// `execute --parallel`) pass a deduping sink so a shared stale action only
Expand All @@ -73,7 +74,8 @@ export async function resolveActionDetails(
}

try {
const result = await api.getActionDetailsWithMeta(actionId, cached?.etag ?? undefined);
const result = await api.getActionDetailsWithMeta(actionId, cached?.etag ?? undefined, opts.signal);
opts.signal?.throwIfAborted();

if (result.status === 304 && cached) {
cached.cachedAt = new Date().toISOString();
Expand All @@ -85,6 +87,9 @@ export async function resolveActionDetails(
writeCache(cachePath, entry);
return { details: result.data, cacheHit: false, stale: false, entry };
} catch (fetchError) {
// Cancellation must not turn into a stale-cache fallback. In particular,
// an aborted preflight must never proceed to a write action.
opts.signal?.throwIfAborted();
if (cached) {
warn(
`Warning: serving cached action details (network unavailable, cached ${formatAge(getAge(cached))} ago)\n`
Expand Down
122 changes: 122 additions & 0 deletions src/lib/api-redirect.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,26 @@ async function close(server: http.Server): Promise<void> {
await new Promise<void>((resolve, reject) => server.close(error => error ? reject(error) : resolve()));
}

/**
* Fails after `ms` instead of waiting forever. The abort tests wait on a real
* request; if the signal ever stops reaching fetch they must fail and still
* close their server. A test-level timeout is not enough: the timed-out body
* never reaches its finally block, so the open server keeps the run alive.
*/
async function bounded<T>(promise: Promise<T>, what: string, ms = 5_000): Promise<T> {
let timer: NodeJS.Timeout | undefined;
try {
return await Promise.race([
promise,
new Promise<never>((_, reject) => {
timer = setTimeout(() => reject(new Error(`${what} did not happen within ${ms}ms`)), ms);
}),
]);
} finally {
if (timer) clearTimeout(timer);
}
}

async function readRequest(req: IncomingMessage): Promise<SeenRequest> {
let body = '';
for await (const chunk of req) body += chunk.toString();
Expand Down Expand Up @@ -106,6 +126,108 @@ describe('OneApi redirect credentials', () => {
}
});

it('preserves an action request signal across a same-origin redirect', async (t) => {
const controller = new AbortController();
const signals: (AbortSignal | null | undefined)[] = [];
t.mock.method(globalThis, 'fetch', async (_url: string | URL | Request, init?: RequestInit) => {
signals.push(init?.signal);
return signals.length === 1
? new Response(null, { status: 307, headers: { Location: '/v1/passthrough/moved' } })
: new Response('{"ok":true}', { status: 200, headers: { 'content-type': 'application/json' } });
});
const api = new OneApi(SECRET, 'https://api.example.test/v1', {});
await api.executePassthroughRequest({
platform: 'test', actionId: action._id, connectionKey: CONNECTION,
signal: controller.signal,
}, action);
assert.deepEqual(signals, [controller.signal, controller.signal]);
});

it('aborts an in-flight passthrough fetch on a local server', async () => {
let received!: () => void;
const entered = new Promise<void>(resolve => { received = resolve; });
const server = await listen((_req, _res) => { received(); });
try {
const controller = new AbortController();
const api = new OneApi(SECRET, `${origin(server)}/v1`, {});
const pending = api.executePassthroughRequest({
platform: 'test', actionId: action._id, connectionKey: CONNECTION,
signal: controller.signal,
}, action);
await bounded(entered, 'the request reaching the server');
controller.abort();
await bounded(assert.rejects(pending), 'the aborted request rejecting');
} finally {
await close(server);
}
});

it('does not call fetch when cancellation precedes passthrough dispatch', async (t) => {
let fetches = 0;
t.mock.method(globalThis, 'fetch', async () => {
fetches++;
return new Response('{}');
});
const controller = new AbortController();
controller.abort();
const api = new OneApi(SECRET, 'https://api.example.test/v1', {});
await assert.rejects(api.executePassthroughRequest({
platform: 'test', actionId: action._id, connectionKey: CONNECTION,
signal: controller.signal,
}, action));
assert.equal(fetches, 0);
});

it('aborts while reading a passthrough response body', async (t) => {
let readingStarted!: () => void;
const reading = new Promise<void>(resolve => { readingStarted = resolve; });
const server = await listen((_req, res) => {
res.writeHead(200, { 'content-type': 'application/json' });
res.write('{"incomplete":');
res.flushHeaders();
});
try {
const nativeFetch = globalThis.fetch;
t.mock.method(globalThis, 'fetch', async (url: string | URL | Request, init?: RequestInit) => {
const response = await nativeFetch(url, init);
const read = response.text.bind(response);
response.text = () => {
readingStarted();
return read();
};
return response;
});
const controller = new AbortController();
const api = new OneApi(SECRET, `${origin(server)}/v1`, {});
const pending = api.executePassthroughRequest({
platform: 'test', actionId: action._id, connectionKey: CONNECTION,
signal: controller.signal,
}, action);
await bounded(reading, 'the response body read starting');
controller.abort();
await bounded(assert.rejects(pending), 'the aborted body read rejecting');
} finally {
await close(server);
}
});

it('does not follow a redirect if the signal was aborted while closing the first response', async (t) => {
const controller = new AbortController();
let fetches = 0;
t.mock.method(globalThis, 'fetch', async () => {
fetches++;
return new Response(new ReadableStream({ cancel: () => controller.abort() }), {
status: 307, headers: { Location: '/v1/passthrough/moved' },
});
});
const api = new OneApi(SECRET, 'https://api.example.test/v1', {});
await assert.rejects(api.executePassthroughRequest({
platform: 'test', actionId: action._id, connectionKey: CONNECTION,
signal: controller.signal,
}, action));
assert.equal(fetches, 1);
});

it('resolves relative redirects against the current URL', async () => {
const paths: string[] = [];
const server = await listen((req, res) => {
Expand Down
26 changes: 19 additions & 7 deletions src/lib/api.ts
Original file line number Diff line number Diff line change
Expand Up @@ -93,6 +93,9 @@ async function fetchApi(url: string, init: RequestInit): Promise<Response> {
let currentUrl = url;
let request = { ...init, redirect: 'manual' as const };
for (let redirects = 0; ; redirects++) {
// The same signal is carried through same-origin redirects. A cancellation
// during response cleanup must not dispatch the next request.
request.signal?.throwIfAborted();
const response = await fetch(currentUrl, request);
if (![301, 302, 303, 307, 308].includes(response.status)) return response;
const location = response.headers.get('location');
Expand Down Expand Up @@ -149,8 +152,8 @@ export class OneApi {
this.apiBase = apiBase ?? 'https://api.withone.ai/v1';
}

private async request<T>(path: string): Promise<T> {
return this.requestFull<T>({ path });
private async request<T>(path: string, signal?: AbortSignal): Promise<T> {
return this.requestFull<T>({ path, signal });
}

private async requestFull<T>(opts: {
Expand All @@ -159,6 +162,7 @@ export class OneApi {
body?: unknown;
headers?: Record<string, string>;
queryParams?: Record<string, string>;
signal?: AbortSignal;
}): Promise<T> {
let url = `${this.apiBase}${opts.path}`;
if (opts.queryParams && Object.keys(opts.queryParams).length > 0) {
Expand All @@ -175,6 +179,7 @@ export class OneApi {
const fetchOpts: RequestInit = {
method: opts.method || 'GET',
headers,
signal: opts.signal,
};

if (opts.body !== undefined) {
Expand Down Expand Up @@ -223,13 +228,13 @@ export class OneApi {
}
}

async listConnections(): Promise<Connection[]> {
async listConnections(signal?: AbortSignal): Promise<Connection[]> {
const allConnections: Connection[] = [];
let page = 1;
let totalPages = 1;

do {
const response = await this.request<ConnectionsResponse>(`/vault/connections?page=${page}&limit=100`);
const response = await this.request<ConnectionsResponse>(`/vault/connections?page=${page}&limit=100`, signal);
allConnections.push(...(response.rows || []));
totalPages = response.pages || 1;
page++;
Expand Down Expand Up @@ -391,10 +396,11 @@ export class OneApi {
return Array.isArray(response) ? response : [];
}

async getActionDetails(actionId: string): Promise<ActionDetails> {
async getActionDetails(actionId: string, signal?: AbortSignal): Promise<ActionDetails> {
const response = await this.requestFull<{ rows: ActionDetails[] }>({
path: '/knowledge',
queryParams: { _id: actionId },
signal,
});

const actions = response?.rows || [];
Expand All @@ -412,6 +418,7 @@ export class OneApi {
headers?: Record<string, string>;
queryParams?: Record<string, string>;
ifNoneMatch?: string;
signal?: AbortSignal;
}): Promise<ApiResponseWithMeta<T>> {
let url = `${this.apiBase}${opts.path}`;
if (opts.queryParams && Object.keys(opts.queryParams).length > 0) {
Expand All @@ -432,6 +439,7 @@ export class OneApi {
const fetchOpts: RequestInit = {
method: opts.method || 'GET',
headers,
signal: opts.signal,
};

if (opts.body !== undefined) {
Expand Down Expand Up @@ -463,12 +471,14 @@ export class OneApi {
*/
async getActionDetailsWithMeta(
actionId: string,
ifNoneMatch?: string
ifNoneMatch?: string,
signal?: AbortSignal,
): Promise<ApiResponseWithMeta<ActionDetails>> {
const result = await this.requestWithMeta<{ rows: ActionDetails[] }>({
path: '/knowledge',
queryParams: { _id: actionId },
ifNoneMatch,
signal,
});

if (result.status === 304) {
Expand All @@ -487,7 +497,7 @@ export class OneApi {
args: ExecuteActionArgs,
preloadedAction?: ActionDetails
): Promise<ExecutePassthroughResponse> {
const action = preloadedAction ?? await this.getActionDetails(args.actionId);
const action = preloadedAction ?? await this.getActionDetails(args.actionId, args.signal);

const method = action.method;
const contentType = args.isFormData
Expand Down Expand Up @@ -571,6 +581,7 @@ export class OneApi {
const fetchOpts: RequestInit = {
method,
headers: requestHeaders,
signal: args.signal,
};

if (method?.toLowerCase() !== 'get' && requestData !== undefined) {
Expand Down Expand Up @@ -627,6 +638,7 @@ export class OneApi {
};
}

args.signal?.throwIfAborted();
const response = await fetchApi(fullUrl, fetchOpts);

if (!response.ok) {
Expand Down
Loading
Loading