@oyasmi/pipiclaw 0.7.7 → 0.8.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +23 -2
- package/dist/agent/channel-runner.d.ts +4 -4
- package/dist/agent/channel-runner.js +25 -23
- package/dist/agent/commands.js +7 -2
- package/dist/agent/job-manager.d.ts +5 -5
- package/dist/agent/prompt-builder.d.ts +3 -13
- package/dist/agent/prompt-builder.js +49 -159
- package/dist/agent/run-queue.js +2 -1
- package/dist/agent/runner-factory.d.ts +1 -2
- package/dist/agent/runner-factory.js +2 -2
- package/dist/agent/status-render.d.ts +0 -7
- package/dist/agent/status-render.js +8 -3
- package/dist/agent/types.d.ts +2 -0
- package/dist/agent/workspace-resources.d.ts +1 -1
- package/dist/agent/workspace-resources.js +3 -15
- package/dist/executor.d.ts +20 -0
- package/dist/{sandbox.js → executor.js} +3 -95
- package/dist/index.d.ts +1 -1
- package/dist/index.js +1 -1
- package/dist/log.d.ts +1 -1
- package/dist/log.js +1 -2
- package/dist/memory/files.js +0 -0
- package/dist/memory/lifecycle.js +6 -5
- package/dist/memory/maintenance-jobs.d.ts +0 -1
- package/dist/memory/maintenance-jobs.js +2 -2
- package/dist/memory/maintenance-state.js +2 -1
- package/dist/memory/post-turn-review.d.ts +0 -1
- package/dist/memory/post-turn-review.js +4 -4
- package/dist/memory/scheduler.d.ts +0 -1
- package/dist/memory/scheduler.js +2 -2
- package/dist/memory/session.js +2 -2
- package/dist/memory/task-digest.js +17 -0
- package/dist/paths.d.ts +2 -0
- package/dist/paths.js +11 -0
- package/dist/playbooks/catalog.d.ts +9 -0
- package/dist/playbooks/catalog.js +44 -0
- package/dist/playbooks/event-scheduling.md +43 -0
- package/dist/playbooks/memory-and-learning.md +45 -0
- package/dist/playbooks/runtime-orientation.md +48 -0
- package/dist/playbooks/task-closeout.md +45 -0
- package/dist/playbooks/task-delegation.md +44 -0
- package/dist/playbooks/task-driving.md +43 -0
- package/dist/playbooks/task-planning.md +47 -0
- package/dist/playbooks/task-recurring.md +42 -0
- package/dist/playbooks/task-repair.md +43 -0
- package/dist/runtime/bootstrap.d.ts +12 -11
- package/dist/runtime/bootstrap.js +81 -57
- package/dist/runtime/delivery.js +4 -3
- package/dist/runtime/dingtalk.d.ts +2 -0
- package/dist/runtime/dingtalk.js +15 -14
- package/dist/runtime/durable-dispatch.d.ts +30 -0
- package/dist/runtime/durable-dispatch.js +172 -0
- package/dist/runtime/event-commands.js +4 -4
- package/dist/runtime/events.d.ts +5 -3
- package/dist/runtime/events.js +17 -13
- package/dist/runtime/task-commands.d.ts +6 -0
- package/dist/runtime/task-commands.js +292 -6
- package/dist/runtime/task-driver.d.ts +32 -0
- package/dist/runtime/task-driver.js +268 -0
- package/dist/security/config.js +2 -1
- package/dist/security/network.js +9 -2
- package/dist/security/path-guard.js +12 -24
- package/dist/security/types.d.ts +0 -1
- package/dist/settings.d.ts +12 -0
- package/dist/settings.js +30 -0
- package/dist/shared/jsonl-appender.js +2 -1
- package/dist/shared/task-ledger.d.ts +35 -0
- package/dist/shared/task-ledger.js +229 -15
- package/dist/shared/text-utils.d.ts +1 -0
- package/dist/shared/text-utils.js +3 -0
- package/dist/subagents/discovery.js +3 -2
- package/dist/subagents/tool.d.ts +15 -3
- package/dist/subagents/tool.js +194 -17
- package/dist/tasks/artifact-subject.d.ts +6 -0
- package/dist/tasks/artifact-subject.js +29 -0
- package/dist/tasks/control.d.ts +83 -0
- package/dist/tasks/control.js +293 -0
- package/dist/tasks/store.d.ts +32 -0
- package/dist/tasks/store.js +142 -0
- package/dist/tasks/verification.d.ts +23 -0
- package/dist/tasks/verification.js +69 -0
- package/dist/tools/bash.d.ts +1 -1
- package/dist/tools/bash.js +3 -5
- package/dist/tools/command-optimizer.d.ts +1 -1
- package/dist/tools/command-optimizer.js +4 -6
- package/dist/tools/config.js +4 -3
- package/dist/tools/edit.d.ts +1 -1
- package/dist/tools/edit.js +0 -0
- package/dist/tools/event-manage.d.ts +0 -1
- package/dist/tools/event-manage.js +9 -14
- package/dist/tools/grep.d.ts +1 -1
- package/dist/tools/grep.js +4 -6
- package/dist/tools/index.d.ts +1 -3
- package/dist/tools/index.js +1 -4
- package/dist/tools/read.d.ts +1 -1
- package/dist/tools/read.js +1 -2
- package/dist/tools/registry.d.ts +2 -3
- package/dist/tools/registry.js +5 -11
- package/dist/tools/skill-manage.d.ts +0 -1
- package/dist/tools/skill-manage.js +7 -14
- package/dist/tools/task-manage.d.ts +37 -4
- package/dist/tools/task-manage.js +398 -39
- package/dist/tools/write-content.d.ts +1 -1
- package/dist/tools/write-content.js +0 -1
- package/dist/tools/write.d.ts +1 -1
- package/dist/tui/app.d.ts +0 -2
- package/dist/tui/app.js +12 -7
- package/dist/tui/cli.d.ts +0 -2
- package/dist/tui/cli.js +3 -25
- package/dist/tui/turn-controller.d.ts +7 -3
- package/dist/tui/turn-controller.js +9 -6
- package/dist/web/client.js +2 -1
- package/package.json +2 -2
- package/dist/sandbox.d.ts +0 -42
|
@@ -4,24 +4,29 @@ import { parseBuiltInCommand } from "../agent/commands.js";
|
|
|
4
4
|
import { getOrCreateRunner } from "../agent/index.js";
|
|
5
5
|
import { resetRunner } from "../agent/runner-factory.js";
|
|
6
6
|
import { renderStatus } from "../agent/status-render.js";
|
|
7
|
+
import { createExecutor } from "../executor.js";
|
|
7
8
|
import * as log from "../log.js";
|
|
8
9
|
import { ensureChannelMemoryFilesSync } from "../memory/files.js";
|
|
9
10
|
import { MemoryMaintenanceScheduler } from "../memory/scheduler.js";
|
|
10
11
|
import { APP_HOME_DIR, APP_NAME, AUTH_CONFIG_PATH, CHANNEL_CONFIG_PATH, EVENT_HISTORY_PATH, MODELS_CONFIG_PATH, SECURITY_CONFIG_PATH, SETTINGS_CONFIG_PATH, TOOLS_CONFIG_PATH, WORKSPACE_DIR, } from "../paths.js";
|
|
11
|
-
import { createExecutor, parseSandboxArg, SandboxConfigError, validateSandbox, } from "../sandbox.js";
|
|
12
12
|
import { loadSecurityConfigWithDiagnostics } from "../security/config.js";
|
|
13
13
|
import { PipiclawSettingsManager } from "../settings.js";
|
|
14
14
|
import { formatConfigDiagnostic } from "../shared/config-diagnostics.js";
|
|
15
|
+
import { readActiveTasks } from "../shared/task-ledger.js";
|
|
16
|
+
import { errorMessage } from "../shared/text-utils.js";
|
|
17
|
+
import { finishTaskAttempt } from "../tasks/store.js";
|
|
15
18
|
import { loadToolsConfigWithDiagnostics } from "../tools/config.js";
|
|
16
19
|
import { getUsageLedger } from "../usage/ledger.js";
|
|
17
20
|
import { parseUsageMode, renderUsageReport } from "../usage/render.js";
|
|
18
21
|
import { ensureChannelDir, getChannelDir } from "./channel-paths.js";
|
|
19
22
|
import { createDingTalkContext } from "./delivery.js";
|
|
20
23
|
import { DingTalkBot, isBusyMessageDefaultConfig, isResponseModeConfig, normalizeBusyMessageDefault, normalizeResponseMode, } from "./dingtalk.js";
|
|
24
|
+
import { DurableDispatchService } from "./durable-dispatch.js";
|
|
21
25
|
import { handleEventsCommand as runEventsCommand } from "./event-commands.js";
|
|
22
26
|
import { createEventsWatcher } from "./events.js";
|
|
23
27
|
import { ChannelStore } from "./store.js";
|
|
24
|
-
import { handleTasksCommand as runTasksCommand } from "./task-commands.js";
|
|
28
|
+
import { pauseTask, handleTasksCommand as runTasksCommand } from "./task-commands.js";
|
|
29
|
+
import { createTaskDriverEvent, TaskDriver } from "./task-driver.js";
|
|
25
30
|
const DEFAULT_SOUL = `# SOUL.md
|
|
26
31
|
|
|
27
32
|
Configure Pipiclaw's identity, voice, and communication style here.
|
|
@@ -206,7 +211,7 @@ function hardenExistingSecretFile(path) {
|
|
|
206
211
|
}
|
|
207
212
|
}
|
|
208
213
|
catch (err) {
|
|
209
|
-
log.logWarning(`Failed to tighten permissions on ${path}`,
|
|
214
|
+
log.logWarning(`Failed to tighten permissions on ${path}`, errorMessage(err));
|
|
210
215
|
}
|
|
211
216
|
}
|
|
212
217
|
export function bootstrapAppHome(paths = DEFAULT_BOOTSTRAP_PATHS) {
|
|
@@ -307,7 +312,7 @@ export function loadConfig(paths = DEFAULT_BOOTSTRAP_PATHS, io = console) {
|
|
|
307
312
|
}
|
|
308
313
|
catch (err) {
|
|
309
314
|
io.error(`Failed to parse configuration: ${paths.channelConfigPath}`);
|
|
310
|
-
io.error(
|
|
315
|
+
io.error(errorMessage(err));
|
|
311
316
|
throw new BootstrapExitError(1);
|
|
312
317
|
}
|
|
313
318
|
const issues = listChannelConfigIssues(parsed);
|
|
@@ -332,34 +337,12 @@ export function loadConfig(paths = DEFAULT_BOOTSTRAP_PATHS, io = console) {
|
|
|
332
337
|
}
|
|
333
338
|
export function parseArgs(argv, paths = DEFAULT_BOOTSTRAP_PATHS, io = console) {
|
|
334
339
|
const args = argv.slice(2);
|
|
335
|
-
let sandbox = { type: "host" };
|
|
336
|
-
const parseSandboxOrExit = (value) => {
|
|
337
|
-
try {
|
|
338
|
-
return parseSandboxArg(value);
|
|
339
|
-
}
|
|
340
|
-
catch (err) {
|
|
341
|
-
if (err instanceof SandboxConfigError) {
|
|
342
|
-
io.error(`Error: ${err.message}`);
|
|
343
|
-
throw new BootstrapExitError(1);
|
|
344
|
-
}
|
|
345
|
-
throw err;
|
|
346
|
-
}
|
|
347
|
-
};
|
|
348
340
|
for (let index = 0; index < args.length; index += 1) {
|
|
349
341
|
const arg = args[index];
|
|
350
|
-
if (arg
|
|
351
|
-
sandbox = parseSandboxOrExit(arg.slice("--sandbox=".length));
|
|
352
|
-
}
|
|
353
|
-
else if (arg === "--sandbox") {
|
|
354
|
-
sandbox = parseSandboxOrExit(args[index + 1] || "");
|
|
355
|
-
index += 1;
|
|
356
|
-
}
|
|
357
|
-
else if (arg === "--help" || arg === "-h") {
|
|
342
|
+
if (arg === "--help" || arg === "-h") {
|
|
358
343
|
io.log(`Usage: ${paths.appName} [options]`);
|
|
359
344
|
io.log("");
|
|
360
345
|
io.log("Options:");
|
|
361
|
-
io.log(" --sandbox=host Run tools on host (default)");
|
|
362
|
-
io.log(" --sandbox=docker:<name> Run tools in Docker container");
|
|
363
346
|
io.log(" --version Print the current version and exit");
|
|
364
347
|
io.log("");
|
|
365
348
|
io.log(`Config: ${paths.channelConfigPath}`);
|
|
@@ -371,7 +354,6 @@ export function parseArgs(argv, paths = DEFAULT_BOOTSTRAP_PATHS, io = console) {
|
|
|
371
354
|
throw new BootstrapExitError(0);
|
|
372
355
|
}
|
|
373
356
|
}
|
|
374
|
-
return { sandbox };
|
|
375
357
|
}
|
|
376
358
|
function waitForTasks(tasks, timeoutMs) {
|
|
377
359
|
if (tasks.length === 0) {
|
|
@@ -391,7 +373,7 @@ function flushInactiveChannelMemory(channelStates) {
|
|
|
391
373
|
continue;
|
|
392
374
|
}
|
|
393
375
|
flushes.push(state.runner.flushMemoryForShutdown().catch((err) => {
|
|
394
|
-
log.logWarning(`[${channelId}] Failed to flush memory during shutdown`,
|
|
376
|
+
log.logWarning(`[${channelId}] Failed to flush memory during shutdown`, errorMessage(err));
|
|
395
377
|
}));
|
|
396
378
|
}
|
|
397
379
|
return flushes;
|
|
@@ -409,6 +391,7 @@ export function createRuntimeContext(options) {
|
|
|
409
391
|
const cliVersion = readCliVersion();
|
|
410
392
|
const channelStates = new Map();
|
|
411
393
|
const activeTasks = new Set();
|
|
394
|
+
let durableDispatch;
|
|
412
395
|
let shuttingDown = false;
|
|
413
396
|
let shutdownPromise = null;
|
|
414
397
|
const archiveIncomingMessage = async (channelId, message, contextLabel) => {
|
|
@@ -416,7 +399,7 @@ export function createRuntimeContext(options) {
|
|
|
416
399
|
await store.logMessage(channelId, message);
|
|
417
400
|
}
|
|
418
401
|
catch (err) {
|
|
419
|
-
log.logWarning(`[${channelId}] Failed to archive ${contextLabel}`,
|
|
402
|
+
log.logWarning(`[${channelId}] Failed to archive ${contextLabel}`, errorMessage(err));
|
|
420
403
|
}
|
|
421
404
|
};
|
|
422
405
|
const getState = (channelId) => {
|
|
@@ -426,7 +409,7 @@ export function createRuntimeContext(options) {
|
|
|
426
409
|
ensureChannelMemoryFilesSync(channelDir);
|
|
427
410
|
state = {
|
|
428
411
|
running: false,
|
|
429
|
-
runner: getOrCreateRunner(
|
|
412
|
+
runner: getOrCreateRunner(channelId, channelDir, {
|
|
430
413
|
appHomeDir: options.paths.appHomeDir,
|
|
431
414
|
authConfigPath: options.paths.authConfigPath,
|
|
432
415
|
modelsConfigPath: options.paths.modelsConfigPath,
|
|
@@ -446,6 +429,15 @@ export function createRuntimeContext(options) {
|
|
|
446
429
|
const state = channelStates.get(channelId);
|
|
447
430
|
if (state?.running) {
|
|
448
431
|
state.stopRequested = true;
|
|
432
|
+
const taskId = /^\[TASK_DRIVER:([A-Za-z0-9._-]+)\]/.exec(state.currentTaskText ?? "")?.[1];
|
|
433
|
+
if (taskId) {
|
|
434
|
+
const pauseResult = await pauseTask({
|
|
435
|
+
args: "",
|
|
436
|
+
channelDir: getChannelDir(options.paths.workspaceDir, channelId),
|
|
437
|
+
approver: "user via /stop",
|
|
438
|
+
}, taskId);
|
|
439
|
+
log.logInfo(`[${channelId}] ${pauseResult}`);
|
|
440
|
+
}
|
|
449
441
|
_bot.discardCard(channelId);
|
|
450
442
|
// Drop queued-but-not-started messages so a burst does not keep
|
|
451
443
|
// running after the user asked to halt; abort the in-flight one.
|
|
@@ -453,8 +445,12 @@ export function createRuntimeContext(options) {
|
|
|
453
445
|
if (dropped > 0) {
|
|
454
446
|
log.logInfo(`[${channelId}] Dropped ${dropped} queued message(s) on stop`);
|
|
455
447
|
}
|
|
448
|
+
const canceled = await durableDispatch?.cancelChannel(channelId);
|
|
449
|
+
if (canceled) {
|
|
450
|
+
log.logInfo(`[${channelId}] Reset ${canceled} durable-dispatch lease(s) on stop`);
|
|
451
|
+
}
|
|
456
452
|
void state.runner.abort().catch((err) => {
|
|
457
|
-
log.logWarning(`[${channelId}] Failed to abort run`,
|
|
453
|
+
log.logWarning(`[${channelId}] Failed to abort run`, errorMessage(err));
|
|
458
454
|
});
|
|
459
455
|
log.logInfo(`[${channelId}] Stop requested`);
|
|
460
456
|
}
|
|
@@ -473,6 +469,14 @@ export function createRuntimeContext(options) {
|
|
|
473
469
|
channelDir: getChannelDir(options.paths.workspaceDir, event.channelId),
|
|
474
470
|
workspaceDir: options.paths.workspaceDir,
|
|
475
471
|
channelId: event.channelId,
|
|
472
|
+
approver: event.userName && event.userName !== event.user ? `${event.userName} (${event.user})` : event.user,
|
|
473
|
+
dispatchTask: async (id) => {
|
|
474
|
+
const channelDir = getChannelDir(options.paths.workspaceDir, event.channelId);
|
|
475
|
+
const entry = (await readActiveTasks(join(channelDir, "tasks"))).find((candidate) => candidate.id === id);
|
|
476
|
+
return entry
|
|
477
|
+
? (durableDispatch?.dispatch(createTaskDriverEvent(event.channelId, entry, Date.now())) ?? false)
|
|
478
|
+
: false;
|
|
479
|
+
},
|
|
476
480
|
});
|
|
477
481
|
await bot.sendPlain(event.channelId, response);
|
|
478
482
|
},
|
|
@@ -481,7 +485,6 @@ export function createRuntimeContext(options) {
|
|
|
481
485
|
state: channelStates.get(event.channelId),
|
|
482
486
|
version: cliVersion,
|
|
483
487
|
uptimeMs: Date.now() - startedAt,
|
|
484
|
-
sandbox: options.sandbox,
|
|
485
488
|
});
|
|
486
489
|
await bot.sendPlain(event.channelId, response);
|
|
487
490
|
},
|
|
@@ -524,7 +527,7 @@ export function createRuntimeContext(options) {
|
|
|
524
527
|
return { kind: "handled" };
|
|
525
528
|
}
|
|
526
529
|
catch (err) {
|
|
527
|
-
const errMsg =
|
|
530
|
+
const errMsg = errorMessage(err);
|
|
528
531
|
if (isNoRunningTaskQueueError(err)) {
|
|
529
532
|
log.logInfo(`[${event.channelId}] Busy ${mode} window closed; requeueing as a normal message`);
|
|
530
533
|
return { kind: "requeue", text: trimmedQueueText };
|
|
@@ -547,6 +550,7 @@ export function createRuntimeContext(options) {
|
|
|
547
550
|
// routed as a fresh run instead of a steer/follow-up.
|
|
548
551
|
state.running = true;
|
|
549
552
|
state.stopRequested = false;
|
|
553
|
+
await durableDispatch?.markStarted(event.dispatchId);
|
|
550
554
|
const task = (async () => {
|
|
551
555
|
try {
|
|
552
556
|
await archiveIncomingMessage(event.channelId, {
|
|
@@ -586,14 +590,25 @@ export function createRuntimeContext(options) {
|
|
|
586
590
|
ctx.primeCard(350);
|
|
587
591
|
}
|
|
588
592
|
const result = await state.runner.run(ctx, store);
|
|
593
|
+
const taskDriverMatch = /^\[TASK_DRIVER:([A-Za-z0-9._-]+)\]/.exec(event.text);
|
|
594
|
+
if (taskDriverMatch?.[1] && result.usage && result.durationMs !== undefined) {
|
|
595
|
+
await finishTaskAttempt(getChannelDir(options.paths.workspaceDir, event.channelId), taskDriverMatch[1], {
|
|
596
|
+
tokens: result.usage.total,
|
|
597
|
+
costUsd: result.usage.cost.total,
|
|
598
|
+
wallTimeMinutes: result.durationMs / 60_000,
|
|
599
|
+
failed: result.stopReason === "error" || result.stopReason === "aborted",
|
|
600
|
+
finishedAt: new Date(),
|
|
601
|
+
});
|
|
602
|
+
}
|
|
589
603
|
if (result.stopReason === "aborted" && state.stopRequested) {
|
|
590
604
|
log.logInfo(`[${event.channelId}] Stopped`);
|
|
591
605
|
}
|
|
592
606
|
}
|
|
593
607
|
catch (err) {
|
|
594
|
-
log.logWarning(`[${event.channelId}] Run error`,
|
|
608
|
+
log.logWarning(`[${event.channelId}] Run error`, errorMessage(err));
|
|
595
609
|
}
|
|
596
610
|
finally {
|
|
611
|
+
await durableDispatch?.markCompleted(event.dispatchId);
|
|
597
612
|
state.running = false;
|
|
598
613
|
state.currentTaskText = undefined;
|
|
599
614
|
}
|
|
@@ -610,10 +625,14 @@ export function createRuntimeContext(options) {
|
|
|
610
625
|
const bot = options.createBot
|
|
611
626
|
? options.createBot(handler, options.dingtalkConfig)
|
|
612
627
|
: new DingTalkBot(handler, options.dingtalkConfig);
|
|
613
|
-
|
|
628
|
+
durableDispatch = new DurableDispatchService({
|
|
629
|
+
stateDir: join(options.paths.appHomeDir, "state", "dispatch"),
|
|
630
|
+
bot,
|
|
631
|
+
});
|
|
632
|
+
const executor = createExecutor();
|
|
614
633
|
const eventsWatcher = options.createEventsWatcher
|
|
615
634
|
? options.createEventsWatcher(options.paths.workspaceDir, bot, executor, options.paths.eventHistoryPath)
|
|
616
|
-
: createEventsWatcher(options.paths.workspaceDir, bot, executor, loadSecurityConfigWithDiagnostics(options.paths.appHomeDir).config.commandGuard, options.paths.eventHistoryPath);
|
|
635
|
+
: createEventsWatcher(options.paths.workspaceDir, bot, executor, loadSecurityConfigWithDiagnostics(options.paths.appHomeDir).config.commandGuard, options.paths.eventHistoryPath, (event) => durableDispatch?.dispatch(event) ?? false);
|
|
617
636
|
const memoryMaintenanceScheduler = options.createMemoryMaintenanceScheduler
|
|
618
637
|
? options.createMemoryMaintenanceScheduler()
|
|
619
638
|
: new MemoryMaintenanceScheduler({
|
|
@@ -633,6 +652,19 @@ export function createRuntimeContext(options) {
|
|
|
633
652
|
},
|
|
634
653
|
intervalMs: options.memoryMaintenanceSchedulerIntervalMs,
|
|
635
654
|
});
|
|
655
|
+
const taskDriver = options.createTaskDriver
|
|
656
|
+
? options.createTaskDriver()
|
|
657
|
+
: new TaskDriver({
|
|
658
|
+
workspaceDir: options.paths.workspaceDir,
|
|
659
|
+
getKnownChannelIds: () => channelStates.keys(),
|
|
660
|
+
isChannelActive: (channelId) => channelStates.get(channelId)?.running ?? false,
|
|
661
|
+
dispatch: (event) => durableDispatch?.dispatch(event) ?? false,
|
|
662
|
+
getSettings: () => {
|
|
663
|
+
runtimeSettingsManager.reload();
|
|
664
|
+
return runtimeSettingsManager.getTaskDriverSettings();
|
|
665
|
+
},
|
|
666
|
+
intervalMs: options.taskDriverIntervalMs,
|
|
667
|
+
});
|
|
636
668
|
const shutdownWithReason = async (reason = "manual") => {
|
|
637
669
|
if (shutdownPromise) {
|
|
638
670
|
return shutdownPromise;
|
|
@@ -640,6 +672,8 @@ export function createRuntimeContext(options) {
|
|
|
640
672
|
shutdownPromise = (async () => {
|
|
641
673
|
shuttingDown = true;
|
|
642
674
|
log.logInfo(`Shutting down (${reason})...`);
|
|
675
|
+
taskDriver.stop();
|
|
676
|
+
durableDispatch?.stop();
|
|
643
677
|
memoryMaintenanceScheduler.stop();
|
|
644
678
|
eventsWatcher.stop();
|
|
645
679
|
await bot.stop();
|
|
@@ -656,7 +690,7 @@ export function createRuntimeContext(options) {
|
|
|
656
690
|
state.stopRequested = true;
|
|
657
691
|
log.logInfo(`[${channelId}] Aborting active run for shutdown`);
|
|
658
692
|
aborts.push(state.runner.abort().catch((err) => {
|
|
659
|
-
log.logWarning(`[${channelId}] Failed to abort run during shutdown`,
|
|
693
|
+
log.logWarning(`[${channelId}] Failed to abort run during shutdown`, errorMessage(err));
|
|
660
694
|
}));
|
|
661
695
|
}
|
|
662
696
|
await Promise.allSettled(aborts);
|
|
@@ -703,6 +737,8 @@ export function createRuntimeContext(options) {
|
|
|
703
737
|
if (startServices) {
|
|
704
738
|
eventsWatcher.start();
|
|
705
739
|
memoryMaintenanceScheduler.start();
|
|
740
|
+
taskDriver.start();
|
|
741
|
+
durableDispatch.start();
|
|
706
742
|
void bot.start();
|
|
707
743
|
}
|
|
708
744
|
return {
|
|
@@ -714,9 +750,9 @@ export function createRuntimeContext(options) {
|
|
|
714
750
|
}
|
|
715
751
|
/**
|
|
716
752
|
* Transport-neutral app services shared by the DingTalk runtime and the terminal
|
|
717
|
-
* TUI: loads settings (surfacing load errors)
|
|
718
|
-
* diagnostics
|
|
719
|
-
*
|
|
753
|
+
* TUI: loads settings (surfacing load errors) and reports tool/security config
|
|
754
|
+
* diagnostics. Does NOT touch DingTalk config, so the TUI can call it without any
|
|
755
|
+
* DingTalk credentials.
|
|
720
756
|
*
|
|
721
757
|
* Extracted verbatim from `bootstrap()`; the DingTalk path calls it in the same
|
|
722
758
|
* position (after `loadConfig`, before `logStartup`) so its behavior is
|
|
@@ -724,7 +760,7 @@ export function createRuntimeContext(options) {
|
|
|
724
760
|
* (DingTalk: `createRuntimeContext`; TUI: right after this) to preserve the
|
|
725
761
|
* existing "diagnostics logged with default logging config" ordering.
|
|
726
762
|
*/
|
|
727
|
-
export
|
|
763
|
+
export function prepareAppServices(paths = DEFAULT_BOOTSTRAP_PATHS) {
|
|
728
764
|
const settingsManager = new PipiclawSettingsManager(paths.appHomeDir);
|
|
729
765
|
for (const { scope, error } of settingsManager.drainErrors()) {
|
|
730
766
|
log.logWarning(`Failed to load ${scope} settings`, `${error.message}\n${paths.settingsConfigPath}`);
|
|
@@ -735,16 +771,6 @@ export async function prepareAppServices(sandbox, paths = DEFAULT_BOOTSTRAP_PATH
|
|
|
735
771
|
for (const diagnostic of loadSecurityConfigWithDiagnostics(paths.appHomeDir).diagnostics) {
|
|
736
772
|
log.logWarning(formatConfigDiagnostic(diagnostic), diagnostic.path);
|
|
737
773
|
}
|
|
738
|
-
try {
|
|
739
|
-
await validateSandbox(sandbox);
|
|
740
|
-
}
|
|
741
|
-
catch (err) {
|
|
742
|
-
if (err instanceof SandboxConfigError) {
|
|
743
|
-
io.error(`Error: ${err.message}`);
|
|
744
|
-
throw new BootstrapExitError(1);
|
|
745
|
-
}
|
|
746
|
-
throw err;
|
|
747
|
-
}
|
|
748
774
|
return { settingsManager };
|
|
749
775
|
}
|
|
750
776
|
export async function bootstrap(argv, options = {}) {
|
|
@@ -752,8 +778,7 @@ export async function bootstrap(argv, options = {}) {
|
|
|
752
778
|
const paths = options.paths ?? DEFAULT_BOOTSTRAP_PATHS;
|
|
753
779
|
const registerSignalHandlers = options.registerSignalHandlers ?? true;
|
|
754
780
|
const startServices = options.startServices ?? true;
|
|
755
|
-
|
|
756
|
-
const sandbox = parsedArgs.sandbox;
|
|
781
|
+
parseArgs(argv, paths, io);
|
|
757
782
|
const bootstrapResult = bootstrapAppHome(paths);
|
|
758
783
|
printBootstrapSummary(bootstrapResult, io, paths);
|
|
759
784
|
if (bootstrapResult.channelTemplateCreated) {
|
|
@@ -762,11 +787,10 @@ export async function bootstrap(argv, options = {}) {
|
|
|
762
787
|
}
|
|
763
788
|
const dingtalkConfig = loadConfig(paths, io);
|
|
764
789
|
dingtalkConfig.stateDir = paths.workspaceDir;
|
|
765
|
-
|
|
766
|
-
log.logStartup(paths.workspaceDir
|
|
790
|
+
prepareAppServices(paths);
|
|
791
|
+
log.logStartup(paths.workspaceDir);
|
|
767
792
|
const runtime = createRuntimeContext({
|
|
768
793
|
paths,
|
|
769
|
-
sandbox,
|
|
770
794
|
dingtalkConfig,
|
|
771
795
|
registerSignalHandlers,
|
|
772
796
|
startServices,
|
package/dist/runtime/delivery.js
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import * as log from "../log.js";
|
|
2
|
+
import { errorMessage } from "../shared/text-utils.js";
|
|
2
3
|
const MIN_UPDATE_INTERVAL_MS = 800;
|
|
3
4
|
const ROLLING_WINDOW_SIZE = 3;
|
|
4
5
|
const NO_CONTENT = "";
|
|
@@ -86,7 +87,7 @@ class ChannelDeliveryController {
|
|
|
86
87
|
await this.bot.ensureCard(this.event.channelId);
|
|
87
88
|
}
|
|
88
89
|
catch (err) {
|
|
89
|
-
log.logWarning(`[${this.event.channelId}] Failed to warm AI card`,
|
|
90
|
+
log.logWarning(`[${this.event.channelId}] Failed to warm AI card`, errorMessage(err));
|
|
90
91
|
this.bot.discardCard(this.event.channelId);
|
|
91
92
|
}
|
|
92
93
|
}
|
|
@@ -99,7 +100,7 @@ class ChannelDeliveryController {
|
|
|
99
100
|
}
|
|
100
101
|
archiveBotResponse(text) {
|
|
101
102
|
void this.store.logBotResponse(this.event.channelId, text, Date.now().toString()).catch((err) => {
|
|
102
|
-
log.logWarning(`[${this.event.channelId}] Failed to archive bot response`,
|
|
103
|
+
log.logWarning(`[${this.event.channelId}] Failed to archive bot response`, errorMessage(err));
|
|
103
104
|
});
|
|
104
105
|
}
|
|
105
106
|
async appendProgress(text, shouldLog) {
|
|
@@ -272,7 +273,7 @@ class ChannelDeliveryController {
|
|
|
272
273
|
}
|
|
273
274
|
}
|
|
274
275
|
catch (err) {
|
|
275
|
-
log.logWarning(`[${this.event.channelId}] Delivery sync failed`,
|
|
276
|
+
log.logWarning(`[${this.event.channelId}] Delivery sync failed`, errorMessage(err));
|
|
276
277
|
this.bot.discardCard(this.event.channelId);
|
|
277
278
|
if (mode === "progress") {
|
|
278
279
|
this.replayRequired = true;
|
|
@@ -29,6 +29,8 @@ export interface DingTalkEvent {
|
|
|
29
29
|
text: string;
|
|
30
30
|
conversationId: string;
|
|
31
31
|
conversationType: string;
|
|
32
|
+
/** Runtime-owned durable-dispatch record, absent for normal inbound messages. */
|
|
33
|
+
dispatchId?: string;
|
|
32
34
|
}
|
|
33
35
|
export type BusyMessageResult = {
|
|
34
36
|
kind: "handled";
|
package/dist/runtime/dingtalk.js
CHANGED
|
@@ -13,6 +13,7 @@ import { existsSync, mkdirSync, readFileSync, writeFileSync } from "fs";
|
|
|
13
13
|
import { dirname, join } from "path";
|
|
14
14
|
import { parseBuiltInCommand, renderBuiltInHelp } from "../agent/commands.js";
|
|
15
15
|
import * as log from "../log.js";
|
|
16
|
+
import { errorMessage } from "../shared/text-utils.js";
|
|
16
17
|
import { isRecord } from "../shared/type-guards.js";
|
|
17
18
|
import { getChannelDir } from "./channel-paths.js";
|
|
18
19
|
const RESPONSE_MODE_VALUES = [
|
|
@@ -81,7 +82,7 @@ class ChannelQueue {
|
|
|
81
82
|
await work();
|
|
82
83
|
}
|
|
83
84
|
catch (err) {
|
|
84
|
-
log.logWarning("Queue error",
|
|
85
|
+
log.logWarning("Queue error", errorMessage(err));
|
|
85
86
|
}
|
|
86
87
|
this.processing = false;
|
|
87
88
|
this.processNext();
|
|
@@ -302,7 +303,7 @@ export class DingTalkBot {
|
|
|
302
303
|
socket.close?.();
|
|
303
304
|
}
|
|
304
305
|
catch (err) {
|
|
305
|
-
log.logWarning(`DingTalk: socket close failed during ${reason}`,
|
|
306
|
+
log.logWarning(`DingTalk: socket close failed during ${reason}`, errorMessage(err));
|
|
306
307
|
}
|
|
307
308
|
const closed = await this.waitForSocketState(socket, SOCKET_STATE_CLOSED, SOCKET_CLOSE_GRACE_MS);
|
|
308
309
|
if (!closed) {
|
|
@@ -311,7 +312,7 @@ export class DingTalkBot {
|
|
|
311
312
|
socket.terminate?.();
|
|
312
313
|
}
|
|
313
314
|
catch (err) {
|
|
314
|
-
log.logWarning(`DingTalk: socket terminate failed during ${reason}`,
|
|
315
|
+
log.logWarning(`DingTalk: socket terminate failed during ${reason}`, errorMessage(err));
|
|
315
316
|
}
|
|
316
317
|
await this.waitForSocketState(socket, SOCKET_STATE_CLOSED, SOCKET_TERMINATE_GRACE_MS);
|
|
317
318
|
}
|
|
@@ -358,7 +359,7 @@ export class DingTalkBot {
|
|
|
358
359
|
this.reconnectTimer = this.setTrackedTimeout(() => {
|
|
359
360
|
this.reconnectTimer = null;
|
|
360
361
|
this.doReconnect(immediate).catch((err) => {
|
|
361
|
-
log.logWarning("DingTalk: reconnect failed",
|
|
362
|
+
log.logWarning("DingTalk: reconnect failed", errorMessage(err));
|
|
362
363
|
});
|
|
363
364
|
}, delayMs);
|
|
364
365
|
}
|
|
@@ -410,11 +411,11 @@ export class DingTalkBot {
|
|
|
410
411
|
}
|
|
411
412
|
// Fire-and-forget processing
|
|
412
413
|
this.onStreamMessage(data).catch((err) => {
|
|
413
|
-
log.logWarning("DingTalk handler error",
|
|
414
|
+
log.logWarning("DingTalk handler error", errorMessage(err));
|
|
414
415
|
});
|
|
415
416
|
}
|
|
416
417
|
catch (err) {
|
|
417
|
-
log.logWarning("DingTalk: failed to parse message",
|
|
418
|
+
log.logWarning("DingTalk: failed to parse message", errorMessage(err));
|
|
418
419
|
}
|
|
419
420
|
return { status: "SUCCESS", message: "OK" };
|
|
420
421
|
}
|
|
@@ -508,7 +509,7 @@ export class DingTalkBot {
|
|
|
508
509
|
await this.cleanupSocket("reconnect failure");
|
|
509
510
|
this.reconnectAttempts++;
|
|
510
511
|
connectionFailed = true;
|
|
511
|
-
log.logWarning("DingTalk: connection failed",
|
|
512
|
+
log.logWarning("DingTalk: connection failed", errorMessage(err));
|
|
512
513
|
}
|
|
513
514
|
finally {
|
|
514
515
|
this.isReconnecting = false;
|
|
@@ -531,7 +532,7 @@ export class DingTalkBot {
|
|
|
531
532
|
await this.cleanupSocket("stop");
|
|
532
533
|
}
|
|
533
534
|
catch (err) {
|
|
534
|
-
log.logWarning("DingTalk: failed to disconnect cleanly",
|
|
535
|
+
log.logWarning("DingTalk: failed to disconnect cleanly", errorMessage(err));
|
|
535
536
|
}
|
|
536
537
|
finally {
|
|
537
538
|
this.client = null;
|
|
@@ -725,7 +726,7 @@ export class DingTalkBot {
|
|
|
725
726
|
log.logWarning(`DingTalk plain send failed (${err.response.status})`, JSON.stringify(err.response.data));
|
|
726
727
|
}
|
|
727
728
|
else {
|
|
728
|
-
log.logWarning("DingTalk plain send error",
|
|
729
|
+
log.logWarning("DingTalk plain send error", errorMessage(err));
|
|
729
730
|
}
|
|
730
731
|
return false;
|
|
731
732
|
}
|
|
@@ -805,7 +806,7 @@ export class DingTalkBot {
|
|
|
805
806
|
log.logWarning(`DingTalk Card: create failed (${err.response.status})`, JSON.stringify(err.response.data));
|
|
806
807
|
}
|
|
807
808
|
else {
|
|
808
|
-
log.logWarning("DingTalk Card: create failed",
|
|
809
|
+
log.logWarning("DingTalk Card: create failed", errorMessage(err));
|
|
809
810
|
}
|
|
810
811
|
return null;
|
|
811
812
|
}
|
|
@@ -867,7 +868,7 @@ export class DingTalkBot {
|
|
|
867
868
|
log.logWarning(`DingTalk Card: streaming failed (${err.response.status})`, JSON.stringify(err.response.data));
|
|
868
869
|
}
|
|
869
870
|
else {
|
|
870
|
-
log.logWarning("DingTalk Card: streaming failed",
|
|
871
|
+
log.logWarning("DingTalk Card: streaming failed", errorMessage(err));
|
|
871
872
|
}
|
|
872
873
|
return false;
|
|
873
874
|
}
|
|
@@ -905,7 +906,7 @@ export class DingTalkBot {
|
|
|
905
906
|
log.logWarning(`DingTalk: failed to get access token (${err.response.status})`, JSON.stringify(err.response.data));
|
|
906
907
|
}
|
|
907
908
|
else {
|
|
908
|
-
log.logWarning("DingTalk: failed to get access token",
|
|
909
|
+
log.logWarning("DingTalk: failed to get access token", errorMessage(err));
|
|
909
910
|
}
|
|
910
911
|
return null;
|
|
911
912
|
}
|
|
@@ -1069,7 +1070,7 @@ export class DingTalkBot {
|
|
|
1069
1070
|
return meta;
|
|
1070
1071
|
}
|
|
1071
1072
|
catch (err) {
|
|
1072
|
-
log.logWarning(`Failed to load conversation metadata for ${channelId}`,
|
|
1073
|
+
log.logWarning(`Failed to load conversation metadata for ${channelId}`, errorMessage(err));
|
|
1073
1074
|
return null;
|
|
1074
1075
|
}
|
|
1075
1076
|
}
|
|
@@ -1083,7 +1084,7 @@ export class DingTalkBot {
|
|
|
1083
1084
|
writeFileSync(metaPath, JSON.stringify(meta, null, 2), "utf-8");
|
|
1084
1085
|
}
|
|
1085
1086
|
catch (err) {
|
|
1086
|
-
log.logWarning(`Failed to persist conversation metadata for ${channelId}`,
|
|
1087
|
+
log.logWarning(`Failed to persist conversation metadata for ${channelId}`, errorMessage(err));
|
|
1087
1088
|
}
|
|
1088
1089
|
}
|
|
1089
1090
|
getConversationMetaPath(channelId) {
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
import type { DingTalkBot, DingTalkEvent } from "./dingtalk.js";
|
|
2
|
+
export interface DurableDispatchOptions {
|
|
3
|
+
stateDir: string;
|
|
4
|
+
bot: Pick<DingTalkBot, "enqueueEvent">;
|
|
5
|
+
leaseMs?: number;
|
|
6
|
+
intervalMs?: number;
|
|
7
|
+
}
|
|
8
|
+
/**
|
|
9
|
+
* Tiny file-backed outbox for synthetic work. It intentionally provides
|
|
10
|
+
* at-least-once delivery: a crash after enqueue may replay a task/event, while
|
|
11
|
+
* a crash can no longer silently discard it merely because it left an in-memory
|
|
12
|
+
* channel queue.
|
|
13
|
+
*/
|
|
14
|
+
export declare class DurableDispatchService {
|
|
15
|
+
private readonly options;
|
|
16
|
+
private readonly queue;
|
|
17
|
+
private readonly leaseMs;
|
|
18
|
+
private timer;
|
|
19
|
+
constructor(options: DurableDispatchOptions);
|
|
20
|
+
start(): void;
|
|
21
|
+
stop(): void;
|
|
22
|
+
dispatch(event: DingTalkEvent): Promise<boolean>;
|
|
23
|
+
/** Reset any in-flight records for a channel so a stop/abort can redeliver on the next tick, not after the lease expires. */
|
|
24
|
+
cancelChannel(channelId: string): Promise<number>;
|
|
25
|
+
markStarted(id: string | undefined): Promise<void>;
|
|
26
|
+
markCompleted(id: string | undefined): Promise<void>;
|
|
27
|
+
drainOnce(now?: number): Promise<void>;
|
|
28
|
+
private read;
|
|
29
|
+
private write;
|
|
30
|
+
}
|