@oyasmi/pipiclaw 0.9.0 → 0.9.1-beta.2

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 (58) hide show
  1. package/dist/agent/channel-runner.d.ts +5 -1
  2. package/dist/agent/channel-runner.js +36 -2
  3. package/dist/agent/commands.js +3 -1
  4. package/dist/agent/runner-factory.d.ts +0 -2
  5. package/dist/agent/types.d.ts +6 -0
  6. package/dist/memory/lifecycle.d.ts +15 -0
  7. package/dist/memory/lifecycle.js +60 -0
  8. package/dist/memory/task-digest.js +0 -2
  9. package/dist/playbooks/agent-delegation.md +3 -2
  10. package/dist/playbooks/task-driving.md +11 -13
  11. package/dist/playbooks/task-planning.md +3 -5
  12. package/dist/runtime/active-session-store.d.ts +12 -0
  13. package/dist/runtime/active-session-store.js +26 -0
  14. package/dist/runtime/bootstrap.d.ts +1 -1
  15. package/dist/runtime/bootstrap.js +87 -49
  16. package/dist/runtime/channel-event.d.ts +0 -6
  17. package/dist/runtime/delivery.js +1 -1
  18. package/dist/runtime/dingtalk.d.ts +7 -0
  19. package/dist/runtime/dingtalk.js +22 -3
  20. package/dist/runtime/task-commands.d.ts +1 -1
  21. package/dist/runtime/task-commands.js +33 -174
  22. package/dist/runtime/task-driver.d.ts +1 -3
  23. package/dist/runtime/task-driver.js +34 -40
  24. package/dist/runtime/task-migration.d.ts +7 -6
  25. package/dist/runtime/task-migration.js +85 -19
  26. package/dist/runtime/task-wake.d.ts +3 -5
  27. package/dist/runtime/task-wake.js +7 -15
  28. package/dist/subagents/external/run.js +18 -1
  29. package/dist/subagents/runs.js +22 -3
  30. package/dist/subagents/tool.d.ts +10 -0
  31. package/dist/subagents/tool.js +32 -7
  32. package/dist/subagents/verification-outcome.js +17 -10
  33. package/dist/tasks/control.d.ts +18 -67
  34. package/dist/tasks/control.js +44 -176
  35. package/dist/tasks/ledger.d.ts +7 -13
  36. package/dist/tasks/ledger.js +13 -49
  37. package/dist/tasks/store.d.ts +15 -48
  38. package/dist/tasks/store.js +22 -154
  39. package/dist/tasks/transitions.d.ts +3 -4
  40. package/dist/tasks/transitions.js +8 -27
  41. package/dist/tools/index.d.ts +0 -2
  42. package/dist/tools/index.js +2 -1
  43. package/dist/tools/registry.d.ts +0 -1
  44. package/dist/tools/registry.js +0 -1
  45. package/dist/tools/subagent-manage.d.ts +8 -1
  46. package/dist/tools/subagent-manage.js +77 -7
  47. package/dist/tools/task-manage/lifecycle.js +19 -17
  48. package/dist/tools/task-manage/schema.d.ts +2 -6
  49. package/dist/tools/task-manage/schema.js +4 -17
  50. package/dist/tools/task-manage/shared.js +1 -6
  51. package/dist/tools/task-manage/types.d.ts +0 -3
  52. package/dist/tools/task-manage/verification.d.ts +9 -6
  53. package/dist/tools/task-manage/verification.js +19 -71
  54. package/dist/tools/task-manage.d.ts +1 -1
  55. package/dist/tools/task-manage.js +2 -4
  56. package/dist/usage/ledger.d.ts +4 -0
  57. package/dist/usage/ledger.js +3 -0
  58. package/package.json +1 -1
@@ -1,4 +1,3 @@
1
- import { existsSync, mkdirSync, writeFileSync } from "fs";
2
1
  import { join } from "path";
3
2
  import { formatUnknownCommandMessage, isRunnerBuiltInCommand, parseBuiltInCommand, slashCommandName, } from "../agent/commands.js";
4
3
  import { channelEffectCount, noteTaskEffects, taskEffectCount } from "../agent/effect-ledger.js";
@@ -14,6 +13,7 @@ import { MemoryMaintenanceScheduler } from "../memory/scheduler.js";
14
13
  import { defaultModel } from "../models/utils.js";
15
14
  import { loadSecurityConfigWithDiagnostics } from "../security/config.js";
16
15
  import { flushSecurityLogs } from "../security/logger.js";
16
+ import { resolveProjectAccessPolicy } from "../security/project-scope.js";
17
17
  import { PipiclawSettingsManager } from "../settings.js";
18
18
  import { formatConfigDiagnostic } from "../shared/config-diagnostic.js";
19
19
  import { fileStamp } from "../shared/file-stamp.js";
@@ -21,10 +21,10 @@ import { errorMessage } from "../shared/text-utils.js";
21
21
  import { loadDetachedSubAgentDiscovery } from "../subagents/detached-discovery.js";
22
22
  import { configureSubAgentRuntime, getSubAgentRunManager, restoreAllSubAgentRuns, stopSubAgentGarbageCollector, } from "../subagents/runs.js";
23
23
  import { readActiveTasks } from "../tasks/ledger.js";
24
- import { finishTaskAttempt } from "../tasks/store.js";
25
24
  import { getToolsConfigPath, loadToolsConfig, loadToolsConfigWithDiagnostics } from "../tools/config.js";
26
25
  import { getUsageLedger } from "../usage/ledger.js";
27
26
  import { parseUsageMode, renderUsageReport } from "../usage/render.js";
27
+ import { createFreshActiveSession } from "./active-session-store.js";
28
28
  import { BootstrapExitError, bootstrapAppHome, DEFAULT_BOOTSTRAP_PATHS, loadConfig, parseArgs, printBootstrapSummary, readCliVersion, } from "./app-home.js";
29
29
  import { createChannelIndex } from "./channel-index.js";
30
30
  import { ensureChannelDir, getChannelDir } from "./channel-paths.js";
@@ -34,11 +34,12 @@ import { DurableDispatchService } from "./durable-dispatch.js";
34
34
  import { handleEventsCommand as runEventsCommand } from "./event-commands.js";
35
35
  import { createEventsWatcher } from "./events.js";
36
36
  import { handleProjectCommand as runProjectCommand } from "./project-commands.js";
37
+ import { resolveProjectScope } from "./project-scope-store.js";
37
38
  import { installLlmProxy } from "./proxy.js";
38
39
  import { ChannelStore } from "./store.js";
39
40
  import { handleSubagentsCommand as runSubagentsCommand } from "./subagent-commands.js";
40
41
  import { pauseTask, handleTasksCommand as runTasksCommand } from "./task-commands.js";
41
- import { createTaskDriverEvent, createTaskVerificationEvent, TaskDriver } from "./task-driver.js";
42
+ import { createTaskDriverEvent, TaskDriver } from "./task-driver.js";
42
43
  import { migrateLegacyTaskScheduleEvents, migrateLegacyTaskState } from "./task-migration.js";
43
44
  import { claimVerifiedDelegationWake, claimVerifiedJobWake } from "./task-wake.js";
44
45
  const SHUTDOWN_WAIT_MS = 15000;
@@ -139,6 +140,7 @@ export async function createRuntimeContext(options) {
139
140
  const startedAt = Date.now();
140
141
  const cliVersion = readCliVersion();
141
142
  const channelRunners = new Map();
143
+ const sessionResetChains = new Map();
142
144
  const activeTasks = new Set();
143
145
  /** Channels with a `/stop` watchdog in flight, so a burst of `/stop` starts only one. */
144
146
  const stopWatchdogs = new Set();
@@ -177,14 +179,6 @@ export async function createRuntimeContext(options) {
177
179
  // `bot` is defined below in this same scope and initialized before any message
178
180
  // (and thus any getRunner call) can arrive.
179
181
  mediaSender: bot,
180
- dispatchVerification: async (taskId) => {
181
- const entries = await readActiveTasks(join(channelDir, "tasks"));
182
- const entry = entries.find((candidate) => candidate.id === taskId);
183
- if (!entry)
184
- return false;
185
- const verificationEvent = createTaskVerificationEvent(channelId, entry, Date.now());
186
- return (await durableDispatch?.dispatch(verificationEvent)) ?? false;
187
- },
188
182
  });
189
183
  channelRunners.set(channelId, runner);
190
184
  void evictIdleRunnersOverCap(channelRunners);
@@ -251,6 +245,69 @@ export async function createRuntimeContext(options) {
251
245
  }
252
246
  return { pausedTaskId };
253
247
  },
248
+ async handleNewSession(event, _bot) {
249
+ if (shuttingDown)
250
+ return;
251
+ const previous = sessionResetChains.get(event.channelId) ?? Promise.resolve();
252
+ const reset = previous
253
+ .catch(() => undefined)
254
+ .then(async () => {
255
+ try {
256
+ const channelDir = ensureChannelDir(options.paths.workspaceDir, event.channelId);
257
+ ensureChannelMemoryFilesSync(channelDir);
258
+ const access = resolveProjectAccessPolicy(loadSecurityConfigWithDiagnostics(options.paths.appHomeDir).config, process.cwd());
259
+ const scope = resolveProjectScope(channelDir, access);
260
+ if (scope.kind === "blocked") {
261
+ throw new Error(scope.reason);
262
+ }
263
+ // The empty session file and active pointer are committed before the old
264
+ // generation is touched. A filesystem failure therefore leaves the live
265
+ // session authoritative and retryable.
266
+ const result = await createFreshActiveSession(channelDir, scope.scope.projectRoot);
267
+ const oldRunner = channelRunners.get(event.channelId);
268
+ if (oldRunner) {
269
+ channelRunners.delete(event.channelId);
270
+ try {
271
+ oldRunner.retireForNewSession?.();
272
+ }
273
+ catch (error) {
274
+ // The active pointer already names the new session. Retirement is
275
+ // best-effort cleanup and must not misreport the committed reset as failed.
276
+ log.logWarning(`[${event.channelId}] Old runner retirement failed after /new`, errorMessage(error));
277
+ }
278
+ }
279
+ const dropped = _bot.resetChannelQueue(event.channelId);
280
+ if (dropped > 0) {
281
+ log.logInfo(`[${event.channelId}] /new discarded ${dropped} queued old-session message(s)`);
282
+ }
283
+ await _bot.sendPlain(event.channelId, `已开启新会话。\n\nSession ID: \`${result.sessionId}\``);
284
+ void archiveIncomingMessage(event.channelId, {
285
+ date: new Date().toISOString(),
286
+ ts: event.ts,
287
+ user: event.user,
288
+ userName: event.userName,
289
+ text: event.text,
290
+ isBot: false,
291
+ }, "/new command");
292
+ }
293
+ catch (error) {
294
+ const message = errorMessage(error);
295
+ log.logWarning(`[${event.channelId}] Failed to create a fresh session`, message);
296
+ await _bot.sendPlain(event.channelId, `新会话创建失败:${message}\n\n旧会话仍保持不变;请重试 \`/new\`。`);
297
+ }
298
+ });
299
+ sessionResetChains.set(event.channelId, reset);
300
+ activeTasks.add(reset);
301
+ try {
302
+ await reset;
303
+ }
304
+ finally {
305
+ activeTasks.delete(reset);
306
+ if (sessionResetChains.get(event.channelId) === reset) {
307
+ sessionResetChains.delete(event.channelId);
308
+ }
309
+ }
310
+ },
254
311
  async runRuntimeCommand(event, name, args) {
255
312
  switch (name) {
256
313
  case "events":
@@ -265,7 +322,7 @@ export async function createRuntimeContext(options) {
265
322
  channelDir: getChannelDir(options.paths.workspaceDir, event.channelId),
266
323
  workspaceDir: options.paths.workspaceDir,
267
324
  channelId: event.channelId,
268
- dispatchTask: async (id, attemptGeneration) => {
325
+ dispatchTask: async (id) => {
269
326
  const channelDir = getChannelDir(options.paths.workspaceDir, event.channelId);
270
327
  const entry = (await readActiveTasks(join(channelDir, "tasks"))).find((candidate) => candidate.id === id);
271
328
  if (!entry)
@@ -273,7 +330,7 @@ export async function createRuntimeContext(options) {
273
330
  // A human asking to run a task twice means twice, so this key is deliberately
274
331
  // unique per invocation rather than sharing the driver's occurrence key (D1).
275
332
  const now = Date.now();
276
- const driverEvent = createTaskDriverEvent(event.channelId, entry, now, attemptGeneration);
333
+ const driverEvent = createTaskDriverEvent(event.channelId, entry, now);
277
334
  return ((await durableDispatch?.dispatch({
278
335
  ...driverEvent,
279
336
  dispatchId: `task:${event.channelId}:${entry.id}:manual:${new Date(now).toISOString()}`,
@@ -345,6 +402,13 @@ export async function createRuntimeContext(options) {
345
402
  await bot.sendPlain(event.channelId, `无法排队:/${commandName} 需要带上消息内容。`);
346
403
  return { kind: "handled" };
347
404
  }
405
+ // Compaction is maintenance, not user work. A new message cancels it and is
406
+ // kept as a normal queued turn instead of trying to steer an agent loop that
407
+ // is currently disconnected for summarization.
408
+ if (runner.interruptCompaction?.()) {
409
+ log.logInfo(`[${event.channelId}] Interrupted compaction for a new user message`);
410
+ return { kind: "requeue", text: trimmedQueueText };
411
+ }
348
412
  if (mode === "followUp") {
349
413
  log.logEvent("info", "agent.turn.followup_queued", "Follow-up queued", {
350
414
  ctx: { channelId: event.channelId, userName: event.userName },
@@ -451,7 +515,7 @@ export async function createRuntimeContext(options) {
451
515
  // y." or "[SUBAGENT:x] ... belongs to task y." — including another user, or an
452
516
  // external agent's own untrusted stdout (spec 040, D8's threat model explicitly
453
517
  // treats external output as untrusted). Activating a waiting task on text pattern
454
- // alone lets that forged claim advance an unrelated task's attempt generation. The
518
+ // alone lets that forged claim wake an unrelated task early. The
455
519
  // pattern match only extracts a *candidate* id pair now; both paths verify the
456
520
  // named run/job actually exists, is done, and really is the one that names this
457
521
  // taskId before ever calling `activateWaitingTask` (T9).
@@ -466,8 +530,6 @@ export async function createRuntimeContext(options) {
466
530
  if (claimed) {
467
531
  if (claimed.activated)
468
532
  recoveredJobTaskId = claimed.taskId;
469
- if (claimed.generation !== undefined)
470
- event.taskAttemptGeneration = claimed.generation;
471
533
  await claimed.finish();
472
534
  structuredWakeFinalized = true;
473
535
  if (event.internalWake?.kind === "job" && !claimed.activated)
@@ -495,8 +557,6 @@ export async function createRuntimeContext(options) {
495
557
  if (claimed) {
496
558
  if (claimed.activated)
497
559
  recoveredDelegationTaskId = claimed.taskId;
498
- if (claimed.generation !== undefined)
499
- event.taskAttemptGeneration = claimed.generation;
500
560
  await claimed.finish();
501
561
  structuredWakeFinalized = true;
502
562
  if (event.internalWake?.kind === "subagent" && !claimed.activated)
@@ -519,18 +579,6 @@ export async function createRuntimeContext(options) {
519
579
  if (taskAttemptId) {
520
580
  noteTaskEffects(event.channelId, taskAttemptId, channelEffectCount(event.channelId) - effectsBefore);
521
581
  }
522
- if (taskAttemptId && result.usage && result.durationMs !== undefined) {
523
- await finishTaskAttempt(getChannelDir(options.paths.workspaceDir, event.channelId), taskAttemptId, {
524
- tokens: result.usage.total,
525
- costUsd: result.usage.cost.total,
526
- costKnown: result.costKnown === true,
527
- wallTimeMinutes: result.durationMs / 60_000,
528
- failed: result.stopReason === "error" || result.stopReason === "aborted",
529
- silent: result.silent,
530
- finishedAt: new Date(),
531
- generation: event.taskAttemptGeneration,
532
- });
533
- }
534
582
  if (result.stopReason === "aborted" && runner.getTurnStatus().stopRequested) {
535
583
  log.logInfo(`[${event.channelId}] Stopped`);
536
584
  }
@@ -760,25 +808,15 @@ export async function createRuntimeContext(options) {
760
808
  });
761
809
  }
762
810
  if (startServices) {
763
- // One-time close of the 027/038 migration windows: fold any residual legacy `.schedule`
764
- // events into task frontmatter, and upgrade v1 task status vocabulary, before the driver
765
- // relies on the v2 contract alone. Both scan every channel's tasks/events, so they are
766
- // gated on a marker file rather than repeated on every restart once a home has migrated.
767
- const taskMigrationMarkerPath = join(options.paths.appHomeDir, "state", "task-migration.done");
768
- if (!existsSync(taskMigrationMarkerPath)) {
769
- void Promise.all([
770
- migrateLegacyTaskScheduleEvents(options.paths.workspaceDir),
771
- migrateLegacyTaskState(options.paths.workspaceDir),
772
- ]).then(() => {
773
- try {
774
- mkdirSync(join(options.paths.appHomeDir, "state"), { recursive: true });
775
- writeFileSync(taskMigrationMarkerPath, `${new Date().toISOString()}\n`);
776
- }
777
- catch (error) {
778
- log.logWarning("Failed to write task migration marker", errorMessage(error));
779
- }
780
- });
781
- }
811
+ // Close the 027/038 migration windows: fold any residual legacy `.schedule` events into task
812
+ // frontmatter, and upgrade any task still on the legacy control/status vocabulary, before the
813
+ // driver relies on the current contract alone. Version-gated, not marker-gated (spec 043,
814
+ // phase 5): each file is judged by what it actually contains, so this is safe and cheap to run
815
+ // on every startup — a hand-edited or freshly-restored legacy file self-heals on the next boot.
816
+ void Promise.all([
817
+ migrateLegacyTaskScheduleEvents(options.paths.workspaceDir),
818
+ migrateLegacyTaskState(options.paths.workspaceDir),
819
+ ]);
782
820
  eventsWatcher.start();
783
821
  memoryMaintenanceScheduler.start();
784
822
  taskDriver.start();
@@ -32,10 +32,4 @@ export interface ChannelEvent {
32
32
  taskId: string;
33
33
  dispatchId: string;
34
34
  };
35
- /**
36
- * The `attemptGeneration` this event's claim recorded, for `[TASK_DRIVER:id]` events only.
37
- * Carried through durable dispatch so `finishTaskAttempt` can tell a stale, superseded claim's
38
- * turn from the current one, even when redelivery or claim races reorder completions.
39
- */
40
- taskAttemptGeneration?: number;
41
35
  }
@@ -63,7 +63,7 @@ class ChannelDeliveryController {
63
63
  respondPlain: async (text, shouldLog = true) => this.sendFinal(text, shouldLog),
64
64
  replaceMessage: async (text) => this.replaceWithFinal(text),
65
65
  respondInThread: async (text) => {
66
- if (!text.trim()) {
66
+ if (this.closed || !text.trim()) {
67
67
  return;
68
68
  }
69
69
  const delivered = await this.bot.sendPlain(this.event.channelId, text);
@@ -60,6 +60,8 @@ export interface DingTalkHandler {
60
60
  reserveEvent?(event: DingTalkEvent): void;
61
61
  handleEvent(event: DingTalkEvent, bot: DingTalkBot, isEvent?: boolean): Promise<void>;
62
62
  handleStop(channelId: string, bot: DingTalkBot): Promise<StopOutcome>;
63
+ /** `/new` bypasses the old per-channel queue and live SDK session. */
64
+ handleNewSession(event: DingTalkEvent, bot: DingTalkBot): Promise<void>;
63
65
  /**
64
66
  * Render one of the stateless report commands (events/tasks/status/usage/context/subagents) to
65
67
  * text. Single dispatch point shared by the busy-turn switch below and bootstrap's idle-turn
@@ -185,6 +187,11 @@ export declare class DingTalkBot implements MediaSender {
185
187
  * do not run after the user halts the current task. Returns dropped count.
186
188
  */
187
189
  clearPendingMessages(channelId: string): number;
190
+ /**
191
+ * Detach all queued work from the previous session generation. The in-flight callback may
192
+ * still unwind on its old queue object, while subsequent messages get a fresh queue.
193
+ */
194
+ resetChannelQueue(channelId: string): number;
188
195
  private getQueue;
189
196
  private getConversationMeta;
190
197
  private setConversationMeta;
@@ -11,7 +11,7 @@ import axios from "axios";
11
11
  import { DWClient, TOPIC_ROBOT } from "dingtalk-stream";
12
12
  import { existsSync, mkdirSync, readFileSync, writeFileSync } from "fs";
13
13
  import { dirname, join } from "path";
14
- import { formatBusyCommandList, parseBuiltInCommand, renderBuiltInHelp, } from "../agent/commands.js";
14
+ import { formatBusyCommandList, parseBuiltInCommand, renderBuiltInHelp, slashCommandName, } from "../agent/commands.js";
15
15
  import * as log from "../log.js";
16
16
  import { errorMessage } from "../shared/text-utils.js";
17
17
  import { isRecord } from "../shared/type-guards.js";
@@ -1069,6 +1069,13 @@ export class DingTalkBot {
1069
1069
  };
1070
1070
  const builtInCommand = parseBuiltInCommand(content);
1071
1071
  const isSlashCommand = content.trim().startsWith("/");
1072
+ // `/new` is an emergency boundary as well as a session command. Route it before
1073
+ // busy checking and before the old channel queue, so a wedged compaction/provider
1074
+ // request cannot prevent recovery.
1075
+ if (slashCommandName(content) === "new") {
1076
+ await this.handler.handleNewSession(event, this);
1077
+ return;
1078
+ }
1072
1079
  // Check if busy
1073
1080
  if (this.handler.isRunning(channelId)) {
1074
1081
  // All built-in transport commands are usable while a task streams.
@@ -1106,10 +1113,10 @@ export class DingTalkBot {
1106
1113
  }
1107
1114
  }
1108
1115
  }
1109
- // Session commands (/model, /new, …) and unknown slash commands cannot
1116
+ // Other session commands (/model, /compact, …) and unknown slash commands cannot
1110
1117
  // run mid-turn: they would need the idle session layer.
1111
1118
  if (isSlashCommand) {
1112
- await this.sendPlain(channelId, `当前已有回合在运行。运行中可用:${formatBusyCommandList()}。会话命令(\`/model\`、\`/new\`、\`/compact\`、\`/session\`)需要等空闲后再用。`);
1119
+ await this.sendPlain(channelId, `当前已有回合在运行。运行中可用:${formatBusyCommandList()}。会话命令(\`/model\`、\`/compact\`、\`/session\`)需要等空闲后再用。`);
1113
1120
  return;
1114
1121
  }
1115
1122
  const result = await this.handler.handleBusyMessage(event, this, this.busyMessageDefault, content);
@@ -1129,6 +1136,18 @@ export class DingTalkBot {
1129
1136
  const queue = this.queues.get(channelId);
1130
1137
  return queue ? queue.clearPending() : 0;
1131
1138
  }
1139
+ /**
1140
+ * Detach all queued work from the previous session generation. The in-flight callback may
1141
+ * still unwind on its old queue object, while subsequent messages get a fresh queue.
1142
+ */
1143
+ resetChannelQueue(channelId) {
1144
+ const queue = this.queues.get(channelId);
1145
+ const dropped = queue?.clearPending() ?? 0;
1146
+ queue?.stop();
1147
+ this.queues.delete(channelId);
1148
+ this.discardCard(channelId);
1149
+ return dropped;
1150
+ }
1132
1151
  getQueue(channelId) {
1133
1152
  this.touchChannel(channelId);
1134
1153
  let queue = this.queues.get(channelId);
@@ -6,7 +6,7 @@ export interface HandleTasksCommandOptions {
6
6
  workspaceDir?: string;
7
7
  channelId?: string;
8
8
  /** Optional immediate task wake, available in the long-lived DingTalk runtime. */
9
- dispatchTask?: (id: string, attemptGeneration?: number) => Promise<boolean>;
9
+ dispatchTask?: (id: string) => Promise<boolean>;
10
10
  }
11
11
  export declare function pauseTask(options: HandleTasksCommandOptions, idInput: string): Promise<string>;
12
12
  export declare function resumeTask(options: HandleTasksCommandOptions, idInput: string): Promise<string>;