@hanzo/build 0.2.122 → 0.2.124

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.
@@ -0,0 +1,59 @@
1
+ /** One action a command performs, as the agent parses it (exec's `command_actions`). */
2
+ export type Action = {
3
+ type: 'read';
4
+ command: string;
5
+ name: string;
6
+ path: string;
7
+ } | {
8
+ type: 'listFiles';
9
+ command: string;
10
+ path: string | null;
11
+ } | {
12
+ type: 'search';
13
+ command: string;
14
+ query: string | null;
15
+ path: string | null;
16
+ } | {
17
+ type: 'unknown';
18
+ command: string;
19
+ };
20
+ /** One call in an Explored block: what it did, and how it exited (null while it runs). */
21
+ export interface Explore {
22
+ actions: Action[];
23
+ exit: number | null;
24
+ }
25
+ /** One line of an Explored block: the CLI's verb, and what it names. */
26
+ export interface Line {
27
+ title: string;
28
+ text: string;
29
+ }
30
+ /** One file of a patch, with the lines it adds and removes — null from a `dev` too old to count them. */
31
+ export interface Changed {
32
+ path: string;
33
+ kind: 'add' | 'delete' | 'update';
34
+ added: number | null;
35
+ removed: number | null;
36
+ }
37
+ /** A file's line counts as the CLI writes them, "(+a -r)", or nothing when they were not counted. */
38
+ export declare const counted: (f: Pick<Changed, 'added' | 'removed'>) => string;
39
+ /** A command's actions as exec's stream states them; anything it does not name is not one. */
40
+ export declare function actions(raw: unknown): Action[];
41
+ /** Whether a call is exploration: it read, listed or searched, and did nothing else. */
42
+ export declare const explores: (a: Action[]) => boolean;
43
+ /**
44
+ * An Explored block's lines, as the CLI writes them: a call that only read, and the
45
+ * reads that follow it, are one "Read" line naming each file once; any other call
46
+ * says each action on a line of its own. A call that exited non-zero says so on its
47
+ * last line — "(command exit N)" for a compound command.
48
+ */
49
+ export declare function explored(calls: Explore[]): Line[];
50
+ /**
51
+ * A command as the CLI shows it: a shell's own wrapper (`bash -lc '…'`) taken off,
52
+ * the script it ran left. exec's stream joins the argv as a shell would (shlex), so
53
+ * the script is the wrapper's last word, unquoted.
54
+ */
55
+ export declare function shown(command: string): string;
56
+ /** A patch's header, as the CLI writes it: one file named with its verb, or the count of files. */
57
+ export declare function edited(files: Changed[]): string;
58
+ /** An MCP call as the CLI names it: server.tool(arguments), the arguments as compact JSON. */
59
+ export declare const called: (server: string, tool: string, args: unknown) => string;
package/lib/api/cli.js ADDED
@@ -0,0 +1,133 @@
1
+ /**
2
+ * A run's tool calls as `dev` prints them in its terminal (hanzoai/dev, the TUI's
3
+ * exec, patch and MCP cells): the run IS `dev exec`, so its transcript reads in
4
+ * the CLI's own words and groups —
5
+ *
6
+ * • Explored reads, listings and searches, consecutive ones in one block
7
+ * └ Search widget in src one line an action
8
+ * Read lib.rs, main.rs consecutive reads, one line, each name once
9
+ * • Ran cargo test any other command, the shell's own wrapper taken off
10
+ * └ ok
11
+ * • Edited lib.rs (+2 -1) a patch: Added / Deleted / Edited, or "Edited N files (+a -r)"
12
+ * • Called hanzo.search({"q":1}) an MCP tool, server.tool(arguments)
13
+ *
14
+ * What a command does is the agent's own parse of it (`command_actions` in exec's
15
+ * stream), and the lines a patch adds and removes are its own count (`added`,
16
+ * `removed`): nothing here parses a command or a diff. Running, a block says
17
+ * Exploring, Running or Calling, as the CLI does.
18
+ */
19
+ import { phrase } from '@hanzo/i18n';
20
+ /** A file's line counts as the CLI writes them, "(+a -r)", or nothing when they were not counted. */
21
+ export const counted = (f) => (f.added === null || f.removed === null ? '' : `(+${f.added} -${f.removed})`);
22
+ const str = (v) => (typeof v === 'string' ? v : '');
23
+ const nullable = (v) => (typeof v === 'string' ? v : null);
24
+ /** A command's actions as exec's stream states them; anything it does not name is not one. */
25
+ export function actions(raw) {
26
+ if (!Array.isArray(raw))
27
+ return [];
28
+ return raw.flatMap((a) => {
29
+ const o = a && typeof a === 'object' ? a : {};
30
+ switch (o.type) {
31
+ case 'read':
32
+ return [{ type: 'read', command: str(o.command), name: str(o.name), path: str(o.path) }];
33
+ case 'listFiles':
34
+ return [{ type: 'listFiles', command: str(o.command), path: nullable(o.path) }];
35
+ case 'search':
36
+ return [{ type: 'search', command: str(o.command), query: nullable(o.query), path: nullable(o.path) }];
37
+ case 'unknown':
38
+ return [{ type: 'unknown', command: str(o.command) }];
39
+ }
40
+ return [];
41
+ });
42
+ }
43
+ /** Whether a call is exploration: it read, listed or searched, and did nothing else. */
44
+ export const explores = (a) => a.length > 0 && a.every((x) => x.type !== 'unknown');
45
+ /**
46
+ * An Explored block's lines, as the CLI writes them: a call that only read, and the
47
+ * reads that follow it, are one "Read" line naming each file once; any other call
48
+ * says each action on a line of its own. A call that exited non-zero says so on its
49
+ * last line — "(command exit N)" for a compound command.
50
+ */
51
+ export function explored(calls) {
52
+ const out = [];
53
+ const failed = (c) => c.exit !== null && c.exit !== 0;
54
+ const reads = (c) => c.actions.every((a) => a.type === 'read');
55
+ for (let i = 0; i < calls.length;) {
56
+ const call = calls[i];
57
+ let n = 1;
58
+ if (reads(call) && !failed(call))
59
+ while (i + n < calls.length && !failed(calls[i + n]) && reads(calls[i + n]))
60
+ n++;
61
+ const group = calls.slice(i, i + n);
62
+ i += n;
63
+ const lines = reads(call)
64
+ ? [{ title: phrase('Read'), text: [...new Set(group.flatMap((c) => c.actions.map((a) => (a.type === 'read' ? a.name : ''))))].join(', ') }]
65
+ : call.actions.map((a) => {
66
+ switch (a.type) {
67
+ case 'read':
68
+ return { title: phrase('Read'), text: a.name };
69
+ case 'listFiles':
70
+ return { title: phrase('List'), text: a.path ?? a.command };
71
+ case 'search':
72
+ return { title: phrase('Search'), text: a.query !== null && a.path !== null ? `${a.query} in ${a.path}` : (a.query ?? a.command) };
73
+ default:
74
+ return { title: phrase('Run'), text: a.command };
75
+ }
76
+ });
77
+ if (failed(call)) {
78
+ const last = lines[lines.length - 1];
79
+ last.text += call.actions.length > 1 ? ` (command exit ${call.exit})` : ` (exit ${call.exit})`;
80
+ }
81
+ out.push(...lines);
82
+ }
83
+ return out;
84
+ }
85
+ /**
86
+ * A command as the CLI shows it: a shell's own wrapper (`bash -lc '…'`) taken off,
87
+ * the script it ran left. exec's stream joins the argv as a shell would (shlex), so
88
+ * the script is the wrapper's last word, unquoted.
89
+ */
90
+ export function shown(command) {
91
+ const m = /^(?:\S*\/)?(?:bash|zsh|sh)\s+-l?c\s+(.+)$/s.exec(command.trim());
92
+ return m ? unquote(m[1]) : command;
93
+ }
94
+ /** One shell word, its quoting taken off: single quotes, double quotes and backslashes. */
95
+ function unquote(word) {
96
+ let out = '';
97
+ for (let i = 0; i < word.length; i++) {
98
+ const c = word[i];
99
+ if (c === "'") {
100
+ const end = word.indexOf("'", i + 1);
101
+ if (end < 0)
102
+ return word;
103
+ out += word.slice(i + 1, end);
104
+ i = end;
105
+ }
106
+ else if (c === '"') {
107
+ let j = i + 1;
108
+ for (; j < word.length && word[j] !== '"'; j++)
109
+ out += word[j] === '\\' && j + 1 < word.length ? word[++j] : word[j];
110
+ i = j;
111
+ }
112
+ else if (c === '\\' && i + 1 < word.length)
113
+ out += word[++i];
114
+ else if (/\s/.test(c))
115
+ return word; // more than one word: not one script
116
+ else
117
+ out += c;
118
+ }
119
+ return out;
120
+ }
121
+ /** A patch's header, as the CLI writes it: one file named with its verb, or the count of files. */
122
+ export function edited(files) {
123
+ if (files.length === 1) {
124
+ const [f] = files;
125
+ const verb = f.kind === 'add' ? 'Added' : f.kind === 'delete' ? 'Deleted' : 'Edited';
126
+ return `${verb} ${f.path} ${counted(f)}`.trim();
127
+ }
128
+ const known = files.every((f) => f.added !== null && f.removed !== null);
129
+ const total = known ? { added: files.reduce((n, f) => n + f.added, 0), removed: files.reduce((n, f) => n + f.removed, 0) } : { added: null, removed: null };
130
+ return `Edited ${files.length} ${files.length === 1 ? 'file' : 'files'} ${counted(total)}`.trim();
131
+ }
132
+ /** An MCP call as the CLI names it: server.tool(arguments), the arguments as compact JSON. */
133
+ export const called = (server, tool, args) => `${server}.${tool}(${args === undefined || args === null ? '' : JSON.stringify(args)})`;
@@ -26,6 +26,12 @@ export interface Ask {
26
26
  effort?: string;
27
27
  /** The number of the issue on `repo` this run resolves: its pull request says `Closes #<n>`. */
28
28
  issue?: number;
29
+ /** Client-generated idempotency key so retries never duplicate a run. */
30
+ requestId?: string;
31
+ /** Out-of-band instructions (skills, memories) kept separate from `prompt`. */
32
+ instructions?: string;
33
+ /** Explicit alias for `instructions` passed via `-c developer_instructions=...`. */
34
+ developerInstructions?: string;
29
35
  }
30
36
  export interface Run {
31
37
  session: string;
@@ -48,7 +54,7 @@ export declare function start(t: Target, ask: Ask): Promise<Run>;
48
54
  * with the words; the follow-up's session arrives on this run's own stream as
49
55
  * its `followed` status (turn.ts `followed`).
50
56
  */
51
- export declare function steer(t: Target, session: string, text: string): Promise<void>;
57
+ export declare function steer(t: Target, session: string, text: string, requestId?: string): Promise<void>;
52
58
  /** A run a follow-up continues, as its record states it. */
53
59
  export interface Earlier {
54
60
  id: string;
package/lib/api/coding.js CHANGED
@@ -40,6 +40,14 @@ export const unhonoured = (mode, target, t = english) => !target?.trim()
40
40
  : mode === 'setup'
41
41
  ? t('A setup runs in the Hanzo sandbox: a machine clones and pushes with its own credential. Choose Cloud, or switch to Build.')
42
42
  : '';
43
+ let reqSeq = 0;
44
+ function newRequestId() {
45
+ const uuid = globalThis.crypto?.randomUUID?.();
46
+ if (uuid)
47
+ return uuid;
48
+ reqSeq += 1;
49
+ return `req_${Date.now().toString(36)}_${reqSeq.toString(36)}`;
50
+ }
43
51
  /**
44
52
  * The request body: only what was asked, with no empty strings sent as values.
45
53
  * A run in the sandbox asks for one with a desktop, so its Desktop tab has a
@@ -47,7 +55,19 @@ export const unhonoured = (mode, target, t = english) => !target?.trim()
47
55
  */
48
56
  export function body(ask) {
49
57
  const out = { prompt: ask.prompt.trim() };
50
- for (const k of ['repo', 'base', 'targetId', 'project', 'after', 'mode', 'model', 'effort']) {
58
+ for (const k of [
59
+ 'repo',
60
+ 'base',
61
+ 'targetId',
62
+ 'project',
63
+ 'after',
64
+ 'mode',
65
+ 'model',
66
+ 'effort',
67
+ 'requestId',
68
+ 'instructions',
69
+ 'developerInstructions',
70
+ ]) {
51
71
  const v = ask[k]?.trim();
52
72
  if (v)
53
73
  out[k] = v;
@@ -64,7 +84,7 @@ export async function start(t, ask) {
64
84
  const why = unhonoured(ask.mode, ask.targetId);
65
85
  if (why)
66
86
  throw new Refusal(400, why);
67
- const r = await call(t, 'POST', '/v1/agent/coding', body(ask));
87
+ const r = await call(t, 'POST', '/v1/agent/coding', body({ ...ask, requestId: ask.requestId?.trim() || newRequestId() }));
68
88
  const s = (k) => (typeof r?.[k] === 'string' ? r[k] : '');
69
89
  if (!s('sessionId'))
70
90
  throw new Refusal(502, phrase('The run was admitted but named no session'));
@@ -83,11 +103,14 @@ export async function start(t, ask) {
83
103
  * with the words; the follow-up's session arrives on this run's own stream as
84
104
  * its `followed` status (turn.ts `followed`).
85
105
  */
86
- export async function steer(t, session, text) {
106
+ export async function steer(t, session, text, requestId) {
87
107
  const words = text.trim();
88
108
  if (!words)
89
109
  throw new Refusal(400, phrase('Say something to the run'));
90
- await call(t, 'POST', `/v1/agent/coding/${seg(session)}/steer`, { text: words });
110
+ await call(t, 'POST', `/v1/agent/coding/${seg(session)}/steer`, {
111
+ text: words,
112
+ requestId: requestId?.trim() || newRequestId(),
113
+ });
91
114
  }
92
115
  /**
93
116
  * The earlier run's ask, without the codebase its title leads with (`universe:
@@ -127,10 +150,14 @@ const modeOf = (m) => (m === 'plan' || m === 'setup' ? m : 'build');
127
150
  * when it carries a paused run on (apps/coding steer.go followUp).
128
151
  */
129
152
  export function followUp(e, said) {
153
+ const next = from(e);
130
154
  const head = headline(e.title, e.repo);
131
155
  const words = said.trim();
132
156
  let prompt;
133
- if (words) {
157
+ if (next.after) {
158
+ prompt = words || 'Continue where the earlier run left off.';
159
+ }
160
+ else if (words) {
134
161
  const was = head ? `This follows an earlier run on this codebase: “${head}”.` : 'This follows an earlier run on this codebase.';
135
162
  prompt = `${words}\n\n${was}${e.pushed ? ' Its work so far is on this branch; build on it.' : ''}`;
136
163
  }
@@ -138,7 +165,7 @@ export function followUp(e, said) {
138
165
  const kept = e.pushed ? 'An earlier run already worked on this; its work so far is on this branch. Build on it. ' : '';
139
166
  prompt = `${head}\n\n${kept}Continue where the earlier run left off.`.trim();
140
167
  }
141
- return { ...from(e), prompt, mode: modeOf(e.mode) };
168
+ return { ...next, prompt, mode: modeOf(e.mode) };
142
169
  }
143
170
  /** A build of what a plan run answered: its ask as the title, and the plan to carry out. */
144
171
  export function approve(e, plan) {
@@ -27,6 +27,12 @@ export interface Session {
27
27
  org: string;
28
28
  /** Whether its story is open to the public build route. Only a run that names a project can be. */
29
29
  published: boolean;
30
+ /** Where it was started: 'app' for a conversation in Dev (talk.ts), '' for a run on its own. */
31
+ channel: string;
32
+ /** The session it belongs to — a conversation, for the coding runs it started — or ''. */
33
+ parent: string;
34
+ /** The top of its tree: its own id for a session of its own. A stream is followed by it. */
35
+ root: string;
30
36
  events: number;
31
37
  createdAt: string;
32
38
  updatedAt: string;
@@ -53,6 +59,8 @@ export declare function event(raw: unknown): Event;
53
59
  export declare function took(runs: Session[], mode: string): [number, number] | null;
54
60
  export interface ListQuery {
55
61
  kind?: string;
62
+ /** The sessions started on one channel: 'app' for Dev's conversations. */
63
+ channel?: string;
56
64
  project?: string;
57
65
  /** running, paused, done or error: the four the platform filters on. */
58
66
  status?: string;
@@ -67,7 +75,16 @@ export interface Page {
67
75
  }
68
76
  export declare function page(t: Target, q?: ListQuery): Promise<Page>;
69
77
  export declare function list(t: Target, q?: ListQuery): Promise<Session[]>;
70
- export declare function get(t: Target, id: string): Promise<Detail>;
78
+ export interface GetOptions {
79
+ limit?: number;
80
+ after?: number;
81
+ }
82
+ export declare function get(t: Target, id: string, opts?: GetOptions): Promise<Detail>;
83
+ /**
84
+ * A session's whole log, oldest first, read a page at a time — what a conversation
85
+ * draws from its first word, where the detail carries only the latest fifty.
86
+ */
87
+ export declare function log(t: Target, id: string): Promise<Event[]>;
71
88
  export declare function message(t: Target, id: string, text: string): Promise<void>;
72
89
  export declare function stop(t: Target, id: string, why?: string): Promise<void>;
73
90
  export declare function pause(t: Target, id: string): Promise<void>;
@@ -88,8 +105,13 @@ export interface Watch {
88
105
  /** Each (re)connect. The first is 0; a later one means frames may have been missed. */
89
106
  open?: (attempt: number) => void;
90
107
  }
108
+ export interface WatchOptions {
109
+ /** Resume replaying missed events strictly after this sequence number. */
110
+ after?: number;
111
+ }
91
112
  /**
92
- * Follow one run's tree until `signal` aborts. Reconnects with a capped backoff;
93
- * a refusal (401/403) ends it, because retrying a no is not recovery.
113
+ * Follow one run's tree until `signal` aborts. Reconnects with a capped backoff
114
+ * and replays missed frames via `?after=<lastSeq>` + `Last-Event-ID`; a refusal
115
+ * (401/403) ends it, because retrying a no is not recovery.
94
116
  */
95
- export declare function watch(t: Target, root: string, on: Watch, signal: AbortSignal): Promise<void>;
117
+ export declare function watch(t: Target, root: string, on: Watch, signal: AbortSignal, opts?: WatchOptions): Promise<void>;
@@ -1,8 +1,10 @@
1
1
  /**
2
- * Runs, as the platform records them: one session per run.
2
+ * Runs, as the platform records them: one session per run — and Dev's
3
+ * conversations (talk.ts), one session for every turn.
3
4
  *
4
- * GET /v1/agent/sessions?kind=&project=&status=&limit=&after= newest first, {sessions, next}
5
+ * GET /v1/agent/sessions?kind=&channel=&project=&status=&limit=&after= newest first, {sessions, next}
5
6
  * GET /v1/agent/sessions/{id} + the 50 most recent events
7
+ * GET /v1/agent/sessions/{id}/events?after=&limit= its whole log, a page at a time, {events, next}
6
8
  * PATCH /v1/agent/sessions/{id} {title}|{published} rename it; open its story to the public build route
7
9
  * POST /v1/agent/sessions/{id}/message {message} steer a running run
8
10
  * POST /v1/agent/sessions/{id}/pause pause it; a sandbox run keeps its work on its branch
@@ -41,6 +43,9 @@ export function session(raw) {
41
43
  sandbox: str(s.sandbox),
42
44
  org: str(s.org),
43
45
  published: s.published === true,
46
+ channel: str(s.channel),
47
+ parent: str(s.parentSessionId),
48
+ root: str(s.rootSessionId),
44
49
  events: num(s.events),
45
50
  createdAt: str(s.createdAt),
46
51
  updatedAt: str(s.updatedAt),
@@ -84,21 +89,45 @@ export async function page(t, q = {}) {
84
89
  export async function list(t, q = {}) {
85
90
  return (await page(t, q)).sessions;
86
91
  }
87
- export async function get(t, id) {
88
- const raw = obj(await call(t, 'GET', `/v1/agent/sessions/${seg(id)}`));
92
+ export async function get(t, id, opts) {
93
+ const raw = obj(await call(t, 'GET', `/v1/agent/sessions/${seg(id)}${query({ limit: opts?.limit, after: opts?.after })}`));
89
94
  let recent = (Array.isArray(raw.recentEvents) ? raw.recentEvents : []).map(event);
90
- // The detail carries the 50 most recent events; when a long run has scrolled
91
- // past seq 1, read the opening turns so the person's full multi-line ask stays
92
- // at the head of the transcript and in Try again.
93
- if (recent.length > 0 && recent[0].seq > 1) {
94
- try {
95
- const head = obj(await call(t, 'GET', `/v1/agent/sessions/${seg(id)}/events?limit=2`));
96
- const first = (Array.isArray(head.events) ? head.events : []).map(event);
97
- const have = new Set(recent.map((e) => e.seq));
98
- recent = [...first.filter((e) => e.seq > 0 && !have.has(e.seq)), ...recent].sort((a, b) => a.seq - b.seq);
95
+ // When `limit` is explicitly requested (e.g. Run's initial 500-event load) and a
96
+ // long coding run still exceeds one page (`recent[0].seq > 1`), page forward from
97
+ // seq 0 so middle history is never dropped. Without `opts`, keep the lightweight
98
+ // 2-event head fetch so short summary callers stay single-hop.
99
+ if (recent.length > 0 && recent[0].seq > 1 && opts?.after === undefined) {
100
+ const tailFloor = recent[0].seq;
101
+ if (opts?.limit && opts.limit > 50) {
102
+ try {
103
+ const earlier = [];
104
+ let cursor = 0;
105
+ for (let page = 0; page < 6 && cursor < tailFloor - 1; page++) {
106
+ const chunk = obj(await call(t, 'GET', `/v1/agent/sessions/${seg(id)}/events${query({ after: cursor || undefined, limit: Math.min(1000, opts.limit) })}`));
107
+ const rows = (Array.isArray(chunk.events) ? chunk.events : []).map(event);
108
+ earlier.push(...rows.filter((e) => e.seq > 0 && e.seq < tailFloor));
109
+ const next = num(chunk.next);
110
+ if (next <= cursor || next >= tailFloor - 1)
111
+ break;
112
+ cursor = next;
113
+ }
114
+ const have = new Set(recent.map((e) => e.seq));
115
+ recent = [...earlier.filter((e) => !have.has(e.seq)), ...recent].sort((a, b) => a.seq - b.seq);
116
+ }
117
+ catch {
118
+ /* keep the tail */
119
+ }
99
120
  }
100
- catch {
101
- /* keep the tail */
121
+ else {
122
+ try {
123
+ const head = obj(await call(t, 'GET', `/v1/agent/sessions/${seg(id)}/events?limit=2`));
124
+ const first = (Array.isArray(head.events) ? head.events : []).map(event);
125
+ const have = new Set(recent.map((e) => e.seq));
126
+ recent = [...first.filter((e) => e.seq > 0 && !have.has(e.seq)), ...recent].sort((a, b) => a.seq - b.seq);
127
+ }
128
+ catch {
129
+ /* keep the tail */
130
+ }
102
131
  }
103
132
  }
104
133
  return {
@@ -106,6 +135,22 @@ export async function get(t, id) {
106
135
  recent,
107
136
  };
108
137
  }
138
+ /**
139
+ * A session's whole log, oldest first, read a page at a time — what a conversation
140
+ * draws from its first word, where the detail carries only the latest fifty.
141
+ */
142
+ export async function log(t, id) {
143
+ const out = [];
144
+ let after = 0;
145
+ for (;;) {
146
+ const raw = obj(await call(t, 'GET', `/v1/agent/sessions/${seg(id)}/events${query({ after: after || undefined, limit: 1000 })}`));
147
+ out.push(...(Array.isArray(raw.events) ? raw.events : []).map(event));
148
+ const next = num(raw.next);
149
+ if (next <= after)
150
+ return out;
151
+ after = next;
152
+ }
153
+ }
109
154
  export async function message(t, id, text) {
110
155
  const m = text.trim();
111
156
  if (!m)
@@ -141,16 +186,21 @@ export async function publish(t, id, on) {
141
186
  /** Where anyone can read a published run's story: the public build route, by org and project. '' without both. */
142
187
  export const story = (t, org, project) => org && project ? `${t.api}/v1/agent/builds/${seg(org)}/${seg(project)}` : '';
143
188
  /**
144
- * Follow one run's tree until `signal` aborts. Reconnects with a capped backoff;
145
- * a refusal (401/403) ends it, because retrying a no is not recovery.
189
+ * Follow one run's tree until `signal` aborts. Reconnects with a capped backoff
190
+ * and replays missed frames via `?after=<lastSeq>` + `Last-Event-ID`; a refusal
191
+ * (401/403) ends it, because retrying a no is not recovery.
146
192
  */
147
- export async function watch(t, root, on, signal) {
193
+ export async function watch(t, root, on, signal, opts) {
148
194
  let opened = 0;
149
195
  let fails = 0;
196
+ let lastSeq = opts?.after && Number.isFinite(opts.after) && opts.after > 0 ? Math.floor(opts.after) : 0;
150
197
  while (!signal.aborted) {
151
198
  try {
152
- const res = await fetch(`${t.api}/v1/agent/sessions/stream${query({ root })}`, {
153
- headers: headers(t, { Accept: 'text/event-stream' }),
199
+ const extra = { Accept: 'text/event-stream' };
200
+ if (lastSeq > 0)
201
+ extra['Last-Event-ID'] = String(lastSeq);
202
+ const res = await fetch(`${t.api}/v1/agent/sessions/stream${query({ root, after: lastSeq > 0 ? lastSeq : undefined })}`, {
203
+ headers: headers(t, extra),
154
204
  cache: 'no-store',
155
205
  signal,
156
206
  });
@@ -170,8 +220,17 @@ export async function watch(t, root, on, signal) {
170
220
  }
171
221
  if (f.event === 'session')
172
222
  on.session?.(session(obj(data).session));
173
- else if (f.event === 'event')
174
- on.event?.(event(obj(data).event));
223
+ else if (f.event === 'event') {
224
+ const ev = event(obj(data).event);
225
+ if (!root || !ev.sessionId || ev.sessionId === root) {
226
+ const fid = Number(f.id);
227
+ if (Number.isInteger(fid) && fid > lastSeq)
228
+ lastSeq = fid;
229
+ if (ev.seq > lastSeq)
230
+ lastSeq = ev.seq;
231
+ }
232
+ on.event?.(ev);
233
+ }
175
234
  }, signal);
176
235
  }
177
236
  catch (e) {
@@ -0,0 +1,48 @@
1
+ import { type Target } from './call.ts';
2
+ import type { Event, Session } from './sessions.ts';
3
+ /** The channel a conversation's session is on. */
4
+ export declare const TALK = "app";
5
+ /**
6
+ * Whether a session is a conversation, rather than one run. A conversation's runs
7
+ * are on its channel too — born in its tree, its person's alone — and are told
8
+ * from it by having a parent: the conversation is the root.
9
+ */
10
+ export declare const talks: (s: Pick<Session, 'channel' | 'parent'> | null | undefined) => boolean;
11
+ export interface Say {
12
+ /** The conversation to continue. Absent starts one. */
13
+ session?: string;
14
+ /** What the person said. */
15
+ input: string;
16
+ /** The model, by the id GET /v1/models lists. */
17
+ model?: string;
18
+ /** The repository: its name in the org, or owner/name on GitHub. */
19
+ repo?: string;
20
+ /** The branch a coding run starts from. */
21
+ base?: string;
22
+ /** One of the org's machines. Absent is the sandbox. */
23
+ target?: string;
24
+ /** How the conversation's coding runs go: on their own, asked for first, or plans only. */
25
+ mode?: 'auto' | 'manual' | 'plan';
26
+ /** How hard a coding run thinks: low, medium or high. */
27
+ effort?: string;
28
+ /** The issue on `repo` a coding run resolves. */
29
+ issue?: number;
30
+ /** Out-of-band instructions (skills, memories) kept separate from `input`. */
31
+ instructions?: string;
32
+ /** Explicit alias for `instructions` forwarded to turns and coding runs. */
33
+ developerInstructions?: string;
34
+ }
35
+ export interface Said {
36
+ /** The conversation: the same id on every turn. */
37
+ session: string;
38
+ /** This turn's run within it. */
39
+ run: string;
40
+ }
41
+ /** The request body: only what was said, with no empty values sent. */
42
+ export declare function body(s: Say): Record<string, string | number | boolean>;
43
+ /** Say one thing in a conversation: a new one without `session`, that one with it. */
44
+ export declare function say(t: Target, s: Say): Promise<Said>;
45
+ /** What a conversation's turn is doing now: its latest progress line, or ''. */
46
+ export declare function now(events: Pick<Event, 'kind' | 'payload' | 'seq'>[]): string;
47
+ /** Answer a question a session's run asked: an option pressed, or the person's own words. */
48
+ export declare function answer(t: Target, session: string, question: string, text: string, chosen: boolean): Promise<void>;
@@ -0,0 +1,81 @@
1
+ /**
2
+ * Dev's conversation, as the platform keeps it (apps/agents talk.go): one
3
+ * session, every turn.
4
+ *
5
+ * POST /v1/agent/turns {session?, input, model?, effort?, repo?, base?, target?, mode?, issue?}
6
+ * → {sessionId, runId}
7
+ * POST /v1/agent/sessions/{id}/answer {question, text, chosen} answer what a turn asked
8
+ *
9
+ * The first thing said opens the conversation; everything said after continues
10
+ * the SAME session under a new run, once its last turn has answered — what is said
11
+ * while a turn still works is that turn's next input (sessions.ts `message`). The
12
+ * agent answers, and decides for itself when a turn needs a sandbox (leased on its
13
+ * first use, kept for the conversation) or a coding run (which carries on the
14
+ * conversation's last, in its sandbox and on its branch). A turn that only talks
15
+ * uses neither, and a turn ends when its answer does: a build it started is
16
+ * followed after, and its outcome is said into the conversation when it ends.
17
+ *
18
+ * The repository, branch, machine and mode are kept on the conversation from the
19
+ * first message: every coding run its turns start works on them, auto starts it,
20
+ * manual asks first (a question answered here), plan only reads and plans. The
21
+ * model and effort ride each turn. Between turns the session rests `paused`.
22
+ */
23
+ import { phrase } from '@hanzo/i18n';
24
+ import { call, Refusal, seg } from './call.js';
25
+ import { decode } from './turn.js';
26
+ /** The channel a conversation's session is on. */
27
+ export const TALK = 'app';
28
+ /**
29
+ * Whether a session is a conversation, rather than one run. A conversation's runs
30
+ * are on its channel too — born in its tree, its person's alone — and are told
31
+ * from it by having a parent: the conversation is the root.
32
+ */
33
+ export const talks = (s) => s?.channel === TALK && !s.parent;
34
+ /** The request body: only what was said, with no empty values sent. */
35
+ export function body(s) {
36
+ const out = { input: s.input.trim() };
37
+ for (const k of [
38
+ 'session',
39
+ 'model',
40
+ 'effort',
41
+ 'repo',
42
+ 'base',
43
+ 'target',
44
+ 'mode',
45
+ 'instructions',
46
+ 'developerInstructions',
47
+ ]) {
48
+ const v = s[k]?.trim();
49
+ if (v)
50
+ out[k] = v;
51
+ }
52
+ if (s.issue && Number.isInteger(s.issue) && s.issue > 0)
53
+ out.issue = s.issue;
54
+ return out;
55
+ }
56
+ /** Say one thing in a conversation: a new one without `session`, that one with it. */
57
+ export async function say(t, s) {
58
+ if (!s.input.trim())
59
+ throw new Refusal(400, phrase('Say something'));
60
+ const r = await call(t, 'POST', '/v1/agent/turns', body(s));
61
+ const session = typeof r?.sessionId === 'string' ? r.sessionId : '';
62
+ if (!session)
63
+ throw new Refusal(502, phrase('The conversation answered with no session'));
64
+ return { session, run: typeof r?.runId === 'string' ? r.runId : '' };
65
+ }
66
+ /** What a conversation's turn is doing now: its latest progress line, or ''. */
67
+ export function now(events) {
68
+ let doing = '';
69
+ for (const e of [...events].sort((a, b) => a.seq - b.seq)) {
70
+ const b = decode(e.payload);
71
+ if (e.kind === 'progress' && b && typeof b !== 'string' && typeof b.activity === 'string')
72
+ doing = b.activity;
73
+ }
74
+ return doing;
75
+ }
76
+ /** Answer a question a session's run asked: an option pressed, or the person's own words. */
77
+ export async function answer(t, session, question, text, chosen) {
78
+ if (!text.trim())
79
+ throw new Refusal(400, phrase('Say an answer'));
80
+ await call(t, 'POST', `/v1/agent/sessions/${seg(session)}/answer`, { question, text: text.trim(), chosen });
81
+ }