@oyasmi/pipiclaw 0.6.10 → 0.7.0
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 +1 -1
- package/dist/agent/channel-runner.d.ts +12 -1
- package/dist/agent/channel-runner.js +58 -3
- package/dist/agent/commands.d.ts +1 -1
- package/dist/agent/commands.js +10 -0
- package/dist/agent/prompt-builder.d.ts +17 -0
- package/dist/agent/prompt-builder.js +42 -23
- package/dist/agent/session-events.d.ts +2 -0
- package/dist/agent/session-events.js +31 -12
- package/dist/agent/types.d.ts +9 -0
- package/dist/agent/types.js +8 -0
- package/dist/index.d.ts +2 -0
- package/dist/index.js +2 -0
- package/dist/log.d.ts +24 -0
- package/dist/log.js +96 -1
- package/dist/memory/bootstrap.js +35 -1
- package/dist/memory/candidates.js +21 -3
- package/dist/memory/consolidation.d.ts +7 -1
- package/dist/memory/consolidation.js +107 -36
- package/dist/memory/files.d.ts +40 -0
- package/dist/memory/files.js +0 -0
- package/dist/memory/lifecycle.js +2 -0
- package/dist/memory/maintenance-jobs.js +10 -4
- package/dist/memory/post-turn-review.js +4 -2
- package/dist/memory/promotion-signals.js +0 -1
- package/dist/memory/recall.d.ts +1 -0
- package/dist/memory/recall.js +11 -2
- package/dist/memory/session-search.d.ts +1 -0
- package/dist/memory/session-search.js +1 -0
- package/dist/memory/session.d.ts +1 -0
- package/dist/memory/session.js +44 -13
- package/dist/memory/sidecar-worker.d.ts +4 -0
- package/dist/memory/sidecar-worker.js +29 -0
- package/dist/memory/transcript.d.ts +9 -0
- package/dist/memory/transcript.js +30 -0
- package/dist/paths.d.ts +3 -0
- package/dist/paths.js +3 -0
- package/dist/runtime/bootstrap.js +151 -15
- package/dist/runtime/delivery.js +17 -0
- package/dist/runtime/dingtalk.d.ts +2 -0
- package/dist/runtime/dingtalk.js +19 -4
- package/dist/sandbox.d.ts +8 -0
- package/dist/sandbox.js +21 -17
- package/dist/settings.d.ts +16 -0
- package/dist/settings.js +22 -0
- package/dist/shared/jsonl-appender.d.ts +25 -0
- package/dist/shared/jsonl-appender.js +85 -0
- package/dist/subagents/tool.d.ts +2 -2
- package/dist/subagents/tool.js +25 -56
- package/dist/tools/bash.d.ts +8 -1
- package/dist/tools/bash.js +46 -21
- package/dist/tools/config.d.ts +3 -0
- package/dist/tools/config.js +9 -0
- package/dist/tools/edit.d.ts +1 -0
- package/dist/tools/edit.js +18 -11
- package/dist/tools/index.js +18 -53
- package/dist/tools/memory-save.d.ts +17 -0
- package/dist/tools/memory-save.js +43 -0
- package/dist/tools/read.d.ts +2 -2
- package/dist/tools/read.js +2 -2
- package/dist/tools/registry.d.ts +63 -0
- package/dist/tools/registry.js +154 -0
- package/dist/tools/session-search.d.ts +3 -2
- package/dist/tools/session-search.js +10 -5
- package/dist/tools/skill-list.js +1 -1
- package/dist/tools/skill-manage.d.ts +1 -1
- package/dist/tools/skill-manage.js +3 -1
- package/dist/tools/skill-view.js +12 -11
- package/dist/tools/web-search.d.ts +1 -1
- package/dist/tools/web-search.js +1 -1
- package/dist/usage/ledger.d.ts +47 -0
- package/dist/usage/ledger.js +95 -0
- package/dist/usage/render.d.ts +11 -0
- package/dist/usage/render.js +67 -0
- package/package.json +5 -5
- package/dist/tools/attach.d.ts +0 -20
- package/dist/tools/attach.js +0 -69
package/dist/runtime/delivery.js
CHANGED
|
@@ -2,6 +2,10 @@ import * as log from "../log.js";
|
|
|
2
2
|
const MIN_UPDATE_INTERVAL_MS = 800;
|
|
3
3
|
const ROLLING_WINDOW_SIZE = 3;
|
|
4
4
|
const NO_CONTENT = "";
|
|
5
|
+
// Last-resort ceiling on how long flush() will block a caller. Outbound HTTP now
|
|
6
|
+
// has its own timeout, so the sync loop is already bounded; this only guards against
|
|
7
|
+
// an unforeseen stall so run()'s finally can never hang the channel forever.
|
|
8
|
+
const FLUSH_DEADLINE_MS = 60_000;
|
|
5
9
|
class ChannelDeliveryController {
|
|
6
10
|
constructor(event, bot, store) {
|
|
7
11
|
this.event = event;
|
|
@@ -306,8 +310,21 @@ class ChannelDeliveryController {
|
|
|
306
310
|
async flush() {
|
|
307
311
|
if (this.isSettled())
|
|
308
312
|
return;
|
|
313
|
+
let deadlineTimer = null;
|
|
309
314
|
await new Promise((resolve) => {
|
|
310
315
|
this.flushWaiters.push(resolve);
|
|
316
|
+
deadlineTimer = setTimeout(() => {
|
|
317
|
+
if (this.flushWaiters.includes(resolve)) {
|
|
318
|
+
log.logWarning(`[${this.event.channelId}] Delivery flush deadline exceeded (${FLUSH_DEADLINE_MS}ms); releasing caller`);
|
|
319
|
+
this.flushWaiters = this.flushWaiters.filter((waiter) => waiter !== resolve);
|
|
320
|
+
resolve();
|
|
321
|
+
}
|
|
322
|
+
}, FLUSH_DEADLINE_MS);
|
|
323
|
+
deadlineTimer.unref?.();
|
|
324
|
+
}).finally(() => {
|
|
325
|
+
if (deadlineTimer) {
|
|
326
|
+
clearTimeout(deadlineTimer);
|
|
327
|
+
}
|
|
311
328
|
});
|
|
312
329
|
}
|
|
313
330
|
async close() {
|
|
@@ -65,6 +65,8 @@ export interface DingTalkHandler {
|
|
|
65
65
|
handleEvent(event: DingTalkEvent, bot: DingTalkBot, isEvent?: boolean): Promise<void>;
|
|
66
66
|
handleStop(channelId: string, bot: DingTalkBot): Promise<void>;
|
|
67
67
|
handleEventsCommand(event: DingTalkEvent, bot: DingTalkBot, args: string): Promise<void>;
|
|
68
|
+
handleStatusCommand(event: DingTalkEvent, bot: DingTalkBot): Promise<void>;
|
|
69
|
+
handleUsageCommand(event: DingTalkEvent, bot: DingTalkBot, args: string): Promise<void>;
|
|
68
70
|
handleBusyMessage(event: DingTalkEvent, bot: DingTalkBot, mode: BusyMessageMode, queueText: string): Promise<BusyMessageResult>;
|
|
69
71
|
}
|
|
70
72
|
export declare class DingTalkBot {
|
package/dist/runtime/dingtalk.js
CHANGED
|
@@ -103,6 +103,13 @@ class ChannelQueue {
|
|
|
103
103
|
// Constants
|
|
104
104
|
// ============================================================================
|
|
105
105
|
const DINGTALK_API = "https://api.dingtalk.com";
|
|
106
|
+
// Bound every outbound DingTalk HTTP call. Without this, axios waits forever on a
|
|
107
|
+
// hung connection, and a stalled card-streaming request would wedge the delivery
|
|
108
|
+
// sync loop (never resolving flush()), leaving the whole channel permanently busy.
|
|
109
|
+
// A timeout turns "hang" into a normal failure that the existing fallback paths
|
|
110
|
+
// (discardCard / replay / sendPlain) already handle.
|
|
111
|
+
const DINGTALK_HTTP_TIMEOUT_MS = 15_000;
|
|
112
|
+
const http = axios.create({ timeout: DINGTALK_HTTP_TIMEOUT_MS });
|
|
106
113
|
const TOKEN_REFRESH_SECS = 90 * 60; // 1.5 hours (tokens expire after 2 hours)
|
|
107
114
|
const CONNECT_ATTEMPT_TIMEOUT_MS = 10_000;
|
|
108
115
|
const SOCKET_CLOSE_GRACE_MS = 1_000;
|
|
@@ -693,7 +700,7 @@ export class DingTalkBot {
|
|
|
693
700
|
body.userIds = [meta.senderId];
|
|
694
701
|
}
|
|
695
702
|
try {
|
|
696
|
-
await
|
|
703
|
+
await http.post(url, body, {
|
|
697
704
|
headers: {
|
|
698
705
|
"x-acs-dingtalk-access-token": token,
|
|
699
706
|
"Content-Type": "application/json",
|
|
@@ -774,7 +781,7 @@ export class DingTalkBot {
|
|
|
774
781
|
body.imRobotOpenDeliverModel = { spaceType: "IM_ROBOT" };
|
|
775
782
|
}
|
|
776
783
|
try {
|
|
777
|
-
await
|
|
784
|
+
await http.post(`${DINGTALK_API}/v1.0/card/instances/createAndDeliver`, body, {
|
|
778
785
|
headers: {
|
|
779
786
|
"x-acs-dingtalk-access-token": token,
|
|
780
787
|
"Content-Type": "application/json",
|
|
@@ -826,7 +833,7 @@ export class DingTalkBot {
|
|
|
826
833
|
};
|
|
827
834
|
const start = Date.now();
|
|
828
835
|
try {
|
|
829
|
-
await
|
|
836
|
+
await http.put(`${DINGTALK_API}/v1.0/card/streaming`, body, {
|
|
830
837
|
headers: {
|
|
831
838
|
"x-acs-dingtalk-access-token": card.accessToken,
|
|
832
839
|
"Content-Type": "application/json",
|
|
@@ -870,7 +877,7 @@ export class DingTalkBot {
|
|
|
870
877
|
}
|
|
871
878
|
async refreshAccessToken() {
|
|
872
879
|
try {
|
|
873
|
-
const resp = await
|
|
880
|
+
const resp = await http.post(`${DINGTALK_API}/v1.0/oauth2/accessToken`, {
|
|
874
881
|
appKey: this.config.clientId,
|
|
875
882
|
appSecret: this.config.clientSecret,
|
|
876
883
|
}, {
|
|
@@ -983,6 +990,14 @@ export class DingTalkBot {
|
|
|
983
990
|
await this.handler.handleEventsCommand(event, this, builtInCommand.args);
|
|
984
991
|
return;
|
|
985
992
|
}
|
|
993
|
+
if (builtInCommand?.name === "status") {
|
|
994
|
+
await this.handler.handleStatusCommand(event, this);
|
|
995
|
+
return;
|
|
996
|
+
}
|
|
997
|
+
if (builtInCommand?.name === "usage") {
|
|
998
|
+
await this.handler.handleUsageCommand(event, this, builtInCommand.args);
|
|
999
|
+
return;
|
|
1000
|
+
}
|
|
986
1001
|
if (builtInCommand) {
|
|
987
1002
|
await this.sendPlain(channelId, `A task is already running. Use \`/stop\`, \`/steer <message>\`, \`/followup <message>\`, or \`/events <action>\`. Plain messages default to ${this.busyMessageDefault}.`);
|
|
988
1003
|
return;
|
package/dist/sandbox.d.ts
CHANGED
|
@@ -4,6 +4,14 @@ export type SandboxConfig = {
|
|
|
4
4
|
type: "docker";
|
|
5
5
|
container: string;
|
|
6
6
|
};
|
|
7
|
+
/**
|
|
8
|
+
* Error raised when sandbox configuration is invalid or the target sandbox is not
|
|
9
|
+
* usable. Thrown instead of calling process.exit so callers (bootstrap) decide how
|
|
10
|
+
* to surface it and the functions stay testable.
|
|
11
|
+
*/
|
|
12
|
+
export declare class SandboxConfigError extends Error {
|
|
13
|
+
constructor(message: string);
|
|
14
|
+
}
|
|
7
15
|
export declare function parseSandboxArg(value: string): SandboxConfig;
|
|
8
16
|
export declare function validateSandbox(config: SandboxConfig): Promise<void>;
|
|
9
17
|
/**
|
package/dist/sandbox.js
CHANGED
|
@@ -1,5 +1,16 @@
|
|
|
1
1
|
import { spawn, spawnSync } from "child_process";
|
|
2
2
|
import { shellEscape } from "./shared/shell-escape.js";
|
|
3
|
+
/**
|
|
4
|
+
* Error raised when sandbox configuration is invalid or the target sandbox is not
|
|
5
|
+
* usable. Thrown instead of calling process.exit so callers (bootstrap) decide how
|
|
6
|
+
* to surface it and the functions stay testable.
|
|
7
|
+
*/
|
|
8
|
+
export class SandboxConfigError extends Error {
|
|
9
|
+
constructor(message) {
|
|
10
|
+
super(message);
|
|
11
|
+
this.name = "SandboxConfigError";
|
|
12
|
+
}
|
|
13
|
+
}
|
|
3
14
|
export function parseSandboxArg(value) {
|
|
4
15
|
if (value === "host") {
|
|
5
16
|
return { type: "host" };
|
|
@@ -7,13 +18,11 @@ export function parseSandboxArg(value) {
|
|
|
7
18
|
if (value.startsWith("docker:")) {
|
|
8
19
|
const container = value.slice("docker:".length);
|
|
9
20
|
if (!container) {
|
|
10
|
-
|
|
11
|
-
process.exit(1);
|
|
21
|
+
throw new SandboxConfigError("docker sandbox requires container name (e.g., docker:pipiclaw-sandbox)");
|
|
12
22
|
}
|
|
13
23
|
return { type: "docker", container };
|
|
14
24
|
}
|
|
15
|
-
|
|
16
|
-
process.exit(1);
|
|
25
|
+
throw new SandboxConfigError(`Invalid sandbox type '${value}'. Use 'host' or 'docker:<container-name>'`);
|
|
17
26
|
}
|
|
18
27
|
export async function validateSandbox(config) {
|
|
19
28
|
if (config.type === "host") {
|
|
@@ -22,8 +31,7 @@ export async function validateSandbox(config) {
|
|
|
22
31
|
resolveWindowsHostShell();
|
|
23
32
|
}
|
|
24
33
|
catch (error) {
|
|
25
|
-
|
|
26
|
-
process.exit(1);
|
|
34
|
+
throw new SandboxConfigError(error instanceof Error ? error.message : String(error));
|
|
27
35
|
}
|
|
28
36
|
}
|
|
29
37
|
return;
|
|
@@ -33,22 +41,18 @@ export async function validateSandbox(config) {
|
|
|
33
41
|
await execSimple("docker", ["--version"]);
|
|
34
42
|
}
|
|
35
43
|
catch {
|
|
36
|
-
|
|
37
|
-
process.exit(1);
|
|
44
|
+
throw new SandboxConfigError("Docker is not installed or not in PATH");
|
|
38
45
|
}
|
|
39
46
|
// Check if container exists and is running
|
|
47
|
+
let running;
|
|
40
48
|
try {
|
|
41
|
-
|
|
42
|
-
if (result.trim() !== "true") {
|
|
43
|
-
console.error(`Error: Container '${config.container}' is not running.`);
|
|
44
|
-
console.error(`Start it with: docker start ${config.container}`);
|
|
45
|
-
process.exit(1);
|
|
46
|
-
}
|
|
49
|
+
running = await execSimple("docker", ["inspect", "-f", "{{.State.Running}}", config.container]);
|
|
47
50
|
}
|
|
48
51
|
catch {
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
+
throw new SandboxConfigError(`Container '${config.container}' does not exist.\nCreate it with: ./docker.sh create <data-dir>`);
|
|
53
|
+
}
|
|
54
|
+
if (running.trim() !== "true") {
|
|
55
|
+
throw new SandboxConfigError(`Container '${config.container}' is not running.\nStart it with: docker start ${config.container}`);
|
|
52
56
|
}
|
|
53
57
|
console.log(` Docker container '${config.container}' is running.`);
|
|
54
58
|
}
|
package/dist/settings.d.ts
CHANGED
|
@@ -87,6 +87,18 @@ export interface PipiclawMemoryMaintenanceSettings {
|
|
|
87
87
|
structuralMaintenanceIntervalHours: number;
|
|
88
88
|
maxConcurrentChannels: number;
|
|
89
89
|
failureBackoffMinutes: number;
|
|
90
|
+
/** Reject a MEMORY.md cleanup whose result shrinks below this ratio of the original. */
|
|
91
|
+
cleanupShrinkGuardMinRatio: number;
|
|
92
|
+
/** Only apply the shrink guard when the original exceeds this length (chars). */
|
|
93
|
+
cleanupShrinkGuardMinChars: number;
|
|
94
|
+
}
|
|
95
|
+
export interface PipiclawLoggingSettings {
|
|
96
|
+
level: "debug" | "info" | "warn" | "error";
|
|
97
|
+
file: {
|
|
98
|
+
enabled: boolean;
|
|
99
|
+
maxSizeBytes: number;
|
|
100
|
+
maxFiles: number;
|
|
101
|
+
};
|
|
90
102
|
}
|
|
91
103
|
export interface PipiclawSessionSearchSettings {
|
|
92
104
|
enabled: boolean;
|
|
@@ -107,6 +119,9 @@ export interface PipiclawSettings {
|
|
|
107
119
|
memoryGrowth?: Partial<PipiclawMemoryGrowthSettings>;
|
|
108
120
|
memoryMaintenance?: Partial<PipiclawMemoryMaintenanceSettings>;
|
|
109
121
|
sessionSearch?: Partial<PipiclawSessionSearchSettings>;
|
|
122
|
+
logging?: Partial<Omit<PipiclawLoggingSettings, "file">> & {
|
|
123
|
+
file?: Partial<PipiclawLoggingSettings["file"]>;
|
|
124
|
+
};
|
|
110
125
|
}
|
|
111
126
|
/**
|
|
112
127
|
* Settings manager for pipiclaw.
|
|
@@ -131,6 +146,7 @@ export declare class PipiclawSettingsManager {
|
|
|
131
146
|
getMemoryGrowthSettings(): PipiclawMemoryGrowthSettings;
|
|
132
147
|
getMemoryMaintenanceSettings(): PipiclawMemoryMaintenanceSettings;
|
|
133
148
|
getSessionSearchSettings(): PipiclawSessionSearchSettings;
|
|
149
|
+
getLoggingSettings(): PipiclawLoggingSettings;
|
|
134
150
|
getRetryEnabled(): boolean;
|
|
135
151
|
setRetryEnabled(enabled: boolean): void;
|
|
136
152
|
getDefaultModel(): string | undefined;
|
package/dist/settings.js
CHANGED
|
@@ -63,6 +63,18 @@ const DEFAULT_MEMORY_MAINTENANCE = {
|
|
|
63
63
|
structuralMaintenanceIntervalHours: 6,
|
|
64
64
|
maxConcurrentChannels: 1,
|
|
65
65
|
failureBackoffMinutes: 30,
|
|
66
|
+
cleanupShrinkGuardMinRatio: 0.4,
|
|
67
|
+
cleanupShrinkGuardMinChars: 2_000,
|
|
68
|
+
};
|
|
69
|
+
// `file.enabled` defaults to true: for a long-lived daemon, persisting logs is
|
|
70
|
+
// worth more than the surprise of a new file under state/logs/. See docs.
|
|
71
|
+
const DEFAULT_LOGGING = {
|
|
72
|
+
level: "info",
|
|
73
|
+
file: {
|
|
74
|
+
enabled: true,
|
|
75
|
+
maxSizeBytes: 5_000_000,
|
|
76
|
+
maxFiles: 3,
|
|
77
|
+
},
|
|
66
78
|
};
|
|
67
79
|
/**
|
|
68
80
|
* Settings manager for pipiclaw.
|
|
@@ -183,6 +195,16 @@ export class PipiclawSettingsManager {
|
|
|
183
195
|
...this.settings.sessionSearch,
|
|
184
196
|
};
|
|
185
197
|
}
|
|
198
|
+
getLoggingSettings() {
|
|
199
|
+
return {
|
|
200
|
+
...DEFAULT_LOGGING,
|
|
201
|
+
...this.settings.logging,
|
|
202
|
+
file: {
|
|
203
|
+
...DEFAULT_LOGGING.file,
|
|
204
|
+
...this.settings.logging?.file,
|
|
205
|
+
},
|
|
206
|
+
};
|
|
207
|
+
}
|
|
186
208
|
getRetryEnabled() {
|
|
187
209
|
return this.settings.retry?.enabled ?? DEFAULT_RETRY.enabled;
|
|
188
210
|
}
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
export interface JsonlAppenderOptions {
|
|
2
|
+
/** Fixed target file. Mutually exclusive with `pathFor`. */
|
|
3
|
+
path?: string;
|
|
4
|
+
/** Resolve the target file per append (e.g. monthly ledger files). */
|
|
5
|
+
pathFor?: (now: Date) => string;
|
|
6
|
+
/** Rotate when the file would exceed this size (bytes). Omit to disable. */
|
|
7
|
+
maxSizeBytes?: number;
|
|
8
|
+
/** Number of rotated backups to keep (`.1`..`.N`). Default 3. */
|
|
9
|
+
maxRotations?: number;
|
|
10
|
+
/** File mode for created files. Default 0o600. */
|
|
11
|
+
mode?: number;
|
|
12
|
+
}
|
|
13
|
+
export interface JsonlAppender {
|
|
14
|
+
/** Serialize `record` as one JSON line. Never throws. */
|
|
15
|
+
append(record: unknown): Promise<void>;
|
|
16
|
+
}
|
|
17
|
+
/**
|
|
18
|
+
* Append-only JSONL writer shared by the runtime log and the usage ledger.
|
|
19
|
+
*
|
|
20
|
+
* Writes are serialized per resolved file path, size-tracked in memory (one
|
|
21
|
+
* initial stat), and rotated via rename. Observability infrastructure must not
|
|
22
|
+
* reach back into the business path, so a failed append only warns once (until
|
|
23
|
+
* the next success) and never rejects.
|
|
24
|
+
*/
|
|
25
|
+
export declare function createJsonlAppender(options: JsonlAppenderOptions): JsonlAppender;
|
|
@@ -0,0 +1,85 @@
|
|
|
1
|
+
import { existsSync, mkdirSync, renameSync, statSync } from "node:fs";
|
|
2
|
+
import { appendFile } from "node:fs/promises";
|
|
3
|
+
import { dirname } from "node:path";
|
|
4
|
+
import { createSerialQueue } from "./serial-queue.js";
|
|
5
|
+
/**
|
|
6
|
+
* Append-only JSONL writer shared by the runtime log and the usage ledger.
|
|
7
|
+
*
|
|
8
|
+
* Writes are serialized per resolved file path, size-tracked in memory (one
|
|
9
|
+
* initial stat), and rotated via rename. Observability infrastructure must not
|
|
10
|
+
* reach back into the business path, so a failed append only warns once (until
|
|
11
|
+
* the next success) and never rejects.
|
|
12
|
+
*/
|
|
13
|
+
export function createJsonlAppender(options) {
|
|
14
|
+
if (!options.path && !options.pathFor) {
|
|
15
|
+
throw new Error("createJsonlAppender requires either `path` or `pathFor`");
|
|
16
|
+
}
|
|
17
|
+
const maxRotations = options.maxRotations ?? 3;
|
|
18
|
+
const mode = options.mode ?? 0o600;
|
|
19
|
+
const queue = createSerialQueue();
|
|
20
|
+
const sizes = new Map();
|
|
21
|
+
const ensuredDirs = new Set();
|
|
22
|
+
let warned = false;
|
|
23
|
+
const resolvePath = (now) => (options.pathFor ? options.pathFor(now) : options.path);
|
|
24
|
+
const ensureDir = (filePath) => {
|
|
25
|
+
const dir = dirname(filePath);
|
|
26
|
+
if (ensuredDirs.has(dir))
|
|
27
|
+
return;
|
|
28
|
+
mkdirSync(dir, { recursive: true });
|
|
29
|
+
ensuredDirs.add(dir);
|
|
30
|
+
};
|
|
31
|
+
const currentSize = (filePath) => {
|
|
32
|
+
const cached = sizes.get(filePath);
|
|
33
|
+
if (cached !== undefined)
|
|
34
|
+
return cached;
|
|
35
|
+
let size = 0;
|
|
36
|
+
try {
|
|
37
|
+
if (existsSync(filePath))
|
|
38
|
+
size = statSync(filePath).size;
|
|
39
|
+
}
|
|
40
|
+
catch {
|
|
41
|
+
size = 0;
|
|
42
|
+
}
|
|
43
|
+
sizes.set(filePath, size);
|
|
44
|
+
return size;
|
|
45
|
+
};
|
|
46
|
+
const rotate = (filePath) => {
|
|
47
|
+
for (let i = maxRotations - 1; i >= 1; i--) {
|
|
48
|
+
const from = `${filePath}.${i}`;
|
|
49
|
+
if (existsSync(from)) {
|
|
50
|
+
renameSync(from, `${filePath}.${i + 1}`);
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
if (existsSync(filePath)) {
|
|
54
|
+
renameSync(filePath, `${filePath}.1`);
|
|
55
|
+
}
|
|
56
|
+
sizes.set(filePath, 0);
|
|
57
|
+
};
|
|
58
|
+
const write = async (filePath, line) => {
|
|
59
|
+
ensureDir(filePath);
|
|
60
|
+
const lineBytes = Buffer.byteLength(line);
|
|
61
|
+
if (options.maxSizeBytes && options.maxSizeBytes > 0) {
|
|
62
|
+
if (currentSize(filePath) + lineBytes > options.maxSizeBytes && currentSize(filePath) > 0) {
|
|
63
|
+
rotate(filePath);
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
await appendFile(filePath, line, { encoding: "utf-8", mode });
|
|
67
|
+
sizes.set(filePath, currentSize(filePath) + lineBytes);
|
|
68
|
+
};
|
|
69
|
+
return {
|
|
70
|
+
async append(record) {
|
|
71
|
+
const filePath = resolvePath(new Date());
|
|
72
|
+
const line = `${JSON.stringify(record)}\n`;
|
|
73
|
+
try {
|
|
74
|
+
await queue.run(filePath, () => write(filePath, line));
|
|
75
|
+
warned = false;
|
|
76
|
+
}
|
|
77
|
+
catch (error) {
|
|
78
|
+
if (!warned) {
|
|
79
|
+
warned = true;
|
|
80
|
+
console.warn(`[jsonl-appender] Failed to append to ${filePath}: ${error instanceof Error ? error.message : String(error)}`);
|
|
81
|
+
}
|
|
82
|
+
}
|
|
83
|
+
},
|
|
84
|
+
};
|
|
85
|
+
}
|
package/dist/subagents/tool.d.ts
CHANGED
|
@@ -20,8 +20,8 @@ declare const subagentSchema: Type.TObject<{
|
|
|
20
20
|
maxToolCalls: Type.TOptional<Type.TNumber>;
|
|
21
21
|
maxWallTimeSec: Type.TOptional<Type.TNumber>;
|
|
22
22
|
bashTimeoutSec: Type.TOptional<Type.TNumber>;
|
|
23
|
-
contextMode: Type.TOptional<Type.
|
|
24
|
-
memory: Type.TOptional<Type.
|
|
23
|
+
contextMode: Type.TOptional<Type.TUnion<[Type.TLiteral<"isolated">, Type.TLiteral<"contextual">]>>;
|
|
24
|
+
memory: Type.TOptional<Type.TUnion<[Type.TLiteral<"none">, Type.TLiteral<"session">, Type.TLiteral<"relevant">]>>;
|
|
25
25
|
paths: Type.TOptional<Type.TArray<Type.TString>>;
|
|
26
26
|
}>;
|
|
27
27
|
export interface SubAgentToolDetails {
|
package/dist/subagents/tool.js
CHANGED
|
@@ -7,12 +7,7 @@ import { formatModelReference } from "../models/utils.js";
|
|
|
7
7
|
import { DEFAULT_SECURITY_CONFIG } from "../security/config.js";
|
|
8
8
|
import { splitH1Sections } from "../shared/markdown-sections.js";
|
|
9
9
|
import { clipText, extractAssistantText, extractLabelFromArgs, HAN_REGEX } from "../shared/text-utils.js";
|
|
10
|
-
import {
|
|
11
|
-
import { createEditTool } from "../tools/edit.js";
|
|
12
|
-
import { createReadTool } from "../tools/read.js";
|
|
13
|
-
import { createWebFetchTool } from "../tools/web-fetch.js";
|
|
14
|
-
import { createWebSearchTool } from "../tools/web-search.js";
|
|
15
|
-
import { createWriteTool } from "../tools/write.js";
|
|
10
|
+
import { buildToolSet } from "../tools/registry.js";
|
|
16
11
|
import { formatSubAgentList, resolveSubAgentConfig, validateSubAgentTask, } from "./discovery.js";
|
|
17
12
|
const subagentSchema = Type.Object({
|
|
18
13
|
label: Type.String({ description: "Brief description of what this sub-agent task does (shown to user)" }),
|
|
@@ -28,10 +23,10 @@ const subagentSchema = Type.Object({
|
|
|
28
23
|
maxToolCalls: Type.Optional(Type.Number({ description: "Optional maximum tool calls for this sub-agent" })),
|
|
29
24
|
maxWallTimeSec: Type.Optional(Type.Number({ description: "Optional wall time budget in seconds for this sub-agent" })),
|
|
30
25
|
bashTimeoutSec: Type.Optional(Type.Number({ description: "Optional default timeout in seconds for bash commands inside this sub-agent" })),
|
|
31
|
-
contextMode: Type.Optional(Type.
|
|
32
|
-
description: 'Optional context mode.
|
|
26
|
+
contextMode: Type.Optional(Type.Union([Type.Literal("isolated"), Type.Literal("contextual")], {
|
|
27
|
+
description: 'Optional context mode. "isolated" (default) runs with no injected context; "contextual" injects selected session and memory context.',
|
|
33
28
|
})),
|
|
34
|
-
memory: Type.Optional(Type.
|
|
29
|
+
memory: Type.Optional(Type.Union([Type.Literal("none"), Type.Literal("session"), Type.Literal("relevant")], {
|
|
35
30
|
description: 'Optional memory mode for contextual sub-agents: "none", "session", or "relevant".',
|
|
36
31
|
})),
|
|
37
32
|
paths: Type.Optional(Type.Array(Type.String(), {
|
|
@@ -88,55 +83,28 @@ function buildStoppedText(config, reason, finalText) {
|
|
|
88
83
|
}
|
|
89
84
|
return `[Sub-agent ${config.name} stopped: ${reason}]\n\n${trimmedFinalText}`;
|
|
90
85
|
}
|
|
91
|
-
|
|
86
|
+
/**
|
|
87
|
+
* Build a sub-agent's tool set from the shared tool registry, filtered to tools flagged
|
|
88
|
+
* available to sub-agents (files + web). Sub-agents run with their own security context
|
|
89
|
+
* (rooted at the sub-agent workspace) and their own per-invocation bash timeout.
|
|
90
|
+
*/
|
|
91
|
+
function buildSubagentTools(executor, bashTimeoutSec, options) {
|
|
92
92
|
const securityConfig = options.securityConfig ?? DEFAULT_SECURITY_CONFIG;
|
|
93
|
-
|
|
93
|
+
return buildToolSet({
|
|
94
|
+
executor,
|
|
95
|
+
securityConfig,
|
|
96
|
+
securityContext: {
|
|
97
|
+
workspaceDir: options.workspaceDir,
|
|
98
|
+
workspacePath: options.runtimeContext.workspacePath,
|
|
99
|
+
cwd: process.cwd(),
|
|
100
|
+
},
|
|
101
|
+
channelId: options.runtimeContext.channelId,
|
|
102
|
+
channelDir: options.channelDir,
|
|
94
103
|
workspaceDir: options.workspaceDir,
|
|
95
104
|
workspacePath: options.runtimeContext.workspacePath,
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
createReadTool(executor, {
|
|
100
|
-
securityConfig,
|
|
101
|
-
securityContext,
|
|
102
|
-
channelId: options.runtimeContext.channelId,
|
|
103
|
-
}),
|
|
104
|
-
createBashTool(executor, {
|
|
105
|
-
defaultTimeoutSeconds: bashTimeoutSec,
|
|
106
|
-
securityConfig,
|
|
107
|
-
securityContext,
|
|
108
|
-
channelId: options.runtimeContext.channelId,
|
|
109
|
-
}),
|
|
110
|
-
createEditTool(executor, {
|
|
111
|
-
securityConfig,
|
|
112
|
-
securityContext,
|
|
113
|
-
channelId: options.runtimeContext.channelId,
|
|
114
|
-
}),
|
|
115
|
-
createWriteTool(executor, {
|
|
116
|
-
securityConfig,
|
|
117
|
-
securityContext,
|
|
118
|
-
channelId: options.runtimeContext.channelId,
|
|
119
|
-
}),
|
|
120
|
-
];
|
|
121
|
-
}
|
|
122
|
-
function createNamedToolSet(executor, bashTimeoutSec, options) {
|
|
123
|
-
const tools = createToolSet(executor, bashTimeoutSec, options);
|
|
124
|
-
const byName = Object.fromEntries(tools.map((tool) => [tool.name, tool]));
|
|
125
|
-
if (options.webConfig && options.webConfig.enable !== false) {
|
|
126
|
-
byName.web_search = createWebSearchTool({
|
|
127
|
-
webConfig: options.webConfig,
|
|
128
|
-
securityConfig: options.securityConfig ?? DEFAULT_SECURITY_CONFIG,
|
|
129
|
-
workspaceDir: options.workspaceDir,
|
|
130
|
-
channelId: options.runtimeContext.channelId,
|
|
131
|
-
});
|
|
132
|
-
byName.web_fetch = createWebFetchTool({
|
|
133
|
-
webConfig: options.webConfig,
|
|
134
|
-
securityConfig: options.securityConfig ?? DEFAULT_SECURITY_CONFIG,
|
|
135
|
-
workspaceDir: options.workspaceDir,
|
|
136
|
-
channelId: options.runtimeContext.channelId,
|
|
137
|
-
});
|
|
138
|
-
}
|
|
139
|
-
return byName;
|
|
105
|
+
webConfig: options.webConfig,
|
|
106
|
+
bashDefaultTimeoutSeconds: bashTimeoutSec,
|
|
107
|
+
}, { forSubagent: true });
|
|
140
108
|
}
|
|
141
109
|
function buildSubAgentTask(task, config, runtimeContext, contextBlocks) {
|
|
142
110
|
const taskText = task.trim();
|
|
@@ -215,6 +183,7 @@ async function buildContextualBlocks(task, config, options, currentModel) {
|
|
|
215
183
|
const recallQuery = [task.trim(), config.description.trim(), ...config.paths].filter(Boolean).join("\n");
|
|
216
184
|
const recalled = await recallRelevantMemory({
|
|
217
185
|
query: recallQuery,
|
|
186
|
+
channelId: options.runtimeContext.channelId,
|
|
218
187
|
workspaceDir: options.workspaceDir,
|
|
219
188
|
channelDir: options.channelDir,
|
|
220
189
|
maxCandidates: recallSettings.maxCandidates,
|
|
@@ -308,7 +277,7 @@ export function createSubAgentTool(options) {
|
|
|
308
277
|
details: createDetails(config, usage, assistantTurns, toolCalls, Date.now() - startedAt, Boolean(failureReason), failureReason),
|
|
309
278
|
});
|
|
310
279
|
};
|
|
311
|
-
const availableTools =
|
|
280
|
+
const availableTools = buildSubagentTools(options.executor, config.bashTimeoutSec, options);
|
|
312
281
|
const worker = options.createWorker?.({
|
|
313
282
|
subAgent: config,
|
|
314
283
|
apiKey,
|
package/dist/tools/bash.d.ts
CHANGED
|
@@ -2,10 +2,17 @@ import type { AgentTool } from "@earendil-works/pi-agent-core";
|
|
|
2
2
|
import { Type } from "typebox";
|
|
3
3
|
import type { Executor } from "../sandbox.js";
|
|
4
4
|
import type { SecurityConfig, SecurityRuntimeContext } from "../security/types.js";
|
|
5
|
+
/**
|
|
6
|
+
* Default wall-clock timeout for bash commands when the caller supplies neither a
|
|
7
|
+
* per-call `timeout` nor a tool-level default. Without this, a hung command (a stray
|
|
8
|
+
* dev server, an interactive prompt) would block the channel's run queue until `/stop`.
|
|
9
|
+
* Callers that legitimately need longer must pass an explicit `timeout`.
|
|
10
|
+
*/
|
|
11
|
+
export declare const DEFAULT_BASH_TIMEOUT_SECONDS = 300;
|
|
5
12
|
declare const bashSchema: Type.TObject<{
|
|
6
13
|
label: Type.TString;
|
|
7
14
|
command: Type.TString;
|
|
8
|
-
timeout: Type.TOptional<Type.
|
|
15
|
+
timeout: Type.TOptional<Type.TInteger>;
|
|
9
16
|
}>;
|
|
10
17
|
export interface BashToolOptions {
|
|
11
18
|
defaultTimeoutSeconds?: number;
|
package/dist/tools/bash.js
CHANGED
|
@@ -1,23 +1,34 @@
|
|
|
1
1
|
import { randomBytes } from "node:crypto";
|
|
2
|
-
import { createWriteStream } from "node:fs";
|
|
3
|
-
import { tmpdir } from "node:os";
|
|
4
|
-
import { join } from "node:path";
|
|
5
2
|
import { Type } from "typebox";
|
|
6
3
|
import { guardCommand } from "../security/command-guard.js";
|
|
7
4
|
import { DEFAULT_SECURITY_CONFIG } from "../security/config.js";
|
|
8
5
|
import { logSecurityEvent } from "../security/logger.js";
|
|
6
|
+
import { shellEscapePath } from "../shared/shell-escape.js";
|
|
9
7
|
import { DEFAULT_MAX_BYTES, DEFAULT_MAX_LINES, formatSize, truncateTail } from "./truncate.js";
|
|
10
8
|
/**
|
|
11
|
-
*
|
|
9
|
+
* Default wall-clock timeout for bash commands when the caller supplies neither a
|
|
10
|
+
* per-call `timeout` nor a tool-level default. Without this, a hung command (a stray
|
|
11
|
+
* dev server, an interactive prompt) would block the channel's run queue until `/stop`.
|
|
12
|
+
* Callers that legitimately need longer must pass an explicit `timeout`.
|
|
12
13
|
*/
|
|
13
|
-
|
|
14
|
+
export const DEFAULT_BASH_TIMEOUT_SECONDS = 300;
|
|
15
|
+
/**
|
|
16
|
+
* Generate a unique spill file path for full bash output. This lives inside the
|
|
17
|
+
* executor's filesystem (the sandbox), not the host, so the path we report back is
|
|
18
|
+
* reachable by the same `read`/`bash` tools the model uses to open it. `/tmp` exists
|
|
19
|
+
* and is writable in both the host and Docker (Alpine) sandboxes.
|
|
20
|
+
*/
|
|
21
|
+
function getSpillFilePath() {
|
|
14
22
|
const id = randomBytes(8).toString("hex");
|
|
15
|
-
return
|
|
23
|
+
return `/tmp/pipiclaw-bash-${id}.log`;
|
|
16
24
|
}
|
|
17
25
|
const bashSchema = Type.Object({
|
|
18
26
|
label: Type.String({ description: "Brief description of what this command does (shown to user)" }),
|
|
19
27
|
command: Type.String({ description: "Bash command to execute" }),
|
|
20
|
-
timeout: Type.Optional(Type.
|
|
28
|
+
timeout: Type.Optional(Type.Integer({
|
|
29
|
+
minimum: 1,
|
|
30
|
+
description: `Timeout in seconds. Defaults to ${DEFAULT_BASH_TIMEOUT_SECONDS}s; pass a larger value for long-running commands.`,
|
|
31
|
+
})),
|
|
21
32
|
});
|
|
22
33
|
function formatCommandBlockMessage(command, category, reason, matchedText) {
|
|
23
34
|
const lines = [`Command blocked${category ? ` [${category}]` : ""}`];
|
|
@@ -42,7 +53,7 @@ export function createBashTool(executor, options = {}) {
|
|
|
42
53
|
return {
|
|
43
54
|
name: "bash",
|
|
44
55
|
label: "bash",
|
|
45
|
-
description: `Execute a bash command in the current working directory. Returns stdout and
|
|
56
|
+
description: `Execute a bash command in the current working directory. Returns stdout, stderr, and the exit code (a non-zero exit code is reported in the output, not raised as an error). Output is truncated to the last ${DEFAULT_MAX_LINES} lines or ${DEFAULT_MAX_BYTES / 1024}KB (whichever is hit first). If truncated, the full output is saved to a temp file whose path is included. Commands time out after ${DEFAULT_BASH_TIMEOUT_SECONDS}s unless you pass a larger \`timeout\`.`,
|
|
46
57
|
parameters: bashSchema,
|
|
47
58
|
execute: async (_toolCallId, { command, timeout }, signal) => {
|
|
48
59
|
if (securityConfig.enabled && securityConfig.commandGuard.enabled) {
|
|
@@ -61,10 +72,7 @@ export function createBashTool(executor, options = {}) {
|
|
|
61
72
|
throw new Error(formatCommandBlockMessage(command, guardResult.category, guardResult.reason, guardResult.matchedText));
|
|
62
73
|
}
|
|
63
74
|
}
|
|
64
|
-
|
|
65
|
-
let tempFilePath;
|
|
66
|
-
let tempFileStream;
|
|
67
|
-
const effectiveTimeout = timeout ?? options.defaultTimeoutSeconds;
|
|
75
|
+
const effectiveTimeout = timeout ?? options.defaultTimeoutSeconds ?? DEFAULT_BASH_TIMEOUT_SECONDS;
|
|
68
76
|
const result = await executor.exec(command, { timeout: effectiveTimeout, signal });
|
|
69
77
|
let output = "";
|
|
70
78
|
if (result.stdout)
|
|
@@ -75,12 +83,24 @@ export function createBashTool(executor, options = {}) {
|
|
|
75
83
|
output += result.stderr;
|
|
76
84
|
}
|
|
77
85
|
const totalBytes = Buffer.byteLength(output, "utf-8");
|
|
78
|
-
//
|
|
86
|
+
// Spill the full output to a temp file (inside the executor's filesystem, so the
|
|
87
|
+
// reported path is reachable by the model) when it exceeds the inline limit.
|
|
88
|
+
// Best-effort: if the write fails, we simply omit the path hint from the notice.
|
|
89
|
+
let tempFilePath;
|
|
79
90
|
if (totalBytes > DEFAULT_MAX_BYTES) {
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
91
|
+
const candidatePath = getSpillFilePath();
|
|
92
|
+
try {
|
|
93
|
+
const spillResult = await executor.exec(`cat > ${shellEscapePath(candidatePath)}`, {
|
|
94
|
+
signal,
|
|
95
|
+
stdin: output,
|
|
96
|
+
});
|
|
97
|
+
if (spillResult.code === 0) {
|
|
98
|
+
tempFilePath = candidatePath;
|
|
99
|
+
}
|
|
100
|
+
}
|
|
101
|
+
catch {
|
|
102
|
+
// Ignore spill failures; the truncated output is still returned.
|
|
103
|
+
}
|
|
84
104
|
}
|
|
85
105
|
// Apply tail truncation
|
|
86
106
|
const truncation = truncateTail(output);
|
|
@@ -95,20 +115,25 @@ export function createBashTool(executor, options = {}) {
|
|
|
95
115
|
// Build actionable notice
|
|
96
116
|
const startLine = truncation.totalLines - truncation.outputLines + 1;
|
|
97
117
|
const endLine = truncation.totalLines;
|
|
118
|
+
const fullOutputHint = tempFilePath ? ` Full output: ${tempFilePath}` : "";
|
|
98
119
|
if (truncation.lastLinePartial) {
|
|
99
120
|
// Edge case: last line alone > 50KB
|
|
100
121
|
const lastLineSize = formatSize(Buffer.byteLength(output.split("\n").pop() || "", "utf-8"));
|
|
101
|
-
outputText += `\n\n[Showing last ${formatSize(truncation.outputBytes)} of line ${endLine} (line is ${lastLineSize})
|
|
122
|
+
outputText += `\n\n[Showing last ${formatSize(truncation.outputBytes)} of line ${endLine} (line is ${lastLineSize}).${fullOutputHint}]`;
|
|
102
123
|
}
|
|
103
124
|
else if (truncation.truncatedBy === "lines") {
|
|
104
|
-
outputText += `\n\n[Showing lines ${startLine}-${endLine} of ${truncation.totalLines}
|
|
125
|
+
outputText += `\n\n[Showing lines ${startLine}-${endLine} of ${truncation.totalLines}.${fullOutputHint}]`;
|
|
105
126
|
}
|
|
106
127
|
else {
|
|
107
|
-
outputText += `\n\n[Showing lines ${startLine}-${endLine} of ${truncation.totalLines} (${formatSize(DEFAULT_MAX_BYTES)} limit)
|
|
128
|
+
outputText += `\n\n[Showing lines ${startLine}-${endLine} of ${truncation.totalLines} (${formatSize(DEFAULT_MAX_BYTES)} limit).${fullOutputHint}]`;
|
|
108
129
|
}
|
|
109
130
|
}
|
|
131
|
+
// A non-zero exit code is a normal result, not a tool failure: commands like
|
|
132
|
+
// `grep` (no match), `diff` (differences), and `test` use exit codes as data.
|
|
133
|
+
// Report the code inline so the model can react without treating it as an error.
|
|
110
134
|
if (result.code !== 0) {
|
|
111
|
-
|
|
135
|
+
outputText += `\n\nExit code: ${result.code}`;
|
|
136
|
+
details = { ...details, exitCode: result.code };
|
|
112
137
|
}
|
|
113
138
|
return { content: [{ type: "text", text: outputText }], details };
|
|
114
139
|
},
|