@oyasmi/pipiclaw 0.6.8 → 0.6.9-beta.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -21,7 +21,6 @@ export declare class MemoryLifecycle {
21
21
  private sessionRefreshQueue;
22
22
  private durableDirty;
23
23
  private durableRevision;
24
- private lastAssistantTurnRevision;
25
24
  private lastDurableConsolidationRevision;
26
25
  private readonly channelMemoryQueue;
27
26
  constructor(options: MemoryLifecycleOptions);
@@ -35,7 +34,7 @@ export declare class MemoryLifecycle {
35
34
  private refreshSessionMemory;
36
35
  private runSessionRefreshSerial;
37
36
  private runDurableMemoryJobSerial;
38
- private hasPendingAssistantSnapshot;
37
+ private hasPendingDurableSnapshot;
39
38
  private markDurableConsolidationCheckpoint;
40
39
  private logConsolidationResult;
41
40
  private appendReviewLog;
@@ -9,7 +9,6 @@ export class MemoryLifecycle {
9
9
  this.sessionRefreshQueue = Promise.resolve();
10
10
  this.durableDirty = false;
11
11
  this.durableRevision = 0;
12
- this.lastAssistantTurnRevision = 0;
13
12
  this.lastDurableConsolidationRevision = 0;
14
13
  this.channelMemoryQueue = options.channelMemoryQueue ?? getDefaultChannelMemoryQueue();
15
14
  }
@@ -49,12 +48,15 @@ export class MemoryLifecycle {
49
48
  noteCompletedAssistantTurn() {
50
49
  this.durableDirty = true;
51
50
  this.durableRevision++;
52
- this.lastAssistantTurnRevision = this.durableRevision;
53
51
  this.recordActivity("assistant-turn-completed");
54
52
  }
55
53
  async flushForShutdown() {
56
54
  await this.runDurableMemoryJobSerial(async () => {
57
- if (!this.hasPendingAssistantSnapshot()) {
55
+ // Shutdown is the last chance to persist, so use a looser gate than the
56
+ // idle/compaction path: consolidate any unconsolidated durable activity,
57
+ // including a session that only produced tool output with no final
58
+ // assistant turn (which hasPendingAssistantSnapshot would skip).
59
+ if (!this.hasPendingDurableSnapshot()) {
58
60
  return;
59
61
  }
60
62
  const messageSnapshot = [...this.options.getMessages()];
@@ -108,8 +110,10 @@ export class MemoryLifecycle {
108
110
  runDurableMemoryJobSerial(job) {
109
111
  return this.channelMemoryQueue.run(this.options.channelId, job);
110
112
  }
111
- hasPendingAssistantSnapshot() {
112
- return this.durableDirty && this.lastAssistantTurnRevision > this.lastDurableConsolidationRevision;
113
+ // Any unconsolidated durable activity since the last checkpoint, regardless of
114
+ // whether it ended on an assistant turn. Used only for the shutdown flush.
115
+ hasPendingDurableSnapshot() {
116
+ return this.durableDirty && this.durableRevision > this.lastDurableConsolidationRevision;
113
117
  }
114
118
  markDurableConsolidationCheckpoint(revision) {
115
119
  this.lastDurableConsolidationRevision = Math.max(this.lastDurableConsolidationRevision, revision);
@@ -1,4 +1,4 @@
1
- import { type Api, type Model } from "@earendil-works/pi-ai";
1
+ import type { Api, Model } from "@earendil-works/pi-ai";
2
2
  import type { ModelRegistry } from "@earendil-works/pi-coding-agent";
3
3
  import type { PipiclawSettingsManager } from "../settings.js";
4
4
  export declare function formatModelReference(model: Model<Api>): string;
@@ -1,4 +1,4 @@
1
- import { getModel } from "@earendil-works/pi-ai";
1
+ import { getBuiltinModel as getModel } from "@earendil-works/pi-ai/providers/all";
2
2
  // Default model - will be overridden by ModelRegistry if custom models are configured
3
3
  const defaultModel = getModel("anthropic", "claude-sonnet-4-5");
4
4
  export function formatModelReference(model) {
@@ -391,6 +391,12 @@ export function createRuntimeContext(options) {
391
391
  if (state?.running) {
392
392
  state.stopRequested = true;
393
393
  _bot.discardCard(channelId);
394
+ // Drop queued-but-not-started messages so a burst does not keep
395
+ // running after the user asked to halt; abort the in-flight one.
396
+ const dropped = _bot.clearPendingMessages(channelId);
397
+ if (dropped > 0) {
398
+ log.logInfo(`[${channelId}] Dropped ${dropped} queued message(s) on stop`);
399
+ }
394
400
  void state.runner.abort().catch((err) => {
395
401
  log.logWarning(`[${channelId}] Failed to abort run`, err instanceof Error ? err.message : String(err));
396
402
  });
@@ -448,9 +454,14 @@ export function createRuntimeContext(options) {
448
454
  return;
449
455
  }
450
456
  const state = getState(event.channelId);
457
+ // Mark running synchronously, before yielding to the async task body.
458
+ // The channel queue invokes this handler's synchronous prefix within the
459
+ // same tick as dispatch, so setting it here closes the window where a
460
+ // second message arriving in the same tick saw running=false and was
461
+ // routed as a fresh run instead of a steer/follow-up.
462
+ state.running = true;
463
+ state.stopRequested = false;
451
464
  const task = (async () => {
452
- state.running = true;
453
- state.stopRequested = false;
454
465
  try {
455
466
  await archiveIncomingMessage(event.channelId, {
456
467
  date: new Date().toISOString(),
@@ -133,13 +133,15 @@ class ChannelDeliveryController {
133
133
  if (this.closed || this.finalResponseDelivered)
134
134
  return this.finalResponseDelivered;
135
135
  this.clearCardWarmup();
136
- if (shouldLog) {
137
- this.archiveBotResponse(text);
138
- }
139
136
  const delivered = await this.bot.sendPlain(this.event.channelId, text);
140
137
  if (!delivered) {
138
+ // Do not archive a response we failed to deliver: the conversation log
139
+ // must not claim we answered when the user never received it.
141
140
  return false;
142
141
  }
142
+ if (shouldLog) {
143
+ this.archiveBotResponse(text);
144
+ }
143
145
  this.finalResponseDelivered = true;
144
146
  this.mode = "finalize-existing";
145
147
  this.bumpRevision(true);
@@ -73,6 +73,7 @@ export declare class DingTalkBot {
73
73
  private tokenExpiry;
74
74
  private tokenRefreshPromise;
75
75
  private activeCards;
76
+ private cardCreationInFlight;
76
77
  private convMeta;
77
78
  private queues;
78
79
  private client;
@@ -155,11 +156,17 @@ export declare class DingTalkBot {
155
156
  */
156
157
  sendPlain(channelId: string, text: string): Promise<boolean>;
157
158
  private createCard;
159
+ private createCardUncached;
158
160
  private streamCard;
159
161
  private getAccessToken;
160
162
  private refreshAccessToken;
161
163
  private extractContent;
162
164
  private onStreamMessage;
165
+ /**
166
+ * Drop queued-but-not-started messages for a channel (e.g. on /stop) so they
167
+ * do not run after the user halts the current task. Returns dropped count.
168
+ */
169
+ clearPendingMessages(channelId: string): number;
163
170
  private getQueue;
164
171
  private getConversationMeta;
165
172
  private setConversationMeta;
@@ -90,6 +90,14 @@ class ChannelQueue {
90
90
  this.stopped = true;
91
91
  this.queue = [];
92
92
  }
93
+ // Drop not-yet-started work without disabling the queue. Used by /stop so a
94
+ // burst of queued messages does not keep running after the user asked to halt.
95
+ // The in-flight item (already shifted) is unaffected; the caller aborts it.
96
+ clearPending() {
97
+ const dropped = this.queue.length;
98
+ this.queue = [];
99
+ return dropped;
100
+ }
93
101
  }
94
102
  // ============================================================================
95
103
  // Constants
@@ -114,6 +122,10 @@ export class DingTalkBot {
114
122
  this.tokenRefreshPromise = null;
115
123
  // Active AI cards: channelId → AICard
116
124
  this.activeCards = new Map();
125
+ // Singleflight for card creation: warmup and the first progress update can
126
+ // race before activeCards is populated, which would create two cards. Sharing
127
+ // the in-flight promise per channel guarantees at most one create call.
128
+ this.cardCreationInFlight = new Map();
117
129
  // Conversation metadata cache: channelId → metadata
118
130
  this.convMeta = new Map();
119
131
  // Per-channel queues
@@ -703,6 +715,23 @@ export class DingTalkBot {
703
715
  // Private - AI Card implementation
704
716
  // ==========================================================================
705
717
  async createCard(channelId) {
718
+ // Re-check under the singleflight: a concurrent caller may have already
719
+ // created the card while we awaited, so avoid a duplicate create.
720
+ const existing = this.activeCards.get(channelId);
721
+ if (existing && !existing.finished) {
722
+ return existing;
723
+ }
724
+ const inFlight = this.cardCreationInFlight.get(channelId);
725
+ if (inFlight) {
726
+ return inFlight;
727
+ }
728
+ const creation = this.createCardUncached(channelId).finally(() => {
729
+ this.cardCreationInFlight.delete(channelId);
730
+ });
731
+ this.cardCreationInFlight.set(channelId, creation);
732
+ return creation;
733
+ }
734
+ async createCardUncached(channelId) {
706
735
  const token = await this.getAccessToken();
707
736
  if (!token)
708
737
  return null;
@@ -967,6 +996,14 @@ export class DingTalkBot {
967
996
  // Enqueue for processing
968
997
  this.enqueueStreamMessage(event);
969
998
  }
999
+ /**
1000
+ * Drop queued-but-not-started messages for a channel (e.g. on /stop) so they
1001
+ * do not run after the user halts the current task. Returns dropped count.
1002
+ */
1003
+ clearPendingMessages(channelId) {
1004
+ const queue = this.queues.get(channelId);
1005
+ return queue ? queue.clearPending() : 0;
1006
+ }
970
1007
  getQueue(channelId) {
971
1008
  let queue = this.queues.get(channelId);
972
1009
  if (!queue) {
@@ -309,14 +309,19 @@ export class EventsWatcher {
309
309
  conversationType: "1",
310
310
  };
311
311
  const enqueued = this.bot.enqueueEvent(syntheticEvent);
312
- if (enqueued && deleteAfter) {
313
- this.deleteFile(filename);
314
- }
315
- else if (!enqueued) {
316
- log.logWarning(`Event queue full, discarded: ${filename}`);
312
+ if (enqueued) {
317
313
  if (deleteAfter) {
318
314
  this.deleteFile(filename);
319
315
  }
316
+ return;
317
+ }
318
+ // Queue full: do not silently drop. Periodic events fire again on their
319
+ // next tick, so just warn. One-shot/immediate events would otherwise be
320
+ // GC'd as "past" with no trace, so leave a visible error marker (and keep
321
+ // the source file) making the loss auditable rather than a silent hole.
322
+ log.logWarning(`Event queue full, could not enqueue: ${filename}`);
323
+ if (deleteAfter) {
324
+ this.markInvalid(filename, `Event queue was full at ${new Date().toISOString()}; this occurrence was not delivered.`);
320
325
  }
321
326
  }
322
327
  async runPreAction(action, filename) {
@@ -234,8 +234,7 @@ function parseShellWords(command) {
234
234
  pushWord();
235
235
  return words;
236
236
  }
237
- function parseCommand(command) {
238
- const words = parseShellWords(command);
237
+ function parsedFromWords(words) {
239
238
  if (words.length === 0) {
240
239
  return null;
241
240
  }
@@ -247,6 +246,97 @@ function parseCommand(command) {
247
246
  normalized: [normalizedCommand, ...args].join(" ").trim(),
248
247
  };
249
248
  }
249
+ function parseCommand(command) {
250
+ return parsedFromWords(parseShellWords(command));
251
+ }
252
+ // Shells that take a script body as a `-c` argument; the body must be guarded
253
+ // recursively because its dangerous content is hidden inside a single token.
254
+ const SHELL_COMMANDS = new Set(["sh", "bash", "zsh", "dash", "ash", "ksh"]);
255
+ // Wrappers that run another command passed as their operands. The inner command
256
+ // must be guarded too, otherwise e.g. `xargs rm -rf` or `timeout 5 shred x`
257
+ // would slip past the direct-command rules.
258
+ const WRAPPER_COMMANDS = new Set([
259
+ "xargs",
260
+ "env",
261
+ "time",
262
+ "nice",
263
+ "ionice",
264
+ "nohup",
265
+ "timeout",
266
+ "stdbuf",
267
+ "setsid",
268
+ "chrt",
269
+ "parallel",
270
+ ]);
271
+ const MAX_GUARD_DEPTH = 6;
272
+ // Pull the script bodies out of `sh -c <script>` style invocations. Combined
273
+ // flags such as `-lc` are handled by matching any single-dash cluster ending
274
+ // in `c`. There can be more than one (`bash -c a -c b`), so return all.
275
+ function extractShellScripts(parsed) {
276
+ if (!SHELL_COMMANDS.has(parsed.command)) {
277
+ return [];
278
+ }
279
+ const scripts = [];
280
+ for (let i = 0; i < parsed.args.length; i++) {
281
+ const arg = parsed.args[i];
282
+ if (/^-[a-z]*c$/.test(arg) && i + 1 < parsed.args.length) {
283
+ scripts.push(parsed.args[i + 1]);
284
+ i++;
285
+ }
286
+ }
287
+ return scripts;
288
+ }
289
+ // Tokens after `find ... -exec`/`-execdir` up to the `;`/`+` terminator form a
290
+ // command run per match. Return each such inner command as word arrays.
291
+ function extractFindExecCommands(parsed) {
292
+ if (parsed.command !== "find") {
293
+ return [];
294
+ }
295
+ const inner = [];
296
+ for (let i = 0; i < parsed.args.length; i++) {
297
+ if (parsed.args[i] === "-exec" || parsed.args[i] === "-execdir") {
298
+ const words = [];
299
+ for (let j = i + 1; j < parsed.args.length; j++) {
300
+ const token = parsed.args[j];
301
+ if (token === ";" || token === "+" || token === "\\;") {
302
+ break;
303
+ }
304
+ words.push(token);
305
+ }
306
+ if (words.length > 0) {
307
+ inner.push(words);
308
+ }
309
+ }
310
+ }
311
+ return inner;
312
+ }
313
+ // For a generic wrapper, the inner command can sit anywhere after the wrapper's
314
+ // own options/operands (whose grammar varies per tool). Rather than parse each
315
+ // wrapper's flags precisely, evaluate every suffix position as a candidate
316
+ // command start — this only ever adds detections, never relaxes them.
317
+ function extractWrapperCandidates(parsed) {
318
+ if (!WRAPPER_COMMANDS.has(parsed.command)) {
319
+ return [];
320
+ }
321
+ const candidates = [];
322
+ for (let i = 0; i < parsed.args.length; i++) {
323
+ candidates.push(parsed.args.slice(i));
324
+ }
325
+ return candidates;
326
+ }
327
+ // An allow pattern exempts an atom only when it matches that atom's command
328
+ // line from the start at a word boundary (exact, or a `pattern + space` prefix).
329
+ // This replaces the old whole-command substring test that let an allowed
330
+ // fragment whitelist an entire chain (e.g. "git status" -> "git status; rm -rf /").
331
+ function atomAllowed(atomNormalized, allowPatterns) {
332
+ return allowPatterns.some((pattern) => {
333
+ const trimmed = pattern.trim();
334
+ if (!trimmed) {
335
+ return false;
336
+ }
337
+ return atomNormalized === trimmed || atomNormalized.startsWith(`${trimmed} `);
338
+ });
339
+ }
250
340
  function hasAnyArg(args, values) {
251
341
  return args.some((arg) => values.includes(arg));
252
342
  }
@@ -399,49 +489,79 @@ function matchRule(parsed, config) {
399
489
  }
400
490
  return null;
401
491
  }
402
- export function guardCommand(command, config) {
403
- if (!config.enabled) {
404
- return { allowed: true };
492
+ // Evaluate a single already-parsed atom: its direct rule, plus any commands it
493
+ // wraps (shell `-c` bodies, find `-exec`, generic wrappers), recursively.
494
+ function inspectParsed(parsed, config, depth) {
495
+ if (atomAllowed(parsed.normalized, config.allowPatterns)) {
496
+ return null;
405
497
  }
406
- if (isWindowsPlatform()) {
407
- return { allowed: true };
498
+ const direct = matchRule(parsed, config);
499
+ if (direct) {
500
+ return direct;
408
501
  }
409
- const atoms = splitCommandChain(command);
410
- const normalizedWhole = stripNullAndNormalize(command);
411
- for (const allowPattern of config.allowPatterns) {
412
- if (normalizedWhole.includes(allowPattern)) {
413
- return { allowed: true };
502
+ if (depth >= MAX_GUARD_DEPTH) {
503
+ return null;
504
+ }
505
+ for (const script of extractShellScripts(parsed)) {
506
+ const nested = evaluateCommand(script, config, depth + 1);
507
+ if (nested) {
508
+ return nested;
414
509
  }
415
510
  }
511
+ for (const words of [...extractFindExecCommands(parsed), ...extractWrapperCandidates(parsed)]) {
512
+ const innerParsed = parsedFromWords(words);
513
+ if (innerParsed) {
514
+ const nested = inspectParsed(innerParsed, config, depth + 1);
515
+ if (nested) {
516
+ return nested;
517
+ }
518
+ }
519
+ }
520
+ return null;
521
+ }
522
+ function evaluateCommand(command, config, depth) {
523
+ const normalizedWhole = stripNullAndNormalize(command);
416
524
  if (config.blockObfuscation &&
417
525
  (/\bbase64\b.*(?:-d|--decode).*?\|\s*(bash|sh|exec|eval)\b/i.test(normalizedWhole) ||
418
526
  /\beval\s+\$\(/i.test(normalizedWhole) ||
419
527
  /\\x[0-9a-f]{2}/i.test(normalizedWhole) ||
420
528
  /\$'/.test(normalizedWhole))) {
421
529
  return {
422
- allowed: false,
423
530
  category: "obfuscation",
424
531
  rule: "obfuscation-whole-command",
425
532
  reason: "Obfuscated command execution is not allowed",
426
533
  matchedText: normalizedWhole,
427
534
  };
428
535
  }
429
- for (const atom of atoms) {
536
+ for (const atom of splitCommandChain(command)) {
430
537
  const parsed = parseCommand(atom);
431
538
  if (!parsed) {
432
539
  continue;
433
540
  }
434
- const match = matchRule(parsed, config);
541
+ const match = inspectParsed(parsed, config, depth);
435
542
  if (match) {
436
- return {
437
- allowed: false,
438
- category: match.category,
439
- rule: match.rule,
440
- reason: match.reason,
441
- matchedText: match.matchedText,
442
- };
543
+ return match;
443
544
  }
444
545
  }
546
+ return null;
547
+ }
548
+ export function guardCommand(command, config) {
549
+ if (!config.enabled) {
550
+ return { allowed: true };
551
+ }
552
+ if (isWindowsPlatform()) {
553
+ return { allowed: true };
554
+ }
555
+ const match = evaluateCommand(command, config, 0);
556
+ if (match) {
557
+ return {
558
+ allowed: false,
559
+ category: match.category,
560
+ rule: match.rule,
561
+ reason: match.reason,
562
+ matchedText: match.matchedText,
563
+ };
564
+ }
445
565
  return { allowed: true };
446
566
  }
447
567
  export const internalCommandGuard = {
@@ -212,6 +212,8 @@ export declare class PipiclawSettingsManager {
212
212
  setNpmCommand(_command: string[] | undefined): void;
213
213
  getGlobalSettings(): Settings;
214
214
  getProjectSettings(): Settings;
215
+ isProjectTrusted(): boolean;
216
+ setProjectTrusted(_trusted: boolean): void;
215
217
  applyOverrides(overrides: Partial<Settings>): void;
216
218
  flush(): Promise<void>;
217
219
  }
package/dist/settings.js CHANGED
@@ -430,6 +430,12 @@ export class PipiclawSettingsManager {
430
430
  getProjectSettings() {
431
431
  return {};
432
432
  }
433
+ isProjectTrusted() {
434
+ return true;
435
+ }
436
+ setProjectTrusted(_trusted) {
437
+ // Pipiclaw handles workspace authorization at the DingTalk/runtime boundary.
438
+ }
433
439
  applyOverrides(overrides) {
434
440
  if (overrides.defaultProvider !== undefined)
435
441
  this.settings.defaultProvider = overrides.defaultProvider;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@oyasmi/pipiclaw",
3
- "version": "0.6.8",
3
+ "version": "0.6.9-beta.1",
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": {
@@ -33,9 +33,9 @@
33
33
  "prepublishOnly": "npm run clean && npm run build && npm run check"
34
34
  },
35
35
  "dependencies": {
36
- "@earendil-works/pi-agent-core": "^0.75.5",
37
- "@earendil-works/pi-ai": "^0.75.5",
38
- "@earendil-works/pi-coding-agent": "^0.75.5",
36
+ "@earendil-works/pi-agent-core": "0.80.2",
37
+ "@earendil-works/pi-ai": "0.80.2",
38
+ "@earendil-works/pi-coding-agent": "0.80.2",
39
39
  "@mozilla/readability": "^0.6.0",
40
40
  "axios": "^1.7.0",
41
41
  "croner": "^9.1.0",