@oyasmi/pipiclaw 0.6.10 → 0.7.0-beta.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 (55) hide show
  1. package/README.md +1 -1
  2. package/dist/agent/channel-runner.d.ts +11 -1
  3. package/dist/agent/channel-runner.js +39 -3
  4. package/dist/agent/commands.d.ts +1 -1
  5. package/dist/agent/commands.js +4 -0
  6. package/dist/agent/prompt-builder.d.ts +17 -0
  7. package/dist/agent/prompt-builder.js +42 -23
  8. package/dist/agent/types.d.ts +7 -0
  9. package/dist/memory/bootstrap.js +35 -1
  10. package/dist/memory/candidates.js +21 -3
  11. package/dist/memory/consolidation.d.ts +6 -1
  12. package/dist/memory/consolidation.js +99 -33
  13. package/dist/memory/files.d.ts +40 -0
  14. package/dist/memory/files.js +0 -0
  15. package/dist/memory/maintenance-jobs.js +9 -4
  16. package/dist/memory/post-turn-review.js +3 -2
  17. package/dist/memory/promotion-signals.js +0 -1
  18. package/dist/memory/recall.js +10 -2
  19. package/dist/memory/session.js +43 -13
  20. package/dist/memory/transcript.d.ts +9 -0
  21. package/dist/memory/transcript.js +30 -0
  22. package/dist/runtime/bootstrap.js +140 -15
  23. package/dist/runtime/delivery.js +17 -0
  24. package/dist/runtime/dingtalk.d.ts +1 -0
  25. package/dist/runtime/dingtalk.js +15 -4
  26. package/dist/sandbox.d.ts +8 -0
  27. package/dist/sandbox.js +21 -17
  28. package/dist/settings.d.ts +4 -0
  29. package/dist/settings.js +2 -0
  30. package/dist/subagents/tool.d.ts +2 -2
  31. package/dist/subagents/tool.js +24 -56
  32. package/dist/tools/bash.d.ts +8 -1
  33. package/dist/tools/bash.js +46 -21
  34. package/dist/tools/config.d.ts +3 -0
  35. package/dist/tools/config.js +9 -0
  36. package/dist/tools/edit.d.ts +1 -0
  37. package/dist/tools/edit.js +18 -11
  38. package/dist/tools/index.js +18 -53
  39. package/dist/tools/memory-save.d.ts +17 -0
  40. package/dist/tools/memory-save.js +43 -0
  41. package/dist/tools/read.d.ts +2 -2
  42. package/dist/tools/read.js +2 -2
  43. package/dist/tools/registry.d.ts +63 -0
  44. package/dist/tools/registry.js +153 -0
  45. package/dist/tools/session-search.d.ts +2 -2
  46. package/dist/tools/session-search.js +9 -5
  47. package/dist/tools/skill-list.js +1 -1
  48. package/dist/tools/skill-manage.d.ts +1 -1
  49. package/dist/tools/skill-manage.js +3 -1
  50. package/dist/tools/skill-view.js +12 -11
  51. package/dist/tools/web-search.d.ts +1 -1
  52. package/dist/tools/web-search.js +1 -1
  53. package/package.json +5 -5
  54. package/dist/tools/attach.d.ts +0 -20
  55. package/dist/tools/attach.js +0 -69
@@ -1,4 +1,4 @@
1
- import { existsSync, mkdirSync, readFileSync, writeFileSync } from "fs";
1
+ import { chmodSync, existsSync, mkdirSync, readFileSync, statSync, writeFileSync } from "fs";
2
2
  import { join } from "path";
3
3
  import { parseBuiltInCommand } from "../agent/commands.js";
4
4
  import { getOrCreateRunner } from "../agent/index.js";
@@ -7,7 +7,7 @@ import * as log from "../log.js";
7
7
  import { ensureChannelMemoryFilesSync } from "../memory/files.js";
8
8
  import { MemoryMaintenanceScheduler } from "../memory/scheduler.js";
9
9
  import { APP_HOME_DIR, APP_NAME, AUTH_CONFIG_PATH, CHANNEL_CONFIG_PATH, EVENT_HISTORY_PATH, MODELS_CONFIG_PATH, SECURITY_CONFIG_PATH, SETTINGS_CONFIG_PATH, TOOLS_CONFIG_PATH, WORKSPACE_DIR, } from "../paths.js";
10
- import { createExecutor, parseSandboxArg, validateSandbox } from "../sandbox.js";
10
+ import { createExecutor, parseSandboxArg, SandboxConfigError, validateSandbox, } from "../sandbox.js";
11
11
  import { loadSecurityConfigWithDiagnostics } from "../security/config.js";
12
12
  import { PipiclawSettingsManager } from "../settings.js";
13
13
  import { formatConfigDiagnostic } from "../shared/config-diagnostics.js";
@@ -175,16 +175,36 @@ function readCliVersion() {
175
175
  return "0.0.0";
176
176
  }
177
177
  }
178
- function writeTextFileIfMissing(path, content, label, created) {
178
+ function writeTextFileIfMissing(path, content, label, created, mode) {
179
179
  if (existsSync(path)) {
180
180
  return false;
181
181
  }
182
- writeFileSync(path, content, "utf-8");
182
+ writeFileSync(path, content, mode !== undefined ? { encoding: "utf-8", mode } : "utf-8");
183
183
  created.push(label);
184
184
  return true;
185
185
  }
186
- function writeJsonFileIfMissing(path, value, label, created) {
187
- return writeTextFileIfMissing(path, `${JSON.stringify(value, null, 2)}\n`, label, created);
186
+ function writeJsonFileIfMissing(path, value, label, created, mode) {
187
+ return writeTextFileIfMissing(path, `${JSON.stringify(value, null, 2)}\n`, label, created, mode);
188
+ }
189
+ // App-level config files that may hold secrets (DingTalk client secret, provider
190
+ // API keys, Brave key). They are created owner-only, and any pre-existing file with
191
+ // looser bits is tightened on startup. No-op on Windows, where POSIX mode bits do
192
+ // not apply.
193
+ const SECRET_FILE_MODE = 0o600;
194
+ function hardenExistingSecretFile(path) {
195
+ if (process.platform === "win32" || !existsSync(path)) {
196
+ return;
197
+ }
198
+ try {
199
+ const mode = statSync(path).mode & 0o777;
200
+ if ((mode & 0o077) !== 0) {
201
+ chmodSync(path, SECRET_FILE_MODE);
202
+ log.logInfo(`Tightened permissions on ${path} to 0600`);
203
+ }
204
+ }
205
+ catch (err) {
206
+ log.logWarning(`Failed to tighten permissions on ${path}`, err instanceof Error ? err.message : String(err));
207
+ }
188
208
  }
189
209
  export function bootstrapAppHome(paths = DEFAULT_BOOTSTRAP_PATHS) {
190
210
  const created = [];
@@ -207,12 +227,24 @@ export function bootstrapAppHome(paths = DEFAULT_BOOTSTRAP_PATHS) {
207
227
  writeTextFileIfMissing(join(paths.workspaceDir, "AGENTS.md"), DEFAULT_AGENT, "workspace/AGENTS.md", created);
208
228
  writeTextFileIfMissing(join(paths.workspaceDir, "MEMORY.md"), DEFAULT_MEMORY, "workspace/MEMORY.md", created);
209
229
  writeTextFileIfMissing(join(paths.workspaceDir, "ENVIRONMENT.md"), DEFAULT_ENVIRONMENT, "workspace/ENVIRONMENT.md", created);
210
- const channelTemplateCreated = writeJsonFileIfMissing(paths.channelConfigPath, CHANNEL_CONFIG_TEMPLATE, "channel.json", created);
211
- writeJsonFileIfMissing(paths.authConfigPath, {}, "auth.json", created);
212
- writeJsonFileIfMissing(paths.modelsConfigPath, MODELS_CONFIG_TEMPLATE, "models.json", created);
213
- writeJsonFileIfMissing(paths.settingsConfigPath, {}, "settings.json", created);
214
- writeJsonFileIfMissing(paths.toolsConfigPath, TOOLS_CONFIG_TEMPLATE, "tools.json", created);
215
- writeJsonFileIfMissing(paths.securityConfigPath, SECURITY_CONFIG_TEMPLATE, "security.json", created);
230
+ const secretConfigPaths = [
231
+ paths.channelConfigPath,
232
+ paths.authConfigPath,
233
+ paths.modelsConfigPath,
234
+ paths.settingsConfigPath,
235
+ paths.toolsConfigPath,
236
+ paths.securityConfigPath,
237
+ ];
238
+ const channelTemplateCreated = writeJsonFileIfMissing(paths.channelConfigPath, CHANNEL_CONFIG_TEMPLATE, "channel.json", created, SECRET_FILE_MODE);
239
+ writeJsonFileIfMissing(paths.authConfigPath, {}, "auth.json", created, SECRET_FILE_MODE);
240
+ writeJsonFileIfMissing(paths.modelsConfigPath, MODELS_CONFIG_TEMPLATE, "models.json", created, SECRET_FILE_MODE);
241
+ writeJsonFileIfMissing(paths.settingsConfigPath, {}, "settings.json", created, SECRET_FILE_MODE);
242
+ writeJsonFileIfMissing(paths.toolsConfigPath, TOOLS_CONFIG_TEMPLATE, "tools.json", created, SECRET_FILE_MODE);
243
+ writeJsonFileIfMissing(paths.securityConfigPath, SECURITY_CONFIG_TEMPLATE, "security.json", created, SECRET_FILE_MODE);
244
+ // Tighten any pre-existing config that predates owner-only creation.
245
+ for (const secretPath of secretConfigPaths) {
246
+ hardenExistingSecretFile(secretPath);
247
+ }
216
248
  return { created, channelTemplateCreated };
217
249
  }
218
250
  function isPlaceholderString(value) {
@@ -298,13 +330,25 @@ export function loadConfig(paths = DEFAULT_BOOTSTRAP_PATHS, io = console) {
298
330
  export function parseArgs(argv, paths = DEFAULT_BOOTSTRAP_PATHS, io = console) {
299
331
  const args = argv.slice(2);
300
332
  let sandbox = { type: "host" };
333
+ const parseSandboxOrExit = (value) => {
334
+ try {
335
+ return parseSandboxArg(value);
336
+ }
337
+ catch (err) {
338
+ if (err instanceof SandboxConfigError) {
339
+ io.error(`Error: ${err.message}`);
340
+ throw new BootstrapExitError(1);
341
+ }
342
+ throw err;
343
+ }
344
+ };
301
345
  for (let index = 0; index < args.length; index += 1) {
302
346
  const arg = args[index];
303
347
  if (arg.startsWith("--sandbox=")) {
304
- sandbox = parseSandboxArg(arg.slice("--sandbox=".length));
348
+ sandbox = parseSandboxOrExit(arg.slice("--sandbox=".length));
305
349
  }
306
350
  else if (arg === "--sandbox") {
307
- sandbox = parseSandboxArg(args[index + 1] || "");
351
+ sandbox = parseSandboxOrExit(args[index + 1] || "");
308
352
  index += 1;
309
353
  }
310
354
  else if (arg === "--help" || arg === "-h") {
@@ -352,11 +396,68 @@ function flushInactiveChannelMemory(channelStates) {
352
396
  function isNoRunningTaskQueueError(err) {
353
397
  return err instanceof Error && err.message === "No task is currently running.";
354
398
  }
399
+ function formatTokenCount(count) {
400
+ if (count < 1000)
401
+ return count.toString();
402
+ if (count < 1_000_000)
403
+ return `${Math.round(count / 1000)}k`;
404
+ return `${(count / 1_000_000).toFixed(1)}M`;
405
+ }
406
+ function formatUptime(ms) {
407
+ const totalSeconds = Math.floor(ms / 1000);
408
+ const days = Math.floor(totalSeconds / 86400);
409
+ const hours = Math.floor((totalSeconds % 86400) / 3600);
410
+ const minutes = Math.floor((totalSeconds % 3600) / 60);
411
+ const parts = [];
412
+ if (days > 0)
413
+ parts.push(`${days}d`);
414
+ if (hours > 0)
415
+ parts.push(`${hours}h`);
416
+ parts.push(`${minutes}m`);
417
+ return parts.join(" ");
418
+ }
419
+ function renderStatus(options) {
420
+ const { state, version, uptimeMs, sandbox } = options;
421
+ const lines = ["# Status"];
422
+ if (state?.running) {
423
+ const task = state.currentTaskText?.trim();
424
+ const preview = task ? `: ${task.length > 80 ? `${task.slice(0, 79)}…` : task}` : "";
425
+ lines.push(`- Run state: running${preview}`);
426
+ }
427
+ else {
428
+ lines.push("- Run state: idle");
429
+ }
430
+ if (state) {
431
+ try {
432
+ const snapshot = state.runner.getStatusSnapshot();
433
+ lines.push(`- Model: ${snapshot.model}`);
434
+ if (snapshot.thinkingLevel && snapshot.thinkingLevel !== "off") {
435
+ lines.push(`- Thinking: ${snapshot.thinkingLevel}`);
436
+ }
437
+ if (snapshot.contextTokens !== undefined && snapshot.contextWindow > 0) {
438
+ const percent = ((snapshot.contextTokens / snapshot.contextWindow) * 100).toFixed(1);
439
+ lines.push(`- Context: ${formatTokenCount(snapshot.contextTokens)} / ${formatTokenCount(snapshot.contextWindow)} (${percent}%)`);
440
+ }
441
+ }
442
+ catch (err) {
443
+ lines.push(`- Model: unavailable (${err instanceof Error ? err.message : String(err)})`);
444
+ }
445
+ }
446
+ else {
447
+ lines.push("- Model: no session started for this channel yet");
448
+ }
449
+ lines.push(`- Sandbox: ${sandbox.type === "host" ? "host" : `docker:${sandbox.container}`}`);
450
+ lines.push(`- Uptime: ${formatUptime(uptimeMs)}`);
451
+ lines.push(`- Version: ${version}`);
452
+ return lines.join("\n");
453
+ }
355
454
  export function createRuntimeContext(options) {
356
455
  const startServices = options.startServices ?? true;
357
456
  const registerSignalHandlers = options.registerSignalHandlers ?? true;
358
457
  const store = new ChannelStore({ workingDir: options.paths.workspaceDir });
359
458
  const runtimeSettingsManager = new PipiclawSettingsManager(options.paths.appHomeDir);
459
+ const startedAt = Date.now();
460
+ const cliVersion = readCliVersion();
360
461
  const channelStates = new Map();
361
462
  const activeTasks = new Set();
362
463
  let shuttingDown = false;
@@ -413,6 +514,15 @@ export function createRuntimeContext(options) {
413
514
  });
414
515
  await bot.sendPlain(event.channelId, response);
415
516
  },
517
+ async handleStatusCommand(event, bot) {
518
+ const response = renderStatus({
519
+ state: channelStates.get(event.channelId),
520
+ version: cliVersion,
521
+ uptimeMs: Date.now() - startedAt,
522
+ sandbox: options.sandbox,
523
+ });
524
+ await bot.sendPlain(event.channelId, response);
525
+ },
416
526
  async handleBusyMessage(event, bot, mode, queueText) {
417
527
  if (shuttingDown) {
418
528
  return { kind: "handled" };
@@ -489,10 +599,15 @@ export function createRuntimeContext(options) {
489
599
  await handler.handleEventsCommand(event, bot, builtInCommand.args);
490
600
  return;
491
601
  }
602
+ if (builtInCommand.name === "status") {
603
+ await handler.handleStatusCommand(event, bot);
604
+ return;
605
+ }
492
606
  await state.runner.handleBuiltinCommand(ctx, builtInCommand);
493
607
  return;
494
608
  }
495
609
  log.logInfo(`[${event.channelId}] Starting run: ${event.text.substring(0, 50)}`);
610
+ state.currentTaskText = event.text;
496
611
  if (!_isEvent) {
497
612
  ctx.primeCard(350);
498
613
  }
@@ -506,6 +621,7 @@ export function createRuntimeContext(options) {
506
621
  }
507
622
  finally {
508
623
  state.running = false;
624
+ state.currentTaskText = undefined;
509
625
  }
510
626
  })();
511
627
  activeTasks.add(task);
@@ -642,7 +758,16 @@ export async function bootstrap(argv, options = {}) {
642
758
  for (const diagnostic of loadSecurityConfigWithDiagnostics(paths.appHomeDir).diagnostics) {
643
759
  log.logWarning(formatConfigDiagnostic(diagnostic), diagnostic.path);
644
760
  }
645
- await validateSandbox(sandbox);
761
+ try {
762
+ await validateSandbox(sandbox);
763
+ }
764
+ catch (err) {
765
+ if (err instanceof SandboxConfigError) {
766
+ io.error(`Error: ${err.message}`);
767
+ throw new BootstrapExitError(1);
768
+ }
769
+ throw err;
770
+ }
646
771
  log.logStartup(paths.workspaceDir, sandbox.type === "host" ? "host" : `docker:${sandbox.container}`);
647
772
  const runtime = createRuntimeContext({
648
773
  paths,
@@ -2,6 +2,10 @@ import * as log from "../log.js";
2
2
  const MIN_UPDATE_INTERVAL_MS = 800;
3
3
  const ROLLING_WINDOW_SIZE = 3;
4
4
  const NO_CONTENT = "";
5
+ // Last-resort ceiling on how long flush() will block a caller. Outbound HTTP now
6
+ // has its own timeout, so the sync loop is already bounded; this only guards against
7
+ // an unforeseen stall so run()'s finally can never hang the channel forever.
8
+ const FLUSH_DEADLINE_MS = 60_000;
5
9
  class ChannelDeliveryController {
6
10
  constructor(event, bot, store) {
7
11
  this.event = event;
@@ -306,8 +310,21 @@ class ChannelDeliveryController {
306
310
  async flush() {
307
311
  if (this.isSettled())
308
312
  return;
313
+ let deadlineTimer = null;
309
314
  await new Promise((resolve) => {
310
315
  this.flushWaiters.push(resolve);
316
+ deadlineTimer = setTimeout(() => {
317
+ if (this.flushWaiters.includes(resolve)) {
318
+ log.logWarning(`[${this.event.channelId}] Delivery flush deadline exceeded (${FLUSH_DEADLINE_MS}ms); releasing caller`);
319
+ this.flushWaiters = this.flushWaiters.filter((waiter) => waiter !== resolve);
320
+ resolve();
321
+ }
322
+ }, FLUSH_DEADLINE_MS);
323
+ deadlineTimer.unref?.();
324
+ }).finally(() => {
325
+ if (deadlineTimer) {
326
+ clearTimeout(deadlineTimer);
327
+ }
311
328
  });
312
329
  }
313
330
  async close() {
@@ -65,6 +65,7 @@ export interface DingTalkHandler {
65
65
  handleEvent(event: DingTalkEvent, bot: DingTalkBot, isEvent?: boolean): Promise<void>;
66
66
  handleStop(channelId: string, bot: DingTalkBot): Promise<void>;
67
67
  handleEventsCommand(event: DingTalkEvent, bot: DingTalkBot, args: string): Promise<void>;
68
+ handleStatusCommand(event: DingTalkEvent, bot: DingTalkBot): Promise<void>;
68
69
  handleBusyMessage(event: DingTalkEvent, bot: DingTalkBot, mode: BusyMessageMode, queueText: string): Promise<BusyMessageResult>;
69
70
  }
70
71
  export declare class DingTalkBot {
@@ -103,6 +103,13 @@ class ChannelQueue {
103
103
  // Constants
104
104
  // ============================================================================
105
105
  const DINGTALK_API = "https://api.dingtalk.com";
106
+ // Bound every outbound DingTalk HTTP call. Without this, axios waits forever on a
107
+ // hung connection, and a stalled card-streaming request would wedge the delivery
108
+ // sync loop (never resolving flush()), leaving the whole channel permanently busy.
109
+ // A timeout turns "hang" into a normal failure that the existing fallback paths
110
+ // (discardCard / replay / sendPlain) already handle.
111
+ const DINGTALK_HTTP_TIMEOUT_MS = 15_000;
112
+ const http = axios.create({ timeout: DINGTALK_HTTP_TIMEOUT_MS });
106
113
  const TOKEN_REFRESH_SECS = 90 * 60; // 1.5 hours (tokens expire after 2 hours)
107
114
  const CONNECT_ATTEMPT_TIMEOUT_MS = 10_000;
108
115
  const SOCKET_CLOSE_GRACE_MS = 1_000;
@@ -693,7 +700,7 @@ export class DingTalkBot {
693
700
  body.userIds = [meta.senderId];
694
701
  }
695
702
  try {
696
- await axios.post(url, body, {
703
+ await http.post(url, body, {
697
704
  headers: {
698
705
  "x-acs-dingtalk-access-token": token,
699
706
  "Content-Type": "application/json",
@@ -774,7 +781,7 @@ export class DingTalkBot {
774
781
  body.imRobotOpenDeliverModel = { spaceType: "IM_ROBOT" };
775
782
  }
776
783
  try {
777
- await axios.post(`${DINGTALK_API}/v1.0/card/instances/createAndDeliver`, body, {
784
+ await http.post(`${DINGTALK_API}/v1.0/card/instances/createAndDeliver`, body, {
778
785
  headers: {
779
786
  "x-acs-dingtalk-access-token": token,
780
787
  "Content-Type": "application/json",
@@ -826,7 +833,7 @@ export class DingTalkBot {
826
833
  };
827
834
  const start = Date.now();
828
835
  try {
829
- await axios.put(`${DINGTALK_API}/v1.0/card/streaming`, body, {
836
+ await http.put(`${DINGTALK_API}/v1.0/card/streaming`, body, {
830
837
  headers: {
831
838
  "x-acs-dingtalk-access-token": card.accessToken,
832
839
  "Content-Type": "application/json",
@@ -870,7 +877,7 @@ export class DingTalkBot {
870
877
  }
871
878
  async refreshAccessToken() {
872
879
  try {
873
- const resp = await axios.post(`${DINGTALK_API}/v1.0/oauth2/accessToken`, {
880
+ const resp = await http.post(`${DINGTALK_API}/v1.0/oauth2/accessToken`, {
874
881
  appKey: this.config.clientId,
875
882
  appSecret: this.config.clientSecret,
876
883
  }, {
@@ -983,6 +990,10 @@ export class DingTalkBot {
983
990
  await this.handler.handleEventsCommand(event, this, builtInCommand.args);
984
991
  return;
985
992
  }
993
+ if (builtInCommand?.name === "status") {
994
+ await this.handler.handleStatusCommand(event, this);
995
+ return;
996
+ }
986
997
  if (builtInCommand) {
987
998
  await this.sendPlain(channelId, `A task is already running. Use \`/stop\`, \`/steer <message>\`, \`/followup <message>\`, or \`/events <action>\`. Plain messages default to ${this.busyMessageDefault}.`);
988
999
  return;
package/dist/sandbox.d.ts CHANGED
@@ -4,6 +4,14 @@ export type SandboxConfig = {
4
4
  type: "docker";
5
5
  container: string;
6
6
  };
7
+ /**
8
+ * Error raised when sandbox configuration is invalid or the target sandbox is not
9
+ * usable. Thrown instead of calling process.exit so callers (bootstrap) decide how
10
+ * to surface it and the functions stay testable.
11
+ */
12
+ export declare class SandboxConfigError extends Error {
13
+ constructor(message: string);
14
+ }
7
15
  export declare function parseSandboxArg(value: string): SandboxConfig;
8
16
  export declare function validateSandbox(config: SandboxConfig): Promise<void>;
9
17
  /**
package/dist/sandbox.js CHANGED
@@ -1,5 +1,16 @@
1
1
  import { spawn, spawnSync } from "child_process";
2
2
  import { shellEscape } from "./shared/shell-escape.js";
3
+ /**
4
+ * Error raised when sandbox configuration is invalid or the target sandbox is not
5
+ * usable. Thrown instead of calling process.exit so callers (bootstrap) decide how
6
+ * to surface it and the functions stay testable.
7
+ */
8
+ export class SandboxConfigError extends Error {
9
+ constructor(message) {
10
+ super(message);
11
+ this.name = "SandboxConfigError";
12
+ }
13
+ }
3
14
  export function parseSandboxArg(value) {
4
15
  if (value === "host") {
5
16
  return { type: "host" };
@@ -7,13 +18,11 @@ export function parseSandboxArg(value) {
7
18
  if (value.startsWith("docker:")) {
8
19
  const container = value.slice("docker:".length);
9
20
  if (!container) {
10
- console.error("Error: docker sandbox requires container name (e.g., docker:pipiclaw-sandbox)");
11
- process.exit(1);
21
+ throw new SandboxConfigError("docker sandbox requires container name (e.g., docker:pipiclaw-sandbox)");
12
22
  }
13
23
  return { type: "docker", container };
14
24
  }
15
- console.error(`Error: Invalid sandbox type '${value}'. Use 'host' or 'docker:<container-name>'`);
16
- process.exit(1);
25
+ throw new SandboxConfigError(`Invalid sandbox type '${value}'. Use 'host' or 'docker:<container-name>'`);
17
26
  }
18
27
  export async function validateSandbox(config) {
19
28
  if (config.type === "host") {
@@ -22,8 +31,7 @@ export async function validateSandbox(config) {
22
31
  resolveWindowsHostShell();
23
32
  }
24
33
  catch (error) {
25
- console.error(`Error: ${error instanceof Error ? error.message : String(error)}`);
26
- process.exit(1);
34
+ throw new SandboxConfigError(error instanceof Error ? error.message : String(error));
27
35
  }
28
36
  }
29
37
  return;
@@ -33,22 +41,18 @@ export async function validateSandbox(config) {
33
41
  await execSimple("docker", ["--version"]);
34
42
  }
35
43
  catch {
36
- console.error("Error: Docker is not installed or not in PATH");
37
- process.exit(1);
44
+ throw new SandboxConfigError("Docker is not installed or not in PATH");
38
45
  }
39
46
  // Check if container exists and is running
47
+ let running;
40
48
  try {
41
- const result = await execSimple("docker", ["inspect", "-f", "{{.State.Running}}", config.container]);
42
- if (result.trim() !== "true") {
43
- console.error(`Error: Container '${config.container}' is not running.`);
44
- console.error(`Start it with: docker start ${config.container}`);
45
- process.exit(1);
46
- }
49
+ running = await execSimple("docker", ["inspect", "-f", "{{.State.Running}}", config.container]);
47
50
  }
48
51
  catch {
49
- console.error(`Error: Container '${config.container}' does not exist.`);
50
- console.error("Create it with: ./docker.sh create <data-dir>");
51
- process.exit(1);
52
+ throw new SandboxConfigError(`Container '${config.container}' does not exist.\nCreate it with: ./docker.sh create <data-dir>`);
53
+ }
54
+ if (running.trim() !== "true") {
55
+ throw new SandboxConfigError(`Container '${config.container}' is not running.\nStart it with: docker start ${config.container}`);
52
56
  }
53
57
  console.log(` Docker container '${config.container}' is running.`);
54
58
  }
@@ -87,6 +87,10 @@ export interface PipiclawMemoryMaintenanceSettings {
87
87
  structuralMaintenanceIntervalHours: number;
88
88
  maxConcurrentChannels: number;
89
89
  failureBackoffMinutes: number;
90
+ /** Reject a MEMORY.md cleanup whose result shrinks below this ratio of the original. */
91
+ cleanupShrinkGuardMinRatio: number;
92
+ /** Only apply the shrink guard when the original exceeds this length (chars). */
93
+ cleanupShrinkGuardMinChars: number;
90
94
  }
91
95
  export interface PipiclawSessionSearchSettings {
92
96
  enabled: boolean;
package/dist/settings.js CHANGED
@@ -63,6 +63,8 @@ const DEFAULT_MEMORY_MAINTENANCE = {
63
63
  structuralMaintenanceIntervalHours: 6,
64
64
  maxConcurrentChannels: 1,
65
65
  failureBackoffMinutes: 30,
66
+ cleanupShrinkGuardMinRatio: 0.4,
67
+ cleanupShrinkGuardMinChars: 2_000,
66
68
  };
67
69
  /**
68
70
  * Settings manager for pipiclaw.
@@ -20,8 +20,8 @@ declare const subagentSchema: Type.TObject<{
20
20
  maxToolCalls: Type.TOptional<Type.TNumber>;
21
21
  maxWallTimeSec: Type.TOptional<Type.TNumber>;
22
22
  bashTimeoutSec: Type.TOptional<Type.TNumber>;
23
- contextMode: Type.TOptional<Type.TString>;
24
- memory: Type.TOptional<Type.TString>;
23
+ contextMode: Type.TOptional<Type.TUnion<[Type.TLiteral<"isolated">, Type.TLiteral<"contextual">]>>;
24
+ memory: Type.TOptional<Type.TUnion<[Type.TLiteral<"none">, Type.TLiteral<"session">, Type.TLiteral<"relevant">]>>;
25
25
  paths: Type.TOptional<Type.TArray<Type.TString>>;
26
26
  }>;
27
27
  export interface SubAgentToolDetails {
@@ -7,12 +7,7 @@ import { formatModelReference } from "../models/utils.js";
7
7
  import { DEFAULT_SECURITY_CONFIG } from "../security/config.js";
8
8
  import { splitH1Sections } from "../shared/markdown-sections.js";
9
9
  import { clipText, extractAssistantText, extractLabelFromArgs, HAN_REGEX } from "../shared/text-utils.js";
10
- import { createBashTool } from "../tools/bash.js";
11
- import { createEditTool } from "../tools/edit.js";
12
- import { createReadTool } from "../tools/read.js";
13
- import { createWebFetchTool } from "../tools/web-fetch.js";
14
- import { createWebSearchTool } from "../tools/web-search.js";
15
- import { createWriteTool } from "../tools/write.js";
10
+ import { buildToolSet } from "../tools/registry.js";
16
11
  import { formatSubAgentList, resolveSubAgentConfig, validateSubAgentTask, } from "./discovery.js";
17
12
  const subagentSchema = Type.Object({
18
13
  label: Type.String({ description: "Brief description of what this sub-agent task does (shown to user)" }),
@@ -28,10 +23,10 @@ const subagentSchema = Type.Object({
28
23
  maxToolCalls: Type.Optional(Type.Number({ description: "Optional maximum tool calls for this sub-agent" })),
29
24
  maxWallTimeSec: Type.Optional(Type.Number({ description: "Optional wall time budget in seconds for this sub-agent" })),
30
25
  bashTimeoutSec: Type.Optional(Type.Number({ description: "Optional default timeout in seconds for bash commands inside this sub-agent" })),
31
- contextMode: Type.Optional(Type.String({
32
- description: 'Optional context mode. Use "contextual" to inject selected session and memory context.',
26
+ contextMode: Type.Optional(Type.Union([Type.Literal("isolated"), Type.Literal("contextual")], {
27
+ description: 'Optional context mode. "isolated" (default) runs with no injected context; "contextual" injects selected session and memory context.',
33
28
  })),
34
- memory: Type.Optional(Type.String({
29
+ memory: Type.Optional(Type.Union([Type.Literal("none"), Type.Literal("session"), Type.Literal("relevant")], {
35
30
  description: 'Optional memory mode for contextual sub-agents: "none", "session", or "relevant".',
36
31
  })),
37
32
  paths: Type.Optional(Type.Array(Type.String(), {
@@ -88,55 +83,28 @@ function buildStoppedText(config, reason, finalText) {
88
83
  }
89
84
  return `[Sub-agent ${config.name} stopped: ${reason}]\n\n${trimmedFinalText}`;
90
85
  }
91
- function createToolSet(executor, bashTimeoutSec, options) {
86
+ /**
87
+ * Build a sub-agent's tool set from the shared tool registry, filtered to tools flagged
88
+ * available to sub-agents (files + web). Sub-agents run with their own security context
89
+ * (rooted at the sub-agent workspace) and their own per-invocation bash timeout.
90
+ */
91
+ function buildSubagentTools(executor, bashTimeoutSec, options) {
92
92
  const securityConfig = options.securityConfig ?? DEFAULT_SECURITY_CONFIG;
93
- const securityContext = {
93
+ return buildToolSet({
94
+ executor,
95
+ securityConfig,
96
+ securityContext: {
97
+ workspaceDir: options.workspaceDir,
98
+ workspacePath: options.runtimeContext.workspacePath,
99
+ cwd: process.cwd(),
100
+ },
101
+ channelId: options.runtimeContext.channelId,
102
+ channelDir: options.channelDir,
94
103
  workspaceDir: options.workspaceDir,
95
104
  workspacePath: options.runtimeContext.workspacePath,
96
- cwd: process.cwd(),
97
- };
98
- return [
99
- createReadTool(executor, {
100
- securityConfig,
101
- securityContext,
102
- channelId: options.runtimeContext.channelId,
103
- }),
104
- createBashTool(executor, {
105
- defaultTimeoutSeconds: bashTimeoutSec,
106
- securityConfig,
107
- securityContext,
108
- channelId: options.runtimeContext.channelId,
109
- }),
110
- createEditTool(executor, {
111
- securityConfig,
112
- securityContext,
113
- channelId: options.runtimeContext.channelId,
114
- }),
115
- createWriteTool(executor, {
116
- securityConfig,
117
- securityContext,
118
- channelId: options.runtimeContext.channelId,
119
- }),
120
- ];
121
- }
122
- function createNamedToolSet(executor, bashTimeoutSec, options) {
123
- const tools = createToolSet(executor, bashTimeoutSec, options);
124
- const byName = Object.fromEntries(tools.map((tool) => [tool.name, tool]));
125
- if (options.webConfig && options.webConfig.enable !== false) {
126
- byName.web_search = createWebSearchTool({
127
- webConfig: options.webConfig,
128
- securityConfig: options.securityConfig ?? DEFAULT_SECURITY_CONFIG,
129
- workspaceDir: options.workspaceDir,
130
- channelId: options.runtimeContext.channelId,
131
- });
132
- byName.web_fetch = createWebFetchTool({
133
- webConfig: options.webConfig,
134
- securityConfig: options.securityConfig ?? DEFAULT_SECURITY_CONFIG,
135
- workspaceDir: options.workspaceDir,
136
- channelId: options.runtimeContext.channelId,
137
- });
138
- }
139
- return byName;
105
+ webConfig: options.webConfig,
106
+ bashDefaultTimeoutSeconds: bashTimeoutSec,
107
+ }, { forSubagent: true });
140
108
  }
141
109
  function buildSubAgentTask(task, config, runtimeContext, contextBlocks) {
142
110
  const taskText = task.trim();
@@ -308,7 +276,7 @@ export function createSubAgentTool(options) {
308
276
  details: createDetails(config, usage, assistantTurns, toolCalls, Date.now() - startedAt, Boolean(failureReason), failureReason),
309
277
  });
310
278
  };
311
- const availableTools = Object.values(createNamedToolSet(options.executor, config.bashTimeoutSec, options));
279
+ const availableTools = buildSubagentTools(options.executor, config.bashTimeoutSec, options);
312
280
  const worker = options.createWorker?.({
313
281
  subAgent: config,
314
282
  apiKey,
@@ -2,10 +2,17 @@ import type { AgentTool } from "@earendil-works/pi-agent-core";
2
2
  import { Type } from "typebox";
3
3
  import type { Executor } from "../sandbox.js";
4
4
  import type { SecurityConfig, SecurityRuntimeContext } from "../security/types.js";
5
+ /**
6
+ * Default wall-clock timeout for bash commands when the caller supplies neither a
7
+ * per-call `timeout` nor a tool-level default. Without this, a hung command (a stray
8
+ * dev server, an interactive prompt) would block the channel's run queue until `/stop`.
9
+ * Callers that legitimately need longer must pass an explicit `timeout`.
10
+ */
11
+ export declare const DEFAULT_BASH_TIMEOUT_SECONDS = 300;
5
12
  declare const bashSchema: Type.TObject<{
6
13
  label: Type.TString;
7
14
  command: Type.TString;
8
- timeout: Type.TOptional<Type.TNumber>;
15
+ timeout: Type.TOptional<Type.TInteger>;
9
16
  }>;
10
17
  export interface BashToolOptions {
11
18
  defaultTimeoutSeconds?: number;