@oyasmi/pipiclaw 0.7.7 → 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 (114) hide show
  1. package/README.md +23 -2
  2. package/dist/agent/channel-runner.d.ts +4 -4
  3. package/dist/agent/channel-runner.js +25 -23
  4. package/dist/agent/commands.js +7 -2
  5. package/dist/agent/job-manager.d.ts +5 -5
  6. package/dist/agent/prompt-builder.d.ts +3 -13
  7. package/dist/agent/prompt-builder.js +49 -159
  8. package/dist/agent/run-queue.js +2 -1
  9. package/dist/agent/runner-factory.d.ts +1 -2
  10. package/dist/agent/runner-factory.js +2 -2
  11. package/dist/agent/status-render.d.ts +0 -7
  12. package/dist/agent/status-render.js +8 -3
  13. package/dist/agent/types.d.ts +2 -0
  14. package/dist/agent/workspace-resources.d.ts +1 -1
  15. package/dist/agent/workspace-resources.js +3 -15
  16. package/dist/executor.d.ts +20 -0
  17. package/dist/{sandbox.js → executor.js} +3 -95
  18. package/dist/index.d.ts +1 -1
  19. package/dist/index.js +1 -1
  20. package/dist/log.d.ts +1 -1
  21. package/dist/log.js +1 -2
  22. package/dist/memory/files.js +0 -0
  23. package/dist/memory/lifecycle.js +6 -5
  24. package/dist/memory/maintenance-jobs.d.ts +0 -1
  25. package/dist/memory/maintenance-jobs.js +2 -2
  26. package/dist/memory/maintenance-state.js +2 -1
  27. package/dist/memory/post-turn-review.d.ts +0 -1
  28. package/dist/memory/post-turn-review.js +4 -4
  29. package/dist/memory/scheduler.d.ts +0 -1
  30. package/dist/memory/scheduler.js +2 -2
  31. package/dist/memory/session.js +2 -2
  32. package/dist/memory/task-digest.js +17 -0
  33. package/dist/paths.d.ts +2 -0
  34. package/dist/paths.js +11 -0
  35. package/dist/playbooks/catalog.d.ts +9 -0
  36. package/dist/playbooks/catalog.js +44 -0
  37. package/dist/playbooks/event-scheduling.md +43 -0
  38. package/dist/playbooks/memory-and-learning.md +45 -0
  39. package/dist/playbooks/runtime-orientation.md +48 -0
  40. package/dist/playbooks/task-closeout.md +45 -0
  41. package/dist/playbooks/task-delegation.md +44 -0
  42. package/dist/playbooks/task-driving.md +43 -0
  43. package/dist/playbooks/task-planning.md +47 -0
  44. package/dist/playbooks/task-recurring.md +42 -0
  45. package/dist/playbooks/task-repair.md +43 -0
  46. package/dist/runtime/bootstrap.d.ts +12 -11
  47. package/dist/runtime/bootstrap.js +81 -57
  48. package/dist/runtime/delivery.js +4 -3
  49. package/dist/runtime/dingtalk.d.ts +2 -0
  50. package/dist/runtime/dingtalk.js +15 -14
  51. package/dist/runtime/durable-dispatch.d.ts +30 -0
  52. package/dist/runtime/durable-dispatch.js +172 -0
  53. package/dist/runtime/event-commands.js +4 -4
  54. package/dist/runtime/events.d.ts +5 -3
  55. package/dist/runtime/events.js +17 -13
  56. package/dist/runtime/task-commands.d.ts +6 -0
  57. package/dist/runtime/task-commands.js +292 -6
  58. package/dist/runtime/task-driver.d.ts +32 -0
  59. package/dist/runtime/task-driver.js +268 -0
  60. package/dist/security/config.js +2 -1
  61. package/dist/security/network.js +9 -2
  62. package/dist/security/path-guard.js +12 -24
  63. package/dist/security/types.d.ts +0 -1
  64. package/dist/settings.d.ts +12 -0
  65. package/dist/settings.js +30 -0
  66. package/dist/shared/jsonl-appender.js +2 -1
  67. package/dist/shared/task-ledger.d.ts +35 -0
  68. package/dist/shared/task-ledger.js +229 -15
  69. package/dist/shared/text-utils.d.ts +1 -0
  70. package/dist/shared/text-utils.js +3 -0
  71. package/dist/subagents/discovery.js +3 -2
  72. package/dist/subagents/tool.d.ts +15 -3
  73. package/dist/subagents/tool.js +194 -17
  74. package/dist/tasks/artifact-subject.d.ts +6 -0
  75. package/dist/tasks/artifact-subject.js +29 -0
  76. package/dist/tasks/control.d.ts +83 -0
  77. package/dist/tasks/control.js +293 -0
  78. package/dist/tasks/store.d.ts +32 -0
  79. package/dist/tasks/store.js +142 -0
  80. package/dist/tasks/verification.d.ts +23 -0
  81. package/dist/tasks/verification.js +69 -0
  82. package/dist/tools/bash.d.ts +1 -1
  83. package/dist/tools/bash.js +3 -5
  84. package/dist/tools/command-optimizer.d.ts +1 -1
  85. package/dist/tools/command-optimizer.js +4 -6
  86. package/dist/tools/config.js +4 -3
  87. package/dist/tools/edit.d.ts +1 -1
  88. package/dist/tools/edit.js +0 -0
  89. package/dist/tools/event-manage.d.ts +0 -1
  90. package/dist/tools/event-manage.js +9 -14
  91. package/dist/tools/grep.d.ts +1 -1
  92. package/dist/tools/grep.js +4 -6
  93. package/dist/tools/index.d.ts +1 -3
  94. package/dist/tools/index.js +1 -4
  95. package/dist/tools/read.d.ts +1 -1
  96. package/dist/tools/read.js +1 -2
  97. package/dist/tools/registry.d.ts +2 -3
  98. package/dist/tools/registry.js +5 -11
  99. package/dist/tools/skill-manage.d.ts +0 -1
  100. package/dist/tools/skill-manage.js +7 -14
  101. package/dist/tools/task-manage.d.ts +37 -4
  102. package/dist/tools/task-manage.js +398 -39
  103. package/dist/tools/write-content.d.ts +1 -1
  104. package/dist/tools/write-content.js +0 -1
  105. package/dist/tools/write.d.ts +1 -1
  106. package/dist/tui/app.d.ts +0 -2
  107. package/dist/tui/app.js +12 -7
  108. package/dist/tui/cli.d.ts +0 -2
  109. package/dist/tui/cli.js +3 -25
  110. package/dist/tui/turn-controller.d.ts +7 -3
  111. package/dist/tui/turn-controller.js +9 -6
  112. package/dist/web/client.js +2 -1
  113. package/package.json +2 -2
  114. package/dist/sandbox.d.ts +0 -42
@@ -0,0 +1,172 @@
1
+ import { createHash } from "node:crypto";
2
+ import { readdir, readFile, unlink } from "node:fs/promises";
3
+ import { join } from "node:path";
4
+ import { writeFileAtomically } from "../shared/atomic-file.js";
5
+ import { createSerialQueue } from "../shared/serial-queue.js";
6
+ const DEFAULT_LEASE_MS = 15 * 60_000;
7
+ const DEFAULT_INTERVAL_MS = 30_000;
8
+ function recordPath(stateDir, id) {
9
+ return join(stateDir, `${id}.json`);
10
+ }
11
+ function dispatchId(event) {
12
+ return createHash("sha256")
13
+ .update(JSON.stringify([event.channelId, event.user, event.ts, event.text, event.conversationId]))
14
+ .digest("hex");
15
+ }
16
+ function isRecord(value) {
17
+ return typeof value === "object" && value !== null;
18
+ }
19
+ function parseRecord(raw) {
20
+ try {
21
+ const value = JSON.parse(raw);
22
+ if (!isRecord(value) ||
23
+ value.version !== 1 ||
24
+ typeof value.id !== "string" ||
25
+ typeof value.createdAt !== "string" ||
26
+ (value.status !== "pending" && value.status !== "queued" && value.status !== "running") ||
27
+ !isRecord(value.event) ||
28
+ typeof value.event.channelId !== "string" ||
29
+ typeof value.event.text !== "string" ||
30
+ typeof value.deliveries !== "number") {
31
+ return undefined;
32
+ }
33
+ return value;
34
+ }
35
+ catch {
36
+ return undefined;
37
+ }
38
+ }
39
+ /**
40
+ * Tiny file-backed outbox for synthetic work. It intentionally provides
41
+ * at-least-once delivery: a crash after enqueue may replay a task/event, while
42
+ * a crash can no longer silently discard it merely because it left an in-memory
43
+ * channel queue.
44
+ */
45
+ export class DurableDispatchService {
46
+ constructor(options) {
47
+ this.options = options;
48
+ this.queue = createSerialQueue();
49
+ this.timer = null;
50
+ this.leaseMs = options.leaseMs ?? DEFAULT_LEASE_MS;
51
+ }
52
+ start() {
53
+ if (this.timer)
54
+ return;
55
+ void this.drainOnce();
56
+ this.timer = setInterval(() => void this.drainOnce(), this.options.intervalMs ?? DEFAULT_INTERVAL_MS);
57
+ this.timer.unref?.();
58
+ }
59
+ stop() {
60
+ if (!this.timer)
61
+ return;
62
+ clearInterval(this.timer);
63
+ this.timer = null;
64
+ }
65
+ async dispatch(event) {
66
+ const id = event.dispatchId ?? dispatchId(event);
67
+ await this.queue.run(id, async () => {
68
+ const existing = await this.read(id);
69
+ if (existing)
70
+ return;
71
+ const record = {
72
+ version: 1,
73
+ id,
74
+ createdAt: new Date().toISOString(),
75
+ status: "pending",
76
+ event: { ...event, dispatchId: id },
77
+ deliveries: 0,
78
+ };
79
+ await this.write(record);
80
+ });
81
+ await this.drainOnce();
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;
111
+ }
112
+ async markStarted(id) {
113
+ if (!id)
114
+ return;
115
+ await this.queue.run(id, async () => {
116
+ const record = await this.read(id);
117
+ if (!record)
118
+ return;
119
+ record.status = "running";
120
+ record.leaseExpiresAt = new Date(Date.now() + this.leaseMs).toISOString();
121
+ await this.write(record);
122
+ });
123
+ }
124
+ async markCompleted(id) {
125
+ if (!id)
126
+ return;
127
+ await this.queue.run(id, async () => {
128
+ await unlink(recordPath(this.options.stateDir, id)).catch(() => undefined);
129
+ });
130
+ }
131
+ async drainOnce(now = Date.now()) {
132
+ let filenames;
133
+ try {
134
+ filenames = (await readdir(this.options.stateDir)).filter((name) => name.endsWith(".json")).sort();
135
+ }
136
+ catch {
137
+ return;
138
+ }
139
+ for (const filename of filenames) {
140
+ const id = filename.slice(0, -".json".length);
141
+ await this.queue.run(id, async () => {
142
+ const record = await this.read(id);
143
+ if (!record)
144
+ return;
145
+ const leaseMs = record.leaseExpiresAt ? new Date(record.leaseExpiresAt).getTime() : undefined;
146
+ if ((record.status === "queued" || record.status === "running") && leaseMs && leaseMs > now)
147
+ return;
148
+ record.status = "queued";
149
+ record.deliveries++;
150
+ record.leaseExpiresAt = new Date(now + this.leaseMs).toISOString();
151
+ await this.write(record);
152
+ const accepted = this.options.bot.enqueueEvent({ ...record.event, dispatchId: record.id });
153
+ if (accepted)
154
+ return;
155
+ record.status = "pending";
156
+ record.leaseExpiresAt = undefined;
157
+ await this.write(record);
158
+ });
159
+ }
160
+ }
161
+ async read(id) {
162
+ try {
163
+ return parseRecord(await readFile(recordPath(this.options.stateDir, id), "utf-8"));
164
+ }
165
+ catch {
166
+ return undefined;
167
+ }
168
+ }
169
+ async write(record) {
170
+ await writeFileAtomically(recordPath(this.options.stateDir, record.id), `${JSON.stringify(record)}\n`);
171
+ }
172
+ }
@@ -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,6 +1,6 @@
1
- import type { Executor } from "../sandbox.js";
1
+ import type { Executor } from "../executor.js";
2
2
  import type { SecurityConfig } from "../security/types.js";
3
- import type { DingTalkBot } from "./dingtalk.js";
3
+ import type { DingTalkBot, DingTalkEvent } from "./dingtalk.js";
4
4
  export interface EventAction {
5
5
  type: "bash";
6
6
  command: string;
@@ -57,6 +57,8 @@ export interface EventHistoryRecord {
57
57
  }
58
58
  export interface EventsWatcherOptions {
59
59
  historyPath?: string;
60
+ /** Persist synthetic work before it enters the in-memory channel queue. */
61
+ dispatch?: (event: DingTalkEvent) => boolean | Promise<boolean>;
60
62
  }
61
63
  export declare function formatLocalTimestamp(date?: Date): string;
62
64
  export declare function parseScheduledEventContent(content: string, filename: string): ScheduledEvent;
@@ -99,4 +101,4 @@ export declare class EventsWatcher {
99
101
  /**
100
102
  * Create and start an events watcher.
101
103
  */
102
- export declare function createEventsWatcher(workspaceDir: string, bot: DingTalkBot, executor: Executor, commandGuardConfig?: SecurityConfig["commandGuard"], historyPath?: string): EventsWatcher;
104
+ export declare function createEventsWatcher(workspaceDir: string, bot: DingTalkBot, executor: Executor, commandGuardConfig?: SecurityConfig["commandGuard"], historyPath?: string, dispatch?: EventsWatcherOptions["dispatch"]): EventsWatcher;
@@ -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
  // ============================================================================
@@ -319,7 +319,7 @@ export class EventsWatcher {
319
319
  this.handleImmediate(filename, event);
320
320
  break;
321
321
  case "one-shot":
322
- this.handleOneShot(filename, event);
322
+ await this.handleOneShot(filename, event);
323
323
  break;
324
324
  case "periodic":
325
325
  this.handlePeriodic(filename, event);
@@ -347,7 +347,7 @@ export class EventsWatcher {
347
347
  this.appendEventHistory(filename, event, "triggered", "ok");
348
348
  await this.execute(filename, event);
349
349
  }
350
- handleOneShot(filename, event) {
350
+ async handleOneShot(filename, event) {
351
351
  const atTime = new Date(event.at).getTime();
352
352
  const now = Date.now();
353
353
  if (!Number.isFinite(atTime)) {
@@ -357,9 +357,11 @@ export class EventsWatcher {
357
357
  return;
358
358
  }
359
359
  if (atTime <= now) {
360
- log.logInfo(`One-shot event in the past, deleting: ${filename}`);
361
- this.appendEventHistory(filename, event, "skipped", "skipped", { reason: "one-shot event is in the past" });
362
- this.deleteFile(filename);
360
+ // A persisted dispatch turns a missed one-shot into a safe fire-once-now
361
+ // recovery instead of silently discarding work after a process restart.
362
+ log.logInfo(`Recovering past one-shot event now: ${filename}`);
363
+ this.appendEventHistory(filename, event, "triggered", "ok", { reason: "one-shot recovered after due time" });
364
+ await this.execute(filename, event);
363
365
  return;
364
366
  }
365
367
  const delay = atTime - now;
@@ -385,7 +387,7 @@ export class EventsWatcher {
385
387
  catch (err) {
386
388
  log.logWarning(`One-shot event execution failed: ${filename}`, String(err));
387
389
  this.appendEventHistory(filename, event, "skipped", "error", {
388
- reason: err instanceof Error ? err.message : String(err),
390
+ reason: errorMessage(err),
389
391
  });
390
392
  }
391
393
  }, delay);
@@ -402,7 +404,7 @@ export class EventsWatcher {
402
404
  catch (err) {
403
405
  log.logWarning(`Periodic event execution failed: ${filename}`, String(err));
404
406
  this.appendEventHistory(filename, event, "skipped", "error", {
405
- reason: err instanceof Error ? err.message : String(err),
407
+ reason: errorMessage(err),
406
408
  });
407
409
  }
408
410
  });
@@ -441,7 +443,7 @@ export class EventsWatcher {
441
443
  });
442
444
  }
443
445
  catch (err) {
444
- const reason = err instanceof Error ? err.message : String(err);
446
+ const reason = errorMessage(err);
445
447
  log.logInfo(`Pre-action gate blocked event: ${filename} (${reason})`);
446
448
  const actionResult = err instanceof EventPreActionError ? err : undefined;
447
449
  this.appendEventHistory(filename, event, actionResult?.kind === "failed" ? "pre_action_failed" : "pre_action_blocked", actionResult?.kind === "failed" ? "error" : "skipped", {
@@ -481,7 +483,9 @@ export class EventsWatcher {
481
483
  conversationId: "",
482
484
  conversationType: "1",
483
485
  };
484
- const enqueued = this.bot.enqueueEvent(syntheticEvent);
486
+ const enqueued = this.options.dispatch
487
+ ? await this.options.dispatch(syntheticEvent)
488
+ : this.bot.enqueueEvent(syntheticEvent);
485
489
  if (enqueued) {
486
490
  this.appendEventHistory(filename, event, "enqueued", "ok", { queue: { accepted: true } });
487
491
  if (deleteAfter) {
@@ -520,7 +524,7 @@ export class EventsWatcher {
520
524
  result = await this.executor.exec(action.command, { timeout: timeoutSeconds });
521
525
  }
522
526
  catch (err) {
523
- throw new EventPreActionError("failed", err instanceof Error ? err.message : String(err), {
527
+ throw new EventPreActionError("failed", errorMessage(err), {
524
528
  durationMs: Date.now() - startedAt,
525
529
  });
526
530
  }
@@ -581,7 +585,7 @@ export class EventsWatcher {
581
585
  /**
582
586
  * Create and start an events watcher.
583
587
  */
584
- export function createEventsWatcher(workspaceDir, bot, executor, commandGuardConfig, historyPath) {
588
+ export function createEventsWatcher(workspaceDir, bot, executor, commandGuardConfig, historyPath, dispatch) {
585
589
  const eventsDir = join(workspaceDir, "events");
586
- return new EventsWatcher(eventsDir, bot, executor, commandGuardConfig, { historyPath });
590
+ return new EventsWatcher(eventsDir, bot, executor, commandGuardConfig, { historyPath, dispatch });
587
591
  }
@@ -5,5 +5,11 @@ export interface HandleTasksCommandOptions {
5
5
  /** Workspace directory; required for `/tasks doctor` because events are workspace-scoped. */
6
6
  workspaceDir?: string;
7
7
  channelId?: string;
8
+ /** Direct command issuer; used to create an auditable external-action approval. */
9
+ approver?: string;
10
+ /** Optional immediate task wake, available in the long-lived DingTalk runtime. */
11
+ dispatchTask?: (id: string) => Promise<boolean>;
8
12
  }
13
+ export declare function pauseTask(options: HandleTasksCommandOptions, idInput: string): Promise<string>;
14
+ export declare function resumeTask(options: HandleTasksCommandOptions, idInput: string): Promise<string>;
9
15
  export declare function handleTasksCommand(options: HandleTasksCommandOptions): Promise<string>;