@oyasmi/pipiclaw 0.8.0 → 0.8.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 (100) hide show
  1. package/README.md +14 -0
  2. package/dist/agent/channel-runner.d.ts +1 -4
  3. package/dist/agent/channel-runner.js +18 -22
  4. package/dist/agent/job-manager.d.ts +5 -5
  5. package/dist/agent/prompt-builder.d.ts +3 -13
  6. package/dist/agent/prompt-builder.js +48 -204
  7. package/dist/agent/run-queue.js +2 -1
  8. package/dist/agent/runner-factory.d.ts +1 -2
  9. package/dist/agent/runner-factory.js +2 -2
  10. package/dist/agent/status-render.d.ts +0 -7
  11. package/dist/agent/status-render.js +8 -3
  12. package/dist/agent/workspace-resources.d.ts +1 -1
  13. package/dist/agent/workspace-resources.js +3 -15
  14. package/dist/executor.d.ts +20 -0
  15. package/dist/{sandbox.js → executor.js} +3 -95
  16. package/dist/index.d.ts +1 -1
  17. package/dist/index.js +1 -1
  18. package/dist/log.d.ts +1 -1
  19. package/dist/log.js +1 -2
  20. package/dist/memory/files.js +0 -0
  21. package/dist/memory/lifecycle.js +6 -5
  22. package/dist/memory/maintenance-jobs.d.ts +0 -1
  23. package/dist/memory/maintenance-jobs.js +2 -2
  24. package/dist/memory/maintenance-state.js +2 -1
  25. package/dist/memory/post-turn-review.d.ts +0 -1
  26. package/dist/memory/post-turn-review.js +4 -4
  27. package/dist/memory/scheduler.d.ts +0 -1
  28. package/dist/memory/scheduler.js +2 -2
  29. package/dist/memory/session.js +2 -2
  30. package/dist/paths.d.ts +2 -0
  31. package/dist/paths.js +11 -0
  32. package/dist/playbooks/catalog.d.ts +9 -0
  33. package/dist/playbooks/catalog.js +44 -0
  34. package/dist/playbooks/event-scheduling.md +43 -0
  35. package/dist/playbooks/memory-and-learning.md +45 -0
  36. package/dist/playbooks/runtime-orientation.md +48 -0
  37. package/dist/playbooks/task-closeout.md +45 -0
  38. package/dist/playbooks/task-delegation.md +44 -0
  39. package/dist/playbooks/task-driving.md +43 -0
  40. package/dist/playbooks/task-planning.md +47 -0
  41. package/dist/playbooks/task-recurring.md +42 -0
  42. package/dist/playbooks/task-repair.md +43 -0
  43. package/dist/runtime/bootstrap.d.ts +7 -11
  44. package/dist/runtime/bootstrap.js +24 -55
  45. package/dist/runtime/delivery.js +4 -3
  46. package/dist/runtime/dingtalk.js +15 -14
  47. package/dist/runtime/durable-dispatch.d.ts +2 -0
  48. package/dist/runtime/durable-dispatch.js +29 -1
  49. package/dist/runtime/event-commands.js +4 -4
  50. package/dist/runtime/events.d.ts +1 -1
  51. package/dist/runtime/events.js +5 -5
  52. package/dist/runtime/task-commands.js +9 -4
  53. package/dist/runtime/task-driver.js +12 -14
  54. package/dist/security/config.js +2 -1
  55. package/dist/security/network.js +9 -2
  56. package/dist/security/path-guard.js +12 -24
  57. package/dist/security/types.d.ts +0 -1
  58. package/dist/shared/jsonl-appender.js +2 -1
  59. package/dist/shared/task-ledger.d.ts +9 -1
  60. package/dist/shared/task-ledger.js +28 -14
  61. package/dist/shared/text-utils.d.ts +1 -0
  62. package/dist/shared/text-utils.js +3 -0
  63. package/dist/subagents/discovery.js +3 -2
  64. package/dist/subagents/tool.d.ts +2 -3
  65. package/dist/subagents/tool.js +9 -24
  66. package/dist/tasks/control.js +2 -1
  67. package/dist/tasks/verification.js +2 -1
  68. package/dist/tools/bash.d.ts +1 -1
  69. package/dist/tools/bash.js +3 -5
  70. package/dist/tools/command-optimizer.d.ts +1 -1
  71. package/dist/tools/command-optimizer.js +4 -6
  72. package/dist/tools/config.js +4 -3
  73. package/dist/tools/edit.d.ts +1 -1
  74. package/dist/tools/edit.js +0 -0
  75. package/dist/tools/event-manage.d.ts +0 -1
  76. package/dist/tools/event-manage.js +9 -14
  77. package/dist/tools/grep.d.ts +1 -1
  78. package/dist/tools/grep.js +4 -6
  79. package/dist/tools/index.d.ts +1 -3
  80. package/dist/tools/index.js +1 -4
  81. package/dist/tools/read.d.ts +1 -1
  82. package/dist/tools/read.js +1 -2
  83. package/dist/tools/registry.d.ts +1 -2
  84. package/dist/tools/registry.js +3 -10
  85. package/dist/tools/skill-manage.d.ts +0 -1
  86. package/dist/tools/skill-manage.js +7 -14
  87. package/dist/tools/task-manage.d.ts +0 -1
  88. package/dist/tools/task-manage.js +18 -16
  89. package/dist/tools/write-content.d.ts +1 -1
  90. package/dist/tools/write-content.js +0 -1
  91. package/dist/tools/write.d.ts +1 -1
  92. package/dist/tui/app.d.ts +0 -2
  93. package/dist/tui/app.js +12 -7
  94. package/dist/tui/cli.d.ts +0 -2
  95. package/dist/tui/cli.js +3 -25
  96. package/dist/tui/turn-controller.d.ts +7 -3
  97. package/dist/tui/turn-controller.js +9 -6
  98. package/dist/web/client.js +2 -1
  99. package/package.json +2 -2
  100. package/dist/sandbox.d.ts +0 -42
@@ -13,6 +13,7 @@ import { existsSync, mkdirSync, readFileSync, writeFileSync } from "fs";
13
13
  import { dirname, join } from "path";
14
14
  import { parseBuiltInCommand, renderBuiltInHelp } from "../agent/commands.js";
15
15
  import * as log from "../log.js";
16
+ import { errorMessage } from "../shared/text-utils.js";
16
17
  import { isRecord } from "../shared/type-guards.js";
17
18
  import { getChannelDir } from "./channel-paths.js";
18
19
  const RESPONSE_MODE_VALUES = [
@@ -81,7 +82,7 @@ class ChannelQueue {
81
82
  await work();
82
83
  }
83
84
  catch (err) {
84
- log.logWarning("Queue error", err instanceof Error ? err.message : String(err));
85
+ log.logWarning("Queue error", errorMessage(err));
85
86
  }
86
87
  this.processing = false;
87
88
  this.processNext();
@@ -302,7 +303,7 @@ export class DingTalkBot {
302
303
  socket.close?.();
303
304
  }
304
305
  catch (err) {
305
- log.logWarning(`DingTalk: socket close failed during ${reason}`, err instanceof Error ? err.message : String(err));
306
+ log.logWarning(`DingTalk: socket close failed during ${reason}`, errorMessage(err));
306
307
  }
307
308
  const closed = await this.waitForSocketState(socket, SOCKET_STATE_CLOSED, SOCKET_CLOSE_GRACE_MS);
308
309
  if (!closed) {
@@ -311,7 +312,7 @@ export class DingTalkBot {
311
312
  socket.terminate?.();
312
313
  }
313
314
  catch (err) {
314
- log.logWarning(`DingTalk: socket terminate failed during ${reason}`, err instanceof Error ? err.message : String(err));
315
+ log.logWarning(`DingTalk: socket terminate failed during ${reason}`, errorMessage(err));
315
316
  }
316
317
  await this.waitForSocketState(socket, SOCKET_STATE_CLOSED, SOCKET_TERMINATE_GRACE_MS);
317
318
  }
@@ -358,7 +359,7 @@ export class DingTalkBot {
358
359
  this.reconnectTimer = this.setTrackedTimeout(() => {
359
360
  this.reconnectTimer = null;
360
361
  this.doReconnect(immediate).catch((err) => {
361
- log.logWarning("DingTalk: reconnect failed", err instanceof Error ? err.message : String(err));
362
+ log.logWarning("DingTalk: reconnect failed", errorMessage(err));
362
363
  });
363
364
  }, delayMs);
364
365
  }
@@ -410,11 +411,11 @@ export class DingTalkBot {
410
411
  }
411
412
  // Fire-and-forget processing
412
413
  this.onStreamMessage(data).catch((err) => {
413
- log.logWarning("DingTalk handler error", err instanceof Error ? err.message : String(err));
414
+ log.logWarning("DingTalk handler error", errorMessage(err));
414
415
  });
415
416
  }
416
417
  catch (err) {
417
- log.logWarning("DingTalk: failed to parse message", err instanceof Error ? err.message : String(err));
418
+ log.logWarning("DingTalk: failed to parse message", errorMessage(err));
418
419
  }
419
420
  return { status: "SUCCESS", message: "OK" };
420
421
  }
@@ -508,7 +509,7 @@ export class DingTalkBot {
508
509
  await this.cleanupSocket("reconnect failure");
509
510
  this.reconnectAttempts++;
510
511
  connectionFailed = true;
511
- log.logWarning("DingTalk: connection failed", err instanceof Error ? err.message : String(err));
512
+ log.logWarning("DingTalk: connection failed", errorMessage(err));
512
513
  }
513
514
  finally {
514
515
  this.isReconnecting = false;
@@ -531,7 +532,7 @@ export class DingTalkBot {
531
532
  await this.cleanupSocket("stop");
532
533
  }
533
534
  catch (err) {
534
- log.logWarning("DingTalk: failed to disconnect cleanly", err instanceof Error ? err.message : String(err));
535
+ log.logWarning("DingTalk: failed to disconnect cleanly", errorMessage(err));
535
536
  }
536
537
  finally {
537
538
  this.client = null;
@@ -725,7 +726,7 @@ export class DingTalkBot {
725
726
  log.logWarning(`DingTalk plain send failed (${err.response.status})`, JSON.stringify(err.response.data));
726
727
  }
727
728
  else {
728
- log.logWarning("DingTalk plain send error", err instanceof Error ? err.message : String(err));
729
+ log.logWarning("DingTalk plain send error", errorMessage(err));
729
730
  }
730
731
  return false;
731
732
  }
@@ -805,7 +806,7 @@ export class DingTalkBot {
805
806
  log.logWarning(`DingTalk Card: create failed (${err.response.status})`, JSON.stringify(err.response.data));
806
807
  }
807
808
  else {
808
- log.logWarning("DingTalk Card: create failed", err instanceof Error ? err.message : String(err));
809
+ log.logWarning("DingTalk Card: create failed", errorMessage(err));
809
810
  }
810
811
  return null;
811
812
  }
@@ -867,7 +868,7 @@ export class DingTalkBot {
867
868
  log.logWarning(`DingTalk Card: streaming failed (${err.response.status})`, JSON.stringify(err.response.data));
868
869
  }
869
870
  else {
870
- log.logWarning("DingTalk Card: streaming failed", err instanceof Error ? err.message : String(err));
871
+ log.logWarning("DingTalk Card: streaming failed", errorMessage(err));
871
872
  }
872
873
  return false;
873
874
  }
@@ -905,7 +906,7 @@ export class DingTalkBot {
905
906
  log.logWarning(`DingTalk: failed to get access token (${err.response.status})`, JSON.stringify(err.response.data));
906
907
  }
907
908
  else {
908
- log.logWarning("DingTalk: failed to get access token", err instanceof Error ? err.message : String(err));
909
+ log.logWarning("DingTalk: failed to get access token", errorMessage(err));
909
910
  }
910
911
  return null;
911
912
  }
@@ -1069,7 +1070,7 @@ export class DingTalkBot {
1069
1070
  return meta;
1070
1071
  }
1071
1072
  catch (err) {
1072
- log.logWarning(`Failed to load conversation metadata for ${channelId}`, err instanceof Error ? err.message : String(err));
1073
+ log.logWarning(`Failed to load conversation metadata for ${channelId}`, errorMessage(err));
1073
1074
  return null;
1074
1075
  }
1075
1076
  }
@@ -1083,7 +1084,7 @@ export class DingTalkBot {
1083
1084
  writeFileSync(metaPath, JSON.stringify(meta, null, 2), "utf-8");
1084
1085
  }
1085
1086
  catch (err) {
1086
- log.logWarning(`Failed to persist conversation metadata for ${channelId}`, err instanceof Error ? err.message : String(err));
1087
+ log.logWarning(`Failed to persist conversation metadata for ${channelId}`, errorMessage(err));
1087
1088
  }
1088
1089
  }
1089
1090
  getConversationMetaPath(channelId) {
@@ -20,6 +20,8 @@ export declare class DurableDispatchService {
20
20
  start(): void;
21
21
  stop(): void;
22
22
  dispatch(event: DingTalkEvent): Promise<boolean>;
23
+ /** Reset any in-flight records for a channel so a stop/abort can redeliver on the next tick, not after the lease expires. */
24
+ cancelChannel(channelId: string): Promise<number>;
23
25
  markStarted(id: string | undefined): Promise<void>;
24
26
  markCompleted(id: string | undefined): Promise<void>;
25
27
  drainOnce(now?: number): Promise<void>;
@@ -79,7 +79,35 @@ export class DurableDispatchService {
79
79
  await this.write(record);
80
80
  });
81
81
  await this.drainOnce();
82
- return true;
82
+ // The record is gone (delivered+completed already) or no longer "pending"
83
+ // (drainOnce only reverts to "pending" when bot.enqueueEvent rejected it).
84
+ const after = await this.read(id);
85
+ return after?.status !== "pending";
86
+ }
87
+ /** Reset any in-flight records for a channel so a stop/abort can redeliver on the next tick, not after the lease expires. */
88
+ async cancelChannel(channelId) {
89
+ let filenames;
90
+ try {
91
+ filenames = (await readdir(this.options.stateDir)).filter((name) => name.endsWith(".json"));
92
+ }
93
+ catch {
94
+ return 0;
95
+ }
96
+ let canceled = 0;
97
+ for (const filename of filenames) {
98
+ const id = filename.slice(0, -".json".length);
99
+ await this.queue.run(id, async () => {
100
+ const record = await this.read(id);
101
+ if (!record || record.event.channelId !== channelId)
102
+ return;
103
+ if (record.status !== "queued" && record.status !== "running")
104
+ return;
105
+ record.leaseExpiresAt = undefined;
106
+ await this.write(record);
107
+ canceled++;
108
+ });
109
+ }
110
+ return canceled;
83
111
  }
84
112
  async markStarted(id) {
85
113
  if (!id)
@@ -1,7 +1,7 @@
1
1
  import { existsSync } from "fs";
2
2
  import { readdir, readFile, unlink } from "fs/promises";
3
3
  import { join, resolve, sep } from "path";
4
- import { eventNameFromFilename } from "../shared/text-utils.js";
4
+ import { errorMessage, eventNameFromFilename } from "../shared/text-utils.js";
5
5
  import { parseScheduledEventContent } from "./events.js";
6
6
  const EVENT_NAME_PATTERN = /^[A-Za-z0-9._-]+$/;
7
7
  const DEFAULT_HISTORY_LIMIT = 20;
@@ -95,7 +95,7 @@ async function listEvents(workspaceDir) {
95
95
  blocks.push(formatEventSummary(name, event));
96
96
  }
97
97
  catch (error) {
98
- const message = error instanceof Error ? error.message : String(error);
98
+ const message = errorMessage(error);
99
99
  blocks.push(`- ${name}\n invalid: ${message}`);
100
100
  }
101
101
  }
@@ -182,7 +182,7 @@ export async function handleEventsCommand(options) {
182
182
  command = parseEventsCommand(options.args);
183
183
  }
184
184
  catch (error) {
185
- const message = error instanceof Error ? error.message : String(error);
185
+ const message = errorMessage(error);
186
186
  return `${message}\n\n${usage()}`;
187
187
  }
188
188
  try {
@@ -198,7 +198,7 @@ export async function handleEventsCommand(options) {
198
198
  }
199
199
  }
200
200
  catch (error) {
201
- const message = error instanceof Error ? error.message : String(error);
201
+ const message = errorMessage(error);
202
202
  return `Could not ${command.action} events: ${message}`;
203
203
  }
204
204
  }
@@ -1,4 +1,4 @@
1
- import type { Executor } from "../sandbox.js";
1
+ import type { Executor } from "../executor.js";
2
2
  import type { SecurityConfig } from "../security/types.js";
3
3
  import type { DingTalkBot, DingTalkEvent } from "./dingtalk.js";
4
4
  export interface EventAction {
@@ -4,7 +4,7 @@ import { readFile } from "fs/promises";
4
4
  import { dirname, join, resolve } from "path";
5
5
  import * as log from "../log.js";
6
6
  import { guardCommand } from "../security/command-guard.js";
7
- import { eventNameFromFilename } from "../shared/text-utils.js";
7
+ import { errorMessage, eventNameFromFilename } from "../shared/text-utils.js";
8
8
  // ============================================================================
9
9
  // EventsWatcher
10
10
  // ============================================================================
@@ -387,7 +387,7 @@ export class EventsWatcher {
387
387
  catch (err) {
388
388
  log.logWarning(`One-shot event execution failed: ${filename}`, String(err));
389
389
  this.appendEventHistory(filename, event, "skipped", "error", {
390
- reason: err instanceof Error ? err.message : String(err),
390
+ reason: errorMessage(err),
391
391
  });
392
392
  }
393
393
  }, delay);
@@ -404,7 +404,7 @@ export class EventsWatcher {
404
404
  catch (err) {
405
405
  log.logWarning(`Periodic event execution failed: ${filename}`, String(err));
406
406
  this.appendEventHistory(filename, event, "skipped", "error", {
407
- reason: err instanceof Error ? err.message : String(err),
407
+ reason: errorMessage(err),
408
408
  });
409
409
  }
410
410
  });
@@ -443,7 +443,7 @@ export class EventsWatcher {
443
443
  });
444
444
  }
445
445
  catch (err) {
446
- const reason = err instanceof Error ? err.message : String(err);
446
+ const reason = errorMessage(err);
447
447
  log.logInfo(`Pre-action gate blocked event: ${filename} (${reason})`);
448
448
  const actionResult = err instanceof EventPreActionError ? err : undefined;
449
449
  this.appendEventHistory(filename, event, actionResult?.kind === "failed" ? "pre_action_failed" : "pre_action_blocked", actionResult?.kind === "failed" ? "error" : "skipped", {
@@ -524,7 +524,7 @@ export class EventsWatcher {
524
524
  result = await this.executor.exec(action.command, { timeout: timeoutSeconds });
525
525
  }
526
526
  catch (err) {
527
- throw new EventPreActionError("failed", err instanceof Error ? err.message : String(err), {
527
+ throw new EventPreActionError("failed", errorMessage(err), {
528
528
  durationMs: Date.now() - startedAt,
529
529
  });
530
530
  }
@@ -3,8 +3,9 @@ import { readdir, readFile } from "node:fs/promises";
3
3
  import { join, resolve, sep } from "node:path";
4
4
  import { isTaskCheckinEvent, isTaskScheduleEvent, parseTaskEventName, taskEventPrefix, taskScheduleEventName, } from "../shared/task-events.js";
5
5
  import { extractTaskTitle, missingStandardTaskSections, normalizeTaskId, readActiveTasks, } from "../shared/task-ledger.js";
6
+ import { errorMessage } from "../shared/text-utils.js";
6
7
  import { taskBudgetViolation } from "../tasks/control.js";
7
- import { readStoredTask, taskBodyHash, writeStoredTask } from "../tasks/store.js";
8
+ import { claimTaskAttempt, readStoredTask, releaseTaskAttemptClaim, taskBodyHash, writeStoredTask, } from "../tasks/store.js";
8
9
  import { parseScheduledEventContent } from "./events.js";
9
10
  function usage() {
10
11
  return `# Tasks
@@ -125,7 +126,7 @@ async function readTaskEvents(workspaceDir, channelId) {
125
126
  info.event = parseScheduledEventContent(await readFile(join(dir, filename), "utf-8"), filename);
126
127
  }
127
128
  catch (error) {
128
- info.error = error instanceof Error ? error.message : String(error);
129
+ info.error = errorMessage(error);
129
130
  }
130
131
  events.push(info);
131
132
  }
@@ -297,7 +298,11 @@ async function runTask(options, idInput) {
297
298
  task.fields.control.blockedReason = undefined;
298
299
  }
299
300
  await writeStoredTask(task);
301
+ const now = new Date();
302
+ const claim = task.fields.control ? await claimTaskAttempt(options.channelDir, id, now) : undefined;
300
303
  const enqueued = await options.dispatchTask?.(id);
304
+ if (!enqueued && claim)
305
+ await releaseTaskAttemptClaim(options.channelDir, id, claim, now);
301
306
  return enqueued
302
307
  ? `Enqueued task ${id} for an immediate attempt.`
303
308
  : `Task ${id} is ready. Start or use the DingTalk daemon for automatic dispatch, or send a normal prompt in this session to advance it.`;
@@ -528,7 +533,7 @@ export async function handleTasksCommand(options) {
528
533
  command = parseTasksCommand(options.args);
529
534
  }
530
535
  catch (error) {
531
- const message = error instanceof Error ? error.message : String(error);
536
+ const message = errorMessage(error);
532
537
  return `${message}\n\n${usage()}`;
533
538
  }
534
539
  try {
@@ -554,7 +559,7 @@ export async function handleTasksCommand(options) {
554
559
  }
555
560
  }
556
561
  catch (error) {
557
- const message = error instanceof Error ? error.message : String(error);
562
+ const message = errorMessage(error);
558
563
  return `Could not ${command.action} tasks: ${message}`;
559
564
  }
560
565
  }
@@ -1,8 +1,10 @@
1
1
  import { readdir, readFile } from "node:fs/promises";
2
2
  import { join } from "node:path";
3
3
  import * as log from "../log.js";
4
+ import { PLAYBOOKS_DIR } from "../paths.js";
4
5
  import { taskEventName } from "../shared/task-events.js";
5
6
  import { readActiveTasks } from "../shared/task-ledger.js";
7
+ import { errorMessage } from "../shared/text-utils.js";
6
8
  import { taskBudgetViolation } from "../tasks/control.js";
7
9
  import { claimTaskAttempt, dependencyState, escalateTask, releaseTaskAttemptClaim } from "../tasks/store.js";
8
10
  import { parseScheduledEventContent } from "./events.js";
@@ -75,12 +77,12 @@ export function createTaskDriverEvent(channelId, entry, nowMs) {
75
77
  const verification = entry.frontmatter.control?.verification;
76
78
  const verificationInstruction = entry.frontmatter.status === "verifying"
77
79
  ? verification?.status === "passed"
78
- ? " Independent verification already passed for the current artifact; finish the task with task_manage done and specific evidence."
79
- : " This task is a verification candidate: call subagent with purpose=verify and taskId, then import its runId with task_manage verify. Do not implement more changes before the verifier reports."
80
+ ? " Independent verification already passed; preserve its body/artifact hashes and follow the closeout playbook."
81
+ : " This is a checker-only turn: read the closeout playbook and do not continue implementation."
80
82
  : "";
81
83
  const repair = entry.frontmatter.readable
82
84
  ? ""
83
- : " Its frontmatter is unreadable: repair it before using task_manage, and do not silently skip the task.";
85
+ : ` Its frontmatter is unreadable: also read ${join(PLAYBOOKS_DIR, "task-repair.md")}.`;
84
86
  const control = entry.frontmatter.control;
85
87
  const capsule = [
86
88
  `Task capsule: title=${entry.title}; status=${entry.frontmatter.status ?? "open"};`,
@@ -95,14 +97,10 @@ export function createTaskDriverEvent(channelId, entry, nowMs) {
95
97
  channelId,
96
98
  user: "TASK_DRIVER",
97
99
  userName: "TASK_DRIVER",
98
- text: `[TASK_DRIVER:${entry.id}] Resume task ${entry.id}. ${capsule}${repair} Open tasks/${entry.id}.md, advance the next ` +
99
- "concrete step, respect its control metadata (budget, dependencies, isolation, and side-effect approval), and " +
100
- "verify the work against its DoD. If it remains open, atomically record what changed, the " +
101
- "next step, status, and any future wake with task_manage progress (or carefully update the task file if that " +
102
- "tool is unavailable). For independent verification, delegate a purpose=verify subagent and register its run " +
103
- "with task_manage verify before task_manage done. Never perform external side effects unless approval is granted. " +
104
- "If complete, use task_manage done with specific evidence. If no user-visible update " +
105
- `is needed, respond with [SILENT].${verificationInstruction}`,
100
+ text: `[TASK_DRIVER:${entry.id}] Resume task ${entry.id}. ${capsule}${repair} ` +
101
+ `Open tasks/${entry.id}.md and read ${join(PLAYBOOKS_DIR, "task-driving.md")} before acting. ` +
102
+ "Advance the next concrete step under the task's current control, acceptance, approval, and verification state. " +
103
+ `If complete or waiting, use the matching task_manage lifecycle/checkpoint action from the playbook.${verificationInstruction}`,
106
104
  ts: String(nowMs),
107
105
  conversationId: "",
108
106
  conversationType: channelId.startsWith("group_") ? "2" : "1",
@@ -115,8 +113,8 @@ function taskEscalationEvent(channelId, entry, reason, nowMs) {
115
113
  user: "TASK_DRIVER",
116
114
  userName: "TASK_DRIVER",
117
115
  text: `[TASK_ESCALATION:${entry.id}] Task ${entry.id} (${entry.title}) was stopped by the deterministic task ` +
118
- `governor: ${reason}. Inform the user concisely, explain the actionable recovery (adjust the task control ` +
119
- "metadata, resolve the dependency, or explicitly cancel/reopen it), and do not continue the task in this run.",
116
+ `governor: ${reason}. Read ${join(PLAYBOOKS_DIR, "task-repair.md")}, diagnose before changing control, ` +
117
+ "inform the user of the cause and recovery, and do not continue implementation in this run.",
120
118
  ts: String(nowMs),
121
119
  conversationId: "",
122
120
  conversationType: channelId.startsWith("group_") ? "2" : "1",
@@ -151,7 +149,7 @@ export class TaskDriver {
151
149
  return;
152
150
  this.timer = setInterval(() => {
153
151
  void this.runOnce().catch((error) => {
154
- log.logWarning("Task driver tick failed", error instanceof Error ? error.message : String(error));
152
+ log.logWarning("Task driver tick failed", errorMessage(error));
155
153
  });
156
154
  }, this.options.intervalMs ?? DEFAULT_SCAN_INTERVAL_MS);
157
155
  this.timer.unref?.();
@@ -1,6 +1,7 @@
1
1
  import { existsSync, readFileSync } from "node:fs";
2
2
  import { join } from "node:path";
3
3
  import { APP_HOME_DIR } from "../paths.js";
4
+ import { errorMessage } from "../shared/text-utils.js";
4
5
  import { isRecord } from "../shared/type-guards.js";
5
6
  export const DEFAULT_SECURITY_CONFIG = {
6
7
  enabled: true,
@@ -122,7 +123,7 @@ export function loadSecurityConfigWithDiagnostics(appHomeDir = APP_HOME_DIR) {
122
123
  source: "security",
123
124
  path: configPath,
124
125
  severity: "error",
125
- message: error instanceof Error ? error.message : String(error),
126
+ message: errorMessage(error),
126
127
  },
127
128
  ],
128
129
  };
@@ -1,5 +1,6 @@
1
1
  import { lookup } from "node:dns/promises";
2
2
  import { isIP } from "node:net";
3
+ import { errorMessage } from "../shared/text-utils.js";
3
4
  export class NetworkGuardError extends Error {
4
5
  constructor(options) {
5
6
  super(options.message);
@@ -24,7 +25,13 @@ const PRIVATE_IPV4_CIDRS = [
24
25
  ];
25
26
  const PRIVATE_IPV6_CIDRS = ["::1/128", "::/128", "fc00::/7", "fe80::/10"];
26
27
  function normalizeHost(host) {
27
- return host.trim().replace(/\.$/, "").toLowerCase();
28
+ // WHATWG URL.hostname keeps the brackets on an IPv6 literal (e.g. "[::1]"),
29
+ // but isIP()/DNS resolution both expect the bare address — without stripping
30
+ // them, every IPv6 literal URL (public or private) falls through to a DNS
31
+ // lookup of the literal bracketed string, which fails and rejects the
32
+ // request regardless of whether the address was actually private.
33
+ const unbracketed = host.startsWith("[") && host.endsWith("]") ? host.slice(1, -1) : host;
34
+ return unbracketed.trim().replace(/\.$/, "").toLowerCase();
28
35
  }
29
36
  function parseIpv4(ip) {
30
37
  const parts = ip.split(".");
@@ -208,7 +215,7 @@ async function validateUrlTarget(rawUrl, context, stage) {
208
215
  url: rawUrl,
209
216
  stage,
210
217
  category: "dns-failure",
211
- message: `Failed to resolve host ${hostname}: ${error instanceof Error ? error.message : String(error)}`,
218
+ message: `Failed to resolve host ${hostname}: ${errorMessage(error)}`,
212
219
  resolvedHost: hostname,
213
220
  });
214
221
  }
@@ -1,6 +1,7 @@
1
1
  import { existsSync, lstatSync, realpathSync } from "node:fs";
2
2
  import { homedir, tmpdir } from "node:os";
3
3
  import { basename, dirname, isAbsolute, normalize, resolve } from "node:path";
4
+ import { PLAYBOOKS_DIR } from "../paths.js";
4
5
  const PRIVATE_KEY_EXTENSIONS = new Set([".pem", ".key", ".p12", ".pfx"]);
5
6
  const PRIVATE_KEY_NAME_HINTS = /(id_rsa|id_ed25519|private|secret|credentials)/i;
6
7
  const PROC_MEM_PATH = /^\/proc\/\d+\/mem(?:\/|$)/;
@@ -63,41 +64,24 @@ function maybeExpandHome(path, homeDir) {
63
64
  function resolveHomeConfiguredPath(rawPath, homeDir) {
64
65
  return normalize(maybeExpandHome(stripNullAndNormalize(rawPath), homeDir));
65
66
  }
66
- function translateRuntimeWorkspacePath(path, ctx) {
67
- if (!isAbsolute(path)) {
68
- return path;
69
- }
70
- if (!ctx.workspacePath || ctx.workspacePath === ctx.workspaceDir) {
71
- return path;
72
- }
73
- if (path === ctx.workspacePath) {
74
- return ctx.workspaceDir;
75
- }
76
- if (path.startsWith(withTrailingSlash(ctx.workspacePath))) {
77
- return resolve(ctx.workspaceDir, path.slice(ctx.workspacePath.length + 1));
78
- }
79
- return path;
80
- }
81
67
  function resolveConfiguredPath(rawPath, ctx) {
82
68
  const homeDir = ctx.homeDir ?? homedir();
83
69
  const normalized = stripNullAndNormalize(rawPath);
84
70
  const expanded = maybeExpandHome(normalized, homeDir);
85
- const translated = translateRuntimeWorkspacePath(expanded, ctx);
86
- if (isAbsolute(translated)) {
87
- return normalize(translated);
71
+ if (isAbsolute(expanded)) {
72
+ return normalize(expanded);
88
73
  }
89
- return resolve(ctx.workspaceDir, translated);
74
+ return resolve(ctx.workspaceDir, expanded);
90
75
  }
91
76
  function resolveTargetPath(rawPath, ctx) {
92
77
  const homeDir = ctx.homeDir ?? homedir();
93
78
  const cwd = ctx.cwd ?? process.cwd();
94
79
  const normalized = stripNullAndNormalize(rawPath);
95
80
  const expanded = maybeExpandHome(normalized, homeDir);
96
- const translated = translateRuntimeWorkspacePath(expanded, ctx);
97
- if (isAbsolute(translated)) {
98
- return normalize(translated);
81
+ if (isAbsolute(expanded)) {
82
+ return normalize(expanded);
99
83
  }
100
- return resolve(cwd, translated);
84
+ return resolve(cwd, expanded);
101
85
  }
102
86
  function resolveExistingAncestor(path) {
103
87
  let current = normalize(path);
@@ -183,6 +167,10 @@ function pathAllowedByDefaults(path, ctx) {
183
167
  const homeDir = ctx.homeDir ?? homedir();
184
168
  return isWithinWorkspace(path, ctx.workspaceDir) || isWithinTemp(path) || isWithinHome(path, homeDir);
185
169
  }
170
+ /** The runtime's own bundled playbooks are readable regardless of where the package is installed. */
171
+ function isBundledPlaybookRead(path, operation) {
172
+ return operation === "read" && startsWithPathPrefix(path, normalize(PLAYBOOKS_DIR));
173
+ }
186
174
  function formatBlockedResult(operation, rawPath, resolvedPath, category, reason) {
187
175
  return {
188
176
  allowed: false,
@@ -227,7 +215,7 @@ export function guardPath(rawPath, operation, ctx) {
227
215
  if (matchesConfiguredPath(guardedPath, operation === "read" ? effectiveCtx.config.readAllow : effectiveCtx.config.writeAllow, effectiveCtx)) {
228
216
  return { allowed: true, operation, rawPath, resolvedPath: guardedPath };
229
217
  }
230
- if (pathAllowedByDefaults(guardedPath, effectiveCtx)) {
218
+ if (pathAllowedByDefaults(guardedPath, effectiveCtx) || isBundledPlaybookRead(guardedPath, operation)) {
231
219
  return { allowed: true, operation, rawPath, resolvedPath: guardedPath };
232
220
  }
233
221
  if (isDeniedSystemPath(guardedPath)) {
@@ -27,7 +27,6 @@ export interface SecurityConfig {
27
27
  }
28
28
  export interface SecurityRuntimeContext {
29
29
  workspaceDir: string;
30
- workspacePath: string;
31
30
  cwd?: string;
32
31
  homeDir?: string;
33
32
  }
@@ -2,6 +2,7 @@ import { existsSync, mkdirSync, renameSync, statSync } from "node:fs";
2
2
  import { appendFile } from "node:fs/promises";
3
3
  import { dirname } from "node:path";
4
4
  import { createSerialQueue } from "./serial-queue.js";
5
+ import { errorMessage } from "./text-utils.js";
5
6
  /**
6
7
  * Append-only JSONL writer shared by the runtime log and the usage ledger.
7
8
  *
@@ -77,7 +78,7 @@ export function createJsonlAppender(options) {
77
78
  catch (error) {
78
79
  if (!warned) {
79
80
  warned = true;
80
- console.warn(`[jsonl-appender] Failed to append to ${filePath}: ${error instanceof Error ? error.message : String(error)}`);
81
+ console.warn(`[jsonl-appender] Failed to append to ${filePath}: ${errorMessage(error)}`);
81
82
  }
82
83
  }
83
84
  },
@@ -76,7 +76,15 @@ export declare function isTaskActionable(frontmatter: TaskFrontmatter, now: numb
76
76
  export declare function extractTaskTitle(content: string, fallbackId: string): string;
77
77
  export declare function hasTaskHeading(content: string, names: readonly string[]): boolean;
78
78
  export declare function missingStandardTaskSections(content: string): string[];
79
- /** Unchecked Markdown acceptance boxes under DoD or Verification sections. */
79
+ /**
80
+ * Unchecked Markdown acceptance boxes under the DoD section, plus a synthetic
81
+ * entry when DoD has content but no checkbox syntax at all.
82
+ *
83
+ * Without the "no checklist items" case, a DoD written as prose or a numbered
84
+ * list (no `- [ ]` anywhere) makes this function return an empty array —
85
+ * indistinguishable from "everything is checked" — which would silently let
86
+ * `task_manage candidate`/`done` through with nothing ever actually verified.
87
+ */
80
88
  export declare function uncheckedTaskAcceptanceItems(content: string): string[];
81
89
  export declare function renderStandardTaskBody(input: TaskSkeletonInput): string;
82
90
  export interface TaskDocumentFields {
@@ -84,11 +84,9 @@ export function isTaskActionable(frontmatter, now) {
84
84
  frontmatter.status === "paused") {
85
85
  return false;
86
86
  }
87
- if (frontmatter.wake) {
88
- const wakeAt = new Date(frontmatter.wake).getTime();
89
- if (Number.isFinite(wakeAt) && wakeAt > now)
90
- return false;
91
- }
87
+ const wakeAt = parseWakeMs(frontmatter);
88
+ if (wakeAt !== undefined && wakeAt > now)
89
+ return false;
92
90
  return true;
93
91
  }
94
92
  /** First `# ` heading after the frontmatter block, or the id when there is none. */
@@ -119,11 +117,21 @@ export function hasTaskHeading(content, names) {
119
117
  export function missingStandardTaskSections(content) {
120
118
  return STANDARD_TASK_SECTIONS.filter((section) => !hasTaskHeading(content, section.names)).map((section) => section.label);
121
119
  }
122
- /** Unchecked Markdown acceptance boxes under DoD or Verification sections. */
120
+ /**
121
+ * Unchecked Markdown acceptance boxes under the DoD section, plus a synthetic
122
+ * entry when DoD has content but no checkbox syntax at all.
123
+ *
124
+ * Without the "no checklist items" case, a DoD written as prose or a numbered
125
+ * list (no `- [ ]` anywhere) makes this function return an empty array —
126
+ * indistinguishable from "everything is checked" — which would silently let
127
+ * `task_manage candidate`/`done` through with nothing ever actually verified.
128
+ */
123
129
  export function uncheckedTaskAcceptanceItems(content) {
124
130
  const unchecked = [];
125
131
  let section;
126
132
  let sectionLevel = 0;
133
+ let dodHasContent = false;
134
+ let dodHasCheckbox = false;
127
135
  for (const line of content.split("\n")) {
128
136
  const heading = /^(#{1,6})\s+(.+?)\s*$/.exec(line);
129
137
  if (heading) {
@@ -143,9 +151,18 @@ export function uncheckedTaskAcceptanceItems(content) {
143
151
  }
144
152
  if (!section)
145
153
  continue;
146
- const item = /^\s*[-*]\s+\[\s\]\s*(.+?)\s*$/.exec(line)?.[1];
147
- if (item)
148
- unchecked.push(`${section}: ${item}`);
154
+ if (section === "DoD" && line.trim())
155
+ dodHasContent = true;
156
+ const checkbox = /^\s*[-*]\s+\[([ xX])\]\s*(.+?)\s*$/.exec(line);
157
+ if (checkbox) {
158
+ if (section === "DoD")
159
+ dodHasCheckbox = true;
160
+ if (checkbox[1] === " ")
161
+ unchecked.push(`${section}: ${checkbox[2]}`);
162
+ }
163
+ }
164
+ if (dodHasContent && !dodHasCheckbox) {
165
+ unchecked.push('DoD has no checklist items — rewrite it as "- [ ] ..." acceptance items before requesting verification or done.');
149
166
  }
150
167
  return unchecked;
151
168
  }
@@ -235,7 +252,6 @@ export function startTaskCycle(content, cycleId) {
235
252
  let currentStart = -1;
236
253
  let currentLevel = 0;
237
254
  let historyStart = -1;
238
- let historyLevel = 0;
239
255
  for (let index = 0; index < lines.length; index++) {
240
256
  const match = /^(#{1,6})\s+(.+?)\s*$/.exec(lines[index] ?? "");
241
257
  if (!match)
@@ -247,7 +263,6 @@ export function startTaskCycle(content, cycleId) {
247
263
  }
248
264
  if (matchesTaskSectionTitle(match[2] ?? "", ["History", "历史"])) {
249
265
  historyStart = index;
250
- historyLevel = level;
251
266
  break;
252
267
  }
253
268
  }
@@ -280,7 +295,6 @@ export function startTaskCycle(content, cycleId) {
280
295
  ];
281
296
  // A nested history heading would be unusual; inserting directly after the
282
297
  // canonical History heading remains predictable and preserves all older notes.
283
- void historyLevel;
284
298
  lines.splice(shiftedHistoryStart + 1, 0, ...historyEntry);
285
299
  return lines.join("\n");
286
300
  }
@@ -309,7 +323,7 @@ function extractLatestNote(content) {
309
323
  }
310
324
  return latest;
311
325
  }
312
- function wakeMsOf(frontmatter) {
326
+ function parseWakeMs(frontmatter) {
313
327
  if (!frontmatter.wake)
314
328
  return undefined;
315
329
  const at = new Date(frontmatter.wake).getTime();
@@ -346,7 +360,7 @@ function toEntry(id, content, now) {
346
360
  title: extractTaskTitle(content, id),
347
361
  frontmatter,
348
362
  actionable: isTaskActionable(frontmatter, now),
349
- wakeMs: wakeMsOf(frontmatter),
363
+ wakeMs: parseWakeMs(frontmatter),
350
364
  latestNote: extractLatestNote(content),
351
365
  };
352
366
  }