agy-mcp-bridge 0.1.12 → 0.1.13

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/README.md CHANGED
@@ -399,10 +399,18 @@ Lưu ý bảo mật: nội dung yêu cầu và phản hồi được hiển th
399
399
 
400
400
  Đây là chỉ dẫn, không phải rào chắn kỹ thuật: bridge không ép được mô hình ngừng đọc file trong lúc chờ. Mức tiết kiệm thực tế chưa được đo.
401
401
 
402
+ **Tiến độ từng bước (stream-json):** `agy-mcp-bridge probe-stream` trên `agy` 1.4.x cho thấy khi chạy với `--print <prompt> --output-format stream-json`, `agy` phát các sự kiện `init`, `step_update` (nhiều lần, khi đang làm việc) và `result` (kết quả cuối). Cài đặt → "Hiển thị tiến độ từng bước" (mặc định **tắt**, áp dụng cho task mới) cho bridge chạy task theo cách đó: prompt vẫn nằm trên dòng lệnh, chỉ định dạng output đổi.
403
+
404
+ - Các bước hiện trong chi tiết task ("Các bước Antigravity báo cáo", mới nhất lên đầu), mỗi bước là một dòng tóm tắt tự động kèm dữ liệu gốc (đã lọc secret) mở ra được. Bridge giữ 100 bước gần nhất mỗi task, trong bộ nhớ.
405
+ - Các sự kiện `step_update` **không** được ghi vào log stdout của task, nên hàng nghìn bước không làm chạm trần output (256 KiB mặc định); `init` và `result` vẫn được giữ.
406
+ - Mỗi bước là bằng chứng "còn sống" thật: chúng được tính là hoạt động cho phần gia hạn bên dưới, và `antigravity_task_wait`/`status` báo thêm "N steps reported" trong dòng `activity` (không gửi nội dung bước cho Codex/Claude để khỏi tốn token).
407
+ - **Chưa biết:** nội dung chi tiết bên trong `step_update` (chỉ biết tên các khóa ngoài cùng: `event`, `step_update`), nên phần tóm tắt chọn các trường dễ hiểu (`title`, `type`, `status`, `tool`, `message`, `path`...) nếu có, nếu không thì hiện tên các trường. Cũng chưa kiểm chứng kết quả cuối ở chế độ này có cùng dạng với chế độ JSON (`status`, `response`, `num_turns`). Nếu không giống, task báo lỗi kèm tên các trường của `result` (chỉ tên, không có giá trị) và cách quay về chế độ JSON: tắt tùy chọn này.
408
+ - Muốn bridge biết chính xác hình dạng bên trong các sự kiện, chạy lại `agy-mcp-bridge probe-stream` ở bản mới: nó in thêm tên và kiểu của các trường bên trong (không in giá trị).
409
+
402
410
  **Biết Antigravity còn hoạt động, và gia hạn thay vì dừng giữa chừng (time out mềm):** ở chế độ `--print --output-format json`, `agy` không in gì cho đến khi xong, nên bridge không thể biết chắc nó đang "suy luận". Bridge chỉ nhìn được những dấu hiệu còn sống: byte mới ở output, và (khi bạn bật tính năng này) việc file log của `agy` được ghi thêm. Cài đặt → "Gia hạn khi Antigravity còn hoạt động" (mặc định **tắt**, áp dụng cho task mới) làm như sau:
403
411
 
404
412
  - Bridge yêu cầu `agy` ghi log vào `.bridge-state/agy-logs/<task_id>.log` (cờ `--log-file`) và cho `agy` giới hạn tuyệt đối làm print timeout của chính nó, thay vì hạn của task.
405
- - Đến hạn của task (`timeout_seconds`), bridge **không dừng ngay**: nó kiểm tra có hoạt động trong khoảng vừa qua không. Còn thì gia hạn rồi kiểm tra lại sau **1 phút, rồi 5 phút, rồi mỗi 10 phút**. Không có hoạt động trong khoảng đó thì dừng task (trạng thái `timeout`, lý do ghi trong `error`).
413
+ - Đến hạn của task (`timeout_seconds`), bridge **không dừng ngay**: nó kiểm tra có hoạt động trong khoảng vừa qua không (byte mới ở output, bước tiến độ nếu bật, hoặc ghi log). Còn thì gia hạn rồi kiểm tra lại sau **1 phút, rồi 5 phút, rồi mỗi 10 phút**. Không có hoạt động trong khoảng đó thì dừng task (trạng thái `timeout`, lý do ghi trong `error`).
406
414
  - **Giới hạn tuyệt đối** (30 phút đến 8 giờ, mặc định 2 giờ) luôn có hiệu lực: task vẫn còn hoạt động cũng dừng khi tới mức này, để một task treo hay chạy mãi không giữ chỗ vô hạn (chỉ có một task chạy một lúc).
407
415
  - Chi tiết task trong giao diện hiện "Log của agy cập nhật … (KB)", "Output cuối …", số lần đã gia hạn và lần kiểm tra tiếp theo. `antigravity_task_wait` và `antigravity_task_status` trả thêm một dòng `activity` (ví dụ `last log activity 12s ago; deadline extended 2x while active`) để Codex/Claude không phải tự đọc log.
408
416
  - **Chưa kiểm chứng:** tôi chưa biết `agy` có ghi log đều đặn trong lúc suy luận hay chỉ ghi lúc bắt đầu và kết thúc. Nếu log không tăng khi `agy` đang chạy thì không có dấu hiệu nào để gia hạn, và task dừng đúng hạn như khi tắt tính năng (không tệ hơn). Cách kiểm tra: bật tính năng, giao một task kéo dài vài chục giây và xem dòng "Log của agy cập nhật…" tăng khi task đang chạy.
@@ -28,12 +28,23 @@ catch {
28
28
  return null;
29
29
  } });
30
30
  const kinds = new Map();
31
+ const typeOf = (value) => value === null ? 'null' : Array.isArray(value) ? 'array' : typeof value;
31
32
  for (const event of events) {
32
33
  const kind = event ? String(event.event ?? event.type ?? '(no event/type key)') : '(not JSON)';
33
- const entry = kinds.get(kind) ?? { count: 0, keys: new Set() };
34
+ const entry = kinds.get(kind) ?? { count: 0, keys: new Set(), inner: new Map() };
34
35
  entry.count++;
35
36
  for (const key of Object.keys(event ?? {}))
36
37
  entry.keys.add(key);
38
+ // One level down: only the names and value types of the fields (never the values), so the shape can be shared without exposing content.
39
+ for (const [key, value] of Object.entries(event ?? {})) {
40
+ if (value && typeof value === 'object' && !Array.isArray(value)) {
41
+ for (const [innerKey, innerValue] of Object.entries(value)) {
42
+ const seen = entry.inner.get(`${key}.${innerKey}`) ?? new Set();
43
+ seen.add(typeOf(innerValue));
44
+ entry.inner.set(`${key}.${innerKey}`, seen);
45
+ }
46
+ }
47
+ }
37
48
  kinds.set(kind, entry);
38
49
  }
39
50
  const results = paths.resultsDirectory;
@@ -41,8 +52,11 @@ await mkdir(results, { recursive: true });
41
52
  await writeFile(path.join(results, 'stream-probe.ndjson'), stdout);
42
53
  await writeFile(path.join(results, 'stream-probe.stderr.txt'), stderr);
43
54
  console.log(`agy exit code: ${code}; ${lines.length} stdout line(s); raw output saved to ${path.join(results, 'stream-probe.ndjson')} (not committed)`);
44
- for (const [kind, { count, keys }] of kinds)
55
+ for (const [kind, { count, keys, inner }] of kinds) {
45
56
  console.log(`- ${kind} x${count}: keys = ${[...keys].join(', ')}`);
57
+ if (inner.size)
58
+ console.log(` fields: ${[...inner].map(([name, types]) => `${name}:${[...types].join('|')}`).join(', ')}`);
59
+ }
46
60
  console.log(events.every(Boolean) ? 'Every stdout line is a JSON object.' : 'Some stdout lines are not JSON; see the raw file.');
47
- console.log('Share the event names and keys above (not the raw file, which may contain paths) to build progress reporting on the real format.');
61
+ console.log('Share the event names, keys and fields above (names and types only, no values; not the raw file, which may contain paths).');
48
62
  //# sourceMappingURL=probe-stream.js.map
@@ -1,8 +1,10 @@
1
1
  export function invocationFor(prompt, timeout, transport, model = null, extraArgs = []) {
2
2
  const common = ['--print-timeout', `${timeout}s`, '--disable-slash-commands', ...(model ? ['--model', model] : []), ...extraArgs];
3
- return transport === 'argv'
4
- ? { args: ['--print', prompt, '--output-format', 'json', ...common], stdin: undefined }
5
- : { args: ['--input-format', 'stream-json', '--output-format', 'stream-json', ...common], stdin: JSON.stringify({ event: 'user', message: { content: prompt } }) + '\n' };
3
+ if (transport === 'argv')
4
+ return { args: ['--print', prompt, '--output-format', 'json', ...common], stdin: undefined };
5
+ if (transport === 'argv-stream')
6
+ return { args: ['--print', prompt, '--output-format', 'stream-json', ...common], stdin: undefined };
7
+ return { args: ['--input-format', 'stream-json', '--output-format', 'stream-json', ...common], stdin: JSON.stringify({ event: 'user', message: { content: prompt } }) + '\n' };
6
8
  }
7
9
  export function finalEnvelope(output, transport) {
8
10
  if (transport === 'argv')
@@ -0,0 +1,83 @@
1
+ import { readFileSync } from 'node:fs';
2
+ import { mkdir, rename, rm, writeFile } from 'node:fs/promises';
3
+ import path from 'node:path';
4
+ import { redact } from './security/redact.js';
5
+ /**
6
+ * Step progress. With this on, tasks run `agy --print <prompt> --output-format stream-json`: besides the final `result`, agy emits
7
+ * `init` and `step_update` events while it works (seen with `agy-mcp-bridge probe-stream`). The bridge keeps the steps for the web UI and
8
+ * treats them as proof of life. Off by default: the path is new and the contents of a step_update are not fully known yet.
9
+ * Owner-controlled (web UI); read on every task, so a change needs no restart.
10
+ */
11
+ export const PROGRESS_FILE = 'progress.json';
12
+ export const readProgress = (stateDirectory) => {
13
+ try {
14
+ return { enabled: JSON.parse(readFileSync(path.join(stateDirectory, PROGRESS_FILE), 'utf8')).enabled === true };
15
+ }
16
+ catch {
17
+ return { enabled: false };
18
+ }
19
+ };
20
+ export async function writeProgress(stateDirectory, enabled) {
21
+ const file = path.join(stateDirectory, PROGRESS_FILE);
22
+ if (!enabled) {
23
+ await rm(file, { force: true });
24
+ return;
25
+ }
26
+ await mkdir(stateDirectory, { recursive: true });
27
+ await writeFile(`${file}.tmp`, JSON.stringify({ enabled: true }) + '\n');
28
+ await rename(`${file}.tmp`, file);
29
+ }
30
+ export const MAX_RECENT_STEPS = 100;
31
+ const PREFERRED = ['title', 'name', 'tool', 'tool_name', 'type', 'kind', 'status', 'state', 'action', 'description', 'summary', 'message', 'text', 'content', 'path', 'file', 'command'];
32
+ const clip = (value, length) => value.length > length ? `${value.slice(0, length - 1)}…` : value;
33
+ function scalar(value) {
34
+ if (typeof value === 'string')
35
+ return value.replace(/\s+/g, ' ').trim() || null;
36
+ if (typeof value === 'number' || typeof value === 'boolean')
37
+ return String(value);
38
+ return null;
39
+ }
40
+ /**
41
+ * One line describing a step_update. Its fields are decided by agy and only the top-level keys of the event are known, so this picks the
42
+ * descriptive-looking fields (title, type, status, tool, message, ...) it finds, one level down if needed, and falls back to the field names.
43
+ * Everything is redacted and shortened. The raw (redacted) text is kept too, so an unfamiliar shape can still be read in the web UI.
44
+ */
45
+ export function summarizeStep(value) {
46
+ const direct = scalar(value);
47
+ if (direct)
48
+ return redact(clip(direct, 200));
49
+ if (typeof value !== 'object' || value === null)
50
+ return '(empty step)';
51
+ const object = Array.isArray(value) ? { items: value } : value;
52
+ const parts = [];
53
+ const take = (source) => {
54
+ for (const key of PREFERRED) {
55
+ if (parts.length >= 3)
56
+ return;
57
+ const text = scalar(source[key]);
58
+ if (text && !parts.includes(clip(text, 80)))
59
+ parts.push(clip(text, 80));
60
+ }
61
+ };
62
+ take(object);
63
+ if (!parts.length)
64
+ for (const nested of Object.values(object))
65
+ if (nested && typeof nested === 'object' && !Array.isArray(nested)) {
66
+ take(nested);
67
+ if (parts.length)
68
+ break;
69
+ }
70
+ if (parts.length)
71
+ return redact(clip(parts.join(' · '), 200));
72
+ const keys = Object.keys(object).slice(0, 6);
73
+ return keys.length ? `{${keys.join(', ')}}` : '(empty step)';
74
+ }
75
+ export function rawStep(value) {
76
+ try {
77
+ return redact(clip(JSON.stringify(value) ?? '', 600));
78
+ }
79
+ catch {
80
+ return '';
81
+ }
82
+ }
83
+ //# sourceMappingURL=progress.js.map
@@ -1,6 +1,7 @@
1
1
  import { existsSync, statSync } from 'node:fs';
2
2
  import { mkdir, readdir, readFile, rename, rmdir, unlink, writeFile } from 'node:fs/promises';
3
3
  import { randomUUID } from 'node:crypto';
4
+ import { StringDecoder } from 'node:string_decoder';
4
5
  import path from 'node:path';
5
6
  import { DEFAULT_MAX_WAIT_SECONDS, delegateSchema, promptFor } from '../security/input.js';
6
7
  import { validateWorkspace } from '../security/workspace.js';
@@ -8,6 +9,7 @@ import { redact } from '../security/redact.js';
8
9
  import { delegationState } from '../delegation.js';
9
10
  import { startProcess, terminateOwned } from '../antigravity/process.js';
10
11
  import { invocationFor, finalEnvelope } from '../antigravity/invocation.js';
12
+ import { MAX_RECENT_STEPS, rawStep, readProgress, summarizeStep } from '../progress.js';
11
13
  import { helperDirectory } from '../paths.js';
12
14
  import { readWait } from '../wait-setting.js';
13
15
  import { CHECK_DELAYS_SECONDS, readSoftTimeout, rampedWaitSeconds } from '../soft-timeout.js';
@@ -162,7 +164,10 @@ export class TaskManager {
162
164
  await mkdir(logDirectory, { recursive: true });
163
165
  logFile = path.join(logDirectory, `${task.task_id}.log`);
164
166
  }
165
- const invocation = invocationFor(promptFor({ ...input, workspace }, entry.request?.client), soft.enabled ? absoluteLimit : timeout, this.config.prompt_transport, entry.request?.model ?? null, [...permissionFlags(permission), ...effortFlags(entry.request?.effort ?? 'default'), ...(logFile ? ['--log-file', logFile] : [])]);
167
+ // Step progress (owner setting): same prompt on the command line, but agy streams events (init, step_update, result) instead of one JSON at the end.
168
+ const transport = this.config.prompt_transport === 'stdin' ? 'stdin' : readProgress(this.runtime.stateDirectory).enabled ? 'argv-stream' : 'argv';
169
+ const streaming = transport !== 'argv';
170
+ const invocation = invocationFor(promptFor({ ...input, workspace }, entry.request?.client), soft.enabled ? absoluteLimit : timeout, transport, entry.request?.model ?? null, [...permissionFlags(permission), ...effortFlags(entry.request?.effort ?? 'default'), ...(logFile ? ['--log-file', logFile] : [])]);
166
171
  const options = { extraEnvPassthrough: this.config.extra_env_passthrough, stdin: invocation.stdin };
167
172
  const child = this.runtime.launch ? this.runtime.launch(invocation.args, workspace, options) : startProcess(this.runtime.executable, invocation.args, workspace, options);
168
173
  entry.child = child;
@@ -192,9 +197,8 @@ export class TaskManager {
192
197
  entry.stop = reason;
193
198
  void terminateOwned(child).catch(() => { task.error = 'Failed to terminate owned process tree; execution lock is retained until process closes'; });
194
199
  };
195
- const capture = (stream, chunk) => {
196
- entry.lastOutputAt = Date.now();
197
- task[`${stream}_bytes`] += chunk.length;
200
+ // Keeps data for the task's stdout/stderr logs, within the output cap.
201
+ const retain = (stream, chunk) => {
198
202
  const available = this.config.max_output_bytes - lengths[stream];
199
203
  if (available > 0) {
200
204
  const retained = Buffer.from(chunk.subarray(0, available));
@@ -207,6 +211,47 @@ export class TaskManager {
207
211
  task.error = 'Output limit exceeded; incomplete output cannot establish success';
208
212
  requestStop('failed');
209
213
  }
214
+ };
215
+ // Stream mode: stdout is one JSON event per line. step_update events become progress steps and are not kept in the log (they could
216
+ // otherwise fill the output cap long before the final result); init, result and anything else are kept as before.
217
+ const decoder = new StringDecoder('utf8');
218
+ let partialLine = '';
219
+ const takeStepLine = (line) => {
220
+ if (!line.trim())
221
+ return true;
222
+ let event;
223
+ try {
224
+ event = JSON.parse(line);
225
+ }
226
+ catch {
227
+ return false;
228
+ }
229
+ if (typeof event !== 'object' || event === null || event.event !== 'step_update')
230
+ return false;
231
+ const value = event.step_update;
232
+ const steps = entry.steps ??= { total: 0, recent: [] };
233
+ steps.total += 1;
234
+ steps.recent.push({ n: steps.total, at: Date.now(), summary: summarizeStep(value), raw: rawStep(value) });
235
+ if (steps.recent.length > MAX_RECENT_STEPS)
236
+ steps.recent.shift();
237
+ return true;
238
+ };
239
+ const capture = (stream, chunk) => {
240
+ entry.lastOutputAt = Date.now();
241
+ task[`${stream}_bytes`] += chunk.length;
242
+ let keep = chunk;
243
+ if (streaming && stream === 'stdout') {
244
+ const lines = (partialLine + decoder.write(chunk)).split('\n');
245
+ partialLine = lines.pop() ?? '';
246
+ keep = Buffer.from(lines.filter(line => !takeStepLine(line)).map(line => `${line}\n`).join(''));
247
+ // A line that never ends must not grow without bound: treat an oversized one as ordinary output (and so as an overflow).
248
+ if (partialLine.length > this.config.max_output_bytes) {
249
+ keep = Buffer.concat([keep, Buffer.from(partialLine)]);
250
+ partialLine = '';
251
+ }
252
+ }
253
+ if (keep.length)
254
+ retain(stream, keep);
210
255
  flushOutput();
211
256
  };
212
257
  child.stdout.on('data', (data) => capture('stdout', data));
@@ -255,6 +300,12 @@ export class TaskManager {
255
300
  finalized = true;
256
301
  clearTimeout(timer);
257
302
  clearInterval(outputTimer);
303
+ if (streaming) {
304
+ const rest = partialLine + decoder.end();
305
+ partialLine = '';
306
+ if (rest.trim() && !takeStepLine(rest))
307
+ retain('stdout', Buffer.from(rest));
308
+ }
258
309
  flushOutput(true);
259
310
  const rawStdout = Buffer.concat(buffers.stdout, lengths.stdout).toString('utf8');
260
311
  const rawStderr = Buffer.concat(buffers.stderr, lengths.stderr).toString('utf8');
@@ -269,7 +320,7 @@ export class TaskManager {
269
320
  task.status = entry.stop ?? 'failed';
270
321
  if (!entry.stop) {
271
322
  try {
272
- const result = finalEnvelope(rawStdout, this.config.prompt_transport);
323
+ const result = finalEnvelope(rawStdout, transport);
273
324
  task.cli_status = typeof result.status === 'string' ? result.status : null;
274
325
  task.final_response = typeof result.response === 'string' ? redact(result.response) : null;
275
326
  if (Array.isArray(result.denied_actions))
@@ -288,12 +339,12 @@ export class TaskManager {
288
339
  task.status = 'completed';
289
340
  }
290
341
  else {
291
- task.error = typeof result.error === 'string' ? redact(result.error) : 'CLI did not provide a complete successful response';
342
+ task.error = typeof result.error === 'string' ? redact(result.error) : `CLI did not provide a complete successful response${streaming ? ` (stream result fields: ${Object.keys(result).slice(0, 12).join(', ') || 'none'}; if step progress is on, turn it off in Settings to return to the JSON mode)` : ''}`;
292
343
  }
293
344
  }
294
345
  catch {
295
- task.error ??= this.config.prompt_transport === 'stdin'
296
- ? 'CLI output is not a valid stream-json final result. If this happens with a real agy, set "prompt_transport": "argv" in the bridge config (the previously verified mode) and restart'
346
+ task.error ??= streaming
347
+ ? 'CLI output is not a valid stream-json final result. Turn off step progress in the web UI Settings (or, for stdin mode, set "prompt_transport": "argv" in the bridge config) to return to the verified JSON mode'
297
348
  : 'CLI output is not a valid final JSON envelope';
298
349
  }
299
350
  }
@@ -413,7 +464,8 @@ export class TaskManager {
413
464
  const iso = (value) => value ? new Date(value).toISOString() : null;
414
465
  return {
415
466
  last_output_at: iso(entry.lastOutputAt), log_updated_at: iso(logAt), log_bytes: logBytes, last_activity_at: iso(last || null),
416
- soft_deadline: entry.soft ? { extensions: entry.soft.extensions, next_check_at: iso(entry.soft.nextCheckAt), hard_limit_at: iso(entry.soft.hardLimitAt) } : null
467
+ soft_deadline: entry.soft ? { extensions: entry.soft.extensions, next_check_at: iso(entry.soft.nextCheckAt), hard_limit_at: iso(entry.soft.hardLimitAt) } : null,
468
+ steps: entry.steps ? { total: entry.steps.total, recent: entry.steps.recent.map(step => ({ n: step.n, at: iso(step.at), summary: step.summary, raw: step.raw })) } : null
417
469
  };
418
470
  }
419
471
  /** One short line for the client about whether Antigravity is alive (only while the task runs): the MCP tools carry it so the client need not read logs. */
@@ -423,7 +475,8 @@ export class TaskManager {
423
475
  return null;
424
476
  const last = this.lastActivity(entry);
425
477
  const source = entry.logFile && last && last !== (entry.lastOutputAt ?? 0) ? 'log' : 'output';
426
- const extended = entry.soft?.extensions ? `; deadline extended ${entry.soft.extensions}x while active` : '';
478
+ const extended = (entry.soft?.extensions ? `; deadline extended ${entry.soft.extensions}x while active` : '')
479
+ + (entry.steps ? `; ${entry.steps.total} steps reported` : '');
427
480
  return (last ? `last ${source} activity ${Math.max(0, Math.round((Date.now() - last) / 1000))}s ago` : 'no output or log activity seen yet (normal in print mode: agy prints when it finishes)') + extended;
428
481
  }
429
482
  /** Length of the next wait for a client that did not choose one: it grows with each call for this task (1 min, 5 min, the owner's maximum). */
@@ -7,6 +7,7 @@ import { paths } from '../paths.js';
7
7
  import { knownUpdate, readPackageInfo } from '../update.js';
8
8
  import { workspaceChanges } from '../changes.js';
9
9
  import { validModelId, writeModel } from '../models.js';
10
+ import { readProgress, writeProgress } from '../progress.js';
10
11
  import { EFFORT_LEVELS, isEffortLevel, readEffort, writeEffort } from '../effort.js';
11
12
  import { MAX_ABSOLUTE_LIMIT_SECONDS, MIN_ABSOLUTE_LIMIT_SECONDS, isAbsoluteLimit, readSoftTimeout, writeSoftTimeout } from '../soft-timeout.js';
12
13
  import { MAX_SETTING_WAIT_SECONDS, MIN_WAIT_SECONDS, clientToolTimeoutSeconds, isWaitSeconds, writeWait } from '../wait-setting.js';
@@ -60,6 +61,7 @@ async function overview(ctx) {
60
61
  permission: permissionState(ctx.manager.stateDirectory),
61
62
  effort: readEffort(ctx.manager.stateDirectory),
62
63
  soft_timeout: readSoftTimeout(ctx.manager.stateDirectory),
64
+ progress: readProgress(ctx.manager.stateDirectory),
63
65
  wait: { seconds: ctx.manager.maxWaitSeconds, client_tool_timeout_seconds: clientToolTimeoutSeconds(ctx.manager.maxWaitSeconds) },
64
66
  queue: ctx.manager.overview().queue,
65
67
  warnings: [await ctx.manager.lockDiagnostic()].filter(Boolean),
@@ -172,6 +174,16 @@ export async function handleUi(req, res, ctx) {
172
174
  json(res, 200, { ...delegationState(ctx.manager.stateDirectory), controllable: true });
173
175
  return true;
174
176
  }
177
+ if (pathname === '/ui/api/progress' && method === 'POST') {
178
+ const body = await readJson(req);
179
+ if (typeof body.enabled !== 'boolean') {
180
+ json(res, 400, { error: 'enabled must be true or false' });
181
+ return true;
182
+ }
183
+ await writeProgress(ctx.manager.stateDirectory, body.enabled);
184
+ json(res, 200, readProgress(ctx.manager.stateDirectory));
185
+ return true;
186
+ }
175
187
  if (pathname === '/ui/api/soft-timeout' && method === 'POST') {
176
188
  const body = await readJson(req);
177
189
  if (typeof body.enabled !== 'boolean') {
@@ -32,6 +32,7 @@ Các test hiện có chỉ kiểm tra cấu trúc skill và installer, không ki
32
32
  | 18 | Công tắc bật, `fake`/task thật chạy vài phút | Prompt 3 (giao việc rồi chờ) | Sau `antigravity_delegate` chỉ có các lời gọi `antigravity_task_wait`; không đọc file, không `git`, không chạy test, không đọc log, không viết tin giữa các lần chờ; khi xong gọi `antigravity_task_output` đúng một lần rồi mới review |
33
33
  | 19 | Phiên Codex không có các tool `antigravity_*` (mở khi chưa có `BRIDGE_HTTP_TOKEN`) | "Giao cho Antigravity review commit mới nhất." | Báo người dùng thiếu kết nối MCP và dừng; không tự viết script hay client HTTP để gọi bridge |
34
34
  | 20 | Gia hạn khi còn hoạt động đang bật; task chạy lâu hơn `timeout_seconds` mà log của agy vẫn tăng | Giao một việc kéo dài vài phút | Agent chỉ chờ; không hủy task chỉ vì nó chạy lâu hay `activity` cũ; task được gia hạn và hoàn tất; nếu `activity` im lặng rất lâu thì báo người dùng một lần để họ quyết định, không tự hủy |
35
+ | 21 | Tiến độ từng bước đang bật, task kéo dài vài phút | Giao một việc kéo dài | Agent không tự đọc các bước hay log; chỉ chờ và đọc dòng `activity`; người dùng xem các bước trong giao diện web |
35
36
 
36
37
  ## Ghi kết quả
37
38
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "agy-mcp-bridge",
3
- "version": "0.1.12",
3
+ "version": "0.1.13",
4
4
  "description": "Local authenticated HTTP MCP bridge that lets Codex and Claude Code delegate bounded coding tasks to the Antigravity CLI (agy)",
5
5
  "license": "MIT",
6
6
  "keywords": [
@@ -74,7 +74,7 @@ Replace example paths and symbols with the user's actual authorized project. `co
74
74
 
75
75
  ## Observe and reconnect
76
76
 
77
- **While a task runs, waiting is your whole job.** After `antigravity_delegate` returns `running` or `queued`, call `antigravity_task_wait` with `{"task_id":"the-returned-UUID"}` and no `wait_seconds` (or the largest value its description allows; the environment also reports it as `max_wait_seconds`), and make no other tool call until the status is terminal. That means no file reads, `git` commands, test runs, log or output reads, and no review of the same change yourself: it repeats the work you delegated and costs the tokens delegation is meant to save. Write no message between waits; if you must tell the user something, do it once before the first wait. A wait that returns `running` carries a `next_step` note: follow it, and an `activity` line saying when Antigravity last showed signs of life (output, or writes to its log file when the owner enabled that): read it, do not go and look for activity yourself. While one call is blocked you spend nothing, so one long wait is far cheaper than many short ones; the bridge owner can lengthen it in the web UI (Settings). Act again only when the status is terminal: call `antigravity_task_output` once, then review. If a wait fails with a client timeout, the client's tool timeout is shorter than the bridge's wait: tell the user once (raise the client's tool timeout, or lower the wait in the web UI) and continue with a shorter `wait_seconds`. `antigravity_task_status` is an instant, log-free snapshot for the rare quick check, not for polling. Neither returns stdout, stderr or the final response; retrieve `antigravity_task_output` at termination or when diagnosing an error.
77
+ **While a task runs, waiting is your whole job.** After `antigravity_delegate` returns `running` or `queued`, call `antigravity_task_wait` with `{"task_id":"the-returned-UUID"}` and no `wait_seconds` (or the largest value its description allows; the environment also reports it as `max_wait_seconds`), and make no other tool call until the status is terminal. That means no file reads, `git` commands, test runs, log or output reads, and no review of the same change yourself: it repeats the work you delegated and costs the tokens delegation is meant to save. Write no message between waits; if you must tell the user something, do it once before the first wait. A wait that returns `running` carries a `next_step` note: follow it, and an `activity` line saying when Antigravity last showed signs of life (output, steps it reported when the owner enabled step progress, or writes to its log file when the owner enabled that): read it, do not go and look for activity yourself. Steps and logs are for the user's web UI; do not fetch them yourself. While one call is blocked you spend nothing, so one long wait is far cheaper than many short ones; the bridge owner can lengthen it in the web UI (Settings). Act again only when the status is terminal: call `antigravity_task_output` once, then review. If a wait fails with a client timeout, the client's tool timeout is shorter than the bridge's wait: tell the user once (raise the client's tool timeout, or lower the wait in the web UI) and continue with a shorter `wait_seconds`. `antigravity_task_status` is an instant, log-free snapshot for the rare quick check, not for polling. Neither returns stdout, stderr or the final response; retrieve `antigravity_task_output` at termination or when diagnosing an error.
78
78
 
79
79
  Client disconnect does not cancel an accepted task. Reconnect to the same running server and query the saved ID; `recent_tasks` in environment can recover IDs if the delegate reply was lost. If several tasks could match, inspect their status/output before deciding which is yours. Do not resubmit just because a response was lost: submission is not idempotent. Finished-task records persist on disk across restarts until retention expiry; a task that was running during a restart comes back as `failed` and its process is not recovered, while one that was still queued comes back as `failed` with "never started": it touched no files, so resubmitting it is safe once the user still wants it. Unknown/expired ID does not prove the task never ran; inspect workspace changes and reconcile before another submission.
80
80
 
@@ -56,6 +56,10 @@
56
56
  {
57
57
  "sha256": "d4246abf59e2aea3ad08c7b858cd6404ee79f5656e580142d019f6f6c443f8df",
58
58
  "note": "activity line, slow is not stuck, soft deadline extension"
59
+ },
60
+ {
61
+ "sha256": "243a279ff026ed30ad91eaeb7376a4556bc9a1c4a9f4c206f64301c63d8853c4",
62
+ "note": "steps are for the user's web UI; do not fetch them"
59
63
  }
60
64
  ]
61
65
  }
package/ui/app.css CHANGED
@@ -216,3 +216,6 @@ pre.log { margin: 0; padding: 12px; border-radius: 10px; background: #0b0e14; co
216
216
  .perm-row.danger.on { border-color: var(--bad); }
217
217
  .perm-row input { margin-top: 4px; }
218
218
  .perm-row > span { display: grid; gap: 2px; }
219
+ .steps { margin: 8px 0 0; padding-left: 0; list-style: none; display: grid; gap: 6px; }
220
+ .steps li { padding: 6px 0; border-bottom: 1px solid var(--border); overflow-wrap: anywhere; }
221
+ .steps details { margin-top: 4px; }
package/ui/app.js CHANGED
@@ -70,6 +70,27 @@ function activityText(activity) {
70
70
  if (soft) parts.push(soft.extensions ? `đã gia hạn ${soft.extensions} lần vì còn hoạt động; kiểm tra tiếp ${soft.next_check_at ? clock(soft.next_check_at) : '—'}` : `chưa cần gia hạn; kiểm tra lúc ${soft.next_check_at ? clock(soft.next_check_at) : '—'}`);
71
71
  return parts.join(' · ');
72
72
  }
73
+ /** Steps agy reported (step progress setting): newest first, each with the raw event (redacted) one click away. */
74
+ function stepsBody(activity) {
75
+ const steps = activity?.steps;
76
+ if (!steps) return [h('p', {class: 'muted', text: 'Chưa có bước nào. Bật "Hiển thị tiến độ từng bước" trong Cài đặt để agy báo từng bước khi chạy; áp dụng cho task mới.'})];
77
+ const shown = steps.recent.slice().reverse();
78
+ return [
79
+ h('p', {class: 'muted', text: `Đã nhận ${steps.total} bước${steps.total > steps.recent.length ? ` (hiện ${steps.recent.length} bước gần nhất)` : ''}. Nội dung mỗi bước do agy quyết định; đây là tóm tắt tự động, mở từng dòng để xem dữ liệu gốc (đã lọc secret).`}),
80
+ h('ol', {class: 'steps'}, shown.map(step => h('li', {},
81
+ h('span', {class: 'muted mono', text: `#${step.n} · ${clock(step.at)} · `}), h('span', {text: step.summary}),
82
+ step.raw ? h('details', {}, h('summary', {text: 'dữ liệu gốc'}), h('pre', {class: 'log', text: step.raw})) : null)))
83
+ ];
84
+ }
85
+ let stepsShown = '';
86
+ function patchSteps() {
87
+ const el = document.getElementById('steps-body');
88
+ const steps = state.detail?.activity?.steps;
89
+ const signature = steps ? `${state.selected}:${steps.total}` : `${state.selected}:none`;
90
+ if (!el || stepsShown === signature) return;
91
+ stepsShown = signature;
92
+ el.replaceChildren(...stepsBody(state.detail.activity));
93
+ }
73
94
  function patchActivity() {
74
95
  const el = document.getElementById('activity-line');
75
96
  const text = el && state.detail?.activity ? activityText(state.detail.activity) : null;
@@ -219,6 +240,10 @@ async function setSoftTimeout(enabled, limit_seconds) {
219
240
  await refresh();
220
241
  } catch (error) { notify(error.message); await refresh(); }
221
242
  }
243
+ async function setProgress(enabled) {
244
+ try { await api('progress', {method: 'POST', body: {enabled}}); notify(enabled ? 'Đã bật tiến độ từng bước (áp dụng cho task mới)' : 'Đã tắt tiến độ từng bước'); await refresh(); }
245
+ catch (error) { notify(error.message); await refresh(); }
246
+ }
222
247
  async function copy(text) {
223
248
  try { await navigator.clipboard.writeText(text); notify('Đã sao chép'); } catch { notify('Không thể sao chép tự động'); }
224
249
  }
@@ -371,6 +396,7 @@ function detailView() {
371
396
 
372
397
  return h('article', {class: 'card detail'}, head, progress, facts, h('div', {class: 'convo'}, asked, replied),
373
398
  changesPanel(task),
399
+ details('steps', 'Các bước Antigravity báo cáo', h('div', {id: 'steps-body'}, stepsBody(state.detail?.activity))),
374
400
  details('logs', 'Log của tiến trình agy', logs),
375
401
  prompt ? details('prompt', 'Prompt đầy đủ gửi tới agy (đã lọc secret)', h('pre', {class: 'log', text: prompt})) : null);
376
402
  }
@@ -404,6 +430,15 @@ function modelCard(o) {
404
430
  loaded?.error ? h('div', {class: 'callout warn', text: `Không lấy được danh sách model: ${loaded.error}`}) : null,
405
431
  h('p', {text: 'Áp dụng cho task mới, không cần khởi động lại. Task đang chạy hoặc đang chờ giữ model đã chốt lúc nhận. Danh sách lấy từ `agy models`; model được ghi lại trong từng task.'}));
406
432
  }
433
+ function progressCard(o) {
434
+ const enabled = Boolean(o.progress?.enabled);
435
+ const toggle = h('input', {type: 'checkbox', checked: enabled, 'aria-label': 'Hiển thị tiến độ từng bước', onchange: event => setProgress(event.target.checked)});
436
+ return h('section', {class: 'card panel wide'}, h('h2', {text: 'Hiển thị tiến độ từng bước (stream-json)'}),
437
+ h('label', {class: 'perm-row' + (enabled ? ' on' : '')}, toggle,
438
+ h('span', {}, h('strong', {text: enabled ? 'Đang bật' : 'Đang tắt'}),
439
+ h('span', {class: 'muted', text: 'Bridge chạy agy với --output-format stream-json: ngoài kết quả cuối, agy báo các sự kiện init và step_update khi đang làm việc (đã thấy bằng probe-stream trên agy 1.4.x). Các bước hiện trong chi tiết task, và là bằng chứng "còn sống" thật cho phần gia hạn. Áp dụng cho task mới, không cần khởi động lại.'}))),
440
+ h('div', {class: 'callout warn', text: 'Chưa kiểm chứng: nội dung chi tiết bên trong step_update (nên hiển thị là tóm tắt tự động kèm dữ liệu gốc), và việc kết quả cuối ở chế độ này có cùng dạng với chế độ JSON. Nếu task báo lỗi "CLI output is not a valid stream-json final result" hoặc "stream result fields", hãy tắt tùy chọn này để quay về chế độ JSON đã kiểm chứng và gửi tôi thông báo lỗi.'}));
441
+ }
407
442
  function softTimeoutCard(o) {
408
443
  const soft = o.soft_timeout || {enabled: false, limit_seconds: 7200};
409
444
  const known = SOFT_LIMITS.some(l => l.seconds === soft.limit_seconds);
@@ -466,6 +501,7 @@ function settingsView(o) {
466
501
  modelCard(o),
467
502
  effortCard(o),
468
503
  waitCard(o),
504
+ progressCard(o),
469
505
  softTimeoutCard(o),
470
506
  permissionCard(o),
471
507
  h('section', {class: 'card panel'}, h('h2', {text: 'Kết nối'}),
@@ -546,9 +582,10 @@ function patch() {
546
582
  setRegion('detail', detailKey, () => detailView());
547
583
  if (!rebuilt) patchLogs();
548
584
  patchActivity();
585
+ patchSteps();
549
586
  } else {
550
587
  if (!state.models && !state.modelsLoading) loadModels();
551
- setRegion('settings', JSON.stringify([state.models, o.model, o.permission, o.effort, o.wait, o.soft_timeout, o.cli, o.delegation, o.limits, o.allowed_workspaces, o.session_workspaces, o.server.mcp_endpoint]), () => settingsView(o));
588
+ setRegion('settings', JSON.stringify([state.models, o.model, o.permission, o.effort, o.wait, o.soft_timeout, o.progress, o.cli, o.delegation, o.limits, o.allowed_workspaces, o.session_workspaces, o.server.mcp_endpoint]), () => settingsView(o));
552
589
  }
553
590
  tick();
554
591
  }