@oyasmi/pipiclaw 0.7.3 → 0.7.5
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/dist/agent/channel-runner.js +14 -0
- package/dist/agent/commands.d.ts +1 -1
- package/dist/agent/commands.js +6 -0
- package/dist/memory/task-digest.d.ts +21 -0
- package/dist/memory/task-digest.js +66 -0
- package/dist/runtime/bootstrap.js +13 -1
- package/dist/runtime/dingtalk.d.ts +1 -0
- package/dist/runtime/dingtalk.js +6 -2
- package/dist/runtime/event-commands.d.ts +5 -0
- package/dist/runtime/event-commands.js +2 -2
- package/dist/runtime/task-commands.d.ts +6 -0
- package/dist/runtime/task-commands.js +133 -0
- package/dist/settings.d.ts +7 -0
- package/dist/settings.js +13 -0
- package/dist/shared/task-ledger.d.ts +53 -0
- package/dist/shared/task-ledger.js +149 -0
- package/dist/subagents/tool.d.ts +1 -0
- package/dist/subagents/tool.js +1 -0
- package/dist/tools/bash.d.ts +6 -0
- package/dist/tools/bash.js +6 -1
- package/dist/tools/command-optimizer.d.ts +6 -0
- package/dist/tools/command-optimizer.js +73 -0
- package/dist/tools/config.d.ts +9 -0
- package/dist/tools/config.js +21 -0
- package/dist/tools/event-manage.d.ts +35 -0
- package/dist/tools/event-manage.js +238 -0
- package/dist/tools/index.js +2 -0
- package/dist/tools/registry.d.ts +2 -0
- package/dist/tools/registry.js +31 -0
- package/dist/tools/task-manage.d.ts +43 -0
- package/dist/tools/task-manage.js +226 -0
- package/dist/tui/app.js +2 -0
- package/dist/tui/commands.d.ts +1 -0
- package/dist/tui/commands.js +3 -0
- package/dist/tui/turn-controller.d.ts +1 -0
- package/dist/tui/turn-controller.js +1 -0
- package/package.json +1 -1
package/dist/subagents/tool.d.ts
CHANGED
package/dist/subagents/tool.js
CHANGED
|
@@ -103,6 +103,7 @@ function buildSubagentTools(executor, bashTimeoutSec, options) {
|
|
|
103
103
|
workspaceDir: options.workspaceDir,
|
|
104
104
|
workspacePath: options.runtimeContext.workspacePath,
|
|
105
105
|
webConfig: options.webConfig,
|
|
106
|
+
rtkEnabled: options.rtkEnabled,
|
|
106
107
|
bashDefaultTimeoutSeconds: bashTimeoutSec,
|
|
107
108
|
}, { forSubagent: true });
|
|
108
109
|
}
|
package/dist/tools/bash.d.ts
CHANGED
|
@@ -19,6 +19,12 @@ export interface BashToolOptions {
|
|
|
19
19
|
securityConfig?: SecurityConfig;
|
|
20
20
|
securityContext?: SecurityRuntimeContext;
|
|
21
21
|
channelId?: string;
|
|
22
|
+
/**
|
|
23
|
+
* When true, route each command through the `rtk` command optimizer before executing
|
|
24
|
+
* (best-effort; falls back to the raw command when rtk is unavailable or declines).
|
|
25
|
+
* Gated by `tools.rtk.enabled` in tools.json.
|
|
26
|
+
*/
|
|
27
|
+
rtkEnabled?: boolean;
|
|
22
28
|
}
|
|
23
29
|
export declare function createBashTool(executor: Executor, options?: BashToolOptions): AgentTool<typeof bashSchema>;
|
|
24
30
|
export {};
|
package/dist/tools/bash.js
CHANGED
|
@@ -4,6 +4,7 @@ import { guardCommand } from "../security/command-guard.js";
|
|
|
4
4
|
import { DEFAULT_SECURITY_CONFIG } from "../security/config.js";
|
|
5
5
|
import { logSecurityEvent } from "../security/logger.js";
|
|
6
6
|
import { shellEscape } from "../shared/shell-escape.js";
|
|
7
|
+
import { maybeOptimizeCommand } from "./command-optimizer.js";
|
|
7
8
|
import { DEFAULT_MAX_BYTES, DEFAULT_MAX_LINES, formatSize, truncateTail } from "./truncate.js";
|
|
8
9
|
/**
|
|
9
10
|
* Default wall-clock timeout for bash commands when the caller supplies neither a
|
|
@@ -72,8 +73,12 @@ export function createBashTool(executor, options = {}) {
|
|
|
72
73
|
throw new Error(formatCommandBlockMessage(command, guardResult.category, guardResult.reason, guardResult.matchedText));
|
|
73
74
|
}
|
|
74
75
|
}
|
|
76
|
+
// Optimize *after* the security guard: the guard must inspect the operator's real
|
|
77
|
+
// intent (`command`), while rtk only reshapes a semantically-equivalent command for
|
|
78
|
+
// compact output. Optimizing first would hide the true command from the guard.
|
|
79
|
+
const effectiveCommand = options.rtkEnabled ? await maybeOptimizeCommand(command, executor, signal) : command;
|
|
75
80
|
const effectiveTimeout = timeout ?? options.defaultTimeoutSeconds ?? DEFAULT_BASH_TIMEOUT_SECONDS;
|
|
76
|
-
const result = await executor.exec(
|
|
81
|
+
const result = await executor.exec(effectiveCommand, { timeout: effectiveTimeout, signal });
|
|
77
82
|
let output = "";
|
|
78
83
|
if (result.stdout)
|
|
79
84
|
output += result.stdout;
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
import type { Executor } from "../sandbox.js";
|
|
2
|
+
/**
|
|
3
|
+
* Return the rtk-optimized form of `command`, or `command` unchanged when rtk is
|
|
4
|
+
* unavailable or declines to rewrite it. Never throws.
|
|
5
|
+
*/
|
|
6
|
+
export declare function maybeOptimizeCommand(command: string, executor: Executor, signal?: AbortSignal): Promise<string>;
|
|
@@ -0,0 +1,73 @@
|
|
|
1
|
+
import { shellEscape } from "../shared/shell-escape.js";
|
|
2
|
+
/**
|
|
3
|
+
* Optional "outbound command transform" for the bash tool. When enabled, a command is
|
|
4
|
+
* handed to the `rtk` binary (https://github.com/rtk-ai/rtk) which rewrites known
|
|
5
|
+
* read-only commands to their token-compact equivalents (e.g. `git status` →
|
|
6
|
+
* `rtk git status`) before execution, cutting the output the model has to read.
|
|
7
|
+
*
|
|
8
|
+
* pipiclaw owns none of rtk's rules: `rtk rewrite` is rtk's single source of truth for
|
|
9
|
+
* hooks. It prints the rewritten command on stdout when it can optimize, and prints
|
|
10
|
+
* nothing when it cannot. We key off stdout, not the exit code: the exit code is not a
|
|
11
|
+
* reliable success signal across rtk versions — 0.43.0 exits 3 on a successful rewrite
|
|
12
|
+
* and 1 on "no equivalent", while its own `--help` claims 0/1. Presence of stdout is the
|
|
13
|
+
* stable contract, so a non-empty line is the rewrite and empty means "keep original".
|
|
14
|
+
*
|
|
15
|
+
* This is best-effort by contract: any failure (rtk absent, timeout, empty output) falls
|
|
16
|
+
* back to the original command. Enabling rtk must never make a bash command fail.
|
|
17
|
+
*/
|
|
18
|
+
/**
|
|
19
|
+
* rtk rewrite is a pure, local string transform (no network), so a tight bound is safe.
|
|
20
|
+
* On timeout we simply run the original command.
|
|
21
|
+
*/
|
|
22
|
+
const RTK_TIMEOUT_SECONDS = 2;
|
|
23
|
+
/**
|
|
24
|
+
* rtk must exist in the *execution environment* — the host PATH for a host executor, or
|
|
25
|
+
* inside the container for a docker executor — not merely on the pipiclaw host. We probe
|
|
26
|
+
* through the executor so the check reflects where the command will actually run, and
|
|
27
|
+
* memoize the probe promise per executor instance so concurrent turns share one probe and
|
|
28
|
+
* we do not re-shell on every command. The instance is stable for a channel's lifetime,
|
|
29
|
+
* so this is effectively "probe once".
|
|
30
|
+
*/
|
|
31
|
+
const availabilityByExecutor = new WeakMap();
|
|
32
|
+
function probeRtk(executor) {
|
|
33
|
+
return executor
|
|
34
|
+
.exec("command -v rtk", { timeout: RTK_TIMEOUT_SECONDS })
|
|
35
|
+
.then((result) => result.code === 0 && result.stdout.trim().length > 0)
|
|
36
|
+
.catch(() => false);
|
|
37
|
+
}
|
|
38
|
+
function isRtkAvailable(executor) {
|
|
39
|
+
let probe = availabilityByExecutor.get(executor);
|
|
40
|
+
if (!probe) {
|
|
41
|
+
probe = probeRtk(executor);
|
|
42
|
+
availabilityByExecutor.set(executor, probe);
|
|
43
|
+
}
|
|
44
|
+
return probe;
|
|
45
|
+
}
|
|
46
|
+
/**
|
|
47
|
+
* Return the rtk-optimized form of `command`, or `command` unchanged when rtk is
|
|
48
|
+
* unavailable or declines to rewrite it. Never throws.
|
|
49
|
+
*/
|
|
50
|
+
export async function maybeOptimizeCommand(command, executor, signal) {
|
|
51
|
+
if (signal?.aborted) {
|
|
52
|
+
return command;
|
|
53
|
+
}
|
|
54
|
+
if (!(await isRtkAvailable(executor))) {
|
|
55
|
+
return command;
|
|
56
|
+
}
|
|
57
|
+
try {
|
|
58
|
+
const result = await executor.exec(`rtk rewrite ${shellEscape(command)}`, {
|
|
59
|
+
timeout: RTK_TIMEOUT_SECONDS,
|
|
60
|
+
signal,
|
|
61
|
+
});
|
|
62
|
+
// Trust stdout over the exit code (see the module comment): a non-empty line is the
|
|
63
|
+
// rewrite; empty output means rtk had no equivalent, so keep the original command.
|
|
64
|
+
const rewritten = result.stdout.trim();
|
|
65
|
+
if (rewritten.length > 0) {
|
|
66
|
+
return rewritten;
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
catch {
|
|
70
|
+
// Any failure — spawn error, timeout, abort — falls back to the original command.
|
|
71
|
+
}
|
|
72
|
+
return command;
|
|
73
|
+
}
|
package/dist/tools/config.d.ts
CHANGED
package/dist/tools/config.js
CHANGED
|
@@ -38,6 +38,15 @@ export const DEFAULT_TOOLS_CONFIG = {
|
|
|
38
38
|
enabled: true,
|
|
39
39
|
},
|
|
40
40
|
},
|
|
41
|
+
events: {
|
|
42
|
+
enabled: true,
|
|
43
|
+
},
|
|
44
|
+
tasks: {
|
|
45
|
+
enabled: true,
|
|
46
|
+
},
|
|
47
|
+
rtk: {
|
|
48
|
+
enabled: false,
|
|
49
|
+
},
|
|
41
50
|
},
|
|
42
51
|
};
|
|
43
52
|
function clampInteger(value, fallback, minimum, maximum) {
|
|
@@ -86,6 +95,9 @@ function mergeToolsConfig(source, configPath, diagnostics) {
|
|
|
86
95
|
const memorySave = isRecord(memory.save) ? memory.save : {};
|
|
87
96
|
const skills = isRecord(tools.skills) ? tools.skills : {};
|
|
88
97
|
const manage = isRecord(skills.manage) ? skills.manage : {};
|
|
98
|
+
const events = isRecord(tools.events) ? tools.events : {};
|
|
99
|
+
const tasks = isRecord(tools.tasks) ? tools.tasks : {};
|
|
100
|
+
const rtk = isRecord(tools.rtk) ? tools.rtk : {};
|
|
89
101
|
const search = isRecord(web.search) ? web.search : {};
|
|
90
102
|
const fetch = isRecord(web.fetch) ? web.fetch : {};
|
|
91
103
|
const providerValue = asTrimmedString(search.provider, DEFAULT_TOOLS_CONFIG.tools.web.search.provider).toLowerCase();
|
|
@@ -169,6 +181,15 @@ function mergeToolsConfig(source, configPath, diagnostics) {
|
|
|
169
181
|
: DEFAULT_TOOLS_CONFIG.tools.skills.manage.enabled,
|
|
170
182
|
},
|
|
171
183
|
},
|
|
184
|
+
events: {
|
|
185
|
+
enabled: typeof events.enabled === "boolean" ? events.enabled : DEFAULT_TOOLS_CONFIG.tools.events.enabled,
|
|
186
|
+
},
|
|
187
|
+
tasks: {
|
|
188
|
+
enabled: typeof tasks.enabled === "boolean" ? tasks.enabled : DEFAULT_TOOLS_CONFIG.tools.tasks.enabled,
|
|
189
|
+
},
|
|
190
|
+
rtk: {
|
|
191
|
+
enabled: typeof rtk.enabled === "boolean" ? rtk.enabled : DEFAULT_TOOLS_CONFIG.tools.rtk.enabled,
|
|
192
|
+
},
|
|
172
193
|
},
|
|
173
194
|
};
|
|
174
195
|
}
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
import type { AgentTool } from "@earendil-works/pi-agent-core";
|
|
2
|
+
import { Type } from "typebox";
|
|
3
|
+
import { type ScheduledEvent } from "../runtime/events.js";
|
|
4
|
+
import type { SecurityConfig } from "../security/types.js";
|
|
5
|
+
declare const eventManageSchema: Type.TObject<{
|
|
6
|
+
label: Type.TString;
|
|
7
|
+
action: Type.TUnion<[Type.TLiteral<"create">, Type.TLiteral<"update">, Type.TLiteral<"delete">]>;
|
|
8
|
+
name: Type.TString;
|
|
9
|
+
definition: Type.TOptional<Type.TString>;
|
|
10
|
+
}>;
|
|
11
|
+
export type EventManageAction = "create" | "update" | "delete";
|
|
12
|
+
export interface EventManageResult {
|
|
13
|
+
action: EventManageAction;
|
|
14
|
+
name: string;
|
|
15
|
+
path: string;
|
|
16
|
+
eventType?: ScheduledEvent["type"];
|
|
17
|
+
channelId?: string;
|
|
18
|
+
bytesWritten?: number;
|
|
19
|
+
deleted?: boolean;
|
|
20
|
+
notice: string;
|
|
21
|
+
}
|
|
22
|
+
export interface EventManageRequest {
|
|
23
|
+
action: EventManageAction;
|
|
24
|
+
name: string;
|
|
25
|
+
definition?: string;
|
|
26
|
+
}
|
|
27
|
+
export interface EventManageToolOptions {
|
|
28
|
+
workspaceDir: string;
|
|
29
|
+
workspacePath: string;
|
|
30
|
+
channelId: string;
|
|
31
|
+
commandGuardConfig: SecurityConfig["commandGuard"];
|
|
32
|
+
}
|
|
33
|
+
export declare function manageEvent(options: EventManageToolOptions, request: EventManageRequest): Promise<EventManageResult>;
|
|
34
|
+
export declare function createEventManageTool(options: EventManageToolOptions): AgentTool<typeof eventManageSchema>;
|
|
35
|
+
export {};
|
|
@@ -0,0 +1,238 @@
|
|
|
1
|
+
import { existsSync } from "node:fs";
|
|
2
|
+
import { readdir, readFile, unlink } from "node:fs/promises";
|
|
3
|
+
import { join } from "node:path";
|
|
4
|
+
import { Cron } from "croner";
|
|
5
|
+
import { Type } from "typebox";
|
|
6
|
+
import { resolveEventPath } from "../runtime/event-commands.js";
|
|
7
|
+
import { parseScheduledEventContent } from "../runtime/events.js";
|
|
8
|
+
import { guardCommand } from "../security/command-guard.js";
|
|
9
|
+
import { writeFileAtomically } from "../shared/atomic-file.js";
|
|
10
|
+
import { isRecord } from "../shared/type-guards.js";
|
|
11
|
+
/** one-shot events must be scheduled at least this far out; anything sooner is effectively self-triggering. */
|
|
12
|
+
const MIN_ONE_SHOT_LEAD_MS = 2 * 60 * 1000;
|
|
13
|
+
/** periodic events without a preAction gate may fire no more often than this. */
|
|
14
|
+
const MIN_PERIODIC_INTERVAL_MS = 30 * 60 * 1000;
|
|
15
|
+
/**
|
|
16
|
+
* periodic events WITH a preAction gate may fire this often: the sensor is the token guard
|
|
17
|
+
* (it exits non-zero and stays silent when there is nothing to do), so a tighter cadence is
|
|
18
|
+
* safe and is exactly the design-endorsed posture for completion-driven checks (e.g. polling
|
|
19
|
+
* an agentmux instance until it goes idle). A hard sub-floor still applies so a bogus
|
|
20
|
+
* always-pass preAction cannot drive an arbitrarily hot loop.
|
|
21
|
+
*/
|
|
22
|
+
const MIN_PERIODIC_INTERVAL_WITH_PREACTION_MS = 5 * 60 * 1000;
|
|
23
|
+
/** sanity cap on total event files to keep the directory (and the scheduler) from being flooded. */
|
|
24
|
+
const MAX_EVENT_FILES = 50;
|
|
25
|
+
const eventManageSchema = Type.Object({
|
|
26
|
+
label: Type.String({ description: "Brief description of the scheduling change (shown to the user)" }),
|
|
27
|
+
action: Type.Union([Type.Literal("create"), Type.Literal("update"), Type.Literal("delete")], {
|
|
28
|
+
description: 'The event management action to perform: "create", "update", or "delete".',
|
|
29
|
+
}),
|
|
30
|
+
name: Type.String({
|
|
31
|
+
description: "Event name (filename without .json). For task-owned events use `task.<channelId>.<taskId>.<use>`, e.g. `task.dm_123.weekly-report.checkin`.",
|
|
32
|
+
}),
|
|
33
|
+
definition: Type.Optional(Type.String({
|
|
34
|
+
description: "Full event JSON (required for create/update). one-shot / periodic only; immediate is rejected. channelId defaults to the current channel.",
|
|
35
|
+
})),
|
|
36
|
+
});
|
|
37
|
+
function parseAction(action) {
|
|
38
|
+
if (action === "create" || action === "update" || action === "delete") {
|
|
39
|
+
return action;
|
|
40
|
+
}
|
|
41
|
+
throw new Error('Unsupported event action. Use "create", "update", or "delete".');
|
|
42
|
+
}
|
|
43
|
+
function toWorkspacePath(options, hostPath) {
|
|
44
|
+
if (hostPath.startsWith(options.workspaceDir)) {
|
|
45
|
+
return `${options.workspacePath}${hostPath.slice(options.workspaceDir.length)}`;
|
|
46
|
+
}
|
|
47
|
+
return hostPath;
|
|
48
|
+
}
|
|
49
|
+
function validateTimezone(timezone) {
|
|
50
|
+
try {
|
|
51
|
+
new Intl.DateTimeFormat(undefined, { timeZone: timezone });
|
|
52
|
+
}
|
|
53
|
+
catch {
|
|
54
|
+
throw new Error(`Invalid timezone: ${timezone}`);
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
function validateOneShot(event) {
|
|
58
|
+
const atTime = new Date(event.at).getTime();
|
|
59
|
+
if (!Number.isFinite(atTime)) {
|
|
60
|
+
throw new Error(`one-shot 'at' is not a valid date: ${event.at}`);
|
|
61
|
+
}
|
|
62
|
+
if (atTime < Date.now() + MIN_ONE_SHOT_LEAD_MS) {
|
|
63
|
+
throw new Error("one-shot 'at' must be at least 2 minutes in the future (self-triggering guard).");
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
function validatePeriodic(event) {
|
|
67
|
+
validateTimezone(event.timezone);
|
|
68
|
+
let runs;
|
|
69
|
+
try {
|
|
70
|
+
const cron = new Cron(event.schedule, { timezone: event.timezone });
|
|
71
|
+
runs = cron.nextRuns(3);
|
|
72
|
+
cron.stop();
|
|
73
|
+
}
|
|
74
|
+
catch (error) {
|
|
75
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
76
|
+
throw new Error(`Invalid cron schedule "${event.schedule}": ${message}`);
|
|
77
|
+
}
|
|
78
|
+
// A preAction gate makes a tighter cadence safe (the sensor keeps most fires silent);
|
|
79
|
+
// without one, hold the 30-minute floor so a bare high-frequency cron can't burn tokens.
|
|
80
|
+
const floorMs = event.preAction ? MIN_PERIODIC_INTERVAL_WITH_PREACTION_MS : MIN_PERIODIC_INTERVAL_MS;
|
|
81
|
+
const floorMinutes = Math.round(floorMs / 60000);
|
|
82
|
+
// Fewer than two upcoming runs means no meaningful cadence to rate-limit (e.g. a one-off cron); allow it.
|
|
83
|
+
for (let i = 1; i < runs.length; i++) {
|
|
84
|
+
if (runs[i].getTime() - runs[i - 1].getTime() < floorMs) {
|
|
85
|
+
throw new Error(`periodic events must fire no more often than every ${floorMinutes} minutes` +
|
|
86
|
+
`${event.preAction ? " (even with a preAction gate)" : "; for tighter checks add a preAction gate (min 5 minutes) instead of a high-frequency cron"}.`);
|
|
87
|
+
}
|
|
88
|
+
}
|
|
89
|
+
}
|
|
90
|
+
function validatePreAction(event, commandGuardConfig) {
|
|
91
|
+
if (!event.preAction)
|
|
92
|
+
return;
|
|
93
|
+
const result = guardCommand(event.preAction.command, commandGuardConfig);
|
|
94
|
+
if (!result.allowed) {
|
|
95
|
+
throw new Error(`preAction command blocked by guard: ${result.reason ?? "not allowed"}`);
|
|
96
|
+
}
|
|
97
|
+
}
|
|
98
|
+
/**
|
|
99
|
+
* Validate an agent-supplied event definition and return the normalized, typed event.
|
|
100
|
+
* Rejects immediate events, near-term one-shots, high-frequency periodics, guard-blocked
|
|
101
|
+
* preActions, and cross-channel channelIds. The returned event is what gets persisted, so
|
|
102
|
+
* the file on disk is exactly what was validated.
|
|
103
|
+
*/
|
|
104
|
+
function validateDefinition(rawDefinition, name, options) {
|
|
105
|
+
let data;
|
|
106
|
+
try {
|
|
107
|
+
data = JSON.parse(rawDefinition);
|
|
108
|
+
}
|
|
109
|
+
catch (error) {
|
|
110
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
111
|
+
throw new Error(`definition is not valid JSON: ${message}`);
|
|
112
|
+
}
|
|
113
|
+
if (!isRecord(data)) {
|
|
114
|
+
throw new Error("definition must be a JSON object.");
|
|
115
|
+
}
|
|
116
|
+
const providedChannelId = data.channelId;
|
|
117
|
+
if (providedChannelId === undefined || providedChannelId === null || providedChannelId === "") {
|
|
118
|
+
data.channelId = options.channelId;
|
|
119
|
+
}
|
|
120
|
+
else if (providedChannelId !== options.channelId) {
|
|
121
|
+
throw new Error(`definition channelId "${String(providedChannelId)}" does not match the current channel "${options.channelId}".`);
|
|
122
|
+
}
|
|
123
|
+
const event = parseScheduledEventContent(JSON.stringify(data), `${name}.json`);
|
|
124
|
+
if (event.type === "immediate") {
|
|
125
|
+
throw new Error("event_manage cannot create or update immediate events (self-triggering loop guard); " +
|
|
126
|
+
"do the work in the current turn instead.");
|
|
127
|
+
}
|
|
128
|
+
if (event.type === "one-shot") {
|
|
129
|
+
validateOneShot(event);
|
|
130
|
+
}
|
|
131
|
+
if (event.type === "periodic") {
|
|
132
|
+
validatePeriodic(event);
|
|
133
|
+
}
|
|
134
|
+
validatePreAction(event, options.commandGuardConfig);
|
|
135
|
+
return event;
|
|
136
|
+
}
|
|
137
|
+
async function readOwnedEvent(eventPath, name, options) {
|
|
138
|
+
let existing;
|
|
139
|
+
try {
|
|
140
|
+
existing = parseScheduledEventContent(await readFile(eventPath, "utf-8"), `${name}.json`);
|
|
141
|
+
}
|
|
142
|
+
catch (error) {
|
|
143
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
144
|
+
throw new Error(`Existing event "${name}" could not be parsed (${message}); use /events to manage it directly.`);
|
|
145
|
+
}
|
|
146
|
+
if (existing.channelId !== options.channelId) {
|
|
147
|
+
throw new Error(`Event "${name}" belongs to another channel and cannot be modified from here.`);
|
|
148
|
+
}
|
|
149
|
+
return existing;
|
|
150
|
+
}
|
|
151
|
+
async function countEventFiles(dir) {
|
|
152
|
+
if (!existsSync(dir))
|
|
153
|
+
return 0;
|
|
154
|
+
const filenames = await readdir(dir);
|
|
155
|
+
return filenames.filter((filename) => filename.endsWith(".json")).length;
|
|
156
|
+
}
|
|
157
|
+
export async function manageEvent(options, request) {
|
|
158
|
+
const { eventName, eventPath } = resolveEventPath(options.workspaceDir, request.name);
|
|
159
|
+
const eventsDir = join(options.workspaceDir, "events");
|
|
160
|
+
if (request.action === "delete") {
|
|
161
|
+
if (!existsSync(eventPath)) {
|
|
162
|
+
return {
|
|
163
|
+
action: "delete",
|
|
164
|
+
name: eventName,
|
|
165
|
+
path: toWorkspacePath(options, eventPath),
|
|
166
|
+
deleted: false,
|
|
167
|
+
notice: `事件 \`${eventName}\` 不存在,无需删除。`,
|
|
168
|
+
};
|
|
169
|
+
}
|
|
170
|
+
await readOwnedEvent(eventPath, eventName, options);
|
|
171
|
+
await unlink(eventPath);
|
|
172
|
+
return {
|
|
173
|
+
action: "delete",
|
|
174
|
+
name: eventName,
|
|
175
|
+
path: toWorkspacePath(options, eventPath),
|
|
176
|
+
deleted: true,
|
|
177
|
+
notice: `已删除事件 \`${eventName}\`。`,
|
|
178
|
+
};
|
|
179
|
+
}
|
|
180
|
+
if (!request.definition || request.definition.trim().length === 0) {
|
|
181
|
+
throw new Error(`${request.action} requires a non-empty definition.`);
|
|
182
|
+
}
|
|
183
|
+
if (request.action === "create") {
|
|
184
|
+
if (existsSync(eventPath)) {
|
|
185
|
+
throw new Error(`Event "${eventName}" already exists; use action "update" to replace it.`);
|
|
186
|
+
}
|
|
187
|
+
if ((await countEventFiles(eventsDir)) >= MAX_EVENT_FILES) {
|
|
188
|
+
throw new Error(`Too many event files (>= ${MAX_EVENT_FILES}) in workspace/events; clean up stale events before creating more.`);
|
|
189
|
+
}
|
|
190
|
+
}
|
|
191
|
+
else {
|
|
192
|
+
if (!existsSync(eventPath)) {
|
|
193
|
+
throw new Error(`Event "${eventName}" does not exist; use action "create" to add it.`);
|
|
194
|
+
}
|
|
195
|
+
const existing = await readOwnedEvent(eventPath, eventName, options);
|
|
196
|
+
if (existing.type === "immediate") {
|
|
197
|
+
throw new Error(`Event "${eventName}" is an immediate event and cannot be updated via event_manage.`);
|
|
198
|
+
}
|
|
199
|
+
}
|
|
200
|
+
const event = validateDefinition(request.definition, eventName, options);
|
|
201
|
+
const content = `${JSON.stringify(event, null, 2)}\n`;
|
|
202
|
+
await writeFileAtomically(eventPath, content);
|
|
203
|
+
return {
|
|
204
|
+
action: request.action,
|
|
205
|
+
name: eventName,
|
|
206
|
+
path: toWorkspacePath(options, eventPath),
|
|
207
|
+
eventType: event.type,
|
|
208
|
+
channelId: event.channelId,
|
|
209
|
+
bytesWritten: Buffer.byteLength(content, "utf-8"),
|
|
210
|
+
notice: request.action === "create"
|
|
211
|
+
? `已创建 ${event.type} 事件 \`${eventName}\`。`
|
|
212
|
+
: `已更新 ${event.type} 事件 \`${eventName}\`。`,
|
|
213
|
+
};
|
|
214
|
+
}
|
|
215
|
+
export function createEventManageTool(options) {
|
|
216
|
+
return {
|
|
217
|
+
name: "event_manage",
|
|
218
|
+
label: "event_manage",
|
|
219
|
+
description: "Create, update, or delete scheduled events (one-shot check-ins and periodic cadences) that wake this " +
|
|
220
|
+
"channel later. Use for task self-scheduling: arrange a follow-up after delegating, reschedule while " +
|
|
221
|
+
"blocked, clean up on close. immediate events are rejected; do that work in the current turn.",
|
|
222
|
+
parameters: eventManageSchema,
|
|
223
|
+
execute: async (_toolCallId, args) => {
|
|
224
|
+
const result = await manageEvent(options, {
|
|
225
|
+
action: parseAction(args.action),
|
|
226
|
+
name: args.name,
|
|
227
|
+
definition: args.definition,
|
|
228
|
+
});
|
|
229
|
+
return {
|
|
230
|
+
content: [{ type: "text", text: JSON.stringify(result, null, 2) }],
|
|
231
|
+
details: {
|
|
232
|
+
kind: "event_manage",
|
|
233
|
+
...result,
|
|
234
|
+
},
|
|
235
|
+
};
|
|
236
|
+
},
|
|
237
|
+
};
|
|
238
|
+
}
|
package/dist/tools/index.js
CHANGED
|
@@ -25,6 +25,7 @@ export function createPipiclawTools(options) {
|
|
|
25
25
|
workspacePath: options.workspacePath,
|
|
26
26
|
webConfig: toolsConfig.tools.web,
|
|
27
27
|
toolsConfig,
|
|
28
|
+
rtkEnabled: toolsConfig.tools.rtk.enabled,
|
|
28
29
|
getCurrentModel: options.getCurrentModel,
|
|
29
30
|
getAvailableModels: options.getAvailableModels,
|
|
30
31
|
resolveApiKey: options.resolveApiKey,
|
|
@@ -45,6 +46,7 @@ export function createPipiclawTools(options) {
|
|
|
45
46
|
memoryCandidateStore: options.memoryCandidateStore,
|
|
46
47
|
securityConfig,
|
|
47
48
|
webConfig: toolsConfig.tools.web,
|
|
49
|
+
rtkEnabled: toolsConfig.tools.rtk.enabled,
|
|
48
50
|
runtimeContext: {
|
|
49
51
|
workspacePath: options.workspacePath,
|
|
50
52
|
channelId: options.channelId,
|
package/dist/tools/registry.d.ts
CHANGED
|
@@ -28,6 +28,8 @@ export interface ToolBuildContext {
|
|
|
28
28
|
toolsConfig?: PipiclawToolsConfig;
|
|
29
29
|
/** Sub-agent set passes its per-invocation bash timeout; the main set relies on the built-in default. */
|
|
30
30
|
bashDefaultTimeoutSeconds?: number;
|
|
31
|
+
/** Gates the bash tool's rtk command optimizer (`tools.rtk.enabled`). Threaded to both sets. */
|
|
32
|
+
rtkEnabled?: boolean;
|
|
31
33
|
getCurrentModel?: () => Model<Api>;
|
|
32
34
|
getAvailableModels?: () => Model<Api>[];
|
|
33
35
|
resolveApiKey?: (model: Model<Api>) => Promise<string>;
|
package/dist/tools/registry.js
CHANGED
|
@@ -1,11 +1,13 @@
|
|
|
1
1
|
import { createBashTool } from "./bash.js";
|
|
2
2
|
import { createEditTool } from "./edit.js";
|
|
3
|
+
import { createEventManageTool } from "./event-manage.js";
|
|
3
4
|
import { createMemorySaveTool } from "./memory-save.js";
|
|
4
5
|
import { createReadTool } from "./read.js";
|
|
5
6
|
import { createSessionSearchTool } from "./session-search.js";
|
|
6
7
|
import { createSkillListTool } from "./skill-list.js";
|
|
7
8
|
import { createSkillManageTool } from "./skill-manage.js";
|
|
8
9
|
import { createSkillViewTool } from "./skill-view.js";
|
|
10
|
+
import { createTaskManageTool } from "./task-manage.js";
|
|
9
11
|
import { createWebFetchTool } from "./web-fetch.js";
|
|
10
12
|
import { createWebSearchTool } from "./web-search.js";
|
|
11
13
|
import { createWriteTool } from "./write.js";
|
|
@@ -44,6 +46,7 @@ export const TOOL_REGISTRY = [
|
|
|
44
46
|
availableToSubagents: true,
|
|
45
47
|
create: (ctx) => createBashTool(ctx.executor, {
|
|
46
48
|
...fileToolOptions(ctx),
|
|
49
|
+
rtkEnabled: ctx.rtkEnabled === true,
|
|
47
50
|
...(ctx.bashDefaultTimeoutSeconds !== undefined
|
|
48
51
|
? { defaultTimeoutSeconds: ctx.bashDefaultTimeoutSeconds }
|
|
49
52
|
: {}),
|
|
@@ -130,6 +133,34 @@ export const TOOL_REGISTRY = [
|
|
|
130
133
|
enabledBy: (ctx) => ctx.toolsConfig?.tools.skills.manage.enabled !== false,
|
|
131
134
|
create: (ctx) => createSkillManageTool({ workspaceDir: ctx.workspaceDir, workspacePath: ctx.workspacePath }),
|
|
132
135
|
},
|
|
136
|
+
{
|
|
137
|
+
name: "event_manage",
|
|
138
|
+
promptHint: "Schedule your own follow-ups: create/update/delete one-shot check-ins and periodic cadences for this channel. " +
|
|
139
|
+
"Name task-owned events `task.<channelId>.<taskId>.<use>` (e.g. .checkin, .schedule) so they clean up together. " +
|
|
140
|
+
"Keep a task's `wake` and its .checkin one-shot in sync — move both, clear both. " +
|
|
141
|
+
"No immediate events; periodic no more often than every 30 min (or 5 min when it carries a preAction gate).",
|
|
142
|
+
availableToSubagents: false,
|
|
143
|
+
enabledBy: (ctx) => ctx.toolsConfig?.tools.events.enabled !== false,
|
|
144
|
+
create: (ctx) => createEventManageTool({
|
|
145
|
+
workspaceDir: ctx.workspaceDir,
|
|
146
|
+
workspacePath: ctx.workspacePath,
|
|
147
|
+
channelId: ctx.channelId,
|
|
148
|
+
commandGuardConfig: ctx.securityConfig.commandGuard,
|
|
149
|
+
}),
|
|
150
|
+
},
|
|
151
|
+
{
|
|
152
|
+
name: "task_manage",
|
|
153
|
+
promptHint: "Update the task ledger: set a task's status/wake/recurrence, close a task out (archives one-shot tasks and " +
|
|
154
|
+
"cleans up its residual events), or list active tasks. Write the task body with write/edit; this owns the frontmatter.",
|
|
155
|
+
availableToSubagents: false,
|
|
156
|
+
enabledBy: (ctx) => ctx.toolsConfig?.tools.tasks.enabled !== false,
|
|
157
|
+
create: (ctx) => createTaskManageTool({
|
|
158
|
+
workspaceDir: ctx.workspaceDir,
|
|
159
|
+
workspacePath: ctx.workspacePath,
|
|
160
|
+
channelDir: ctx.channelDir,
|
|
161
|
+
channelId: ctx.channelId,
|
|
162
|
+
}),
|
|
163
|
+
},
|
|
133
164
|
];
|
|
134
165
|
/** Prompt hint for the `subagent` tool, which is registered outside TOOL_REGISTRY. */
|
|
135
166
|
export const SUBAGENT_TOOL_HINT = "Delegate a focused task to a sub-agent with its own isolated context";
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
import type { AgentTool } from "@earendil-works/pi-agent-core";
|
|
2
|
+
import { Type } from "typebox";
|
|
3
|
+
declare const taskManageSchema: Type.TObject<{
|
|
4
|
+
label: Type.TString;
|
|
5
|
+
action: Type.TUnion<[Type.TLiteral<"set">, Type.TLiteral<"done">, Type.TLiteral<"list">]>;
|
|
6
|
+
id: Type.TOptional<Type.TString>;
|
|
7
|
+
status: Type.TOptional<Type.TUnion<Type.TLiteral<"open" | "blocked" | "in-progress" | "awaiting-user">[]>>;
|
|
8
|
+
wake: Type.TOptional<Type.TString>;
|
|
9
|
+
recurrence: Type.TOptional<Type.TString>;
|
|
10
|
+
}>;
|
|
11
|
+
export type TaskManageAction = "set" | "done" | "list";
|
|
12
|
+
export interface TaskManageResult {
|
|
13
|
+
action: TaskManageAction;
|
|
14
|
+
id?: string;
|
|
15
|
+
path?: string;
|
|
16
|
+
status?: string;
|
|
17
|
+
archived?: boolean;
|
|
18
|
+
deletedEvents?: string[];
|
|
19
|
+
tasks?: Array<{
|
|
20
|
+
id: string;
|
|
21
|
+
title: string;
|
|
22
|
+
status: string;
|
|
23
|
+
wake?: string;
|
|
24
|
+
actionable: boolean;
|
|
25
|
+
}>;
|
|
26
|
+
notice: string;
|
|
27
|
+
}
|
|
28
|
+
export interface TaskManageRequest {
|
|
29
|
+
action: TaskManageAction;
|
|
30
|
+
id?: string;
|
|
31
|
+
status?: string;
|
|
32
|
+
wake?: string;
|
|
33
|
+
recurrence?: string;
|
|
34
|
+
}
|
|
35
|
+
export interface TaskManageToolOptions {
|
|
36
|
+
workspaceDir: string;
|
|
37
|
+
workspacePath: string;
|
|
38
|
+
channelDir: string;
|
|
39
|
+
channelId: string;
|
|
40
|
+
}
|
|
41
|
+
export declare function manageTask(options: TaskManageToolOptions, request: TaskManageRequest): Promise<TaskManageResult>;
|
|
42
|
+
export declare function createTaskManageTool(options: TaskManageToolOptions): AgentTool<typeof taskManageSchema>;
|
|
43
|
+
export {};
|