@oyasmi/pipiclaw 0.9.0-beta.5 → 0.9.0-beta.7

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 (76) hide show
  1. package/README.md +146 -177
  2. package/dist/agent/channel-runner.d.ts +8 -0
  3. package/dist/agent/channel-runner.js +154 -132
  4. package/dist/agent/commands.d.ts +6 -0
  5. package/dist/agent/job-manager.js +6 -10
  6. package/dist/agent/progress-formatter.js +3 -3
  7. package/dist/index.d.ts +2 -1
  8. package/dist/index.js +2 -1
  9. package/dist/main.js +2 -1
  10. package/dist/memory/extraction.js +0 -1
  11. package/dist/memory/maintenance-gates.d.ts +1 -1
  12. package/dist/memory/maintenance-jobs.js +2 -3
  13. package/dist/memory/metadata.d.ts +0 -15
  14. package/dist/memory/metadata.js +0 -7
  15. package/dist/memory/probation.d.ts +1 -5
  16. package/dist/memory/probation.js +2 -6
  17. package/dist/models/auth-cli.d.ts +1 -1
  18. package/dist/models/auth-cli.js +3 -2
  19. package/dist/paths.d.ts +0 -6
  20. package/dist/paths.js +0 -6
  21. package/dist/playbooks/agent-delegation.md +9 -8
  22. package/dist/playbooks/background-jobs.md +1 -1
  23. package/dist/playbooks/catalog.d.ts +2 -2
  24. package/dist/playbooks/catalog.js +20 -9
  25. package/dist/playbooks/event-scheduling.md +1 -1
  26. package/dist/playbooks/memory-and-learning.md +1 -1
  27. package/dist/playbooks/outbound-media.md +5 -5
  28. package/dist/playbooks/runtime-orientation.md +1 -1
  29. package/dist/playbooks/task-driving.md +1 -1
  30. package/dist/playbooks/task-planning.md +1 -1
  31. package/dist/runtime/app-home.d.ts +32 -0
  32. package/dist/runtime/app-home.js +319 -0
  33. package/dist/runtime/bootstrap.d.ts +3 -69
  34. package/dist/runtime/bootstrap.js +113 -511
  35. package/dist/runtime/delivery.js +1 -1
  36. package/dist/runtime/dingtalk.d.ts +7 -6
  37. package/dist/runtime/dingtalk.js +5 -13
  38. package/dist/runtime/task-wake.d.ts +54 -0
  39. package/dist/runtime/task-wake.js +99 -0
  40. package/dist/shared/host-process.d.ts +5 -5
  41. package/dist/shared/host-process.js +19 -0
  42. package/dist/shared/wake-claim.d.ts +23 -0
  43. package/dist/shared/wake-claim.js +26 -0
  44. package/dist/subagents/discovery.d.ts +9 -1
  45. package/dist/subagents/discovery.js +37 -9
  46. package/dist/subagents/external/claude-code.js +4 -5
  47. package/dist/subagents/external/codex-cli.js +1 -7
  48. package/dist/subagents/external/exec.js +7 -2
  49. package/dist/subagents/external/harness.d.ts +0 -3
  50. package/dist/subagents/external/harness.js +18 -3
  51. package/dist/subagents/external/run.d.ts +5 -0
  52. package/dist/subagents/external/run.js +70 -31
  53. package/dist/subagents/runs.d.ts +40 -9
  54. package/dist/subagents/runs.js +194 -31
  55. package/dist/subagents/tool.d.ts +3 -1
  56. package/dist/subagents/tool.js +33 -14
  57. package/dist/tools/memory-manage.js +0 -1
  58. package/dist/tools/subagent-manage.js +18 -1
  59. package/dist/tui/app.d.ts +1 -1
  60. package/dist/tui/app.js +3 -2
  61. package/dist/tui/cli.d.ts +1 -1
  62. package/dist/tui/cli.js +1 -1
  63. package/dist/tui/terminal-media-sender.d.ts +1 -1
  64. package/examples/sub-agents/README.md +25 -16
  65. package/examples/sub-agents/builder-hard.md +9 -8
  66. package/examples/sub-agents/builder.md +12 -11
  67. package/examples/sub-agents/documenter.md +11 -14
  68. package/examples/sub-agents/explorer.md +16 -13
  69. package/examples/sub-agents/git-committer.md +18 -16
  70. package/examples/sub-agents/log-sifter.md +19 -16
  71. package/examples/sub-agents/planner.md +17 -17
  72. package/examples/sub-agents/reviewer.md +13 -23
  73. package/examples/sub-agents/scout.md +5 -6
  74. package/examples/sub-agents/verifier.md +8 -14
  75. package/examples/sub-agents/worker.md +7 -8
  76. package/package.json +1 -1
@@ -379,151 +379,173 @@ export class ChannelRunner {
379
379
  });
380
380
  }
381
381
  finally {
382
- this.setPhase(ownTurn, "finishing");
383
- // Debug dump (PIPICLAW_DEBUG=1). Written after the run so `systemPrompt` is the
384
- // string the provider actually received — base sections, pi's tail, and the boundary
385
- // footer the prompt extension appends at before_agent_start.
386
- if (process.env.PIPICLAW_DEBUG) {
387
- const debugContext = {
388
- systemPrompt: this.lastFinalPrompt ?? this.agent.state.systemPrompt,
389
- promptManifest: this.lastPromptBuild
390
- ? buildPromptManifest(this.lastPromptBuild, this.lastFinalPrompt)
391
- : undefined,
392
- messages: this.session.messages,
393
- durableMemoryBootstrap: durableMemoryBootstrapText || undefined,
394
- taskDigest: taskDigestText || undefined,
395
- recalledContext: recalledContextText || undefined,
396
- newUserMessage: promptText,
397
- };
398
- await writeFile(join(this.channelDir, "last_prompt.json"), JSON.stringify(debugContext, null, 2)).catch((error) => log.logWarning(`[${this.channelId}] Failed to write last_prompt.json`, errorMessage(error)));
399
- }
400
- if (!promptSubmitted) {
401
- const discarded = this.session.clearQueue();
402
- const discardedCount = discarded.steering.length + discarded.followUp.length;
403
- if (discardedCount > 0) {
404
- log.logWarning(`[${this.channelId}] Discarded ${discardedCount} queued busy message(s) after run setup failed`);
405
- }
382
+ await this.finishTurn({
383
+ ctx,
384
+ ownTurn,
385
+ implicitTurn,
386
+ promptSubmitted,
387
+ runQueue,
388
+ fallbackAttempted,
389
+ fallbackTargetRef,
390
+ promptText,
391
+ durableMemoryBootstrapText,
392
+ taskDigestText,
393
+ recalledContextText,
394
+ });
395
+ }
396
+ return {
397
+ stopReason: this.runState.stopReason,
398
+ errorMessage: this.runState.errorMessage,
399
+ usage: { ...this.runState.totalUsage, cost: { ...this.runState.totalUsage.cost } },
400
+ costKnown: this.runState.usageSources > 0 && this.runState.costKnown,
401
+ durationMs: Date.now() - startedAt,
402
+ silent: this.runState.finalOutcome.kind === "silent",
403
+ };
404
+ }
405
+ /**
406
+ * The epilogue shared by every exit path out of `run()`'s try/catch: debug dump, delivery of
407
+ * whatever final message the turn settled on, usage/ledger accounting, the end-of-turn memory
408
+ * flush, and clearing run state. Pulled out of `run()` itself only to keep that method's main
409
+ * line (prepare → prompt with fallback) readable; every input here is `run()`-local, not
410
+ * instance state, so it is threaded through explicitly rather than promoted to a field.
411
+ */
412
+ async finishTurn(input) {
413
+ const { ctx, ownTurn, implicitTurn, promptSubmitted, runQueue, fallbackAttempted, fallbackTargetRef } = input;
414
+ this.setPhase(ownTurn, "finishing");
415
+ // Debug dump (PIPICLAW_DEBUG=1). Written after the run so `systemPrompt` is the
416
+ // string the provider actually received — base sections, pi's tail, and the boundary
417
+ // footer the prompt extension appends at before_agent_start.
418
+ if (process.env.PIPICLAW_DEBUG) {
419
+ const debugContext = {
420
+ systemPrompt: this.lastFinalPrompt ?? this.agent.state.systemPrompt,
421
+ promptManifest: this.lastPromptBuild
422
+ ? buildPromptManifest(this.lastPromptBuild, this.lastFinalPrompt)
423
+ : undefined,
424
+ messages: this.session.messages,
425
+ durableMemoryBootstrap: input.durableMemoryBootstrapText || undefined,
426
+ taskDigest: input.taskDigestText || undefined,
427
+ recalledContext: input.recalledContextText || undefined,
428
+ newUserMessage: input.promptText,
429
+ };
430
+ await writeFile(join(this.channelDir, "last_prompt.json"), JSON.stringify(debugContext, null, 2)).catch((error) => log.logWarning(`[${this.channelId}] Failed to write last_prompt.json`, errorMessage(error)));
431
+ }
432
+ if (!promptSubmitted) {
433
+ const discarded = this.session.clearQueue();
434
+ const discardedCount = discarded.steering.length + discarded.followUp.length;
435
+ if (discardedCount > 0) {
436
+ log.logWarning(`[${this.channelId}] Discarded ${discardedCount} queued busy message(s) after run setup failed`);
406
437
  }
407
- await runQueue.drain();
408
- const finalOutcome = this.runState.finalOutcome;
409
- const finalOutcomeText = getFinalOutcomeText(finalOutcome);
410
- try {
411
- if (this.runState.stopReason === "error" &&
412
- this.runState.errorMessage &&
413
- !this.runState.finalResponseDelivered) {
414
- try {
415
- const baseErrorSummary = this.runState.errorMessage.length > 240
416
- ? `${this.runState.errorMessage.slice(0, 237)}...`
417
- : this.runState.errorMessage;
418
- const compactionSummary = this.runState.lastCompactionError &&
419
- this.runState.lastCompactionError !== this.runState.errorMessage
420
- ? this.runState.lastCompactionError.length > 240
421
- ? `${this.runState.lastCompactionError.slice(0, 237)}...`
422
- : this.runState.lastCompactionError
423
- : undefined;
424
- const detailLines = [`\`${baseErrorSummary}\``];
425
- if (compactionSummary) {
426
- detailLines.push(`恢复尝试:\`${compactionSummary}\``);
427
- }
428
- if (fallbackAttempted && fallbackTargetRef) {
429
- detailLines.push(`已切换备用模型 \`${fallbackTargetRef}\` 重试,仍失败。`);
430
- }
431
- await ctx.replaceMessage(`_抱歉,出错了。_\n\n${detailLines.join("\n\n")}`);
438
+ }
439
+ await runQueue.drain();
440
+ const finalOutcome = this.runState.finalOutcome;
441
+ const finalOutcomeText = getFinalOutcomeText(finalOutcome);
442
+ try {
443
+ if (this.runState.stopReason === "error" &&
444
+ this.runState.errorMessage &&
445
+ !this.runState.finalResponseDelivered) {
446
+ try {
447
+ const baseErrorSummary = this.runState.errorMessage.length > 240
448
+ ? `${this.runState.errorMessage.slice(0, 237)}...`
449
+ : this.runState.errorMessage;
450
+ const compactionSummary = this.runState.lastCompactionError && this.runState.lastCompactionError !== this.runState.errorMessage
451
+ ? this.runState.lastCompactionError.length > 240
452
+ ? `${this.runState.lastCompactionError.slice(0, 237)}...`
453
+ : this.runState.lastCompactionError
454
+ : undefined;
455
+ const detailLines = [`\`${baseErrorSummary}\``];
456
+ if (compactionSummary) {
457
+ detailLines.push(`恢复尝试:\`${compactionSummary}\``);
432
458
  }
433
- catch (err) {
434
- const errMsg = errorMessage(err);
435
- log.logWarning("Failed to post error message", errMsg);
459
+ if (fallbackAttempted && fallbackTargetRef) {
460
+ detailLines.push(`已切换备用模型 \`${fallbackTargetRef}\` 重试,仍失败。`);
436
461
  }
462
+ await ctx.replaceMessage(`_抱歉,出错了。_\n\n${detailLines.join("\n\n")}`);
437
463
  }
438
- else if (isSilentOutcome(finalOutcome)) {
439
- try {
440
- await ctx.deleteMessage();
441
- log.logInfo("Silent response - deleted message");
442
- }
443
- catch (err) {
444
- const errMsg = errorMessage(err);
445
- log.logWarning("Failed to delete message for silent response", errMsg);
446
- }
464
+ catch (err) {
465
+ const errMsg = errorMessage(err);
466
+ log.logWarning("Failed to post error message", errMsg);
447
467
  }
448
- else if (this.runState.stopReason === "aborted" && !this.runState.finalResponseDelivered) {
449
- try {
450
- await ctx.deleteMessage();
451
- log.logInfo("Aborted response - discarded active delivery state");
452
- }
453
- catch (err) {
454
- const errMsg = errorMessage(err);
455
- log.logWarning("Failed to discard active delivery state after abort", errMsg);
456
- }
468
+ }
469
+ else if (isSilentOutcome(finalOutcome)) {
470
+ try {
471
+ await ctx.deleteMessage();
472
+ log.logInfo("Silent response - deleted message");
457
473
  }
458
- else if (finalOutcomeText && !this.runState.finalResponseDelivered) {
459
- try {
460
- await ctx.replaceMessage(finalOutcomeText);
461
- }
462
- catch (err) {
463
- const errMsg = errorMessage(err);
464
- log.logWarning("Failed to replace message with final text", errMsg);
465
- }
474
+ catch (err) {
475
+ const errMsg = errorMessage(err);
476
+ log.logWarning("Failed to delete message for silent response", errMsg);
466
477
  }
467
- await ctx.flush();
468
478
  }
469
- finally {
470
- await ctx.close();
479
+ else if (this.runState.stopReason === "aborted" && !this.runState.finalResponseDelivered) {
480
+ try {
481
+ await ctx.deleteMessage();
482
+ log.logInfo("Aborted response - discarded active delivery state");
483
+ }
484
+ catch (err) {
485
+ const errMsg = errorMessage(err);
486
+ log.logWarning("Failed to discard active delivery state after abort", errMsg);
487
+ }
471
488
  }
472
- // Log usage summary. Gated on tokens as well as cost: a local (or pricing-less) model
473
- // bills nothing, and skipping it here left both the log and the ledger empty.
474
- if (this.runState.totalUsage.cost.total > 0 || this.runState.totalUsage.total > 0) {
475
- const lastAssistantMessage = getLastAssistantUsage(this.session.messages);
476
- const contextTokens = lastAssistantMessage
477
- ? lastAssistantMessage.usage.input +
478
- lastAssistantMessage.usage.output +
479
- lastAssistantMessage.usage.cacheRead +
480
- lastAssistantMessage.usage.cacheWrite
481
- : 0;
482
- const currentRunModel = this.session.model ?? this.activeModel;
483
- const contextWindow = currentRunModel.contextWindow || 200000;
484
- log.logUsageSummary(this.runState.logCtx, this.runState.totalUsage, contextTokens, contextWindow);
485
- const responseModel = lastAssistantMessage?.responseModel;
486
- // Ledger turn entry: assistant-only usage (sub-agents recorded separately),
487
- // keeping Σ(entries) == real spend with no double counting.
488
- this.ledger.record({
489
- channelId: this.channelId,
490
- kind: "turn",
491
- model: responseModel ?? formatModelReference(currentRunModel),
492
- usage: {
493
- input: this.runState.assistantUsage.input,
494
- output: this.runState.assistantUsage.output,
495
- cacheRead: this.runState.assistantUsage.cacheRead,
496
- cacheWrite: this.runState.assistantUsage.cacheWrite,
497
- total: this.runState.assistantUsage.total,
498
- },
499
- cost: { ...this.runState.assistantUsage.cost },
500
- });
501
- if (responseModel &&
502
- responseModel !== formatModelReference(currentRunModel) &&
503
- responseModel !== currentRunModel.id) {
504
- log.logInfo(`[${this.channelId}] Actual model: ${responseModel} (configured: ${formatModelReference(currentRunModel)})`);
489
+ else if (finalOutcomeText && !this.runState.finalResponseDelivered) {
490
+ try {
491
+ await ctx.replaceMessage(finalOutcomeText);
492
+ }
493
+ catch (err) {
494
+ const errMsg = errorMessage(err);
495
+ log.logWarning("Failed to replace message with final text", errMsg);
505
496
  }
506
497
  }
507
- // The turn is over, so the channel is about to look idle to the maintenance gates —
508
- // which is exactly when this state has to be on disk. Everything buffered during the
509
- // turn lands here in one write.
510
- await this.flushMemoryActivity();
511
- // Clear run state
512
- this.runState.ctx = null;
513
- this.runState.logCtx = null;
514
- this.runState.queue = null;
515
- if (implicitTurn) {
516
- this.endTurn();
498
+ await ctx.flush();
499
+ }
500
+ finally {
501
+ await ctx.close();
502
+ }
503
+ // Log usage summary. Gated on tokens as well as cost: a local (or pricing-less) model
504
+ // bills nothing, and skipping it here left both the log and the ledger empty.
505
+ if (this.runState.totalUsage.cost.total > 0 || this.runState.totalUsage.total > 0) {
506
+ const lastAssistantMessage = getLastAssistantUsage(this.session.messages);
507
+ const contextTokens = lastAssistantMessage
508
+ ? lastAssistantMessage.usage.input +
509
+ lastAssistantMessage.usage.output +
510
+ lastAssistantMessage.usage.cacheRead +
511
+ lastAssistantMessage.usage.cacheWrite
512
+ : 0;
513
+ const currentRunModel = this.session.model ?? this.activeModel;
514
+ const contextWindow = currentRunModel.contextWindow || 200000;
515
+ log.logUsageSummary(this.runState.logCtx, this.runState.totalUsage, contextTokens, contextWindow);
516
+ const responseModel = lastAssistantMessage?.responseModel;
517
+ // Ledger turn entry: assistant-only usage (sub-agents recorded separately),
518
+ // keeping Σ(entries) == real spend with no double counting.
519
+ this.ledger.record({
520
+ channelId: this.channelId,
521
+ kind: "turn",
522
+ model: responseModel ?? formatModelReference(currentRunModel),
523
+ usage: {
524
+ input: this.runState.assistantUsage.input,
525
+ output: this.runState.assistantUsage.output,
526
+ cacheRead: this.runState.assistantUsage.cacheRead,
527
+ cacheWrite: this.runState.assistantUsage.cacheWrite,
528
+ total: this.runState.assistantUsage.total,
529
+ },
530
+ cost: { ...this.runState.assistantUsage.cost },
531
+ });
532
+ if (responseModel &&
533
+ responseModel !== formatModelReference(currentRunModel) &&
534
+ responseModel !== currentRunModel.id) {
535
+ log.logInfo(`[${this.channelId}] Actual model: ${responseModel} (configured: ${formatModelReference(currentRunModel)})`);
517
536
  }
518
537
  }
519
- return {
520
- stopReason: this.runState.stopReason,
521
- errorMessage: this.runState.errorMessage,
522
- usage: { ...this.runState.totalUsage, cost: { ...this.runState.totalUsage.cost } },
523
- costKnown: this.runState.usageSources > 0 && this.runState.costKnown,
524
- durationMs: Date.now() - startedAt,
525
- silent: this.runState.finalOutcome.kind === "silent",
526
- };
538
+ // The turn is over, so the channel is about to look idle to the maintenance gates —
539
+ // which is exactly when this state has to be on disk. Everything buffered during the
540
+ // turn lands here in one write.
541
+ await this.flushMemoryActivity();
542
+ // Clear run state
543
+ this.runState.ctx = null;
544
+ this.runState.logCtx = null;
545
+ this.runState.queue = null;
546
+ if (implicitTurn) {
547
+ this.endTurn();
548
+ }
527
549
  }
528
550
  async handleBuiltinCommand(ctx, command) {
529
551
  try {
@@ -1,6 +1,12 @@
1
1
  export type BuiltInCommandName = "help" | "steer" | "followup" | "stop" | "events" | "tasks" | "status" | "usage" | "context" | "subagents";
2
2
  /** The four transport commands handled by `ChannelRunner.handleBuiltinCommand`. */
3
3
  export type RunnerBuiltInCommandName = "help" | "stop" | "steer" | "followup" | "context";
4
+ /**
5
+ * The commands with no mid-turn state to touch: each renders a text report from disk/in-memory
6
+ * state and is dispatched the same way whether a turn is running or the channel is idle. Derived
7
+ * from `BuiltInCommandName` rather than hand-listed, so it can never drift from the source table.
8
+ */
9
+ export type RuntimeCommandName = Exclude<BuiltInCommandName, "help" | "steer" | "followup" | "stop">;
4
10
  export interface BuiltInCommand {
5
11
  name: BuiltInCommandName;
6
12
  args: string;
@@ -8,6 +8,7 @@ import { createSerialQueue } from "../shared/serial-queue.js";
8
8
  import { shellEscape } from "../shared/shell-escape.js";
9
9
  import { errorMessage } from "../shared/text-utils.js";
10
10
  import { isRecord } from "../shared/type-guards.js";
11
+ import { beginWakeClaim, finishWakeClaim } from "../shared/wake-claim.js";
11
12
  /** Cap on concurrently running jobs per channel, so a runaway model can't spawn unbounded processes. */
12
13
  export const MAX_RUNNING_JOBS = 5;
13
14
  /** Longest a single `poll` call blocks before returning a snapshot; the model can poll again. */
@@ -394,16 +395,12 @@ export class ChannelJobManager {
394
395
  return this.wakeQueue.run(id, async () => {
395
396
  const record = this.jobs.get(id);
396
397
  const expected = `job:${this.channelId}:${id}:done`;
397
- if (!record ||
398
- record.status === "running" ||
399
- record.contract.taskId !== taskId ||
400
- dispatchId !== expected ||
401
- record.wakeConsumedAt ||
402
- (record.wakeClaimDispatchId && record.wakeClaimDispatchId !== dispatchId)) {
398
+ if (!record)
403
399
  return false;
404
- }
400
+ const eligible = record.status !== "running" && record.contract.taskId === taskId && dispatchId === expected;
405
401
  const previousClaim = record.wakeClaimDispatchId;
406
- record.wakeClaimDispatchId = dispatchId;
402
+ if (!beginWakeClaim(record, eligible, dispatchId))
403
+ return false;
407
404
  try {
408
405
  await this.persist(record, true);
409
406
  }
@@ -417,9 +414,8 @@ export class ChannelJobManager {
417
414
  async finishWakeConsumption(id, dispatchId) {
418
415
  await this.wakeQueue.run(id, async () => {
419
416
  const record = this.jobs.get(id);
420
- if (!record || record.wakeClaimDispatchId !== dispatchId || record.wakeConsumedAt)
417
+ if (!record || !finishWakeClaim(record, dispatchId))
421
418
  return;
422
- record.wakeConsumedAt = Date.now();
423
419
  try {
424
420
  await this.persist(record, true);
425
421
  }
@@ -32,11 +32,11 @@ export function formatProgressEntry(kind, text) {
32
32
  const normalized = cleaned.replace(/\n+/g, " ").trim();
33
33
  switch (kind) {
34
34
  case "tool":
35
- return `▶ ${normalized}`;
35
+ return `➜ ${normalized}`;
36
36
  case "thinking":
37
- return `● ${normalized}`;
37
+ return `✦ ${normalized}`;
38
38
  case "error":
39
- return `✖ ${normalized}`;
39
+ return `✕ ${normalized}`;
40
40
  case "assistant":
41
41
  return normalized;
42
42
  }
package/dist/index.d.ts CHANGED
@@ -10,7 +10,8 @@
10
10
  * because `src/index.ts` is a knip entry point.
11
11
  */
12
12
  export { APP_HOME_DIR, APP_NAME, AUTH_CONFIG_PATH, CHANNEL_CONFIG_PATH, MODELS_CONFIG_PATH, SECURITY_CONFIG_PATH, SETTINGS_CONFIG_PATH, TOOLS_CONFIG_PATH, WORKSPACE_DIR, } from "./paths.js";
13
- export { type AppContext, type BootstrapOptions, type BootstrapPaths, type BootstrapResult, bootstrap, isBootstrapExitError, } from "./runtime/bootstrap.js";
13
+ export { type BootstrapPaths, type BootstrapResult, isBootstrapExitError } from "./runtime/app-home.js";
14
+ export { type AppContext, type BootstrapOptions, bootstrap } from "./runtime/bootstrap.js";
14
15
  export type { ChannelContext, FinalDelivery, ProgressStyle } from "./runtime/channel-context.js";
15
16
  export { DingTalkBot, type DingTalkConfig, type DingTalkEvent, type DingTalkHandler, type ResponseMode, } from "./runtime/dingtalk.js";
16
17
  export type { PipiclawSettings } from "./settings.js";
package/dist/index.js CHANGED
@@ -10,5 +10,6 @@
10
10
  * because `src/index.ts` is a knip entry point.
11
11
  */
12
12
  export { APP_HOME_DIR, APP_NAME, AUTH_CONFIG_PATH, CHANNEL_CONFIG_PATH, MODELS_CONFIG_PATH, SECURITY_CONFIG_PATH, SETTINGS_CONFIG_PATH, TOOLS_CONFIG_PATH, WORKSPACE_DIR, } from "./paths.js";
13
- export { bootstrap, isBootstrapExitError, } from "./runtime/bootstrap.js";
13
+ export { isBootstrapExitError } from "./runtime/app-home.js";
14
+ export { bootstrap } from "./runtime/bootstrap.js";
14
15
  export { DingTalkBot, } from "./runtime/dingtalk.js";
package/dist/main.js CHANGED
@@ -1,6 +1,7 @@
1
1
  #!/usr/bin/env node
2
2
  import { runAuth } from "./models/auth-cli.js";
3
- import { bootstrap, isBootstrapExitError } from "./runtime/bootstrap.js";
3
+ import { isBootstrapExitError } from "./runtime/app-home.js";
4
+ import { bootstrap } from "./runtime/bootstrap.js";
4
5
  import { runTui } from "./tui/cli.js";
5
6
  function handleError(error) {
6
7
  if (isBootstrapExitError(error)) {
@@ -140,7 +140,6 @@ export function toMemoryOp(candidate, provenance, tier) {
140
140
  const metadata = {
141
141
  kind: candidate.kind,
142
142
  sourceType: "agent",
143
- trust: "inferred",
144
143
  sourceCorrelationId: provenance.correlationId,
145
144
  probationUntil: tier === "probationary" ? probationDeadline() : null,
146
145
  };
@@ -41,7 +41,7 @@ export interface StructuralMaintenanceMaterial {
41
41
  historyFoldingNeeded: boolean;
42
42
  hasMemoryContent: boolean;
43
43
  hasHistoryContent: boolean;
44
- /** Active entries whose probation lapsed or `expiresAt` was reached (spec 037, D8). */
44
+ /** Active entries whose probation lapsed (spec 037, D8). */
45
45
  expiredEntryCount: number;
46
46
  }
47
47
  export interface StructuralMaintenanceGateInput {
@@ -245,9 +245,8 @@ export async function runStructuralMaintenanceJob(input) {
245
245
  try {
246
246
  const correlationId = `structural-maintenance:${formatLocalTime(now)}`;
247
247
  const options = makeRunOptions(input, correlationId);
248
- // Probation/expiresAt eviction runs first, deterministically, before the LLM cleanup
249
- // pass sees the file — no point spending a cleanup prompt on entries about to be
250
- // invalidated (spec 037, D8).
248
+ // Probation eviction runs first, deterministically, before the LLM cleanup pass sees the
249
+ // file — no point spending a cleanup prompt on entries about to be invalidated (spec 037, D8).
251
250
  const expiredCount = decision.runProbationExpiry ? await expireMemoryEntries(input.channelDir, now) : 0;
252
251
  const [cachedMemory, currentHistory] = await loadFiles();
253
252
  // `loadFiles`'s cached read predates the expiry write above, so a fresh read is needed
@@ -1,17 +1,9 @@
1
1
  export type MemoryEntryKind = "fact" | "preference" | "decision" | "constraint" | "open-loop" | "lesson";
2
2
  export type MemorySourceType = "user" | "agent" | "repo" | "tool" | "web" | "legacy";
3
- export type MemoryTrust = "explicit" | "verified" | "inferred" | "untrusted";
4
- export type MemorySensitivity = "normal" | "personal" | "secret";
5
3
  export type MemoryEntryStatus = "active" | "superseded" | "invalidated" | "forgotten";
6
4
  export interface MemoryWriteMetadataInput {
7
5
  kind?: MemoryEntryKind;
8
- subjectId?: string;
9
- ownerId?: string;
10
6
  sourceType?: MemorySourceType;
11
- trust?: MemoryTrust;
12
- validFrom?: string;
13
- expiresAt?: string;
14
- sensitivity?: MemorySensitivity;
15
7
  sourceCorrelationId?: string;
16
8
  /**
17
9
  * Probationary write deadline (spec 037, D6/D7): `undefined` leaves any existing value alone,
@@ -24,19 +16,12 @@ export interface MemoryWriteMetadataInput {
24
16
  export interface MemoryEntryMetadata {
25
17
  id: string;
26
18
  kind: MemoryEntryKind;
27
- scope: "channel";
28
- subjectId?: string;
29
- ownerId?: string;
30
19
  sourceEntryIds: string[];
31
20
  sourceCorrelationIds: string[];
32
21
  sourceType: MemorySourceType;
33
- trust: MemoryTrust;
34
22
  createdAt: string;
35
23
  updatedAt: string;
36
- validFrom?: string;
37
- expiresAt?: string;
38
24
  status: MemoryEntryStatus;
39
- sensitivity: MemorySensitivity;
40
25
  sectionHeading: string;
41
26
  contentHash: string;
42
27
  recallCount: number;
@@ -57,22 +57,15 @@ export async function syncMemoryMetadata(channelDir, activeEntries, updates = []
57
57
  entries[entry.id] = {
58
58
  id: entry.id,
59
59
  kind: hint?.kind ?? previous?.kind ?? inferKind(entry.sectionHeading),
60
- scope: "channel",
61
- subjectId: hint?.subjectId ?? previous?.subjectId,
62
- ownerId: hint?.ownerId ?? previous?.ownerId,
63
60
  sourceEntryIds: Array.from(new Set([...(previous?.sourceEntryIds ?? []), ...(update?.sourceEntryIds ?? [])])),
64
61
  sourceCorrelationIds: Array.from(new Set([
65
62
  ...(previous?.sourceCorrelationIds ?? []),
66
63
  ...(hint?.sourceCorrelationId ? [hint.sourceCorrelationId] : []),
67
64
  ])),
68
65
  sourceType: hint?.sourceType ?? previous?.sourceType ?? "legacy",
69
- trust: hint?.trust ?? previous?.trust ?? "inferred",
70
66
  createdAt: previous?.createdAt ?? entry.timestamp ?? timestamp,
71
67
  updatedAt: update || previous?.contentHash !== contentHash(entry.content) ? timestamp : previous.updatedAt,
72
- validFrom: hint?.validFrom ?? previous?.validFrom,
73
- expiresAt: hint?.expiresAt ?? previous?.expiresAt,
74
68
  status: "active",
75
- sensitivity: hint?.sensitivity ?? previous?.sensitivity ?? "normal",
76
69
  sectionHeading: entry.sectionHeading,
77
70
  contentHash: contentHash(entry.content),
78
71
  recallCount: previous?.recallCount ?? 0,
@@ -6,11 +6,7 @@ import { readMemoryMetadata } from "./metadata.js";
6
6
  */
7
7
  export declare const MEMORY_PROBATION_DAYS = 30;
8
8
  export declare function probationDeadline(now?: Date): string;
9
- /**
10
- * Active entries whose probation lapsed, or whose (otherwise unconsumed) `expiresAt` was
11
- * reached. Both are "this entry's time is up" — they share one eviction path even though their
12
- * semantics differ: `probationUntil` is cancelled by use, `expiresAt` is unconditional.
13
- */
9
+ /** Active entries whose probation lapsed. */
14
10
  export declare function collectExpiredEntryIds(metadata: Awaited<ReturnType<typeof readMemoryMetadata>>, now?: Date): string[];
15
11
  /**
16
12
  * Evict every expired entry via `invalidate`, never `forget` (spec 037, D8): probation lapsing
@@ -16,15 +16,11 @@ function isPast(value, nowMs) {
16
16
  const ms = parseLocalTime(value);
17
17
  return ms !== undefined && ms <= nowMs;
18
18
  }
19
- /**
20
- * Active entries whose probation lapsed, or whose (otherwise unconsumed) `expiresAt` was
21
- * reached. Both are "this entry's time is up" — they share one eviction path even though their
22
- * semantics differ: `probationUntil` is cancelled by use, `expiresAt` is unconditional.
23
- */
19
+ /** Active entries whose probation lapsed. */
24
20
  export function collectExpiredEntryIds(metadata, now = new Date()) {
25
21
  const nowMs = now.getTime();
26
22
  return Object.values(metadata.entries)
27
- .filter((entry) => entry.status === "active" && (isPast(entry.probationUntil, nowMs) || isPast(entry.expiresAt, nowMs)))
23
+ .filter((entry) => entry.status === "active" && isPast(entry.probationUntil, nowMs))
28
24
  .map((entry) => entry.id);
29
25
  }
30
26
  /**
@@ -1,4 +1,4 @@
1
- import { type BootstrapIO, type BootstrapPaths } from "../runtime/bootstrap.js";
1
+ import { type BootstrapIO, type BootstrapPaths } from "../runtime/app-home.js";
2
2
  export type ParsedAuth = {
3
3
  kind: "status";
4
4
  } | {
@@ -7,7 +7,8 @@
7
7
  */
8
8
  import { createInterface } from "node:readline/promises";
9
9
  import * as log from "../log.js";
10
- import { BootstrapExitError, bootstrapAppHome, DEFAULT_BOOTSTRAP_PATHS, prepareAppServices, printBootstrapSummary, readCliVersion, } from "../runtime/bootstrap.js";
10
+ import { BootstrapExitError, bootstrapAppHome, DEFAULT_BOOTSTRAP_PATHS, printBootstrapSummary, readCliVersion, } from "../runtime/app-home.js";
11
+ import { prepareAppServices } from "../runtime/bootstrap.js";
11
12
  import { ReadlineLoginUi } from "./login-ui.js";
12
13
  import { LoginCancelledError, listProviderLoginOptions, loginProvider, logoutProvider, renderAuthStatus, } from "./provider-login.js";
13
14
  import { createModelRuntime, formatModelReference } from "./utils.js";
@@ -317,7 +318,7 @@ export async function runAuth(argv, io = console, paths = DEFAULT_BOOTSTRAP_PATH
317
318
  io.error("pipiclaw auth login/logout requires an interactive terminal (stdin is not a TTY).");
318
319
  throw new BootstrapExitError(1);
319
320
  }
320
- printBootstrapSummary(bootstrapAppHome(paths, io), io, paths);
321
+ printBootstrapSummary(bootstrapAppHome(paths), io, paths);
321
322
  prepareAppServices(paths);
322
323
  const runtime = await createModelRuntime({
323
324
  authConfigPath: paths.authConfigPath,
package/dist/paths.d.ts CHANGED
@@ -1,12 +1,6 @@
1
1
  export declare const APP_NAME = "pipiclaw";
2
2
  /** Prefer live source docs in a checkout; installed packages fall back to dist/playbooks. */
3
3
  export declare const PLAYBOOKS_DIR: string;
4
- /**
5
- * Legacy default app home used before the `~/.pipiclaw` default (introduced in
6
- * 0.8.x). Kept only so bootstrap can migrate an existing install to the new
7
- * default. FIXME(0.9.0): drop this together with the migration in bootstrap.ts.
8
- */
9
- export declare const LEGACY_APP_HOME_DIR: string;
10
4
  /** The built-in default app home, independent of any `PIPICLAW_HOME` override. */
11
5
  export declare const DEFAULT_APP_HOME_DIR: string;
12
6
  export declare const APP_HOME_DIR: string;
package/dist/paths.js CHANGED
@@ -12,12 +12,6 @@ const bundledPlaybooksDir = fileURLToPath(new URL("./playbooks", import.meta.url
12
12
  const checkoutPlaybooksDir = fileURLToPath(new URL("../src/playbooks", import.meta.url));
13
13
  /** Prefer live source docs in a checkout; installed packages fall back to dist/playbooks. */
14
14
  export const PLAYBOOKS_DIR = existsSync(checkoutPlaybooksDir) ? checkoutPlaybooksDir : bundledPlaybooksDir;
15
- /**
16
- * Legacy default app home used before the `~/.pipiclaw` default (introduced in
17
- * 0.8.x). Kept only so bootstrap can migrate an existing install to the new
18
- * default. FIXME(0.9.0): drop this together with the migration in bootstrap.ts.
19
- */
20
- export const LEGACY_APP_HOME_DIR = join(homedir(), ".pi", APP_NAME);
21
15
  /** The built-in default app home, independent of any `PIPICLAW_HOME` override. */
22
16
  export const DEFAULT_APP_HOME_DIR = join(homedir(), `.${APP_NAME}`);
23
17
  export const APP_HOME_DIR = process.env.PIPICLAW_HOME ?? DEFAULT_APP_HOME_DIR;