@oyasmi/pipiclaw 0.8.7-beta.2 → 0.8.7-beta.3

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.
@@ -17,13 +17,14 @@ export declare class ChannelRunner implements AgentRunner {
17
17
  private agent;
18
18
  private sessionManager;
19
19
  private readonly settingsManager;
20
- private readonly modelRegistry;
20
+ private modelRuntime;
21
+ private modelRegistry;
21
22
  private readonly memoryLifecycle;
22
23
  private readonly ledger;
23
24
  private readonly memoryCandidateStore;
24
25
  private readonly sessionResourceGate;
25
26
  private readonly sessionReady;
26
- private readonly sessionRuntime;
27
+ private sessionRuntime;
27
28
  private sessionUnsubscribe?;
28
29
  private subAgentDiscovery;
29
30
  private activeModel;
@@ -1,5 +1,5 @@
1
1
  import { Agent } from "@earendil-works/pi-agent-core";
2
- import { AgentSession, AgentSessionRuntime, AuthStorage, convertToLlm, createExtensionRuntime, DefaultResourceLoader, SessionManager, } from "@earendil-works/pi-coding-agent";
2
+ import { AgentSession, AgentSessionRuntime, convertToLlm, createExtensionRuntime, DefaultResourceLoader, SessionManager, } from "@earendil-works/pi-coding-agent";
3
3
  import { mkdir, readFile, writeFile } from "fs/promises";
4
4
  import { dirname, join, resolve } from "path";
5
5
  import { createExecutor } from "../executor.js";
@@ -13,7 +13,7 @@ import { applyMemoryActivityToState, updateMemoryMaintenanceState, } from "../me
13
13
  import { MEMORY_RECALL_MAX_UNITS, recallRelevantMemory } from "../memory/recall.js";
14
14
  import { buildTaskDigest, TASK_AGENDA_MAX_UNITS } from "../memory/task-digest.js";
15
15
  import { getApiKeyForModel } from "../models/api-keys.js";
16
- import { createModelRegistry, findExactModelReferenceMatch, formatModelReference, resolveInitialModel, } from "../models/utils.js";
16
+ import { createModelRuntime, defaultModel, findExactModelReferenceMatch, formatModelReference, resolveInitialModel, wrapModelRegistry, } from "../models/utils.js";
17
17
  import { loadRuntimePlaybookCatalog, selectRuntimePlaybooks } from "../playbooks/catalog.js";
18
18
  import { loadSecurityConfigWithDiagnostics } from "../security/config.js";
19
19
  import { PipiclawSettingsManager } from "../settings.js";
@@ -86,14 +86,10 @@ export class ChannelRunner {
86
86
  this.settingsManager = new PipiclawSettingsManager(this.appHomeDir);
87
87
  this.reportSettingsDiagnostics();
88
88
  this.memoryCandidateStore = createMemoryCandidateStore();
89
- // Create AuthStorage and ModelRegistry
90
- const authStorage = AuthStorage.create(this.authConfigPath);
91
- this.modelRegistry = createModelRegistry(authStorage, this.modelsConfigPath);
92
- // Resolve model: prefer saved global default, fall back to first available model
93
- this.activeModel = resolveInitialModel(this.modelRegistry, this.settingsManager);
94
- log.logInfo(`Using model: ${this.activeModel.provider}/${this.activeModel.id} (${this.activeModel.name})`);
95
- this.subAgentDiscovery = this.refreshSubAgentDiscovery();
96
- const initialSessionManager = this.sessionManager;
89
+ // The real model/auth runtime is built asynchronously in initializeSession
90
+ // (ModelRuntime.create is async). Until then the agent runs on a placeholder
91
+ // model; initializeSession corrects it before any turn (via sessionReady).
92
+ this.activeModel = defaultModel;
97
93
  const initialTools = this.buildRuntimeTools();
98
94
  this.agent = new Agent({
99
95
  initialState: {
@@ -118,38 +114,9 @@ export class ChannelRunner {
118
114
  void this.recordMemoryActivity(event);
119
115
  },
120
116
  });
121
- const initialResourceLoader = this.createResourceLoader();
122
- const baseToolsOverride = Object.fromEntries(initialTools.map((tool) => [tool.name, tool]));
123
- this.session = new AgentSession({
124
- agent: this.agent,
125
- sessionManager: initialSessionManager,
126
- settingsManager: asSdkSettingsManager(this.settingsManager),
127
- cwd: process.cwd(),
128
- modelRegistry: this.modelRegistry,
129
- resourceLoader: initialResourceLoader,
130
- baseToolsOverride,
131
- });
132
- this.sessionRuntime = new AgentSessionRuntime(this.session, this.createAgentSessionServices(initialResourceLoader), async ({ sessionManager, sessionStartEvent }) => {
133
- const next = this.createSessionRuntime(sessionManager, sessionStartEvent);
134
- return {
135
- session: next.session,
136
- extensionsResult: this.createEmptyExtensionsResult(),
137
- services: this.createAgentSessionServices(next.resourceLoader),
138
- diagnostics: [],
139
- };
140
- });
141
- this.sessionRuntime.setRebindSession(async (session) => {
142
- this.session = session;
143
- this.agent = session.agent;
144
- this.sessionManager = session.sessionManager;
145
- await this.bindSessionExtensions();
146
- this.subscribeToSessionEvents();
147
- });
148
117
  this.sessionResourceGate = new SessionResourceGate(async () => {
149
118
  await this.reloadSessionResources();
150
119
  });
151
- // Subscribe to session events
152
- this.subscribeToSessionEvents();
153
120
  this.sessionReady = this.initializeSession();
154
121
  }
155
122
  // === Public API ===
@@ -741,8 +708,8 @@ export class ChannelRunner {
741
708
  if (!reference) {
742
709
  return null;
743
710
  }
744
- this.modelRegistry.refresh();
745
- const available = await this.modelRegistry.getAvailable();
711
+ await this.modelRegistry.refresh();
712
+ const available = this.modelRegistry.getAvailable();
746
713
  const { match, ambiguous } = findExactModelReferenceMatch(reference, available);
747
714
  if (!match) {
748
715
  log.logWarning(`[${this.channelId}] fallbackModel "${reference}" ${ambiguous ? "is ambiguous" : "not found"}; skipping fallback`);
@@ -758,6 +725,46 @@ export class ChannelRunner {
758
725
  return match;
759
726
  }
760
727
  async initializeSession() {
728
+ // Build the canonical async model/auth runtime and its synchronous read shell.
729
+ this.modelRuntime = await createModelRuntime({
730
+ authConfigPath: this.authConfigPath,
731
+ modelsConfigPath: this.modelsConfigPath,
732
+ });
733
+ this.modelRegistry = wrapModelRegistry(this.modelRuntime);
734
+ // Resolve model: prefer saved global default, fall back to first available model.
735
+ this.activeModel = resolveInitialModel(this.modelRegistry, this.settingsManager);
736
+ this.agent.state.model = this.activeModel; // correct the placeholder default
737
+ log.logInfo(`Using model: ${this.activeModel.provider}/${this.activeModel.id} (${this.activeModel.name})`);
738
+ this.subAgentDiscovery = await this.refreshSubAgentDiscovery();
739
+ const initialResourceLoader = this.createResourceLoader();
740
+ const baseToolsOverride = Object.fromEntries(this.currentTools.map((tool) => [tool.name, tool]));
741
+ this.session = new AgentSession({
742
+ agent: this.agent,
743
+ sessionManager: this.sessionManager,
744
+ settingsManager: asSdkSettingsManager(this.settingsManager),
745
+ cwd: process.cwd(),
746
+ modelRuntime: this.modelRuntime,
747
+ resourceLoader: initialResourceLoader,
748
+ baseToolsOverride,
749
+ });
750
+ this.sessionRuntime = new AgentSessionRuntime(this.session, this.createAgentSessionServices(initialResourceLoader), async ({ sessionManager, sessionStartEvent }) => {
751
+ const next = this.createSessionRuntime(sessionManager, sessionStartEvent);
752
+ return {
753
+ session: next.session,
754
+ extensionsResult: this.createEmptyExtensionsResult(),
755
+ services: this.createAgentSessionServices(next.resourceLoader),
756
+ diagnostics: [],
757
+ };
758
+ });
759
+ this.sessionRuntime.setRebindSession(async (session) => {
760
+ this.session = session;
761
+ this.agent = session.agent;
762
+ this.sessionManager = session.sessionManager;
763
+ await this.bindSessionExtensions();
764
+ this.subscribeToSessionEvents();
765
+ });
766
+ // Subscribe to session events
767
+ this.subscribeToSessionEvents();
761
768
  await this.reloadSessionResources();
762
769
  await this.bindSessionExtensions();
763
770
  }
@@ -766,7 +773,7 @@ export class ChannelRunner {
766
773
  this.reportSettingsDiagnostics();
767
774
  const skills = loadPipiclawSkills(this.channelDir);
768
775
  this.currentSkills = skills;
769
- this.subAgentDiscovery = this.refreshSubAgentDiscovery();
776
+ this.subAgentDiscovery = await this.refreshSubAgentDiscovery();
770
777
  this.rebuildSessionTools();
771
778
  await this.session.reload();
772
779
  }
@@ -818,8 +825,8 @@ export class ChannelRunner {
818
825
  log.logWarning(`[${this.channelId}] Preventive compaction failed`, message);
819
826
  }
820
827
  }
821
- refreshSubAgentDiscovery() {
822
- this.modelRegistry.refresh();
828
+ async refreshSubAgentDiscovery() {
829
+ await this.modelRegistry.refresh();
823
830
  const discovery = discoverSubAgents(this.workspaceDir, this.modelRegistry.getAvailable());
824
831
  for (const warning of discovery.warnings) {
825
832
  log.logWarning(`Sub-agent config warning (${this.channelId})`, warning);
@@ -896,8 +903,8 @@ export class ChannelRunner {
896
903
  createCommandExtension({
897
904
  getCurrentModel: () => this.session.model ?? this.activeModel,
898
905
  getAvailableModels: async () => {
899
- this.modelRegistry.refresh();
900
- return await this.modelRegistry.getAvailable();
906
+ await this.modelRegistry.refresh();
907
+ return this.modelRegistry.getAvailable();
901
908
  },
902
909
  getSessionStats: () => this.session.getSessionStats(),
903
910
  getThinkingLevel: () => this.session.thinkingLevel,
@@ -936,9 +943,8 @@ export class ChannelRunner {
936
943
  return {
937
944
  cwd: process.cwd(),
938
945
  agentDir: this.appHomeDir,
939
- authStorage: AuthStorage.create(this.authConfigPath),
940
946
  settingsManager: asSdkSettingsManager(this.settingsManager),
941
- modelRegistry: this.modelRegistry,
947
+ modelRuntime: this.modelRuntime,
942
948
  resourceLoader,
943
949
  diagnostics: [],
944
950
  };
@@ -968,7 +974,7 @@ export class ChannelRunner {
968
974
  sessionManager,
969
975
  settingsManager: asSdkSettingsManager(this.settingsManager),
970
976
  cwd: process.cwd(),
971
- modelRegistry: this.modelRegistry,
977
+ modelRuntime: this.modelRuntime,
972
978
  resourceLoader,
973
979
  baseToolsOverride: Object.fromEntries(tools.map((tool) => [tool.name, tool])),
974
980
  sessionStartEvent,
@@ -1021,7 +1027,7 @@ export class ChannelRunner {
1021
1027
  // === Session event subscription ===
1022
1028
  subscribeToSessionEvents() {
1023
1029
  this.sessionUnsubscribe?.();
1024
- this.sessionUnsubscribe = this.session.subscribe(async (event) => {
1030
+ this.sessionUnsubscribe = this.session.subscribe((event) => {
1025
1031
  if (isRecord(event) && event.type === "message_start" && this.turn.phase === "preparing") {
1026
1032
  this.turn.phase = "streaming";
1027
1033
  }
@@ -1030,7 +1036,10 @@ export class ChannelRunner {
1030
1036
  }
1031
1037
  if (!this.runState.ctx || !this.runState.logCtx || !this.runState.queue)
1032
1038
  return;
1033
- await handleSessionEvent(event, {
1039
+ // The SDK listener signature is `(event) => void`, so the promise below is fire-and-forget.
1040
+ // Without this catch, a rejection inside handleSessionEvent becomes an unhandled rejection
1041
+ // that terminates the daemon under Node's default policy.
1042
+ handleSessionEvent(event, {
1034
1043
  ctx: this.runState.ctx,
1035
1044
  logCtx: this.runState.logCtx,
1036
1045
  queue: this.runState.queue,
@@ -1042,6 +1051,8 @@ export class ChannelRunner {
1042
1051
  refreshSessionResources: async () => {
1043
1052
  await this.refreshSessionResources();
1044
1053
  },
1054
+ }).catch((err) => {
1055
+ log.logWarning(`[${this.channelId}] session event handler failed`, errorMessage(err));
1045
1056
  });
1046
1057
  });
1047
1058
  }
@@ -1,5 +1,7 @@
1
1
  import { randomBytes } from "node:crypto";
2
+ import * as log from "../log.js";
2
3
  import { shellEscape } from "../shared/shell-escape.js";
4
+ import { errorMessage } from "../shared/text-utils.js";
3
5
  /** Cap on concurrently running jobs per channel, so a runaway model can't spawn unbounded processes. */
4
6
  export const MAX_RUNNING_JOBS = 5;
5
7
  /** Longest a single `poll` call blocks before returning a snapshot; the model can poll again. */
@@ -117,7 +119,9 @@ export class ChannelJobManager {
117
119
  try {
118
120
  for (const record of this.jobs.values()) {
119
121
  if (record.status === "running") {
120
- await this.refresh(record).catch(() => { });
122
+ await this.refresh(record).catch((error) => {
123
+ log.logWarning(`Background job sweep failed to refresh job ${record.id}`, errorMessage(error));
124
+ });
121
125
  }
122
126
  }
123
127
  }
@@ -1,8 +1,8 @@
1
1
  import { statSync } from "node:fs";
2
2
  import { join } from "node:path";
3
- import { AuthStorage, SessionManager } from "@earendil-works/pi-coding-agent";
3
+ import { SessionManager } from "@earendil-works/pi-coding-agent";
4
4
  import { getApiKeyForModel } from "../models/api-keys.js";
5
- import { createModelRegistry, resolveInitialModel } from "../models/utils.js";
5
+ import { createModelRuntime, resolveInitialModel, wrapModelRegistry } from "../models/utils.js";
6
6
  import { loadPipiclawSkills } from "./workspace-resources.js";
7
7
  // The maintenance scheduler visits idle channels every tick; re-parsing an
8
8
  // unchanged context.jsonl each time would be pure I/O waste for long-dead
@@ -47,8 +47,11 @@ export async function loadDetachedMaintenanceContext(options) {
47
47
  }
48
48
  transcriptCache.set(options.channelDir, cached);
49
49
  }
50
- const authStorage = AuthStorage.create(options.authConfigPath);
51
- const modelRegistry = createModelRegistry(authStorage, options.modelsConfigPath);
50
+ const modelRuntime = await createModelRuntime({
51
+ authConfigPath: options.authConfigPath,
52
+ modelsConfigPath: options.modelsConfigPath,
53
+ });
54
+ const modelRegistry = wrapModelRegistry(modelRuntime);
52
55
  const model = resolveInitialModel(modelRegistry, options.settingsManager);
53
56
  options.settingsManager.reload();
54
57
  return {
@@ -1,6 +1,7 @@
1
+ import * as log from "../log.js";
1
2
  import { parseJsonObject } from "../shared/llm-json.js";
2
3
  import { countPromptUnits } from "../shared/prompt-units.js";
3
- import { HAN_REGEX } from "../shared/text-utils.js";
4
+ import { errorMessage, HAN_REGEX } from "../shared/text-utils.js";
4
5
  import { buildMemoryCandidates, createMemoryCandidateStore, } from "./candidates.js";
5
6
  import { COMMON_CHINESE_WORDS } from "./chinese-words.js";
6
7
  import { recordMemoryRecall, syncMemoryMetadata } from "./metadata.js";
@@ -435,7 +436,8 @@ async function rerankCandidates(request, candidates) {
435
436
  const selected = candidates.filter(({ candidate }) => selectedIds.has(candidate.id));
436
437
  return selected.length > 0 ? selected : candidates;
437
438
  }
438
- catch {
439
+ catch (error) {
440
+ log.logWarning("Memory recall LLM selection failed; falling back to all candidates", errorMessage(error));
439
441
  return candidates;
440
442
  }
441
443
  }
@@ -1,8 +1,21 @@
1
1
  import type { Api, Model } from "@earendil-works/pi-ai";
2
- import { type AuthStorage, ModelRegistry } from "@earendil-works/pi-coding-agent";
2
+ import { ModelRegistry, ModelRuntime } from "@earendil-works/pi-coding-agent";
3
3
  import type { PipiclawSettingsManager } from "../settings.js";
4
- /** SDK-version-tolerant construction: newer SDKs expose a static create(), older ones a constructor. */
5
- export declare function createModelRegistry(authStorage: AuthStorage, modelsJsonPath: string): ModelRegistry;
4
+ export declare const defaultModel: Model<"anthropic-messages">;
5
+ /**
6
+ * Construct the canonical async model/auth runtime (replaces the old
7
+ * `AuthStorage.create` + `ModelRegistry` pairing). pi 0.80.8+ folded auth and
8
+ * model resolution into a single async `ModelRuntime`.
9
+ */
10
+ export declare function createModelRuntime(options: {
11
+ authConfigPath: string;
12
+ modelsConfigPath: string;
13
+ }): Promise<ModelRuntime>;
14
+ /**
15
+ * Wrap a ModelRuntime in the synchronous extension-facing ModelRegistry shell so
16
+ * existing `getAvailable`/`find`/`getApiKeyForProvider` call sites stay unchanged.
17
+ */
18
+ export declare function wrapModelRegistry(modelRuntime: ModelRuntime): ModelRegistry;
6
19
  export declare function formatModelReference(model: Model<Api>): string;
7
20
  export declare function findExactModelReferenceMatch(modelReference: string, availableModels: Model<Api>[]): {
8
21
  match?: Model<Api>;
@@ -1,13 +1,24 @@
1
1
  import { getBuiltinModel as getModel } from "@earendil-works/pi-ai/providers/all";
2
- import { ModelRegistry } from "@earendil-works/pi-coding-agent";
2
+ import { ModelRegistry, ModelRuntime } from "@earendil-works/pi-coding-agent";
3
3
  // Default model - will be overridden by ModelRegistry if custom models are configured
4
- const defaultModel = getModel("anthropic", "claude-sonnet-4-5");
5
- /** SDK-version-tolerant construction: newer SDKs expose a static create(), older ones a constructor. */
6
- export function createModelRegistry(authStorage, modelsJsonPath) {
7
- const registryClass = ModelRegistry;
8
- return typeof registryClass.create === "function"
9
- ? registryClass.create(authStorage, modelsJsonPath)
10
- : new registryClass(authStorage, modelsJsonPath);
4
+ export const defaultModel = getModel("anthropic", "claude-sonnet-4-5");
5
+ /**
6
+ * Construct the canonical async model/auth runtime (replaces the old
7
+ * `AuthStorage.create` + `ModelRegistry` pairing). pi 0.80.8+ folded auth and
8
+ * model resolution into a single async `ModelRuntime`.
9
+ */
10
+ export async function createModelRuntime(options) {
11
+ return ModelRuntime.create({
12
+ authPath: options.authConfigPath,
13
+ modelsPath: options.modelsConfigPath,
14
+ });
15
+ }
16
+ /**
17
+ * Wrap a ModelRuntime in the synchronous extension-facing ModelRegistry shell so
18
+ * existing `getAvailable`/`find`/`getApiKeyForProvider` call sites stay unchanged.
19
+ */
20
+ export function wrapModelRegistry(modelRuntime) {
21
+ return new ModelRegistry(modelRuntime);
11
22
  }
12
23
  export function formatModelReference(model) {
13
24
  return `${model.provider}/${model.id}`;
@@ -120,15 +120,6 @@ export declare class DingTalkBot {
120
120
  * Append a delta to the active card transcript.
121
121
  */
122
122
  appendToCard(channelId: string, content: string, finalize?: boolean, failed?: boolean): Promise<boolean>;
123
- /**
124
- * Stream content to the active AI Card for a channel using full replacement semantics.
125
- */
126
- streamToCard(channelId: string, content: string, finalize?: boolean): Promise<boolean>;
127
- /**
128
- * Finalize the active card for a channel without falling back to a plain message.
129
- * Returns true if a card was finalized, false if no active card existed.
130
- */
131
- finalizeExistingCard(channelId: string, content: string): Promise<boolean>;
132
123
  /**
133
124
  * Finalize and remove the active card for a channel.
134
125
  */
@@ -622,23 +622,6 @@ export class DingTalkBot {
622
622
  }
623
623
  return streamed;
624
624
  }
625
- /**
626
- * Stream content to the active AI Card for a channel using full replacement semantics.
627
- */
628
- async streamToCard(channelId, content, finalize = false) {
629
- return this.replaceCard(channelId, content, finalize, false);
630
- }
631
- /**
632
- * Finalize the active card for a channel without falling back to a plain message.
633
- * Returns true if a card was finalized, false if no active card existed.
634
- */
635
- async finalizeExistingCard(channelId, content) {
636
- const finalized = await this.replaceCard(channelId, content, true, false);
637
- if (!finalized) {
638
- return false;
639
- }
640
- return true;
641
- }
642
625
  /**
643
626
  * Finalize and remove the active card for a channel.
644
627
  */
@@ -3,6 +3,7 @@ import { readdir, readFile, unlink } from "node:fs/promises";
3
3
  import { join } from "node:path";
4
4
  import { writeFileAtomically } from "../shared/atomic-file.js";
5
5
  import { createSerialQueue } from "../shared/serial-queue.js";
6
+ import { isRecord } from "../shared/type-guards.js";
6
7
  const DEFAULT_LEASE_MS = 15 * 60_000;
7
8
  const DEFAULT_INTERVAL_MS = 30_000;
8
9
  function recordPath(stateDir, id) {
@@ -13,9 +14,6 @@ function dispatchId(event) {
13
14
  .update(JSON.stringify([event.channelId, event.user, event.ts, event.text, event.conversationId]))
14
15
  .digest("hex");
15
16
  }
16
- function isRecord(value) {
17
- return typeof value === "object" && value !== null;
18
- }
19
17
  function parseRecord(raw) {
20
18
  try {
21
19
  const value = JSON.parse(raw);
@@ -35,6 +35,21 @@ function asStringArray(value) {
35
35
  function asOptionalString(value) {
36
36
  return typeof value === "string" && value.trim() ? value : undefined;
37
37
  }
38
+ // Deny patterns are compiled as case-insensitive regexes in command-guard. Validate them at
39
+ // load time so an operator who fat-fingers a pattern gets a diagnostic instead of silently
40
+ // losing that protection (the guard itself swallows the compile error at match time).
41
+ function asDenyPatternArray(value, diagnostics, configPath, field) {
42
+ return asStringArray(value).filter((pattern) => {
43
+ try {
44
+ new RegExp(pattern, "i");
45
+ return true;
46
+ }
47
+ catch (error) {
48
+ pushInvalidSecurityDiagnostic(diagnostics, configPath, field, `invalid regex ${JSON.stringify(pattern)} ignored: ${errorMessage(error)}`);
49
+ return false;
50
+ }
51
+ });
52
+ }
38
53
  function pushInvalidSecurityDiagnostic(diagnostics, configPath, field, message) {
39
54
  diagnostics.push({
40
55
  source: "security",
@@ -65,7 +80,7 @@ function mergeSecurityConfig(source, configPath, diagnostics) {
65
80
  enabled: typeof commandGuard.enabled === "boolean"
66
81
  ? commandGuard.enabled
67
82
  : DEFAULT_SECURITY_CONFIG.commandGuard.enabled,
68
- additionalDenyPatterns: asStringArray(commandGuard.additionalDenyPatterns),
83
+ additionalDenyPatterns: asDenyPatternArray(commandGuard.additionalDenyPatterns, diagnostics, configPath, "commandGuard.additionalDenyPatterns"),
69
84
  allowPatterns: asStringArray(commandGuard.allowPatterns),
70
85
  blockObfuscation: typeof commandGuard.blockObfuscation === "boolean"
71
86
  ? commandGuard.blockObfuscation
@@ -1,4 +1,5 @@
1
1
  import { Type } from "typebox";
2
+ import * as log from "../log.js";
2
3
  import { getDefaultChannelMemoryQueue } from "../memory/channel-maintenance-queue.js";
3
4
  import { applyChannelMemoryOps, getChannelMemoryPath, parseChannelMemoryEntries } from "../memory/files.js";
4
5
  import { containsSecret } from "../memory/policy.js";
@@ -6,6 +7,7 @@ import { recallRelevantMemory } from "../memory/recall.js";
6
7
  import { appendMemoryReviewLog } from "../memory/review-log.js";
7
8
  import { hashMemoryContent } from "../memory/tombstones.js";
8
9
  import { readOptionalTextFile } from "../shared/fs-utils.js";
10
+ import { errorMessage } from "../shared/text-utils.js";
9
11
  const memoryManageSchema = Type.Object({
10
12
  label: Type.String({ description: "Brief description of the memory change (shown to user)" }),
11
13
  op: Type.Union([Type.Literal("save"), Type.Literal("search"), Type.Literal("forget")], {
@@ -145,7 +147,9 @@ export function createMemoryManageTool(options) {
145
147
  channelId: options.channelId,
146
148
  reason: "user-forget",
147
149
  actions: [{ op: "forget", entryId: removed.id, contentHash: hashMemoryContent(removed.content) }],
148
- }).catch(() => { });
150
+ }).catch((error) => {
151
+ log.logWarning(`Failed to append memory review log for channel ${options.channelId}`, errorMessage(error));
152
+ });
149
153
  return textResult("Removed the entry from active channel memory and recorded a tombstone so automatic maintenance will not restore it. Original session history and retention backups are unchanged.", { kind: "memory_manage", op: "forget", forgotten: true, entryId: removed.id });
150
154
  }
151
155
  return {
@@ -92,7 +92,7 @@ function parseAction(action) {
92
92
  action === "list") {
93
93
  return action;
94
94
  }
95
- throw new Error("Unsupported task action. Use create, progress, set, verify, done, cancel, start-cycle, or list.");
95
+ throw new Error("Unsupported task action. Use create, progress, candidate, set, verify, done, cancel, start-cycle, or list.");
96
96
  }
97
97
  function tasksDir(options) {
98
98
  return join(options.channelDir, "tasks");
@@ -1,4 +1,7 @@
1
1
  import { Buffer } from "node:buffer";
2
+ import { Agent as HttpAgent } from "node:http";
3
+ import { Agent as HttpsAgent } from "node:https";
4
+ import { isIP } from "node:net";
2
5
  import axios from "axios";
3
6
  import { HttpProxyAgent } from "http-proxy-agent";
4
7
  import { HttpsProxyAgent } from "https-proxy-agent";
@@ -40,6 +43,23 @@ function buildUrlWithParams(url, params) {
40
43
  }
41
44
  return resolved.toString();
42
45
  }
46
+ // Pin the exact IP that the network guard validated so the actual socket connects there,
47
+ // closing the DNS-rebinding TOCTOU where axios would otherwise re-resolve the hostname and
48
+ // could reach a private address the guard already vetted against. The hostname is still used
49
+ // for the Host header and TLS SNI/cert validation — only address resolution is overridden.
50
+ function pinnedLookup(address) {
51
+ const family = isIP(address);
52
+ return ((_hostname, options, callback) => {
53
+ const cb = (typeof options === "function" ? options : callback);
54
+ const wantsAll = typeof options === "object" && options?.all === true;
55
+ if (wantsAll) {
56
+ cb(null, [{ address, family }]);
57
+ }
58
+ else {
59
+ cb(null, address, family);
60
+ }
61
+ });
62
+ }
43
63
  function getProxyAgent(requestUrl, explicitProxy) {
44
64
  const proxyUrl = explicitProxy?.trim() || getProxyForUrl(requestUrl);
45
65
  if (!proxyUrl) {
@@ -94,13 +114,12 @@ export class WebHttpClient {
94
114
  let method = options.method ?? "GET";
95
115
  let data = options.data;
96
116
  for (let redirectCount = 0; redirectCount <= maxRedirects; redirectCount++) {
117
+ let validatedAddress;
97
118
  try {
98
- if (redirectCount === 0) {
99
- await validateNetworkTarget(currentUrl, { config: this.context.securityConfig });
100
- }
101
- else {
102
- await validateRedirectTarget(currentUrl, { config: this.context.securityConfig });
103
- }
119
+ const validated = redirectCount === 0
120
+ ? await validateNetworkTarget(currentUrl, { config: this.context.securityConfig })
121
+ : await validateRedirectTarget(currentUrl, { config: this.context.securityConfig });
122
+ validatedAddress = validated.resolvedAddress;
104
123
  }
105
124
  catch (error) {
106
125
  if (error instanceof NetworkGuardError) {
@@ -108,7 +127,23 @@ export class WebHttpClient {
108
127
  }
109
128
  throw error;
110
129
  }
111
- const agent = getProxyAgent(currentUrl, this.context.webConfig.proxy);
130
+ const proxyAgent = getProxyAgent(currentUrl, this.context.webConfig.proxy);
131
+ // Without a proxy, pin the socket to the guard-validated IP. With a proxy, the proxy
132
+ // resolves DNS itself, so client-side pinning does not apply.
133
+ const isHttps = new URL(currentUrl).protocol === "https:";
134
+ let httpAgent = proxyAgent;
135
+ let httpsAgent = proxyAgent;
136
+ if (!proxyAgent && validatedAddress) {
137
+ const pinned = isHttps
138
+ ? new HttpsAgent({ lookup: pinnedLookup(validatedAddress) })
139
+ : new HttpAgent({ lookup: pinnedLookup(validatedAddress) });
140
+ if (isHttps) {
141
+ httpsAgent = pinned;
142
+ }
143
+ else {
144
+ httpAgent = pinned;
145
+ }
146
+ }
112
147
  let response;
113
148
  try {
114
149
  response = await axios.request({
@@ -127,8 +162,8 @@ export class WebHttpClient {
127
162
  maxRedirects: 0,
128
163
  maxContentLength: options.maxResponseBytes ?? Number.POSITIVE_INFINITY,
129
164
  proxy: false,
130
- httpAgent: agent,
131
- httpsAgent: agent,
165
+ httpAgent,
166
+ httpsAgent,
132
167
  });
133
168
  }
134
169
  catch (error) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@oyasmi/pipiclaw",
3
- "version": "0.8.7-beta.2",
3
+ "version": "0.8.7-beta.3",
4
4
  "description": "An AI assistant runtime for coding and team workflows, with DingTalk AI Cards, sub-agents, memory, and scheduled events.",
5
5
  "type": "module",
6
6
  "bin": {
@@ -34,10 +34,10 @@
34
34
  "prepublishOnly": "npm run clean && npm run build && npm run check"
35
35
  },
36
36
  "dependencies": {
37
- "@earendil-works/pi-agent-core": "0.80.3",
38
- "@earendil-works/pi-ai": "0.80.3",
39
- "@earendil-works/pi-coding-agent": "0.80.3",
40
- "@earendil-works/pi-tui": "0.80.3",
37
+ "@earendil-works/pi-agent-core": "0.80.10",
38
+ "@earendil-works/pi-ai": "0.80.10",
39
+ "@earendil-works/pi-coding-agent": "0.80.10",
40
+ "@earendil-works/pi-tui": "0.80.10",
41
41
  "@mozilla/readability": "^0.6.0",
42
42
  "axios": "^1.7.0",
43
43
  "croner": "^9.1.0",