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: 3 additions & 1 deletion docs/operations.md
Original file line number Diff line number Diff line change
Expand Up @@ -63,7 +63,7 @@ With `--wait`, the command stays until the question has an outcome, or until you
| 16 | `wait-timeout` | `--wait-timeout` (1s to 365d) passed first. The question is left as it is. |
| 130 | `interrupted` | SIGINT (143: SIGTERM) came first. The question is left as it is. |

Status 1 is an error (a relay that refuses this client, a revoked device, an unknown question ID) and 2 a usage error (a malformed flag, both deadlines); neither is a question outcome, and neither prints a result. Stopping a wait never cancels the question: resume it with `decisions wait <question_id>`. An outcome that arrives as the wait stops is the one reported. A question that needs a person's attention (an answer that could not be accepted, a notice that could not be written) is reported once on standard error, and the wait goes on: `--wait-timeout` bounds it.
Status 1 is an error (a relay that refuses this client, a revoked device, an unknown question ID) and 2 a usage error (a malformed flag, both deadlines); neither is a question outcome, and neither prints a result. Stopping a wait never cancels the question: resume it with `decisions wait <question_id>`. An outcome that arrives as the wait stops is the one reported. A question that needs a person's attention (an answer that could not be accepted, a notice that could not be written) is reported once on standard error, and the wait goes on until it has an outcome: `--wait-timeout` bounds it. An advisory plan whose notice the receiving process's sink refused (a `file:` sink whose directory is missing, or an `exec:` sink whose shell could not be started) has its outcome all the same, in every process: `advisory-expired` (13), `fallback_due: true` and `delivery: needs-attention`, or `expired` once this computer's policy no longer allows advice. (A command that starts and then exits with any status but 0 or 75, a missing program included, leaves the notice `uncertain` instead, which every process also reports; 75 asks for the write to be tried again later.)

With `--json`, standard output carries one JSON object per line, each with a `record` field: `asked` (the receipt), then `notice` lines when this process's own stdout sink writes one (the text the sink would type), and finally `result`. A script reads the last line, or the line whose `record` is `result`; diagnostics (relay connection, sync failures, warnings) go to standard error only. The `result` record has `outcome`, `exit_code`, `delivery`, `signal` (for `interrupted`), and every field of `get_decision`: `status`, `provenance`, `choice`, `text`, `closed_reason`, `fallback_due`, `advisory_timeout`, `publication`, `expires_at`, `reply_mode`, `planned_fallback`, `thread` and the rest. `delivery` says where the outcome's notice stands in the receiving process's sink, kept apart from the outcome: `delivered` (the sink confirmed the write), `pending`, `uncertain` (a write may or may not have happened, and it is never written again on its own), `needs-attention` (nothing was written, and a person has to decide), or `none` (none is due). An answer whose notice is `uncertain` is still the answer in the record. Without `--json`, the receipt and the result are plain sentences, and the outcome is in the exit status.

Expand All @@ -74,6 +74,8 @@ With `--json`, standard output carries one JSON object per line, each with a `re

Both take `--pane mcp` for a question an agent asked through `decisions mcp`; the default is a question asked with `decisions ask`. A question asked from another pane is reported as unknown. Both read the state directory's local copy, which a running receiver keeps current.

While another process receives, `wait` and `get` report an advisory plan as due only once that receiver has read the relay and acted on the plan's notice: written it, perhaps written it, or had its sink refuse the write. Until then `wait` goes on and `get` reports `outcome: null` and `fallback_due: false`; neither can see whether the receiver is still reading the relay, where a reopen may be on its way. So while the notice waits to be written again (an `exec:` command that exited 75), or needs attention for another reason (no terminal to write to, or a refusal recorded by an earlier version of decisions), the receiver's own `get_decision` can already say `fallback_due: true` when `get` does not. The receiver writing the notice settles it, and so does stopping the receiver: `wait` then receives itself and reports from its own read of the relay.

### Who gets the notice

Stdout belongs to the process running the sink. A notice is written by the one process that receives for the state directory, to its own sink:
Expand Down
12 changes: 9 additions & 3 deletions packages/cli/src/commands/ask.ts
Original file line number Diff line number Diff line change
Expand Up @@ -93,7 +93,7 @@ function currentAdvisoryTimeout(v: DecisionView) {
*
* `receiving`: this process runs the bridge that reads the relay, so its own view of the ledger decides that. A process
* that does not (another one receives, or `get`) cannot see a replay under way there, so it takes the plan as due only
* once the receiver has written, or may have written, its notice.
* once the receiver has written, or may have written, its notice, or had its sink refuse a write it admitted.
*/
export function outcomeOf(
v: DecisionView,
Expand All @@ -102,8 +102,14 @@ export function outcomeOf(
const advisory = currentAdvisoryTimeout(v);
if (advisory?.disposition === 'fallback-due') {
if (!v.fallbackDue) return null;
// Written, or perhaps written, by the receiver: it read the relay before it wrote. Nothing written proves nothing.
if (!o.receiving && advisory.notice !== 'delivered' && advisory.notice !== 'uncertain')
// Written, perhaps written, or refused by the receiver's sink: it read the relay before it wrote. A notice it never
// tried to write proves nothing.
if (
!o.receiving &&
advisory.notice !== 'delivered' &&
advisory.notice !== 'uncertain' &&
!advisory.writeRefused
)
return null;
}
switch (v.status) {
Expand Down
121 changes: 121 additions & 0 deletions packages/cli/tests/ask-wait.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -119,6 +119,7 @@ describe('the outcome a wait reports', () => {
disposition: 'fallback-due' as const,
notice: 'delivered' as const,
injectionId: 'i',
writeRefused: false,
agentAction: 'unobserved' as const,
...o,
});
Expand Down Expand Up @@ -206,6 +207,34 @@ describe('the outcome a wait reports', () => {
});
expect(outcomeOf(unwritten)).toBeNull();
expect(outcomeOf(unwritten, { receiving: true })).toBe('advisory-expired');
// Unless the receiver's sink refused a write it admitted: it read the relay before it tried.
const refused = v({
...expired,
fallbackDue: true,
advisoryTimeout: timeout({
notice: 'needs-attention',
injectionId: null,
writeRefused: true,
}),
});
expect(outcomeOf(refused)).toBe('advisory-expired');
expect(deliveryOf(refused, 'advisory-expired')).toBe('needs-attention');
// Still held where it reads (an event of its question waits to be applied): no outcome yet.
expect(outcomeOf({ ...refused, fallbackDue: false })).toBeNull();
// A policy that withholds it now: a plain expiry, from any process.
expect(
outcomeOf(
v({
...expired,
fallbackDue: false,
advisoryTimeout: timeout({
disposition: 'fallback-withheld',
notice: 'needs-attention',
writeRefused: true,
}),
}),
),
).toBe('expired');
const withheld = v({
...expired,
advisoryTimeout: timeout({ disposition: 'fallback-withheld', notice: 'pending' }),
Expand Down Expand Up @@ -1113,6 +1142,98 @@ describe('the standalone flow through decisions mcp', () => {
}
});

it("reports a due advisory plan from another process while the receiver's sink cannot write its notice", async () => {
const e = await env({ advisory: true });
const server = e.proc({ json: false });
let release!: () => void;
const until = new Promise<void>((r) => (release = r));
let ready!: (url: string, token: string) => void;
const up = new Promise<{ url: string; token: string }>(
(r) => (ready = (url, token) => r({ url, token })),
);
const serving = daemon(
server.ctx,
{},
{
socket: false,
poll: FAST,
pumpIntervalMs: 20,
// A directory that does not exist: the notice can never be written.
sink: `file:${join(e.home, 'missing', 'notices.log')}`,
until,
mcp: { port: 0 },
onReady: (h) => ready(h.mcp!.url, h.token!),
},
);
const { url, token } = await up;
const call = async (name: string, args: unknown) => {
const r = await fetch(url, {
method: 'POST',
headers: { 'content-type': 'application/json', authorization: `Bearer ${token}` },
body: JSON.stringify({
jsonrpc: '2.0',
id: 1,
method: 'tools/call',
params: { name, arguments: args },
}),
});
return (
(await r.json()) as {
result: { isError?: boolean; structuredContent: Record<string, unknown> };
}
).result;
};
try {
const asked = await vi.waitFor(async () => {
const r = await call('ask_human', {
question: 'Which fixture should I use?',
expires_in: '15m',
planned_fallback: 'I will use the in-memory fixture.',
});
expect(r.isError).toBeFalsy();
return r.structuredContent;
});
const id = asked.question_id as string;
await vi.waitFor(() => expect(e.created()).toEqual([id]));

const waiter = e.proc();
const waiting = waitCmd(waiter.ctx, {}, id, {
pane: 'mcp',
waitTimeout: '3s',
stopped: never(),
...QUICK,
});
// It only reads: the server receives, and its sink is the one that refuses the notice.
await vi.waitFor(() =>
expect(waiter.err.join('\n')).toMatch(/another decisions process receives/),
);
e.clock.skew = 16 * MIN;
e.relay.expiryEvent({ questionId: id });
expect(await waiting).toBe(13);
expect(waiter.records()).toHaveLength(1);
expect(result(waiter.records())).toMatchObject({
outcome: 'advisory-expired',
exit_code: 13,
fallback_due: true,
delivery: 'needs-attention',
advisory_timeout: { disposition: 'fallback-due', notice: 'needs-attention' },
});
expect(waiter.calls.filter((c) => c.includes('/events'))).toEqual([]);

const viaMcp = (await call('get_decision', { question_id: id })).structuredContent;
expect(viaMcp).toMatchObject({ status: 'expired', fallback_due: true });
const got = e.proc();
await getCmd(got.ctx, {}, id, { pane: 'mcp' });
const viaCli = JSON.parse(got.out[0]!) as Record<string, unknown>;
expect(viaCli).toMatchObject({ outcome: 'advisory-expired', delivery: 'needs-attention' });
const { outcome: _o, delivery: _d, ...fields } = viaCli;
expect(fields).toEqual(viaMcp);
} finally {
release();
await serving;
}
});

it('writes the notice through an exec sink while the result stays on stdout', async () => {
const e = await env();
const copy = join(e.home, 'exec.log');
Expand Down
6 changes: 6 additions & 0 deletions packages/client/src/answers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,12 @@ export interface AnswerEntry {
* reopen has replaced the round; the notice is never typed again on its own.
*/
uncertain_injection_id?: string;
/**
* An advisory notice only: its sink refused a write this host had admitted (the ledger had settled for its round, as
* for a write that lands), so nothing was typed and a person has to decide. Kept with the entry so a process that
* does not receive can tell the plan was settled; a retry clears it.
*/
write_refused?: boolean;
/** Replaces an earlier answer. */
correction: boolean;
created_at: string;
Expand Down
68 changes: 54 additions & 14 deletions packages/client/src/bridge.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ import {
type AttachmentSpool,
type BridgeContext,
} from './context.js';
import { DeliveryEngine, type DrainResult } from './delivery.js';
import { ADVISORY_LEDGER_WAIT_MS, DeliveryEngine, type DrainResult } from './delivery.js';
import { EventVerifier } from './inbound.js';
import { Inbox } from './inbox.js';
import {
Expand Down Expand Up @@ -206,6 +206,15 @@ const CATCH_UP_TIMEOUT_MS = 30_000;
/** How many stored, unapplied events `ledgerUnsettled` looks through for the question's own. */
const UNAPPLIED_SCAN = 500;

/** The question a stored ledger event is about, when it names one. */
function eventQuestionId(e: { json: string }): unknown {
try {
return (JSON.parse(e.json) as { question_id?: unknown }).question_id;
} catch {
return undefined;
}
}

/**
* The protocol extensions the bridge declares to the relay (section 19), on its socket ticket and its event
* pages. `phone-images-v1` is declared with or without a `phoneImages` store: a relay hides an image-bearing
Expand Down Expand Up @@ -349,8 +358,9 @@ export interface DecisionView {
* round's deadline passed unanswered (`advisoryTimeout`, `fallback-due`), or the question never reached the relay
* before it, under a host that delivers advisory outcomes and whose policy allows them. A notice already typed
* keeps what it said; one still to be typed follows the policy as it is now, and is false while it waits for this
* desktop to read the relay (a reopen may be on its way). It is never an answer or an approval: the person decided
* nothing.
* desktop to read the relay (a reopen may be on its way), unless its sink refused a write admitted after that read
* (`advisoryTimeout.writeRefused`): that one waits only on what this computer's store shows, an event of its question
* not yet applied among them. It is never an answer or an approval: the person decided nothing.
*/
fallbackDue: boolean;
/**
Expand Down Expand Up @@ -415,6 +425,12 @@ export interface AdvisoryTimeoutView {
notice: 'pending' | 'delivered' | 'uncertain' | 'needs-attention' | 'superseded';
/** The write that delivered the notice, or that may have; null otherwise. */
injectionId: string | null;
/**
* True when the notice needs attention because its sink refused a write this host had admitted, once it had read the
* relay for the notice's round as for a write that lands: the plan is settled as for a written notice, although
* nothing was typed. False otherwise, a notice that needs attention for another reason (its pane gone) included.
*/
writeRefused: boolean;
/** Always `unobserved`: Decisions never sees whether the agent carried out the plan. */
agentAction: 'unobserved';
}
Expand Down Expand Up @@ -1408,12 +1424,17 @@ export class DecisionsBridge {
// ahead here either.
const noticeWaits =
timeout?.inForce === true &&
(timeout.view.notice === 'pending' || timeout.view.notice === 'needs-attention');
(timeout.view.notice === 'pending' ||
(timeout.view.notice === 'needs-attention' && !timeout.view.writeRefused));
// Read (and the hold timed from now, if it is not yet) only once a notice waits; an earlier unsettled read wins.
const held = noticeWaits
? await this.delivery.ledgerHolds(row.question_id).catch(() => true)
: false;
const waiting = noticeWaits && (unsettled === true || held);
// One whose admitted write its sink refused was settled as a typed one is, so only what the store shows every
// process alike holds it (`refusalHeld`).
const refusedWaits =
timeout?.inForce === true && timeout.view.writeRefused ? await this.refusalHeld(row) : false;
const waiting = (noticeWaits && (unsettled === true || held)) || refusedWaits;
const answered = row.local_status === 'human-answered' || row.local_status === 'proxy-answered';
// The answer in force is the last one that carried content; a later confirm-proxy makes it the human's.
let current: OpenAnswerEntry | undefined;
Expand Down Expand Up @@ -1566,6 +1587,7 @@ export class DecisionsBridge {
: notice === 'uncertain'
? (e.uncertain_injection_id ?? null)
: null,
writeRefused: notice === 'needs-attention' && e.write_refused === true,
agentAction: 'unobserved',
},
};
Expand Down Expand Up @@ -1647,21 +1669,39 @@ export class DecisionsBridge {
*/
private async ledgerUnsettled(questionId: string): Promise<'unapplied' | 'reading' | null> {
const stored = await this.ctx.store.unprocessedEvents(UNAPPLIED_SCAN);
for (const e of stored) {
let id: unknown;
try {
id = (JSON.parse(e.json) as { question_id?: unknown }).question_id;
} catch {
id = undefined;
}
if (id === questionId) return 'unapplied';
}
if (stored.some((e) => eventQuestionId(e) === questionId)) return 'unapplied';
// More than were looked through: one of them may be the question's, so the wait is bounded like a read's.
return this.socketReplay || this.paging !== null || !this.ledgerRead || stored.length > 0
? 'reading'
: null;
}

/**
* Whether an advisory notice of `row` whose write its sink refused still waits (`view`), from the store alone: an event
* of its question is stored and not yet applied (a reopen read past a gap), the store cannot be read, or the row has
* moved on since it was read. More stored than one look reads may hide one of the question's, so they hold it as a
* read under way does, two minutes at most, timed from the refused attempt. Looked at after the row was read, so an
* event stored before the refusal is either still waiting here or applied, which the row read again shows.
*/
private async refusalHeld(row: QuestionRow): Promise<boolean> {
try {
const stored = await this.ctx.store.unprocessedEvents(UNAPPLIED_SCAN);
if (stored.some((e) => eventQuestionId(e) === row.question_id)) return true;
const tried = row.last_attempt_at ? Date.parse(row.last_attempt_at) : NaN;
if (stored.length >= UNAPPLIED_SCAN && !(this.ctx.now() - tried >= ADVISORY_LEDGER_WAIT_MS))
return true;
const now = await this.ctx.store.getQuestion(row.question_id);
return (
!now ||
now.local_status !== row.local_status ||
now.question_revision !== row.question_revision ||
now.answers_json !== row.answers_json
);
} catch {
return true;
}
}

/** The pane became idle (Daintree's wake gate): try pending deliveries now. */
async notifyPaneIdle(): Promise<DrainResult> {
return this.delivery.drain();
Expand Down
Loading
Loading