@pasko70/pibo 3.0.2 → 3.1.1

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.
Files changed (72) hide show
  1. package/compute-image/Dockerfile +47 -0
  2. package/compute-image/Dockerfile.dockerignore +5 -0
  3. package/dist/agent-runtime/contract.js +78 -28
  4. package/dist/agent-runtime/portable-history.js +19 -9
  5. package/dist/agent-runtime/registry.js +8 -2
  6. package/dist/agent-runtime/routed-session.js +12 -6
  7. package/dist/agent-runtimes/pi/routed-session.js +10 -4
  8. package/dist/apps/chat/agent-store.js +55 -3
  9. package/dist/apps/chat/data/project-service.js +119 -15
  10. package/dist/apps/chat/data/room-service.js +21 -0
  11. package/dist/apps/chat/loop-api.js +10 -2
  12. package/dist/apps/chat/web-app.js +84 -25
  13. package/dist/apps/chat-ui/assets/{dist-CvaPTBTN.js → dist-CUQJqggN.js} +1 -1
  14. package/dist/apps/chat-ui/assets/{dist-BPotHecb.js → dist-ClUlQWYN.js} +1 -1
  15. package/dist/apps/chat-ui/assets/{dist-BzqQKeVO.js → dist-Djul9BmZ.js} +1 -1
  16. package/dist/apps/chat-ui/assets/{dist-paagejNj.js → dist-GD0JGdCi.js} +1 -1
  17. package/dist/apps/chat-ui/assets/{dist-B6GZgWSj.js → dist-W5HOqHym.js} +1 -1
  18. package/dist/apps/chat-ui/assets/index-BcjkX-iP.js +228 -0
  19. package/dist/apps/chat-ui/assets/index-CmqRSbBU.css +1 -0
  20. package/dist/apps/chat-ui/index.html +2 -2
  21. package/dist/apps/chat-vscode-web/assets/index-JvrPUGvI.js +43 -0
  22. package/dist/apps/chat-vscode-web/index.html +1 -1
  23. package/dist/apps/cli-ui/InkSessionApp.js +111 -12
  24. package/dist/compute/cli.js +35 -16
  25. package/dist/compute/docker.js +341 -94
  26. package/dist/config/config.js +3 -0
  27. package/dist/core/output-render-sequence.js +148 -1
  28. package/dist/core/session-router.js +33 -105
  29. package/dist/data/ingest-service.js +14 -6
  30. package/dist/data/pibo-store.js +8 -1
  31. package/dist/data/schema.js +135 -5
  32. package/dist/debug/agents.js +91 -89
  33. package/dist/debug/index.js +2 -0
  34. package/dist/debug/pty.js +127 -48
  35. package/dist/gateway/cli.js +4 -0
  36. package/dist/loops/channel.js +3 -1
  37. package/dist/loops/cli.js +2 -1
  38. package/dist/loops/service.js +90 -11
  39. package/dist/loops/store.js +100 -74
  40. package/dist/mcp/agent-context.js +13 -26
  41. package/dist/mcp/commands/info.js +3 -1
  42. package/dist/mcp/config-command.js +46 -2
  43. package/dist/mcp/config.js +18 -4
  44. package/dist/plugins/context-files-store.js +6 -6
  45. package/dist/previews/base-url.js +34 -0
  46. package/dist/previews/config.js +2 -32
  47. package/dist/ralph/store.js +5 -0
  48. package/dist/reliability/store.js +174 -111
  49. package/dist/session-ui/terminalRows.js +2 -1
  50. package/dist/sessions/pibo-data-store.js +81 -0
  51. package/dist/subagents/observation-query.js +121 -0
  52. package/dist/tools/agent-browser-leases.js +58 -23
  53. package/dist/tools/agent-browser-wrapper.js +1 -1
  54. package/dist/tools/browser-use-leases.js +129 -16
  55. package/dist/tools/browser-use-wrapper.js +1 -1
  56. package/dist/tools/index.js +27 -11
  57. package/dist/tools/python-runtime.js +10 -3
  58. package/dist/tools/registry.js +1 -1
  59. package/dist/tools/runtime/node-backend.js +16 -5
  60. package/dist/tools/runtime/node-worker-source.js +112 -33
  61. package/dist/tools/runtime/python-backend.js +16 -5
  62. package/dist/tools/runtime/python-worker-source.js +167 -16
  63. package/dist/tools/runtime/registry.js +23 -10
  64. package/dist/user-skills/store.js +0 -1
  65. package/npm-shrinkwrap.json +9 -2
  66. package/package.json +8 -2
  67. package/scripts/docker-entrypoint.sh +46 -0
  68. package/scripts/prepare-agent-browser-wrapper.sh +70 -0
  69. package/scripts/prepare-browser-use-wrapper.sh +255 -0
  70. package/dist/apps/chat-ui/assets/index-6JJV-eic.js +0 -228
  71. package/dist/apps/chat-ui/assets/index-CeL9JPP5.css +0 -1
  72. package/dist/apps/chat-vscode-web/assets/index-U-MSErGa.js +0 -43
@@ -1,4 +1,5 @@
1
- import { normalizePiboAgentObservationCursor, normalizePiboAgentObservationLimit, normalizePiboAgentObservationOrder, parsePiboAgentObservationTimestamp, piboAgentObservationDetails, piboAgentObservationKind, piboAgentObservationRole, piboAgentObservationText, } from "../subagents/observations.js";
1
+ import { normalizePiboAgentObservationLimit, piboAgentObservationDetails, piboAgentObservationKind, piboAgentObservationRole, piboAgentObservationText, } from "../subagents/observations.js";
2
+ import { preparePiboAgentObservationQuery, selectPiboAgentObservationPage, } from "../subagents/observation-query.js";
2
3
  import { createDebugPayloadStore, hydrateDebugEventRow } from "./persisted-payloads.js";
3
4
  import { eventAttributes, eventPayload } from "./payloads.js";
4
5
  import { openReadOnlyDebugDatabase, withStorePath } from "./sql.js";
@@ -36,17 +37,21 @@ export async function runDebugAgentsCli(args) {
36
37
  return;
37
38
  }
38
39
  const result = inspectDebugAgentObservations(parentPiboSessionId, store, {
40
+ toolCallIds: parsed.toolCallIds.length ? parsed.toolCallIds : undefined,
39
41
  agentIds: parsed.agentIds.length ? parsed.agentIds : undefined,
40
42
  names: parsed.names.length ? parsed.names : undefined,
41
43
  threadKeys: parsed.threadKeys.length ? parsed.threadKeys : undefined,
42
44
  eventTypes: parsed.eventTypes.length ? parsed.eventTypes : undefined,
43
45
  kinds: parsed.kinds.length ? parsed.kinds : undefined,
46
+ roles: parsed.roles.length ? parsed.roles : undefined,
44
47
  since: parsed.since,
45
48
  until: parsed.until,
46
49
  textContains: parsed.textContains,
47
50
  afterSequence: parsed.afterSequence,
48
51
  order: parsed.order,
49
52
  limit: parsed.limit,
53
+ includeTools: parsed.includeTools || undefined,
54
+ toolDetail: parsed.toolDetail,
50
55
  includeDetails: parsed.details,
51
56
  });
52
57
  if (parsed.json)
@@ -75,104 +80,70 @@ export function inspectDebugAgentObservations(parentPiboSessionId, store, input
75
80
  throw new Error(`Debug store "pibo-data" not found at ${store.path}`);
76
81
  const db = openReadOnlyDebugDatabase(store);
77
82
  try {
78
- const order = normalizePiboAgentObservationOrder(input.order);
79
- const limit = normalizePiboAgentObservationLimit(input.limit);
80
- const afterSequence = normalizePiboAgentObservationCursor(input.afterSequence);
81
- const since = parsePiboAgentObservationTimestamp(input.since, "since");
82
- const until = parsePiboAgentObservationTimestamp(input.until, "until");
83
- if (since !== undefined && until !== undefined && since > until)
84
- throw new Error("Agent observation since must not be after until.");
83
+ const query = preparePiboAgentObservationQuery(input);
85
84
  const owned = readOwnedAgents(db, parentPiboSessionId);
86
85
  const ownedById = new Map(owned.map((agent) => [agent.agentId, agent]));
87
86
  for (const agentId of input.agentIds ?? []) {
88
87
  if (!ownedById.has(agentId))
89
88
  throw new Error(`Agent "${agentId}" is not owned by Pibo session "${parentPiboSessionId}".`);
90
89
  }
91
- const agentIds = input.agentIds ? new Set(input.agentIds) : undefined;
92
- const names = input.names ? new Set(input.names) : undefined;
93
- const threadKeys = input.threadKeys ? new Set(input.threadKeys) : undefined;
94
- const eventTypes = input.eventTypes ? new Set(input.eventTypes) : undefined;
95
- const kinds = input.kinds ? new Set(input.kinds) : undefined;
96
90
  const payloadStore = createDebugPayloadStore(db, store);
97
91
  const clauses = ["s.parent_id = ?", "s.channel = 'pibo.subagents'", "s.kind = 'subagent'", "s.deleted_at IS NULL"];
98
92
  const values = [parentPiboSessionId];
99
- if (afterSequence !== undefined) {
93
+ if (query.afterSequence !== undefined) {
100
94
  clauses.push("e.stream_id > ?");
101
- values.push(afterSequence);
95
+ values.push(query.afterSequence);
96
+ }
97
+ if (query.scanEventTypes && query.scanEventTypes.length > 0) {
98
+ clauses.push(`e.type IN (${query.scanEventTypes.map(() => "?").join(", ")})`);
99
+ values.push(...query.scanEventTypes);
102
100
  }
103
- const scanOrder = afterSequence !== undefined ? "ASC" : order.toUpperCase();
104
101
  const statement = db.prepare(`
105
102
  SELECT e.stream_id, e.session_id, e.session_sequence, e.event_id, e.type, e.created_at,
106
103
  e.payload_ref, e.preview_text, e.attributes_json, s.profile, s.metadata_json
107
104
  FROM event_log e
108
105
  JOIN sessions s ON s.id = e.session_id
109
106
  WHERE ${clauses.join(" AND ")}
110
- ORDER BY e.stream_id ${scanOrder}
107
+ ORDER BY e.stream_id ${query.scanOrder.toUpperCase()}
111
108
  `);
112
- const textContains = input.textContains?.toLowerCase();
113
- const matches = [];
114
- for (const rawRow of statement.iterate(...values)) {
115
- const agent = ownedById.get(rawRow.session_id ?? "");
116
- if (!agent)
117
- continue;
118
- if (agentIds && !agentIds.has(agent.agentId))
119
- continue;
120
- if (names && !names.has(agent.name))
121
- continue;
122
- if (threadKeys && (!agent.threadKey || !threadKeys.has(agent.threadKey)))
123
- continue;
124
- if (eventTypes && !eventTypes.has(rawRow.type))
125
- continue;
126
- const kind = piboAgentObservationKind(rawRow.type);
127
- if (kinds && !kinds.has(kind))
128
- continue;
129
- const createdAt = Date.parse(rawRow.created_at);
130
- if (since !== undefined && createdAt < since)
131
- continue;
132
- if (until !== undefined && createdAt > until)
133
- continue;
134
- const row = hydrateDebugEventRow(rawRow, payloadStore);
135
- const attributes = eventAttributes(row);
136
- const payload = { ...attributes, ...eventPayload(row) };
137
- const source = debugAgentObservationSource(row, attributes);
138
- const text = piboAgentObservationText(source);
139
- if (textContains && !(text ?? "").toLowerCase().includes(textContains))
140
- continue;
141
- const role = piboAgentObservationRole(source);
142
- matches.push({
143
- streamId: row.stream_id,
144
- createdAt: row.created_at,
145
- agentId: agent.agentId,
146
- name: agent.name,
147
- ...(agent.threadKey ? { threadKey: agent.threadKey } : {}),
148
- eventType: row.type,
149
- kind,
150
- ...(role ? { role } : {}),
151
- ...(text ? { text } : {}),
152
- ...(typeof payload.toolName === "string" ? { toolName: payload.toolName } : {}),
153
- ...(typeof payload.toolCallId === "string" ? { toolCallId: payload.toolCallId } : {}),
154
- ...(row.type === "tool_execution_finished" ? { isError: payload.isError === true } : row.type === "session_error" ? { isError: true } : {}),
155
- ...(input.includeDetails === true ? { details: piboAgentObservationDetails(debugAgentObservationDetails(row, payload)) } : {}),
156
- });
157
- if (matches.length > limit)
158
- break;
109
+ function* normalizedObservations() {
110
+ for (const rawRow of statement.iterate(...values)) {
111
+ const agent = ownedById.get(rawRow.session_id ?? "");
112
+ if (!agent)
113
+ continue;
114
+ const row = hydrateDebugEventRow(rawRow, payloadStore);
115
+ const attributes = eventAttributes(row);
116
+ const payload = { ...attributes, ...eventPayload(row) };
117
+ const source = debugAgentObservationSource(row, attributes);
118
+ const text = piboAgentObservationText(source);
119
+ const role = piboAgentObservationRole(source);
120
+ yield {
121
+ sequence: row.stream_id,
122
+ createdAt: row.created_at,
123
+ agentId: agent.agentId,
124
+ name: agent.name,
125
+ ...(agent.threadKey ? { threadKey: agent.threadKey } : {}),
126
+ eventType: row.type,
127
+ kind: piboAgentObservationKind(row.type),
128
+ ...(role ? { role } : {}),
129
+ ...(text ? { text } : {}),
130
+ ...(typeof payload.toolName === "string" ? { toolName: payload.toolName } : {}),
131
+ ...(typeof payload.toolCallId === "string" ? { toolCallId: payload.toolCallId } : {}),
132
+ ...(row.type === "tool_execution_finished" ? { isError: payload.isError === true } : row.type === "session_error" ? { isError: true } : {}),
133
+ details: piboAgentObservationDetails(debugAgentObservationDetails(row, payload, source)),
134
+ };
135
+ }
159
136
  }
160
- const truncated = matches.length > limit;
161
- const observations = matches.slice(0, limit);
162
- if (afterSequence !== undefined && order === "desc")
163
- observations.reverse();
137
+ const page = selectPiboAgentObservationPage(normalizedObservations(), query);
164
138
  return {
165
139
  parentPiboSessionId,
166
- filters: {
167
- ...input,
168
- ...(afterSequence !== undefined ? { afterSequence } : {}),
169
- order,
170
- limit,
171
- includeDetails: input.includeDetails === true,
172
- },
173
- observations,
174
- nextAfterSequence: observations.reduce((maximum, observation) => Math.max(maximum, observation.streamId), afterSequence ?? 0),
175
- truncated,
140
+ filters: page.filters,
141
+ observations: page.observations.map(({ sequence, ...observation }) => ({
142
+ streamId: sequence,
143
+ ...observation,
144
+ })),
145
+ nextAfterSequence: page.nextAfterSequence,
146
+ truncated: page.truncated,
176
147
  };
177
148
  }
178
149
  catch (error) {
@@ -237,12 +208,15 @@ function debugAgentObservationSource(row, attributes) {
237
208
  source.subagentName = attributes.subagentName;
238
209
  return source;
239
210
  }
240
- function debugAgentObservationDetails(row, payload) {
211
+ function debugAgentObservationDetails(row, payload, source) {
241
212
  return {
242
213
  type: row.type,
243
214
  ...(row.session_id ? { piboSessionId: row.session_id } : {}),
244
215
  ...(row.event_id ? { eventId: row.event_id } : {}),
245
216
  ...payload,
217
+ ...(source.args !== undefined ? { args: source.args } : {}),
218
+ ...(source.partialResult !== undefined ? { partialResult: source.partialResult } : {}),
219
+ ...(source.result !== undefined ? { result: source.result } : {}),
246
220
  };
247
221
  }
248
222
  function parseObject(value) {
@@ -306,17 +280,31 @@ Filters use exact values. The command inspects only direct pibo.subagents childr
306
280
  console.log(`pibo debug agents ${parentPiboSessionId} observe
307
281
 
308
282
  Usage:
309
- pibo debug agents ${parentPiboSessionId} observe [--agent-id ps_...] [--name name] [--thread-key key]
310
- [--event-type type] [--kind message|thinking|tool|error|lifecycle|event]
311
- [--since iso] [--until iso] [--contains text] [--after-sequence n]
312
- [--order asc|desc] [--limit 1..200] [--details] [--json]
283
+ pibo debug agents ${parentPiboSessionId} observe [--tool-call-id id] [--agent-id ps_...] [--name name]
284
+ [--thread-key key] [--event-type type] [--kind message|thinking|tool|error|lifecycle|event]
285
+ [--role role] [--since iso] [--until iso] [--contains text] [--after-sequence n]
286
+ [--order asc|desc] [--limit 1..200] [--include-tools]
287
+ [--tool-detail summary|full] [--details] [--json]
313
288
 
314
- Repeat --agent-id, --name, --thread-key, --event-type, or --kind for OR within that field.
289
+ Default: the newest 20 completed assistant messages, with streaming deltas and tools hidden.
290
+ Use --include-tools for compact tool calls and terminal results. Explicit --event-type or --kind
291
+ filters retain access to progress events. Repeat plural filters for OR within that field.
315
292
  Different fields combine with AND. With --after-sequence, pages always consume the oldest unseen rows;
316
293
  --order desc reverses only the returned page, so nextAfterSequence remains safe for polling.`);
317
294
  }
318
295
  function parseAgentDebugOptions(args) {
319
- const parsed = { json: false, details: false, agentIds: [], names: [], threadKeys: [], eventTypes: [], kinds: [] };
296
+ const parsed = {
297
+ json: false,
298
+ details: false,
299
+ includeTools: false,
300
+ toolCallIds: [],
301
+ agentIds: [],
302
+ names: [],
303
+ threadKeys: [],
304
+ eventTypes: [],
305
+ kinds: [],
306
+ roles: [],
307
+ };
320
308
  for (let index = 0; index < args.length; index += 1) {
321
309
  const arg = args[index];
322
310
  if (arg === "--json") {
@@ -327,10 +315,16 @@ function parseAgentDebugOptions(args) {
327
315
  parsed.details = true;
328
316
  continue;
329
317
  }
318
+ if (arg === "--include-tools") {
319
+ parsed.includeTools = true;
320
+ continue;
321
+ }
330
322
  const value = args[index + 1];
331
323
  if (!value)
332
324
  throw new Error(`${arg} requires a value`);
333
- if (arg === "--agent-id")
325
+ if (arg === "--tool-call-id")
326
+ parsed.toolCallIds.push(value);
327
+ else if (arg === "--agent-id")
334
328
  parsed.agentIds.push(value);
335
329
  else if (arg === "--name")
336
330
  parsed.names.push(value);
@@ -343,6 +337,8 @@ function parseAgentDebugOptions(args) {
343
337
  throw new Error(`Invalid --kind "${value}"`);
344
338
  parsed.kinds.push(value);
345
339
  }
340
+ else if (arg === "--role")
341
+ parsed.roles.push(value);
346
342
  else if (arg === "--status") {
347
343
  if (!["running", "idle", "killed"].includes(value))
348
344
  throw new Error(`Invalid --status "${value}"`);
@@ -363,6 +359,11 @@ function parseAgentDebugOptions(args) {
363
359
  }
364
360
  else if (arg === "--limit")
365
361
  parsed.limit = normalizePiboAgentObservationLimit(parseNonNegativeInteger(value, arg));
362
+ else if (arg === "--tool-detail") {
363
+ if (value !== "summary" && value !== "full")
364
+ throw new Error(`Invalid --tool-detail "${value}"`);
365
+ parsed.toolDetail = value;
366
+ }
366
367
  else
367
368
  throw new Error(`Unknown pibo debug agents option "${arg}"`);
368
369
  index += 1;
@@ -373,10 +374,11 @@ function validateAgentDebugOptions(command, parsed) {
373
374
  if (command === "list") {
374
375
  if (parsed.names.length > 1)
375
376
  throw new Error("pibo debug agents list accepts at most one --name value");
376
- if (parsed.details || parsed.agentIds.length > 0 || parsed.threadKeys.length > 0 || parsed.eventTypes.length > 0
377
- || parsed.kinds.length > 0 || parsed.since !== undefined || parsed.until !== undefined
377
+ if (parsed.details || parsed.includeTools || parsed.toolCallIds.length > 0 || parsed.agentIds.length > 0
378
+ || parsed.threadKeys.length > 0 || parsed.eventTypes.length > 0 || parsed.kinds.length > 0
379
+ || parsed.roles.length > 0 || parsed.since !== undefined || parsed.until !== undefined
378
380
  || parsed.textContains !== undefined || parsed.afterSequence !== undefined || parsed.order !== undefined
379
- || parsed.limit !== undefined)
381
+ || parsed.limit !== undefined || parsed.toolDetail !== undefined)
380
382
  throw new Error("Unsupported option for pibo debug agents list. Run the list command with --help.");
381
383
  return;
382
384
  }
@@ -604,6 +604,8 @@ async function runDebugEvents(args) {
604
604
  if (!selector)
605
605
  throw new Error("pibo debug events <pibo-session-id> show requires <stream-id-or-event-id>");
606
606
  const result = inspectDebugEventShow(piboSessionId, resolveDebugStore("chat"), selector, { ...detailOptions(options), payload: options.payload, raw: options.raw, field: options.field });
607
+ if (!result.event)
608
+ process.exitCode = 1;
607
609
  if (options.json)
608
610
  console.log(formatJson(result));
609
611
  else
package/dist/debug/pty.js CHANGED
@@ -1,6 +1,7 @@
1
1
  import { spawn, spawnSync } from "node:child_process";
2
2
  import { mkdir, readFile, writeFile } from "node:fs/promises";
3
3
  import path from "node:path";
4
+ import { performance } from "node:perf_hooks";
4
5
  const DEFAULT_ROWS = 24;
5
6
  const DEFAULT_COLS = 100;
6
7
  const DEFAULT_TIMEOUT_MS = 60_000;
@@ -95,6 +96,12 @@ if exit_code is None:
95
96
  exit_code = proc.wait(timeout=1)
96
97
  sys.exit(exit_code if exit_code is not None else 1)
97
98
  `;
99
+ class WallClockTimeoutError extends Error {
100
+ constructor(timeoutMs) {
101
+ super(`PTY command timed out after ${timeoutMs}ms`);
102
+ this.name = "WallClockTimeoutError";
103
+ }
104
+ }
98
105
  export async function runDebugPty(args) {
99
106
  if (args.length === 0 || args[0] === "--help" || args[0] === "-h") {
100
107
  printPtyDiscovery();
@@ -409,26 +416,31 @@ function parseSteps(value, source) {
409
416
  }
410
417
  async function executePtyScenario(input, options) {
411
418
  const scenario = normalizeScenario(input, options);
412
- const started = Date.now();
413
- const startedAt = new Date(started).toISOString();
419
+ const startedAt = new Date().toISOString();
420
+ const started = performance.now();
421
+ const deadline = createDeadline(scenario.timeoutMs, started);
414
422
  let runner;
415
423
  const assertions = [];
416
424
  let iterations = 0;
417
425
  let stopReason = "completed";
426
+ let exitCode = null;
427
+ let signal = null;
418
428
  try {
419
429
  validateProviderSafety(scenario, options);
420
430
  runner = await startRunner(scenario);
421
- let lastOutputAt = Date.now();
431
+ throwIfDeadlineExpired(deadline);
432
+ let lastOutputAt = performance.now();
422
433
  let outputLength = 0;
423
434
  const refreshOutputTimestamp = () => {
424
435
  const raw = runner?.getRawOutput() ?? "";
425
436
  if (raw.length !== outputLength) {
426
437
  outputLength = raw.length;
427
- lastOutputAt = Date.now();
438
+ lastOutputAt = performance.now();
428
439
  }
429
440
  return lastOutputAt;
430
441
  };
431
442
  for (const step of scenario.steps) {
443
+ throwIfDeadlineExpired(deadline);
432
444
  if (step.iteration === true) {
433
445
  iterations += 1;
434
446
  if (scenario.providerMode === "real" && scenario.maxIterations !== undefined && iterations > scenario.maxIterations) {
@@ -437,7 +449,8 @@ async function executePtyScenario(input, options) {
437
449
  }
438
450
  }
439
451
  await checkIdle(runner, refreshOutputTimestamp, scenario.idleTimeoutMs);
440
- await runStep(runner, scenario, step, assertions, refreshOutputTimestamp);
452
+ await runStep(runner, scenario, step, assertions, refreshOutputTimestamp, deadline);
453
+ throwIfDeadlineExpired(deadline);
441
454
  refreshOutputTimestamp();
442
455
  const clean = cleanTerminalText(runner.getRawOutput());
443
456
  const matchedStop = scenario.stopPatterns.find((pattern) => clean.includes(pattern));
@@ -446,32 +459,40 @@ async function executePtyScenario(input, options) {
446
459
  break;
447
460
  }
448
461
  }
449
- const exit = await waitForExitOrIdle(runner, Math.max(1, scenario.timeoutMs - (Date.now() - started)), scenario.idleTimeoutMs, refreshOutputTimestamp);
462
+ const stoppedByPattern = stopReason.startsWith("stop_pattern:");
463
+ if (stoppedByPattern)
464
+ await runner.terminate(stopReason);
465
+ const exit = await waitForExitOrIdle(runner, deadline, scenario.idleTimeoutMs, refreshOutputTimestamp);
466
+ exitCode = exit.exitCode;
467
+ signal = exit.signal;
450
468
  if (exit.idleTimedOut) {
451
469
  stopReason = "idle_timeout";
452
470
  throw new Error(`PTY command produced no output for ${scenario.idleTimeoutMs}ms`);
453
471
  }
454
472
  if (exit.timedOut) {
455
- stopReason = stopReason === "completed" ? "wall_clock_timeout" : stopReason;
456
- throw new Error(`PTY command timed out after ${scenario.timeoutMs}ms`);
473
+ throw new WallClockTimeoutError(scenario.timeoutMs);
457
474
  }
475
+ throwIfDeadlineExpired(deadline);
458
476
  const clean = cleanTerminalText(runner.getRawOutput());
459
477
  assertPatterns(clean, scenario.expect, scenario.reject, assertions);
460
- if (exit.exitCode !== 0) {
478
+ throwIfDeadlineExpired(deadline);
479
+ if (exit.exitCode !== 0 && !stoppedByPattern) {
461
480
  stopReason = `exit_code:${exit.exitCode ?? "signal"}`;
462
481
  throw new Error(`PTY command exited with status ${exit.exitCode ?? exit.signal ?? "unknown"}`);
463
482
  }
464
- const result = buildResult(scenario, runner, true, assertions, iterations, started, startedAt, stopReason, exit.exitCode, exit.signal);
483
+ const result = buildResult(scenario, runner, true, assertions, iterations, started, startedAt, stopReason, exitCode, signal);
465
484
  if (scenario.writeArtifactsOnSuccess)
466
485
  result.artifactDir = await writeArtifacts(scenario, result);
467
486
  return result;
468
487
  }
469
488
  catch (error) {
470
- if (stopReason === "completed")
489
+ if (error instanceof WallClockTimeoutError && stopReason === "completed")
490
+ stopReason = "wall_clock_timeout";
491
+ else if (stopReason === "completed")
471
492
  stopReason = runner ? "error" : "preflight_error";
472
493
  if (runner)
473
494
  await runner.terminate(stopReason);
474
- const result = buildResult(scenario, runner, false, assertions, iterations, started, startedAt, stopReason, null, null);
495
+ const result = buildResult(scenario, runner, false, assertions, iterations, started, startedAt, stopReason, exitCode, signal);
475
496
  result.artifactDir = await writeArtifacts(scenario, result, error instanceof Error ? error.message : String(error));
476
497
  const message = `${error instanceof Error ? error.message : String(error)}\nPTY artifacts: ${result.artifactDir}`;
477
498
  throw new Error(message);
@@ -601,6 +622,26 @@ function wrapChild(child, backend, ptyMethod) {
601
622
  driverStderr += `${error.message}\n`;
602
623
  events.push({ t: Date.now(), source: "system", kind: "error", detail: error.message });
603
624
  });
625
+ const waitForExit = async (timeoutMs) => {
626
+ if (exitState)
627
+ return { ...exitState, timedOut: false };
628
+ if (timeoutMs <= 0)
629
+ return { exitCode: null, signal: null, timedOut: true };
630
+ return new Promise((resolve) => {
631
+ let settled = false;
632
+ let timer;
633
+ const finish = (value) => {
634
+ if (settled)
635
+ return;
636
+ settled = true;
637
+ if (timer)
638
+ clearTimeout(timer);
639
+ resolve(value);
640
+ };
641
+ exitPromise.then((value) => finish({ ...value, timedOut: false }));
642
+ timer = setTimeout(() => finish({ exitCode: null, signal: null, timedOut: true }), timeoutMs);
643
+ });
644
+ };
604
645
  return {
605
646
  backend,
606
647
  ptyMethod,
@@ -615,51 +656,46 @@ function wrapChild(child, backend, ptyMethod) {
615
656
  if (exitState)
616
657
  return;
617
658
  child.kill("SIGTERM");
618
- await Promise.race([
619
- exitPromise,
620
- delay(1_000).then(() => {
621
- if (!exitState)
622
- child.kill("SIGKILL");
623
- }),
624
- ]);
625
- },
626
- async waitForExit(timeoutMs) {
627
- if (exitState)
628
- return { ...exitState, timedOut: false };
629
- const timeout = delay(timeoutMs).then(() => ({ exitCode: null, signal: null, timedOut: true }));
630
- const exit = exitPromise.then((value) => ({ ...value, timedOut: false }));
631
- return Promise.race([exit, timeout]);
659
+ if (await waitForChildExit(exitPromise, 1_000))
660
+ return;
661
+ child.kill("SIGKILL");
662
+ await waitForChildExit(exitPromise, 1_000);
632
663
  },
664
+ waitForExit,
633
665
  getRawOutput: () => rawOutput,
634
666
  getDriverStderr: () => driverStderr,
635
667
  getEvents: () => events,
636
668
  };
637
669
  }
638
- async function runStep(runner, scenario, step, assertions, markOutput) {
670
+ async function runStep(runner, scenario, step, assertions, markOutput, deadline) {
639
671
  if (step.waitFor !== undefined) {
640
- await waitForText(runner, step.waitFor, step.timeoutMs ?? scenario.timeoutMs, scenario.idleTimeoutMs, markOutput);
672
+ await waitForText(runner, step.waitFor, step.timeoutMs ?? scenario.timeoutMs, scenario.idleTimeoutMs, markOutput, deadline);
641
673
  return;
642
674
  }
643
675
  if (step.typeText !== undefined) {
644
676
  for (const char of step.typeText) {
677
+ throwIfDeadlineExpired(deadline);
645
678
  await runner.write(char);
646
- if (scenario.inputDelayMs > 0)
647
- await delay(scenario.inputDelayMs);
679
+ throwIfDeadlineExpired(deadline);
680
+ await delayWithinDeadline(scenario.inputDelayMs, deadline);
648
681
  }
649
682
  return;
650
683
  }
651
684
  if (step.writeBytes !== undefined) {
685
+ throwIfDeadlineExpired(deadline);
652
686
  await runner.write(step.writeBytes);
687
+ throwIfDeadlineExpired(deadline);
653
688
  return;
654
689
  }
655
690
  if (step.press !== undefined) {
691
+ throwIfDeadlineExpired(deadline);
656
692
  await runner.write(keySequence(step.press));
657
- if (scenario.inputDelayMs > 0)
658
- await delay(scenario.inputDelayMs);
693
+ throwIfDeadlineExpired(deadline);
694
+ await delayWithinDeadline(scenario.inputDelayMs, deadline);
659
695
  return;
660
696
  }
661
697
  if (step.sleepMs !== undefined) {
662
- await delay(step.sleepMs);
698
+ await delayWithinDeadline(step.sleepMs, deadline);
663
699
  return;
664
700
  }
665
701
  const clean = cleanTerminalText(runner.getRawOutput());
@@ -670,35 +706,41 @@ async function runStep(runner, scenario, step, assertions, markOutput) {
670
706
  if (step.reject !== undefined)
671
707
  assertPatterns(clean, [], [step.reject], assertions);
672
708
  }
673
- async function waitForText(runner, pattern, timeoutMs, idleTimeoutMs, markOutput) {
674
- const deadline = Date.now() + timeoutMs;
675
- while (Date.now() < deadline) {
709
+ async function waitForText(runner, pattern, timeoutMs, idleTimeoutMs, markOutput, globalDeadline) {
710
+ const stepDeadline = performance.now() + timeoutMs;
711
+ while (true) {
712
+ throwIfDeadlineExpired(globalDeadline);
676
713
  const lastOutputAt = markOutput();
677
714
  if (cleanTerminalText(runner.getRawOutput()).includes(pattern))
678
715
  return;
679
- if (Date.now() - lastOutputAt > idleTimeoutMs) {
716
+ const now = performance.now();
717
+ if (now - lastOutputAt > idleTimeoutMs) {
680
718
  await runner.terminate("idle_timeout");
681
719
  throw new Error(`PTY command produced no output for ${idleTimeoutMs}ms while waiting for ${JSON.stringify(pattern)}`);
682
720
  }
683
- await delay(50);
721
+ if (now >= stepDeadline)
722
+ break;
723
+ await delay(Math.max(1, Math.min(50, stepDeadline - now, remainingMs(globalDeadline), idleTimeoutMs - (now - lastOutputAt))));
684
724
  }
685
725
  throw new Error(`Timed out waiting for PTY output ${JSON.stringify(pattern)} after ${timeoutMs}ms`);
686
726
  }
687
- async function waitForExitOrIdle(runner, timeoutMs, idleTimeoutMs, markOutput) {
688
- const deadline = Date.now() + timeoutMs;
689
- while (Date.now() < deadline) {
727
+ async function waitForExitOrIdle(runner, deadline, idleTimeoutMs, markOutput) {
728
+ while (remainingMs(deadline) > 0) {
690
729
  const lastOutputAt = markOutput();
691
- const remaining = Math.max(1, Math.min(100, deadline - Date.now()));
730
+ const remaining = Math.max(1, Math.min(100, remainingMs(deadline)));
692
731
  const exit = await runner.waitForExit(remaining);
693
- if (!exit.timedOut)
732
+ if (!exit.timedOut) {
733
+ if (remainingMs(deadline) <= 0)
734
+ return { exitCode: null, signal: null, timedOut: true, idleTimedOut: false };
694
735
  return { ...exit, timedOut: false, idleTimedOut: false };
695
- if (Date.now() - lastOutputAt > idleTimeoutMs)
736
+ }
737
+ if (performance.now() - lastOutputAt > idleTimeoutMs)
696
738
  return { exitCode: null, signal: null, timedOut: false, idleTimedOut: true };
697
739
  }
698
740
  return { exitCode: null, signal: null, timedOut: true, idleTimedOut: false };
699
741
  }
700
742
  async function checkIdle(runner, lastOutputAt, idleTimeoutMs) {
701
- if (Date.now() - lastOutputAt() > idleTimeoutMs) {
743
+ if (performance.now() - lastOutputAt() > idleTimeoutMs) {
702
744
  await runner.terminate("idle_timeout");
703
745
  throw new Error(`PTY command produced no output for ${idleTimeoutMs}ms`);
704
746
  }
@@ -741,7 +783,7 @@ function cleanTerminalText(raw) {
741
783
  .replace(/\r/g, "\n");
742
784
  }
743
785
  function buildResult(scenario, runner, ok, assertions, iterations, started, startedAt, stopReason, exitCode, signal) {
744
- const ended = Date.now();
786
+ const endedAt = new Date().toISOString();
745
787
  return {
746
788
  ok,
747
789
  name: scenario.name,
@@ -750,8 +792,8 @@ function buildResult(scenario, runner, ok, assertions, iterations, started, star
750
792
  signal,
751
793
  stopReason,
752
794
  startedAt,
753
- endedAt: new Date(ended).toISOString(),
754
- durationMs: ended - started,
795
+ endedAt,
796
+ durationMs: Math.round(performance.now() - started),
755
797
  rawOutput: runner?.getRawOutput() ?? "",
756
798
  driverStderr: runner?.getDriverStderr() ?? "",
757
799
  events: runner?.getEvents() ?? [],
@@ -915,9 +957,46 @@ function optionalStringRecord(value, field, source) {
915
957
  function safeName(name) {
916
958
  return name.toLowerCase().replace(/[^a-z0-9._-]+/g, "-").replace(/^-+|-+$/g, "") || "pty-scenario";
917
959
  }
960
+ function createDeadline(timeoutMs, started = performance.now()) {
961
+ return { expiresAt: started + timeoutMs, timeoutMs };
962
+ }
963
+ function remainingMs(deadline) {
964
+ return Math.max(0, deadline.expiresAt - performance.now());
965
+ }
966
+ function throwIfDeadlineExpired(deadline) {
967
+ if (remainingMs(deadline) <= 0)
968
+ throw new WallClockTimeoutError(deadline.timeoutMs);
969
+ }
970
+ async function delayWithinDeadline(ms, deadline) {
971
+ throwIfDeadlineExpired(deadline);
972
+ if (ms <= 0)
973
+ return;
974
+ const remaining = remainingMs(deadline);
975
+ if (ms >= remaining) {
976
+ await delay(remaining);
977
+ throw new WallClockTimeoutError(deadline.timeoutMs);
978
+ }
979
+ await delay(ms);
980
+ throwIfDeadlineExpired(deadline);
981
+ }
918
982
  function delay(ms) {
919
983
  return new Promise((resolve) => setTimeout(resolve, ms));
920
984
  }
985
+ async function waitForChildExit(exitPromise, timeoutMs) {
986
+ let timeout;
987
+ try {
988
+ return await Promise.race([
989
+ exitPromise.then(() => true),
990
+ new Promise((resolve) => {
991
+ timeout = setTimeout(() => resolve(false), timeoutMs);
992
+ }),
993
+ ]);
994
+ }
995
+ finally {
996
+ if (timeout)
997
+ clearTimeout(timeout);
998
+ }
999
+ }
921
1000
  export const __debugPtyForTests = {
922
1001
  cleanTerminalText,
923
1002
  keySequence,
@@ -407,6 +407,10 @@ export async function runGatewayCli(argv = process.argv) {
407
407
  const subcommand = args[1];
408
408
  const hasForceFlag = args.includes("--force");
409
409
  if (subcommand === "web" || subcommand === "dev") {
410
+ if (args.slice(2).some((arg) => arg === "--help" || arg === "-h")) {
411
+ printGatewayHelp();
412
+ return;
413
+ }
410
414
  const handled = await runManagedGatewayCommand(subcommand, args[2], args.slice(3), argv);
411
415
  if (!handled) {
412
416
  console.error(`Unknown gateway ${subcommand} subcommand: ${args[2] ?? ""}`);
@@ -4,5 +4,7 @@ let currentLoopService;
4
4
  export function getPiboLoopService() { return currentLoopService; }
5
5
  export function createPiboLoopChannel(options = {}) {
6
6
  return { name: 'pibo.loop', kind: 'custom', description: 'Runs continuous Loop Pibo agent jobs.', auth: { mode: 'trusted-local' }, start(context) { if (currentLoopService)
7
- return; currentLoopService = new PiboLoopService({ ...options, context, store: createDefaultPiboLoopStore({ path: options.loopStorePath }) }); currentLoopService.start(); }, stop() { currentLoopService?.stop(); currentLoopService = undefined; } };
7
+ return; currentLoopService = new PiboLoopService({ ...options, context, store: createDefaultPiboLoopStore({ path: options.loopStorePath }) }); currentLoopService.start(); }, async stop() { const service = currentLoopService; if (!service)
8
+ return; await service.stop(); if (currentLoopService === service)
9
+ currentLoopService = undefined; } };
8
10
  }
package/dist/loops/cli.js CHANGED
@@ -27,7 +27,8 @@ Commands:
27
27
 
28
28
  Next: ${commandName} add --help`);
29
29
  }
30
- function targetFromOptions(options) { if (options.room)
30
+ function targetFromOptions(options) { if (options.room && options.defaultChat)
31
+ throw new Error('Choose either --room <room-id> or --default-chat, not both'); if (options.room)
31
32
  return { kind: 'room', roomId: options.room }; if (options.defaultChat)
32
33
  return { kind: 'default-chat' }; throw new Error('Choose a target: --room <room-id> or --default-chat'); }
33
34
  function maybeTargetFromOptions(options) { if (options.room || options.defaultChat)