@oyasmi/pipiclaw 0.9.3 → 0.9.4-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 (113) hide show
  1. package/dist/agent/channel-runner.js +137 -61
  2. package/dist/agent/command-extension.js +47 -34
  3. package/dist/agent/job-manager.js +31 -11
  4. package/dist/agent/model-fallback.js +1 -1
  5. package/dist/agent/prompt/manifest.d.ts +6 -1
  6. package/dist/agent/prompt/manifest.js +45 -64
  7. package/dist/agent/prompt/resources.js +4 -1
  8. package/dist/agent/run-queue.js +7 -2
  9. package/dist/agent/session-adapter.js +1 -1
  10. package/dist/agent/session-events.js +17 -6
  11. package/dist/agent/session-resource-gate.js +3 -1
  12. package/dist/agent/status-render.d.ts +0 -1
  13. package/dist/agent/status-render.js +4 -16
  14. package/dist/agent/turn-error.d.ts +31 -0
  15. package/dist/agent/turn-error.js +68 -0
  16. package/dist/app-services.js +7 -4
  17. package/dist/channel/channel-index.js +4 -1
  18. package/dist/channel/project-scope-store.js +1 -1
  19. package/dist/commands/catalog.d.ts +21 -4
  20. package/dist/commands/catalog.js +88 -41
  21. package/dist/commands/reply-limits.d.ts +6 -0
  22. package/dist/commands/reply-limits.js +24 -0
  23. package/dist/events/event-commands.js +94 -44
  24. package/dist/events/event-validation.d.ts +13 -2
  25. package/dist/events/event-validation.js +17 -9
  26. package/dist/events/events.js +77 -32
  27. package/dist/executor.js +2 -2
  28. package/dist/log.d.ts +12 -2
  29. package/dist/log.js +26 -34
  30. package/dist/main.js +1 -1
  31. package/dist/memory/commands.js +29 -23
  32. package/dist/memory/lifecycle.js +26 -5
  33. package/dist/memory/maintenance-state.js +4 -1
  34. package/dist/memory/scheduler.js +3 -1
  35. package/dist/models/auth-cli.js +3 -2
  36. package/dist/paths.d.ts +2 -0
  37. package/dist/paths.js +9 -0
  38. package/dist/playbooks/agent-delegation.md +2 -2
  39. package/dist/runtime/app-home.d.ts +6 -0
  40. package/dist/runtime/app-home.js +21 -3
  41. package/dist/runtime/bootstrap.js +189 -60
  42. package/dist/runtime/channel-queue.js +1 -1
  43. package/dist/runtime/delivery.js +29 -15
  44. package/dist/runtime/dingtalk.js +96 -42
  45. package/dist/runtime/durable-dispatch.d.ts +27 -1
  46. package/dist/runtime/durable-dispatch.js +111 -3
  47. package/dist/runtime/project-commands.js +16 -15
  48. package/dist/runtime/proxy.js +4 -2
  49. package/dist/runtime/report-commands.js +1 -1
  50. package/dist/runtime/skill-commands.d.ts +1 -1
  51. package/dist/runtime/skill-commands.js +17 -10
  52. package/dist/runtime/subagent-commands.d.ts +5 -4
  53. package/dist/runtime/subagent-commands.js +116 -77
  54. package/dist/runtime/task-commands.d.ts +1 -1
  55. package/dist/runtime/task-commands.js +110 -64
  56. package/dist/runtime/task-driver.d.ts +4 -2
  57. package/dist/runtime/task-driver.js +55 -20
  58. package/dist/runtime/task-migration.js +23 -6
  59. package/dist/runtime/task-spawn.js +12 -5
  60. package/dist/runtime/wake-coalescing.d.ts +18 -0
  61. package/dist/runtime/wake-coalescing.js +29 -0
  62. package/dist/security/block-message.d.ts +22 -1
  63. package/dist/security/block-message.js +66 -1
  64. package/dist/security/network.d.ts +2 -1
  65. package/dist/security/network.js +3 -2
  66. package/dist/security/path-guard-check.js +2 -2
  67. package/dist/settings.d.ts +3 -2
  68. package/dist/settings.js +4 -1
  69. package/dist/shared/format.d.ts +12 -0
  70. package/dist/shared/format.js +37 -0
  71. package/dist/shared/host-process.js +15 -3
  72. package/dist/shared/with-timeout.d.ts +3 -2
  73. package/dist/shared/with-timeout.js +14 -3
  74. package/dist/subagents/external/claude-code.js +23 -1
  75. package/dist/subagents/external/progress-tail.d.ts +17 -0
  76. package/dist/subagents/external/progress-tail.js +64 -17
  77. package/dist/subagents/external/run.d.ts +3 -0
  78. package/dist/subagents/external/run.js +21 -7
  79. package/dist/subagents/external/settlement.d.ts +3 -0
  80. package/dist/subagents/external/settlement.js +1 -1
  81. package/dist/subagents/runs.d.ts +21 -1
  82. package/dist/subagents/runs.js +137 -32
  83. package/dist/subagents/tool.d.ts +22 -15
  84. package/dist/subagents/tool.js +226 -32
  85. package/dist/subagents/workspace-summary.d.ts +16 -4
  86. package/dist/subagents/workspace-summary.js +74 -18
  87. package/dist/tasks/board.d.ts +8 -1
  88. package/dist/tasks/board.js +37 -2
  89. package/dist/tasks/frontmatter.d.ts +5 -0
  90. package/dist/tasks/frontmatter.js +8 -0
  91. package/dist/tasks/log.d.ts +11 -1
  92. package/dist/tasks/log.js +58 -2
  93. package/dist/tasks/store.js +4 -2
  94. package/dist/tasks/ticket.d.ts +3 -1
  95. package/dist/tasks/ticket.js +19 -1
  96. package/dist/tools/bash.js +2 -2
  97. package/dist/tools/index.d.ts +2 -0
  98. package/dist/tools/index.js +1 -0
  99. package/dist/tools/memory-manage.js +4 -1
  100. package/dist/tools/subagent-manage.d.ts +1 -1
  101. package/dist/tools/subagent-manage.js +16 -11
  102. package/dist/tools/task-manage/step-end.js +4 -1
  103. package/dist/tools/tool-details.d.ts +10 -2
  104. package/dist/tools/tool-details.js +39 -2
  105. package/dist/tui/cli.js +2 -2
  106. package/dist/tui/commands.js +4 -4
  107. package/dist/tui/pitui-frontend.js +1 -1
  108. package/dist/tui/renderer.js +3 -2
  109. package/dist/tui/turn-controller.d.ts +2 -0
  110. package/dist/tui/turn-controller.js +36 -21
  111. package/dist/usage/ledger.js +3 -1
  112. package/dist/usage/render.js +3 -1
  113. package/package.json +1 -1
@@ -26,9 +26,17 @@ export const MIN_PERIODIC_INTERVAL_MS = 30 * 60 * 1000;
26
26
  export const MIN_PERIODIC_INTERVAL_WITH_PREACTION_MS = 5 * 60 * 1000;
27
27
  /** sanity cap on total scheduled events to keep the directory (and the scheduler) from being flooded. */
28
28
  export const MAX_EVENT_FILES = 50;
29
- export class EventValidationError extends Error {
30
- constructor(message, recoverable = true) {
29
+ /** A definition the file parser rejects. Kept distinct from `EventValidationError`, which the tool treats as model-fixable. */
30
+ export class EventDefinitionError extends Error {
31
+ constructor(kind, message) {
31
32
  super(message);
33
+ this.kind = kind;
34
+ this.name = "EventDefinitionError";
35
+ }
36
+ }
37
+ export class EventValidationError extends EventDefinitionError {
38
+ constructor(kind, message, recoverable = true) {
39
+ super(kind, message);
32
40
  this.name = "EventValidationError";
33
41
  this.recoverable = recoverable;
34
42
  }
@@ -36,19 +44,19 @@ export class EventValidationError extends Error {
36
44
  export function validateOneShotLead(event, now = Date.now()) {
37
45
  const atTime = parseLocalTime(event.at);
38
46
  if (atTime === undefined) {
39
- throw new EventValidationError(`one-shot 'at' is not a valid local time: ${event.at}`);
47
+ throw new EventValidationError("one-shot-time", `one-shot 'at' is not a valid local time: ${event.at}`);
40
48
  }
41
49
  if (atTime < now + MIN_ONE_SHOT_LEAD_MS) {
42
- throw new EventValidationError("one-shot 'at' must be at least 2 minutes in the future (self-triggering guard).");
50
+ throw new EventValidationError("one-shot-too-soon", "one-shot 'at' must be at least 2 minutes in the future (self-triggering guard).");
43
51
  }
44
52
  }
45
53
  function validateOneShotMaximumDelay(event, now = Date.now()) {
46
54
  const atTime = parseLocalTime(event.at);
47
55
  if (atTime === undefined) {
48
- throw new EventValidationError(`one-shot 'at' is not a valid local time: ${event.at}`);
56
+ throw new EventValidationError("one-shot-time", `one-shot 'at' is not a valid local time: ${event.at}`);
49
57
  }
50
58
  if (atTime - now > MAX_ONE_SHOT_DELAY_MS) {
51
- throw new EventValidationError("one-shot 'at' must be within about 24.8 days; use a periodic event for longer delays.");
59
+ throw new EventValidationError("one-shot-too-far", "one-shot 'at' must be within about 24.8 days; use a periodic event for longer delays.");
52
60
  }
53
61
  }
54
62
  export function validatePeriodicCadence(event) {
@@ -59,7 +67,7 @@ export function validatePeriodicCadence(event) {
59
67
  cron.stop();
60
68
  }
61
69
  catch (error) {
62
- throw new EventValidationError(`Invalid cron schedule "${event.schedule}": ${errorMessage(error)}`);
70
+ throw new EventValidationError("cron-invalid", `Invalid cron schedule "${event.schedule}": ${errorMessage(error)}`);
63
71
  }
64
72
  // A preAction gate makes a tighter cadence safe (the sensor keeps most fires silent);
65
73
  // without one, hold the 30-minute floor so a bare high-frequency cron can't burn tokens.
@@ -68,7 +76,7 @@ export function validatePeriodicCadence(event) {
68
76
  // Fewer than two upcoming runs means no meaningful cadence to rate-limit (e.g. a one-off cron); allow it.
69
77
  for (let i = 1; i < runs.length; i++) {
70
78
  if (runs[i].getTime() - runs[i - 1].getTime() < floorMs) {
71
- throw new EventValidationError(`periodic events must fire no more often than every ${floorMinutes} minutes` +
79
+ throw new EventValidationError("cadence-too-frequent", `periodic events must fire no more often than every ${floorMinutes} minutes` +
72
80
  `${event.preAction ? " (even with a preAction gate)" : "; for tighter checks add a preAction gate (min 5 minutes) instead of a high-frequency cron"}.`);
73
81
  }
74
82
  }
@@ -78,7 +86,7 @@ export function validatePreActionCommand(event, commandGuardConfig) {
78
86
  return;
79
87
  const result = guardCommand(event.preAction.command, commandGuardConfig);
80
88
  if (!result.allowed) {
81
- throw new EventValidationError(`preAction command blocked by guard: ${result.reason ?? "not allowed"}`, false);
89
+ throw new EventValidationError("pre-action-blocked", `preAction command blocked by guard: ${result.reason ?? "not allowed"}`, false);
82
90
  }
83
91
  }
84
92
  /** Apply every admission rule that depends only on the definition itself. */
@@ -10,7 +10,7 @@ import { formatLocalTime, parseLocalTime } from "../shared/local-time.js";
10
10
  import { clipText, errorMessage, eventNameFromFilename } from "../shared/text-utils.js";
11
11
  import { isPlainObject } from "../shared/type-guards.js";
12
12
  import { validateTaskContractInput } from "../tasks/contract-input.js";
13
- import { MAX_EVENT_FILES, MAX_ONE_SHOT_DELAY_MS, validateScheduledEvent } from "./event-validation.js";
13
+ import { EventDefinitionError, MAX_EVENT_FILES, MAX_ONE_SHOT_DELAY_MS, validateScheduledEvent, } from "./event-validation.js";
14
14
  // ============================================================================
15
15
  // EventsWatcher
16
16
  // ============================================================================
@@ -30,7 +30,7 @@ function truncateTextPreview(text) {
30
30
  function readRequiredString(data, field, filename) {
31
31
  const value = data[field];
32
32
  if (typeof value !== "string" || value.trim().length === 0) {
33
- throw new Error(`Missing required fields (type, channelId, and text or task) in ${filename}`);
33
+ throw new EventDefinitionError("missing-field", `Missing required fields (type, channelId, and text or task) in ${filename}`);
34
34
  }
35
35
  return value;
36
36
  }
@@ -39,7 +39,7 @@ function parsePayload(data, filename) {
39
39
  const hasText = typeof data.text === "string" && data.text.trim().length > 0;
40
40
  const hasTask = data.task !== undefined;
41
41
  if (hasText === hasTask) {
42
- throw new Error(`An event needs exactly one of 'text' (a chat message) or 'task' (a task template) in ${filename}`);
42
+ throw new EventDefinitionError("payload", `An event needs exactly one of 'text' (a chat message) or 'task' (a task template) in ${filename}`);
43
43
  }
44
44
  if (hasText)
45
45
  return { text: data.text };
@@ -47,25 +47,25 @@ function parsePayload(data, filename) {
47
47
  return { task: validateTaskContractInput(data.task) };
48
48
  }
49
49
  catch (error) {
50
- throw new Error(`Invalid 'task' template in ${filename}: ${errorMessage(error)}`);
50
+ throw new EventDefinitionError("task-template", `Invalid 'task' template in ${filename}: ${errorMessage(error)}`);
51
51
  }
52
52
  }
53
53
  function parsePreAction(data, filename) {
54
54
  if (!data.preAction)
55
55
  return undefined;
56
56
  if (!isPlainObject(data.preAction)) {
57
- throw new Error(`Invalid 'preAction' field in ${filename}, expected an object`);
57
+ throw new EventDefinitionError("pre-action", `Invalid 'preAction' field in ${filename}, expected an object`);
58
58
  }
59
59
  const action = data.preAction;
60
60
  if (action.type !== "bash") {
61
- throw new Error(`Unsupported preAction type '${String(action.type)}' in ${filename}, only 'bash' is supported`);
61
+ throw new EventDefinitionError("pre-action", `Unsupported preAction type '${String(action.type)}' in ${filename}, only 'bash' is supported`);
62
62
  }
63
63
  if (typeof action.command !== "string" || action.command.trim().length === 0) {
64
- throw new Error(`Missing or empty 'preAction.command' in ${filename}`);
64
+ throw new EventDefinitionError("pre-action", `Missing or empty 'preAction.command' in ${filename}`);
65
65
  }
66
66
  if (action.timeout !== undefined) {
67
67
  if (typeof action.timeout !== "number" || !Number.isFinite(action.timeout) || action.timeout <= 0) {
68
- throw new Error(`Invalid 'preAction.timeout' in ${filename}, expected a positive millisecond value`);
68
+ throw new EventDefinitionError("pre-action", `Invalid 'preAction.timeout' in ${filename}, expected a positive millisecond value`);
69
69
  }
70
70
  }
71
71
  return {
@@ -75,9 +75,15 @@ function parsePreAction(data, filename) {
75
75
  };
76
76
  }
77
77
  export function parseScheduledEventContent(content, filename) {
78
- const data = JSON.parse(content);
78
+ let data;
79
+ try {
80
+ data = JSON.parse(content);
81
+ }
82
+ catch (error) {
83
+ throw new EventDefinitionError("malformed", `Invalid JSON in ${filename}: ${errorMessage(error)}`);
84
+ }
79
85
  if (!isPlainObject(data)) {
80
- throw new Error(`Missing required fields (type, channelId, and text or task) in ${filename}`);
86
+ throw new EventDefinitionError("missing-field", `Missing required fields (type, channelId, and text or task) in ${filename}`);
81
87
  }
82
88
  const type = readRequiredString(data, "type", filename);
83
89
  const channelId = readRequiredString(data, "channelId", filename);
@@ -89,17 +95,17 @@ export function parseScheduledEventContent(content, filename) {
89
95
  // one. Rejecting it here — rather than only in `event_manage` — is what makes the guard
90
96
  // enforced, since the events directory is agent-writable.
91
97
  case "immediate":
92
- throw new Error(`Immediate events are no longer supported (${filename}); do the work in the current turn, ` +
98
+ throw new EventDefinitionError("immediate", `Immediate events are no longer supported (${filename}); do the work in the current turn, ` +
93
99
  "or schedule a one-shot at least 2 minutes out via event_manage.");
94
100
  case "one-shot": {
95
101
  if (typeof data.at !== "string" || data.at.trim().length === 0) {
96
- throw new Error(`Missing 'at' field for one-shot event in ${filename}`);
102
+ throw new EventDefinitionError("missing-field", `Missing 'at' field for one-shot event in ${filename}`);
97
103
  }
98
104
  return { type, channelId, ...payload, at: data.at, ...(preAction ? { preAction } : {}) };
99
105
  }
100
106
  case "periodic": {
101
107
  if (typeof data.schedule !== "string" || data.schedule.trim().length === 0) {
102
- throw new Error(`Missing 'schedule' field for periodic event in ${filename}`);
108
+ throw new EventDefinitionError("missing-field", `Missing 'schedule' field for periodic event in ${filename}`);
103
109
  }
104
110
  return {
105
111
  type,
@@ -110,7 +116,7 @@ export function parseScheduledEventContent(content, filename) {
110
116
  };
111
117
  }
112
118
  default:
113
- throw new Error(`Unknown event type '${type}' in ${filename}`);
119
+ throw new EventDefinitionError("unknown-type", `Unknown event type '${type}' in ${filename}`);
114
120
  }
115
121
  }
116
122
  /**
@@ -208,7 +214,7 @@ export class EventsWatcher {
208
214
  chmodSync(this.options.historyPath, 0o600);
209
215
  }
210
216
  catch (err) {
211
- log.logWarning("Failed to initialize event history file", String(err));
217
+ log.logWarn("events.history.init_failed", "Event history file init failed", { reason: String(err) });
212
218
  }
213
219
  }
214
220
  appendHistory(record) {
@@ -223,7 +229,7 @@ export class EventsWatcher {
223
229
  ...rest,
224
230
  };
225
231
  if (!this.historyAppender?.tryAppend(fullRecord, "critical")) {
226
- log.logWarning("Failed to queue event history", "Retry after pending event history writes drain");
232
+ log.logWarn("events.history.queue_full", "Event history write dropped while earlier writes drain");
227
233
  }
228
234
  }
229
235
  appendEventHistory(filename, event, action, result, extra = {}) {
@@ -255,7 +261,7 @@ export class EventsWatcher {
255
261
  files = readdirSync(this.eventsDir).filter((f) => f.endsWith(".json"));
256
262
  }
257
263
  catch (err) {
258
- log.logWarning("Failed to read events directory", String(err));
264
+ log.logWarn("events.dir.read_failed", "Events directory read failed", { reason: String(err) });
259
265
  return;
260
266
  }
261
267
  for (let offset = 0; this.started && offset < files.length; offset += SCAN_CONCURRENCY) {
@@ -264,7 +270,10 @@ export class EventsWatcher {
264
270
  await this.handleFile(filename);
265
271
  }
266
272
  catch (err) {
267
- log.logWarning(`Failed to restore event file: ${filename}`, errorMessage(err));
273
+ log.logWarn("events.file.restore_failed", "Event file restore failed", {
274
+ reason: errorMessage(err),
275
+ fields: { file: filename },
276
+ });
268
277
  }
269
278
  }));
270
279
  }
@@ -290,7 +299,10 @@ export class EventsWatcher {
290
299
  */
291
300
  handleFileSafely(filename) {
292
301
  void this.handleFile(filename).catch((err) => {
293
- log.logWarning(`Failed to load event file: ${filename}`, errorMessage(err));
302
+ log.logWarn("events.file.load_failed", "Event file load failed", {
303
+ reason: errorMessage(err),
304
+ fields: { file: filename },
305
+ });
294
306
  });
295
307
  }
296
308
  handleDelete(filename) {
@@ -348,7 +360,10 @@ export class EventsWatcher {
348
360
  }
349
361
  }
350
362
  if (!event) {
351
- log.logWarning(`Failed to parse event file after ${MAX_RETRIES} retries: ${filename}`, lastError?.message);
363
+ log.logWarn("events.file.parse_failed", "Event file parse failed", {
364
+ reason: lastError?.message,
365
+ fields: { file: filename, attempts: MAX_RETRIES },
366
+ });
352
367
  this.appendHistory({
353
368
  filename,
354
369
  eventType: "unknown",
@@ -361,7 +376,7 @@ export class EventsWatcher {
361
376
  }
362
377
  const rejection = this.admissionFailure(filename, event);
363
378
  if (rejection) {
364
- log.logWarning(`Rejected event file: ${filename}`, rejection);
379
+ log.logWarn("events.file.rejected", "Event file rejected", { reason: rejection, fields: { file: filename } });
365
380
  this.appendEventHistory(filename, event, "invalid", "error", { reason: rejection });
366
381
  this.markInvalid(filename, rejection);
367
382
  return;
@@ -416,7 +431,9 @@ export class EventsWatcher {
416
431
  const atTime = parseLocalTime(event.at);
417
432
  const now = Date.now();
418
433
  if (atTime === undefined) {
419
- log.logWarning(`Invalid one-shot time for ${filename}: ${event.at}`);
434
+ log.logWarn("events.oneshot.invalid_time", "One-shot event time invalid", {
435
+ fields: { file: filename, at: event.at },
436
+ });
420
437
  this.appendEventHistory(filename, event, "invalid", "error", { reason: `Invalid one-shot time: ${event.at}` });
421
438
  this.markInvalid(filename, `Invalid one-shot time: ${event.at}`);
422
439
  return;
@@ -431,7 +448,9 @@ export class EventsWatcher {
431
448
  }
432
449
  const delay = atTime - now;
433
450
  if (delay > MAX_ONE_SHOT_DELAY_MS) {
434
- log.logWarning(`One-shot event exceeds maximum supported delay for ${filename}: ${event.at}. Use a periodic cron event instead.`);
451
+ log.logWarn("events.oneshot.too_far", "One-shot event exceeds the maximum delay; use a periodic event", {
452
+ fields: { file: filename, at: event.at },
453
+ });
435
454
  this.appendEventHistory(filename, event, "skipped", "skipped", {
436
455
  reason: `One-shot event exceeds maximum supported delay: ${event.at}`,
437
456
  });
@@ -450,7 +469,10 @@ export class EventsWatcher {
450
469
  await this.execute(filename, event);
451
470
  }
452
471
  catch (err) {
453
- log.logWarning(`One-shot event execution failed: ${filename}`, String(err));
472
+ log.logWarn("events.oneshot.failed", "One-shot event execution failed", {
473
+ reason: String(err),
474
+ fields: { file: filename },
475
+ });
454
476
  this.appendEventHistory(filename, event, "skipped", "error", {
455
477
  reason: errorMessage(err),
456
478
  });
@@ -468,7 +490,10 @@ export class EventsWatcher {
468
490
  await this.execute(filename, event, false, cron.currentRun() ?? new Date());
469
491
  }
470
492
  catch (err) {
471
- log.logWarning(`Periodic event execution failed: ${filename}`, String(err));
493
+ log.logWarn("events.periodic.failed", "Periodic event execution failed", {
494
+ reason: String(err),
495
+ fields: { file: filename },
496
+ });
472
497
  this.appendEventHistory(filename, event, "skipped", "error", {
473
498
  reason: errorMessage(err),
474
499
  });
@@ -480,7 +505,10 @@ export class EventsWatcher {
480
505
  this.appendEventHistory(filename, event, "scheduled", "ok", next ? { nextRunAt: formatLocalTime(next) } : {});
481
506
  }
482
507
  catch (err) {
483
- log.logWarning(`Invalid cron schedule for ${filename}: ${event.schedule}`, String(err));
508
+ log.logWarn("events.periodic.invalid_cron", "Periodic event cron invalid", {
509
+ reason: String(err),
510
+ fields: { file: filename, schedule: event.schedule },
511
+ });
484
512
  this.appendEventHistory(filename, event, "invalid", "error", {
485
513
  reason: `Invalid cron schedule: ${event.schedule}\n${String(err)}`,
486
514
  });
@@ -572,7 +600,9 @@ export class EventsWatcher {
572
600
  // next tick, so just warn. One-shot/immediate events would otherwise be
573
601
  // GC'd as "past" with no trace, so leave a visible error marker (and keep
574
602
  // the source file) making the loss auditable rather than a silent hole.
575
- log.logWarning(`Event queue full, could not enqueue: ${filename}`);
603
+ log.logWarn("events.enqueue.queue_full", "Event not enqueued: channel queue full", {
604
+ fields: { file: filename },
605
+ });
576
606
  this.appendEventHistory(filename, event, "queue_full", "error", {
577
607
  reason: "channel queue full",
578
608
  queue: { accepted: false },
@@ -612,7 +642,10 @@ export class EventsWatcher {
612
642
  }
613
643
  catch (err) {
614
644
  const reason = errorMessage(err);
615
- log.logWarning(`Could not spawn a task for event: ${filename}`, reason);
645
+ log.logWarn("events.task_spawn.failed", "Task spawn for event failed", {
646
+ reason: reason,
647
+ fields: { file: filename },
648
+ });
616
649
  this.appendEventHistory(filename, event, "skipped", "error", { reason });
617
650
  if (deleteAfter) {
618
651
  this.markInvalid(filename, `Could not create the task instance at ${new Date().toISOString()}: ${reason}`);
@@ -624,7 +657,10 @@ export class EventsWatcher {
624
657
  if (this.commandGuardConfig?.enabled) {
625
658
  const guardResult = guardCommand(action.command, this.commandGuardConfig);
626
659
  if (!guardResult.allowed) {
627
- log.logWarning(`Pre-action command blocked by guard for ${filename}: ${guardResult.reason}`);
660
+ log.logWarn("events.preaction.blocked", "Event pre-action blocked by guard", {
661
+ reason: guardResult.reason,
662
+ fields: { file: filename },
663
+ });
628
664
  throw new EventPreActionError("blocked", `guard: ${guardResult.reason}`, {
629
665
  durationMs: Date.now() - startedAt,
630
666
  });
@@ -656,7 +692,10 @@ export class EventsWatcher {
656
692
  }
657
693
  catch (err) {
658
694
  if (err instanceof Error && "code" in err && err.code !== "ENOENT") {
659
- log.logWarning(`Failed to delete event file: ${filename}`, String(err));
695
+ log.logWarn("events.file.delete_failed", "Event file delete failed", {
696
+ reason: String(err),
697
+ fields: { file: filename },
698
+ });
660
699
  }
661
700
  }
662
701
  this.clearInvalidMarker(filename);
@@ -676,7 +715,10 @@ export class EventsWatcher {
676
715
  writeFileAtomicallySync(this.getInvalidMarkerPath(filename), [`timestamp: ${formatLocalTime()}`, `file: ${filename}`, "", message.trim()].join("\n"));
677
716
  }
678
717
  catch (err) {
679
- log.logWarning(`Failed to write event error marker: ${filename}`, String(err));
718
+ log.logWarn("events.marker.write_failed", "Event error marker write failed", {
719
+ reason: String(err),
720
+ fields: { file: filename },
721
+ });
680
722
  }
681
723
  this.knownFiles.add(filename);
682
724
  }
@@ -687,7 +729,10 @@ export class EventsWatcher {
687
729
  }
688
730
  catch (err) {
689
731
  if (err instanceof Error && "code" in err && err.code !== "ENOENT") {
690
- log.logWarning(`Failed to delete event error marker: ${filename}`, String(err));
732
+ log.logWarn("events.marker.delete_failed", "Event error marker delete failed", {
733
+ reason: String(err),
734
+ fields: { file: filename },
735
+ });
691
736
  }
692
737
  }
693
738
  }
package/dist/executor.js CHANGED
@@ -1,7 +1,7 @@
1
1
  import { createWriteStream, existsSync } from "node:fs";
2
2
  import { join as joinPath, delimiter as PATH_DELIMITER } from "node:path";
3
3
  import { spawn } from "child_process";
4
- import { logWarning } from "./log.js";
4
+ import * as log from "./log.js";
5
5
  /**
6
6
  * The `bash` tool's schema says "Bash command" and models write bash-only syntax (`[[ ]]`, arrays,
7
7
  * `set -o pipefail`, process substitution). `/bin/sh` is `dash` on many hosts, so those fail with a
@@ -24,7 +24,7 @@ function resolveShell() {
24
24
  }
25
25
  const RESOLVED_SHELL = resolveShell();
26
26
  if (!RESOLVED_SHELL.isBash) {
27
- logWarning("executor: no `bash` binary found on this host; the bash tool is running commands via POSIX /bin/sh");
27
+ log.logWarn("runtime.executor.no_bash", "No bash binary on this host; the bash tool runs commands via POSIX /bin/sh");
28
28
  }
29
29
  /** True when the executor found a real `bash`; `bash.ts` uses this to keep its description honest. */
30
30
  export const EXECUTOR_SHELL_IS_BASH = RESOLVED_SHELL.isBash;
package/dist/log.d.ts CHANGED
@@ -38,8 +38,18 @@ export declare function logResponseStart(ctx: LogContext): void;
38
38
  export declare function logThinking(ctx: LogContext, thinking: string): void;
39
39
  export declare function logResponse(ctx: LogContext, text: string): void;
40
40
  export declare function logInfo(message: string, details?: string): void;
41
- export declare function logWarning(message: string, details?: string): void;
41
+ export interface EventLogOptions {
42
+ channelId?: string;
43
+ /** Why it happened (an error message, a rejection). Kept out of `message` so the message stays greppable. */
44
+ reason?: string;
45
+ /** Ids and counts the event is about. */
46
+ fields?: Record<string, unknown>;
47
+ }
48
+ export declare function logWarn(event: string, message: string, options?: EventLogOptions): void;
49
+ export declare function logInfoEvent(event: string, message: string, options?: EventLogOptions): void;
50
+ export declare function logDebugEvent(event: string, message: string, options?: EventLogOptions): void;
42
51
  export declare function logModelFallback(ctx: LogContext, from: string, to: string, error: string): void;
52
+ /** One structured record per turn's usage; the context fill rides along when known. */
43
53
  export declare function logUsageSummary(ctx: LogContext, usage: {
44
54
  input: number;
45
55
  output: number;
@@ -52,6 +62,6 @@ export declare function logUsageSummary(ctx: LogContext, usage: {
52
62
  cacheWrite: number;
53
63
  total: number;
54
64
  };
55
- }, contextTokens?: number, contextWindow?: number): string;
65
+ }, contextTokens?: number, contextWindow?: number): void;
56
66
  export declare function logStartup(workingDir: string): void;
57
67
  export declare function logConnected(): void;
package/dist/log.js CHANGED
@@ -216,9 +216,11 @@ export function logResponse(ctx, text) {
216
216
  });
217
217
  }
218
218
  // Compatibility helpers keep lower-risk call sites centralized while they use
219
- // the same output contract as structured events.
219
+ // the same output contract as structured events. The channel prefix accepts any non-blank id:
220
+ // a group channel is `group_<conversationId>`, and DingTalk conversation ids are base64 (`+`, `/`,
221
+ // `=`), which a word-character class silently failed to match — group logs lost their `channel`.
220
222
  function legacyContext(message) {
221
- const match = /^\[([A-Za-z0-9._-]+)\]\s*/.exec(message);
223
+ const match = /^\[([^\]\s]+)\]\s*/.exec(message);
222
224
  return match ? { message: message.slice(match[0].length), ctx: { channelId: match[1] } } : { message };
223
225
  }
224
226
  export function logInfo(message, details) {
@@ -228,43 +230,33 @@ export function logInfo(message, details) {
228
230
  ...(details ? { details, fields: { reason: details } } : {}),
229
231
  });
230
232
  }
231
- export function logWarning(message, details) {
232
- const legacy = legacyContext(message);
233
- logEvent("warn", "system.warning", legacy.message, {
234
- ctx: legacy.ctx,
235
- ...(details ? { details, fields: { reason: details } } : {}),
233
+ /**
234
+ * One runtime event with a filterable `<domain>.<object>.<verb>` name (spec 053, D12). `message`
235
+ * is a fixed sentence (`<Subject> failed`); what varies goes to `reason` and `fields`, which the
236
+ * console line and the JSONL record both carry.
237
+ */
238
+ function logNamedEvent(level, event, message, options) {
239
+ const fields = { ...options.fields, ...(options.reason ? { reason: options.reason } : {}) };
240
+ logEvent(level, event, message, {
241
+ ...(options.channelId ? { ctx: { channelId: options.channelId } } : {}),
242
+ ...(options.reason ? { details: options.reason } : {}),
243
+ ...(Object.keys(fields).length > 0 ? { fields } : {}),
236
244
  });
237
245
  }
246
+ export function logWarn(event, message, options = {}) {
247
+ logNamedEvent("warn", event, message, options);
248
+ }
249
+ export function logInfoEvent(event, message, options = {}) {
250
+ logNamedEvent("info", event, message, options);
251
+ }
252
+ export function logDebugEvent(event, message, options = {}) {
253
+ logNamedEvent("debug", event, message, options);
254
+ }
238
255
  export function logModelFallback(ctx, from, to, error) {
239
256
  logEvent("warn", "agent.model.fallback", "Using fallback model", { ctx, fields: { from, to, error } });
240
257
  }
258
+ /** One structured record per turn's usage; the context fill rides along when known. */
241
259
  export function logUsageSummary(ctx, usage, contextTokens, contextWindow) {
242
- const formatTokens = (count) => {
243
- if (count < 1000)
244
- return count.toString();
245
- if (count < 10000)
246
- return `${(count / 1000).toFixed(1)}k`;
247
- if (count < 1000000)
248
- return `${Math.round(count / 1000)}k`;
249
- return `${(count / 1000000).toFixed(1)}M`;
250
- };
251
- const lines = [
252
- "**Usage Summary**",
253
- `Tokens: ${usage.input.toLocaleString()} in, ${usage.output.toLocaleString()} out`,
254
- ...(usage.cacheRead > 0 || usage.cacheWrite > 0
255
- ? [`Cache: ${usage.cacheRead.toLocaleString()} read, ${usage.cacheWrite.toLocaleString()} write`]
256
- : []),
257
- ...(contextTokens && contextWindow
258
- ? [
259
- `Context: ${formatTokens(contextTokens)} / ${formatTokens(contextWindow)} (${((contextTokens / contextWindow) * 100).toFixed(1)}%)`,
260
- ]
261
- : []),
262
- `Cost: $${usage.cost.input.toFixed(4)} in, $${usage.cost.output.toFixed(4)} out` +
263
- (usage.cacheRead > 0 || usage.cacheWrite > 0
264
- ? `, $${usage.cost.cacheRead.toFixed(4)} cache read, $${usage.cost.cacheWrite.toFixed(4)} cache write`
265
- : ""),
266
- `**Total: $${usage.cost.total.toFixed(4)}** (incl. sub-agents)`,
267
- ];
268
260
  logEvent("info", "agent.usage", "Usage recorded", {
269
261
  ctx,
270
262
  fields: {
@@ -273,9 +265,9 @@ export function logUsageSummary(ctx, usage, contextTokens, contextWindow) {
273
265
  cacheRead: usage.cacheRead,
274
266
  cacheWrite: usage.cacheWrite,
275
267
  cost: usage.cost,
268
+ ...(contextTokens && contextWindow ? { contextTokens, contextWindow } : {}),
276
269
  },
277
270
  });
278
- return lines.join("\n");
279
271
  }
280
272
  export function logStartup(workingDir) {
281
273
  logEvent("info", "runtime.started", "Starting pipiclaw", { fields: { workingDir } });
package/dist/main.js CHANGED
@@ -62,6 +62,6 @@ else {
62
62
  console.error(`Unknown command: ${command}`);
63
63
  for (const line of formatCliCommandsHelp("pipiclaw"))
64
64
  console.error(line);
65
- console.error("Run `pipiclaw --help` for options.");
65
+ console.error("Run `pipiclaw --help` for usage.");
66
66
  process.exit(1);
67
67
  }
@@ -1,5 +1,5 @@
1
1
  import { renderSubcommandUsage } from "../commands/catalog.js";
2
- import { capReply } from "../commands/reply-limits.js";
2
+ import { capReply, flattenMarkdownForChat } from "../commands/reply-limits.js";
3
3
  import { localDayKey } from "../shared/local-time.js";
4
4
  import { getDefaultChannelMemoryQueue } from "./channel-maintenance-queue.js";
5
5
  import { buildChannelIndexForBootstrap, CHANNEL_INDEX_MAX_UNITS } from "./index-budget.js";
@@ -32,10 +32,10 @@ async function handleStatus(options) {
32
32
  "**记忆状态**",
33
33
  "",
34
34
  `- 频道条目:\`${entries.length}\`(${MEMORY_TYPE_ORDER.map((type) => `${type} ${byType.get(type) ?? 0}`).join(" / ")})`,
35
- `- 试用期条目:\`${probationary.length}\`${probationary.length > 0 ? `(最早到期 \`${probationary[0].expires}\`)` : ""}`,
36
- `- frontmatter 解析异常的文件:\`${malformed.length}\`${malformed.length > 0 ? `(${malformed.map((e) => e.name).join(", ")})` : ""}`,
37
- `- 上次反思:\`${state?.lastReflectAt ?? "从未"}\`${state?.lastReflectedEntryId ? `(游标 \`${state.lastReflectedEntryId}\`)` : ""}`,
38
- `- 索引预算:${tiered.overBudget ? `超出,注入时按 updated 降序分层;下次反思会尝试合并` : "未超出,整份注入"}`,
35
+ `- 观察期条目:\`${probationary.length}\`${probationary.length > 0 ? `(最早到期 \`${probationary[0].expires}\`)` : ""}`,
36
+ `- 文件头解析异常:\`${malformed.length}\`${malformed.length > 0 ? `(${malformed.map((e) => e.name).join("、")})` : ""}`,
37
+ `- 上次后台整理:\`${state?.lastReflectAt ?? "从未"}\``,
38
+ `- 索引大小:${tiered.overBudget ? "超出预算,注入时优先带最近更新的条目;下次整理会尝试合并" : "未超出预算,整份注入"}`,
39
39
  ].join("\n");
40
40
  }
41
41
  async function handleList(options, typeArg) {
@@ -45,10 +45,12 @@ async function handleList(options, typeArg) {
45
45
  const entries = await listMemoryEntries(options.channelDir);
46
46
  const filtered = typeArg ? entries.filter((entry) => entry.type === typeArg) : entries;
47
47
  if (filtered.length === 0) {
48
- return typeArg ? `**记忆条目(${typeArg})**\n\n暂无该类型的记忆。` : "**记忆条目**\n\n暂无生效的频道记忆。";
48
+ return typeArg
49
+ ? `暂无 \`${typeArg}\` 类型的记忆。\n用 \`/memory list\` 查看全部。`
50
+ : "暂无生效的频道记忆。\n在对话里告诉我需要长期记住的事,我会保存下来。";
49
51
  }
50
52
  const lines = filtered.map((entry) => {
51
- const marker = entry.body.trim() ? " (+)" : "";
53
+ const marker = entry.body.trim() ? "(有正文)" : "";
52
54
  const probation = entry.expires ? `(观察期至 \`${entry.expires}\`)` : "";
53
55
  return `- \`${entry.name}\` [${entry.type}]${probation} ${entry.description}${marker}`;
54
56
  });
@@ -58,32 +60,34 @@ async function handleList(options, typeArg) {
58
60
  }
59
61
  async function handleShow(options, name) {
60
62
  if (!name)
61
- return `缺少记忆名称。${renderUsage()}`;
63
+ return `缺少记忆名称。\n\n${renderUsage()}`;
62
64
  const entry = await readMemoryEntry(options.channelDir, name);
63
65
  if (!entry)
64
66
  return `未找到记忆 \`${name}\`。用 \`/memory list\` 查看可用名称。`;
67
+ // Frontmatter keys stay visible (the user sees them when opening the file), introduced by a
68
+ // Chinese label rather than shown bare (spec 053, D1).
65
69
  const lines = [
66
70
  `**记忆 ${name}**`,
67
71
  "",
68
- `- type: \`${entry.type}\``,
69
- `- source: \`${entry.source}\``,
70
- `- created: \`${entry.created}\` / updated: \`${entry.updated}\``,
72
+ `- 类型(type):\`${entry.type}\``,
73
+ `- 来源(source):\`${entry.source}\``,
74
+ `- 创建(created):\`${entry.created}\`;更新(updated):\`${entry.updated}\``,
71
75
  ];
72
76
  if (entry.expires)
73
- lines.push(`- expires: \`${entry.expires}\``);
77
+ lines.push(`- 观察期至(expires):\`${entry.expires}\``);
74
78
  if (entry.malformed)
75
- lines.push("- ⚠️ frontmatter 解析异常,以第一段作为 description");
79
+ lines.push("- ⚠️ 文件头解析异常,以第一段作为描述");
76
80
  lines.push("", entry.description);
77
81
  if (entry.body.trim())
78
- lines.push("", entry.body.trim());
79
- return lines.join("\n");
82
+ lines.push("", flattenMarkdownForChat(entry.body.trim()));
83
+ return capReply(lines.join("\n"), { nextStepHint: "完整内容在频道目录的 `memory/` 下" }).text;
80
84
  }
81
85
  async function handleForget(options, name) {
82
86
  if (!name)
83
- return `缺少记忆名称。${renderUsage()}`;
87
+ return `缺少记忆名称。\n\n${renderUsage()}`;
84
88
  const entry = await readMemoryEntry(options.channelDir, name);
85
89
  if (!entry)
86
- return `未找到记忆 \`${name}\`;未做任何改动。`;
90
+ return `未找到记忆 \`${name}\`,未做任何改动。用 \`/memory list\` 查看可用名称。`;
87
91
  await getDefaultChannelMemoryQueue().run(options.channelId, () => applyMemoryOps(options.channelDir, [{ op: "delete", name, reason: "/memory forget" }]));
88
92
  await appendMemoryReviewLog(options.channelDir, {
89
93
  timestamp: new Date().toISOString(),
@@ -91,20 +95,22 @@ async function handleForget(options, name) {
91
95
  reason: "memory-forget",
92
96
  actions: [{ op: "forget", name, contentHash: hashMemoryContent(entry.description) }],
93
97
  }).catch(() => { });
94
- return `已删除 \`${name}\`。内容按哈希墓碑化,避免被反思重新写入;重新说出该事实仍可被学到。`;
98
+ return `已删除 \`${name}\`,并记入忽略名单,后台整理不会再自动写回;你之后重新说起这件事,仍然可以被记住。`;
95
99
  }
96
100
  async function handleJournal(options, dateArg) {
97
101
  const date = dateArg ?? localDayKey();
98
102
  if (!/^\d{4}-\d{2}-\d{2}$/.test(date)) {
99
- return `日期格式应为 \`YYYY-MM-DD\`。${renderUsage()}`;
103
+ return `日期格式应为 \`YYYY-MM-DD\`。\n\n${renderUsage()}`;
100
104
  }
101
105
  const content = await readJournalDay(options.channelDir, date);
102
106
  if (!content.trim()) {
103
107
  const dates = await listJournalDates(options.channelDir);
104
- const hint = dates.length > 0 ? `\n\n有记录的日期:${dates.slice(-10).join(", ")}` : "";
105
- return `**日志 ${date}**\n\n当天没有记录。${hint}`;
108
+ const hint = dates.length > 0
109
+ ? `有记录的日期:${dates.slice(-10).join("、")}`
110
+ : "工作日记由后台整理按天写入,有对话之后会出现。";
111
+ return `暂无 ${date} 的工作日记。\n${hint}`;
106
112
  }
107
- return capReply(`**日志 ${date}**\n\n${content.trim()}`, {
113
+ return capReply(`**工作日记 ${date}**\n\n${flattenMarkdownForChat(content.trim())}`, {
108
114
  nextStepHint: "用 `/memory journal <YYYY-MM-DD>` 查看其他日期",
109
115
  }).text;
110
116
  }
@@ -120,5 +126,5 @@ export async function handleMemoryCommand(options) {
120
126
  return handleForget(options, argument);
121
127
  if (action === "journal")
122
128
  return handleJournal(options, argument);
123
- return `未知的 memory 命令 \`${action}\`。${renderUsage()}`;
129
+ return `未知子命令 \`${action}\`。\n\n${renderUsage()}`;
124
130
  }