@oyasmi/pipiclaw 0.9.2-beta.3 → 0.9.2-beta.6

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.
Files changed (142) hide show
  1. package/README.md +3 -0
  2. package/dist/agent/channel-runner.d.ts +45 -19
  3. package/dist/agent/channel-runner.js +156 -102
  4. package/dist/agent/command-extension.js +1 -1
  5. package/dist/agent/context-budget.d.ts +17 -1
  6. package/dist/agent/context-budget.js +20 -6
  7. package/dist/agent/job-manager.d.ts +3 -1
  8. package/dist/agent/job-manager.js +7 -1
  9. package/dist/agent/prompt/builder.d.ts +0 -1
  10. package/dist/agent/prompt/builder.js +1 -14
  11. package/dist/agent/prompt/manifest.js +2 -1
  12. package/dist/agent/prompt/sections.js +1 -1
  13. package/dist/agent/runner-factory.d.ts +19 -1
  14. package/dist/agent/runner-factory.js +8 -1
  15. package/dist/agent/session-events.d.ts +2 -2
  16. package/dist/agent/session-events.js +2 -22
  17. package/dist/agent/turn-prompt.d.ts +35 -0
  18. package/dist/agent/turn-prompt.js +37 -0
  19. package/dist/agent/turn-recovery.js +1 -1
  20. package/dist/agent/turn-state.d.ts +60 -0
  21. package/dist/agent/turn-state.js +95 -0
  22. package/dist/agent/types.d.ts +5 -4
  23. package/dist/{runtime → channel}/channel-context.d.ts +10 -2
  24. package/dist/{runtime → channel}/channel-context.js +6 -2
  25. package/dist/{runtime → channel}/channel-event.d.ts +39 -0
  26. package/dist/channel/channel-event.js +11 -0
  27. package/dist/channel/channel-paths.d.ts +16 -0
  28. package/dist/{runtime → channel}/channel-paths.js +20 -0
  29. package/dist/{runtime → channel}/project-scope-store.js +6 -11
  30. package/dist/{runtime → channel}/store.d.ts +7 -0
  31. package/dist/{agent/commands.d.ts → commands/catalog.d.ts} +17 -2
  32. package/dist/{agent/commands.js → commands/catalog.js} +30 -0
  33. package/dist/index.d.ts +1 -1
  34. package/dist/log.js +14 -5
  35. package/dist/main.js +29 -0
  36. package/dist/memory/bootstrap.js +3 -5
  37. package/dist/memory/candidates.js +2 -4
  38. package/dist/memory/commands.js +2 -2
  39. package/dist/memory/files.d.ts +0 -1
  40. package/dist/memory/files.js +6 -9
  41. package/dist/memory/maintenance-state.d.ts +8 -0
  42. package/dist/memory/maintenance-state.js +51 -4
  43. package/dist/memory/scheduler.d.ts +6 -0
  44. package/dist/memory/scheduler.js +19 -16
  45. package/dist/playbooks/agent-delegation.md +2 -2
  46. package/dist/runtime/bootstrap.d.ts +14 -8
  47. package/dist/runtime/bootstrap.js +158 -81
  48. package/dist/runtime/delivery.d.ts +3 -3
  49. package/dist/runtime/delivery.js +1 -0
  50. package/dist/runtime/dingtalk.d.ts +62 -6
  51. package/dist/runtime/dingtalk.js +194 -85
  52. package/dist/runtime/durable-dispatch.d.ts +7 -1
  53. package/dist/runtime/durable-dispatch.js +12 -2
  54. package/dist/runtime/event-commands.js +2 -2
  55. package/dist/runtime/events.d.ts +8 -1
  56. package/dist/runtime/events.js +15 -3
  57. package/dist/runtime/inbound-media.d.ts +60 -0
  58. package/dist/runtime/inbound-media.js +95 -0
  59. package/dist/runtime/project-commands.js +2 -2
  60. package/dist/runtime/skill-commands.d.ts +27 -0
  61. package/dist/runtime/skill-commands.js +72 -0
  62. package/dist/runtime/subagent-commands.js +1 -1
  63. package/dist/runtime/task-commands.js +2 -2
  64. package/dist/runtime/task-driver.d.ts +12 -1
  65. package/dist/runtime/task-driver.js +36 -56
  66. package/dist/runtime/task-migration.d.ts +11 -0
  67. package/dist/runtime/task-migration.js +14 -2
  68. package/dist/runtime/task-wake.d.ts +1 -1
  69. package/dist/runtime/task-wake.js +1 -1
  70. package/dist/security/command-guard.js +1 -3
  71. package/dist/security/config.d.ts +1 -1
  72. package/dist/security/config.js +8 -32
  73. package/dist/security/path-guard.js +1 -6
  74. package/dist/security/project-scope.js +1 -3
  75. package/dist/settings.d.ts +3 -2
  76. package/dist/settings.js +82 -20
  77. package/dist/shared/atomic-file.d.ts +2 -3
  78. package/dist/shared/atomic-file.js +8 -9
  79. package/dist/shared/config-diagnostic.d.ts +21 -0
  80. package/dist/shared/config-diagnostic.js +32 -0
  81. package/dist/shared/numeric.d.ts +7 -0
  82. package/dist/shared/numeric.js +19 -0
  83. package/dist/shared/text-utils.d.ts +10 -0
  84. package/dist/shared/text-utils.js +16 -0
  85. package/dist/shared/token-estimate.d.ts +1 -0
  86. package/dist/shared/token-estimate.js +19 -0
  87. package/dist/shared/types.d.ts +23 -0
  88. package/dist/shared/types.js +12 -0
  89. package/dist/shared/with-timeout.d.ts +3 -0
  90. package/dist/shared/with-timeout.js +8 -0
  91. package/dist/subagents/discovery.d.ts +7 -7
  92. package/dist/subagents/discovery.js +27 -59
  93. package/dist/subagents/runs.d.ts +15 -4
  94. package/dist/subagents/runs.js +118 -11
  95. package/dist/subagents/tool.js +199 -131
  96. package/dist/subagents/workspace-lease.js +1 -3
  97. package/dist/tasks/control.d.ts +2 -0
  98. package/dist/tasks/control.js +2 -0
  99. package/dist/tasks/ledger.d.ts +0 -9
  100. package/dist/tasks/ledger.js +92 -158
  101. package/dist/tools/config.d.ts +1 -1
  102. package/dist/tools/config.js +9 -46
  103. package/dist/tools/glob-match.d.ts +25 -4
  104. package/dist/tools/glob-match.js +175 -53
  105. package/dist/tools/glob.js +5 -2
  106. package/dist/tools/index.d.ts +1 -1
  107. package/dist/tools/registry.d.ts +1 -1
  108. package/dist/tools/send-media.d.ts +1 -1
  109. package/dist/tools/skill.d.ts +15 -0
  110. package/dist/tools/skill.js +17 -11
  111. package/dist/tools/truncate.js +24 -28
  112. package/dist/tui/app.js +6 -4
  113. package/dist/tui/commands.d.ts +1 -0
  114. package/dist/tui/commands.js +3 -1
  115. package/dist/tui/terminal-context.d.ts +2 -2
  116. package/dist/tui/terminal-media-sender.d.ts +1 -1
  117. package/dist/tui/turn-controller.d.ts +2 -1
  118. package/dist/tui/turn-controller.js +2 -1
  119. package/dist/web/config.js +3 -15
  120. package/examples/sub-agents/README.md +2 -2
  121. package/examples/sub-agents/builder.md +1 -1
  122. package/examples/sub-agents/documenter.md +1 -1
  123. package/examples/sub-agents/explorer.md +4 -4
  124. package/examples/sub-agents/git-committer.md +5 -4
  125. package/examples/sub-agents/log-sifter.md +4 -4
  126. package/examples/sub-agents/planner.md +1 -1
  127. package/examples/sub-agents/reviewer.md +1 -1
  128. package/examples/sub-agents/verifier.md +1 -1
  129. package/examples/sub-agents/worker.md +3 -3
  130. package/package.json +3 -2
  131. package/dist/agent/index.d.ts +0 -2
  132. package/dist/agent/index.js +0 -1
  133. package/dist/runtime/channel-event.js +0 -1
  134. package/dist/runtime/channel-paths.d.ts +0 -4
  135. /package/dist/{runtime → channel}/active-session-store.d.ts +0 -0
  136. /package/dist/{runtime → channel}/active-session-store.js +0 -0
  137. /package/dist/{runtime → channel}/channel-index.d.ts +0 -0
  138. /package/dist/{runtime → channel}/channel-index.js +0 -0
  139. /package/dist/{runtime → channel}/project-scope-store.d.ts +0 -0
  140. /package/dist/{runtime → channel}/store.js +0 -0
  141. /package/dist/{agent → commands}/reply-limits.d.ts +0 -0
  142. /package/dist/{agent → commands}/reply-limits.js +0 -0
@@ -1,75 +1,197 @@
1
1
  /**
2
- * Compile a shell-style glob pattern into a `RegExp` matched against a POSIX-relative file path.
2
+ * Compile a shell-style glob pattern into a matcher for POSIX-relative file paths.
3
3
  *
4
4
  * Semantics follow the convention the model already knows from `find`/`fd`/Claude Code's own glob
5
5
  * tool: a pattern with no `/` matches the *basename* at any depth (so `*.ts` searches the whole
6
6
  * tree, not just its top level); `**` matches any number of path segments, including zero, when it
7
- * sits between (or at the start/end of) path separators; `{a,b}` is brace-expanded into an
8
- * alternation. Matching is always case-sensitive and always against `/`-joined relative paths —
7
+ * sits between (or at the start/end of) path separators; `{a,b}` is brace-expanded into
8
+ * alternatives. Matching is always case-sensitive and always against `/`-joined relative paths —
9
9
  * callers never see platform separators.
10
+ *
11
+ * ## Why this is not a regular expression
12
+ *
13
+ * The obvious implementation compiles the whole pattern into one `RegExp` — and that regex is a
14
+ * denial-of-service primitive, because the pattern is a model-supplied argument and the matcher
15
+ * runs once per walked file on the event loop. Nested unbounded quantifiers backtrack
16
+ * exponentially on a *near* miss: `**​/` repeated ten times took ~2s per path, `{*,*}` repeated
17
+ * five times ~145ms and rising by ~17x per group, and `*a*a*a*a*a*a*a*azzz` — nineteen
18
+ * characters, no `**`, no braces — took **32 seconds** against a sixty-character name. Folding
19
+ * `**​/` or capping the pattern length only removes particular spellings; the blow-up belongs to
20
+ * the whole class of "several stars separated by literals", which no length bound can exclude.
21
+ *
22
+ * So the pattern is matched structurally instead: braces expand to a bounded set of variants,
23
+ * each variant is split into path segments, and both the segment sequence and each segment's
24
+ * characters are matched by the classic single-backtrack-point wildcard algorithm. That is
25
+ * O(n·m) in the worst case with no nested quantifiers, so every shape above matches in
26
+ * microseconds and no pattern can stall the walk.
10
27
  */
28
+ /** A pattern longer than this is a mistake or an attack; neither deserves a match attempt. */
29
+ const MAX_PATTERN_LENGTH = 512;
30
+ /** Brace expansion multiplies: `{a,b}` ten times over is 1024 variants of the same walk. */
31
+ const MAX_BRACE_VARIANTS = 64;
32
+ /** A path segment that is exactly `**`: any number of segments, including none. */
33
+ const GLOBSTAR = Symbol("globstar");
34
+ /** `*` inside a segment: any run of characters, not crossing a separator. */
35
+ const STAR = Symbol("star");
36
+ /** `?` inside a segment: exactly one character. */
37
+ const ANY = Symbol("any");
11
38
  export function compileGlobPattern(pattern) {
12
- const body = globToRegExpSource(pattern);
13
- return pattern.includes("/") ? new RegExp(`^${body}$`) : new RegExp(`(?:^|/)${body}$`);
39
+ if (pattern.length > MAX_PATTERN_LENGTH) {
40
+ throw new Error(`pattern is longer than ${MAX_PATTERN_LENGTH} characters`);
41
+ }
42
+ // The anchoring decision is made on the pattern as written, before expansion: `{src/a,b}`
43
+ // carries a separator and is therefore path-anchored for *both* of its alternatives.
44
+ const matchBasenameOnly = !pattern.includes("/");
45
+ const variants = expandBraces(pattern).map(compileVariant);
46
+ return {
47
+ test(path) {
48
+ const segments = matchBasenameOnly ? [path.slice(path.lastIndexOf("/") + 1)] : path.split("/");
49
+ return variants.some((variant) => matchVariant(variant, segments));
50
+ },
51
+ };
14
52
  }
15
- /** Single-pass translation so `**` can see the literal `/` characters on either side of it. */
16
- function globToRegExpSource(pattern) {
17
- let out = "";
18
- let i = 0;
19
- const n = pattern.length;
20
- while (i < n) {
21
- const ch = pattern[i];
22
- if (ch === "*" && pattern[i + 1] === "*") {
23
- const precededByBoundary = i === 0 || pattern[i - 1] === "/";
24
- const followedBySlash = pattern[i + 2] === "/";
25
- const followedByEnd = i + 2 === n;
26
- if (precededByBoundary && followedBySlash) {
27
- // `**/`: zero or more complete path segments.
28
- out += "(?:.*/)?";
29
- i += 3;
30
- continue;
53
+ /**
54
+ * Expand `{a,b}` alternations into concrete patterns, innermost group last so nesting works.
55
+ *
56
+ * Braces are located by depth-counted scanning rather than the first `}` found, so `{a,{b,c}}`
57
+ * and a comma inside a nested group are read the way the writer meant. An unmatched `{` stays a
58
+ * literal character, as it did before.
59
+ */
60
+ function expandBraces(pattern) {
61
+ const open = findBraceGroup(pattern);
62
+ if (!open)
63
+ return [pattern];
64
+ const results = [];
65
+ for (const alternative of open.alternatives) {
66
+ for (const expanded of expandBraces(`${open.prefix}${alternative}${open.suffix}`)) {
67
+ results.push(expanded);
68
+ if (results.length > MAX_BRACE_VARIANTS) {
69
+ throw new Error(`brace expansion produces more than ${MAX_BRACE_VARIANTS} patterns`);
31
70
  }
32
- if (precededByBoundary && followedByEnd) {
33
- // trailing `**`: everything under this point.
34
- out += ".*";
35
- i += 2;
36
- continue;
71
+ }
72
+ }
73
+ return results;
74
+ }
75
+ function findBraceGroup(pattern) {
76
+ const start = pattern.indexOf("{");
77
+ if (start === -1)
78
+ return undefined;
79
+ let depth = 0;
80
+ const alternatives = [];
81
+ let current = "";
82
+ for (let i = start; i < pattern.length; i++) {
83
+ const char = pattern[i];
84
+ if (char === "{") {
85
+ depth++;
86
+ if (depth === 1)
87
+ continue; // the group's own opening brace is not content
88
+ }
89
+ else if (char === "}") {
90
+ depth--;
91
+ if (depth === 0) {
92
+ alternatives.push(current);
93
+ return { prefix: pattern.slice(0, start), alternatives, suffix: pattern.slice(i + 1) };
37
94
  }
38
- // `**` not cleanly bounded by separators — fall back to single-segment `*` semantics.
39
- out += "[^/]*";
40
- i += 2;
95
+ }
96
+ else if (char === "," && depth === 1) {
97
+ alternatives.push(current);
98
+ current = "";
41
99
  continue;
42
100
  }
43
- if (ch === "*") {
44
- out += "[^/]*";
45
- i += 1;
101
+ current += char;
102
+ }
103
+ return undefined; // unbalanced `{` — leave it as a literal
104
+ }
105
+ function compileVariant(pattern) {
106
+ const rawSegments = pattern.split("/");
107
+ const segments = rawSegments.map((segment) => segment === "**" ? GLOBSTAR : compileSegment(segment));
108
+ const trailingGlobstar = segments.length > 1 && segments[segments.length - 1] === GLOBSTAR;
109
+ return { segments, trailingGlobstar };
110
+ }
111
+ function compileSegment(segment) {
112
+ const tokens = [];
113
+ for (const char of segment) {
114
+ if (char === "*") {
115
+ // Adjacent stars are the same star. A `**` that is not a whole segment (`a**b`) has
116
+ // always meant single-segment `*`, and collapsing keeps that without a second token.
117
+ if (tokens[tokens.length - 1] !== STAR)
118
+ tokens.push(STAR);
46
119
  continue;
47
120
  }
48
- if (ch === "?") {
49
- out += "[^/]";
50
- i += 1;
121
+ tokens.push(char === "?" ? ANY : char);
122
+ }
123
+ return tokens;
124
+ }
125
+ /**
126
+ * Match a segment sequence, with `**` as the only construct that can span segments.
127
+ *
128
+ * The single backtrack point (`starIndex`/`starSegment`) is what keeps this linear-ish: on a
129
+ * mismatch the matcher advances the most recent globstar by one segment instead of exploring
130
+ * every combination of every globstar, which is the search space a regex engine would walk.
131
+ */
132
+ function matchVariant(variant, path) {
133
+ const { segments, trailingGlobstar } = variant;
134
+ // The trailing `**` is handled after the loop, so drop it here and require a remainder there.
135
+ const patternLength = trailingGlobstar ? segments.length - 1 : segments.length;
136
+ let patternIndex = 0;
137
+ let pathIndex = 0;
138
+ let starIndex = -1;
139
+ let starPathIndex = 0;
140
+ while (pathIndex < path.length) {
141
+ const segment = patternIndex < patternLength ? segments[patternIndex] : undefined;
142
+ // Pattern spent with path left over: a trailing `**` takes the whole remainder.
143
+ if (segment === undefined && trailingGlobstar)
144
+ break;
145
+ if (segment === GLOBSTAR) {
146
+ starIndex = patternIndex;
147
+ starPathIndex = pathIndex;
148
+ patternIndex++;
51
149
  continue;
52
150
  }
53
- if (ch === "{") {
54
- const close = pattern.indexOf("}", i);
55
- if (close === -1) {
56
- out += escapeRegExpChar(ch);
57
- i += 1;
58
- continue;
59
- }
60
- const alternatives = pattern
61
- .slice(i + 1, close)
62
- .split(",")
63
- .map((alt) => globToRegExpSource(alt));
64
- out += `(?:${alternatives.join("|")})`;
65
- i = close + 1;
151
+ if (segment !== undefined && matchSegment(segment, path[pathIndex])) {
152
+ patternIndex++;
153
+ pathIndex++;
66
154
  continue;
67
155
  }
68
- out += escapeRegExpChar(ch);
69
- i += 1;
156
+ if (starIndex === -1)
157
+ return false;
158
+ // Let the last globstar swallow one more segment and retry from just after it.
159
+ starPathIndex++;
160
+ pathIndex = starPathIndex;
161
+ patternIndex = starIndex + 1;
70
162
  }
71
- return out;
163
+ while (patternIndex < patternLength && segments[patternIndex] === GLOBSTAR)
164
+ patternIndex++;
165
+ if (patternIndex !== patternLength)
166
+ return false;
167
+ return trailingGlobstar ? pathIndex < path.length : pathIndex === path.length;
72
168
  }
73
- function escapeRegExpChar(ch) {
74
- return /[.+^${}()|[\]\\]/.test(ch) ? `\\${ch}` : ch;
169
+ /** The same algorithm one level down: `*` is the backtrack point, `?` and literals advance. */
170
+ function matchSegment(tokens, text) {
171
+ let tokenIndex = 0;
172
+ let textIndex = 0;
173
+ let starIndex = -1;
174
+ let starTextIndex = 0;
175
+ while (textIndex < text.length) {
176
+ const token = tokenIndex < tokens.length ? tokens[tokenIndex] : undefined;
177
+ if (token === STAR) {
178
+ starIndex = tokenIndex;
179
+ starTextIndex = textIndex;
180
+ tokenIndex++;
181
+ continue;
182
+ }
183
+ if (token === ANY || (typeof token === "string" && token === text[textIndex])) {
184
+ tokenIndex++;
185
+ textIndex++;
186
+ continue;
187
+ }
188
+ if (starIndex === -1)
189
+ return false;
190
+ starTextIndex++;
191
+ textIndex = starTextIndex;
192
+ tokenIndex = starIndex + 1;
193
+ }
194
+ while (tokenIndex < tokens.length && tokens[tokenIndex] === STAR)
195
+ tokenIndex++;
196
+ return tokenIndex === tokens.length;
75
197
  }
@@ -3,6 +3,7 @@ import { Type } from "typebox";
3
3
  import { DEFAULT_SECURITY_CONFIG } from "../security/config.js";
4
4
  import { checkPathGuard } from "../security/path-guard-check.js";
5
5
  import { RecoverableToolError } from "../shared/recoverable-error.js";
6
+ import { errorMessage } from "../shared/text-utils.js";
6
7
  import { compileGlobPattern } from "./glob-match.js";
7
8
  import { IGNORED_DIR_SEGMENTS } from "./ignore-dirs.js";
8
9
  import { DEFAULT_MAX_BYTES, formatSize, truncateHead } from "./truncate.js";
@@ -52,8 +53,10 @@ export function createGlobTool(fileStore, options = {}) {
52
53
  try {
53
54
  matcher = compileGlobPattern(pattern);
54
55
  }
55
- catch {
56
- throw new RecoverableToolError(`Invalid glob pattern: ${pattern}`);
56
+ catch (error) {
57
+ // The reason is part of the message: a pattern rejected for complexity is fixed by
58
+ // simplifying it, which "invalid pattern" alone does not tell the model.
59
+ throw new RecoverableToolError(`Invalid glob pattern: ${pattern} (${errorMessage(error)})`);
57
60
  }
58
61
  const walk = await fileStore.walkFiles(target, {
59
62
  maxEntries: MAX_SCAN_ENTRIES,
@@ -1,9 +1,9 @@
1
1
  import type { AgentTool } from "@earendil-works/pi-agent-core";
2
2
  import type { Api, Model } from "@earendil-works/pi-ai";
3
+ import type { MediaSender } from "../channel/channel-context.js";
3
4
  import type { Executor } from "../executor.js";
4
5
  import type { FileStore } from "../file-store.js";
5
6
  import type { MemoryCandidateStore } from "../memory/candidates.js";
6
- import type { MediaSender } from "../runtime/channel-context.js";
7
7
  import type { ProjectScope } from "../security/project-scope.js";
8
8
  import type { SecurityConfig } from "../security/types.js";
9
9
  import type { PipiclawMemoryRecallSettings, PipiclawSessionSearchSettings } from "../settings.js";
@@ -1,10 +1,10 @@
1
1
  import type { AgentTool } from "@earendil-works/pi-agent-core";
2
2
  import type { Api, Model } from "@earendil-works/pi-ai";
3
3
  import type { ChannelJobManager } from "../agent/job-manager.js";
4
+ import type { MediaSender } from "../channel/channel-context.js";
4
5
  import type { Executor } from "../executor.js";
5
6
  import type { FileStore } from "../file-store.js";
6
7
  import type { MemoryCandidateStore } from "../memory/candidates.js";
7
- import type { MediaSender } from "../runtime/channel-context.js";
8
8
  import type { SecurityConfig, SecurityRuntimeContext } from "../security/types.js";
9
9
  import type { PipiclawSessionSearchSettings } from "../settings.js";
10
10
  import type { PipiclawToolsConfig, PipiclawWebToolsConfig } from "./config.js";
@@ -1,7 +1,7 @@
1
1
  import type { AgentTool } from "@earendil-works/pi-agent-core";
2
2
  import { Type } from "typebox";
3
+ import type { MediaSender } from "../channel/channel-context.js";
3
4
  import type { FileStore } from "../file-store.js";
4
- import type { MediaSender } from "../runtime/channel-context.js";
5
5
  import type { SecurityConfig, SecurityRuntimeContext } from "../security/types.js";
6
6
  declare const sendMediaSchema: Type.TObject<{
7
7
  path: Type.TString;
@@ -27,5 +27,20 @@ export interface SkillToolOptions {
27
27
  export declare function listWorkspaceSkills(options: {
28
28
  workspaceDir: string;
29
29
  }): Promise<WorkspaceSkillSummary[]>;
30
+ export interface WorkspaceSkillFile {
31
+ name: string;
32
+ /** The guard-resolved path actually opened — never the raw pre-guard path. */
33
+ path: string;
34
+ content: string;
35
+ truncated: boolean;
36
+ }
37
+ /**
38
+ * Load one skill's `SKILL.md` bytes through the same path-guard every other file read goes
39
+ * through. Shared by the `skill` tool's `read` action and the `/skills show` runtime command
40
+ * (`src/runtime/skill-commands.ts`) — a `SKILL.md` that is itself a symlink pointing outside
41
+ * `workspace/skills/` (planted via `bash ln -s`, not via `name` -- `resolveSkillPath` already
42
+ * confines that) is caught here in both callers instead of being read verbatim.
43
+ */
44
+ export declare function loadWorkspaceSkillFile(options: SkillToolOptions, name: string): Promise<WorkspaceSkillFile>;
30
45
  export declare function createSkillTool(options: SkillToolOptions): AgentTool<typeof skillSchema>;
31
46
  export {};
@@ -4,6 +4,7 @@ import { dirname, join } from "node:path";
4
4
  import { Type } from "typebox";
5
5
  import { DEFAULT_SECURITY_CONFIG } from "../security/config.js";
6
6
  import { checkPathGuard } from "../security/path-guard-check.js";
7
+ import { isNodeError } from "../shared/fs-utils.js";
7
8
  import { RecoverableToolError } from "../shared/recoverable-error.js";
8
9
  import { resolveSkillPath, scanSkillContent, validateSkillFrontmatter, validateSkillName } from "./skill-security.js";
9
10
  import { DEFAULT_MAX_BYTES, formatSize, truncateHead } from "./truncate.js";
@@ -20,9 +21,6 @@ const skillSchema = Type.Object({
20
21
  }),
21
22
  name: Type.Optional(Type.String({ description: "Exact workspace skill name from the list (required for read)." })),
22
23
  });
23
- function isNodeError(error) {
24
- return error instanceof Error && "code" in error;
25
- }
26
24
  function extractDescription(content) {
27
25
  const match = content.replace(/\r\n/g, "\n").match(/^---\n([\s\S]*?)\n---/);
28
26
  if (!match) {
@@ -85,7 +83,14 @@ export async function listWorkspaceSkills(options) {
85
83
  }
86
84
  return summaries;
87
85
  }
88
- async function readWorkspaceSkill(options, name) {
86
+ /**
87
+ * Load one skill's `SKILL.md` bytes through the same path-guard every other file read goes
88
+ * through. Shared by the `skill` tool's `read` action and the `/skills show` runtime command
89
+ * (`src/runtime/skill-commands.ts`) — a `SKILL.md` that is itself a symlink pointing outside
90
+ * `workspace/skills/` (planted via `bash ln -s`, not via `name` -- `resolveSkillPath` already
91
+ * confines that) is caught here in both callers instead of being read verbatim.
92
+ */
93
+ export async function loadWorkspaceSkillFile(options, name) {
89
94
  const nameValidation = validateSkillName(name);
90
95
  if (!nameValidation.ok) {
91
96
  throw new RecoverableToolError(nameValidation.error ?? `Invalid skill name "${name}".`);
@@ -95,9 +100,6 @@ async function readWorkspaceSkill(options, name) {
95
100
  if (!existsSync(rawPath)) {
96
101
  throw new RecoverableToolError(`Workspace skill "${name}" does not exist. Use action "list" to see what's available.`);
97
102
  }
98
- // Runs the same path-guard every other read goes through: a `SKILL.md` that is itself a
99
- // symlink pointing outside `workspace/skills/` (planted via `bash ln -s`, not via `name` --
100
- // `resolveSkillPath` already confines that) is caught here instead of being read verbatim.
101
103
  const securityConfig = options.securityConfig ?? DEFAULT_SECURITY_CONFIG;
102
104
  const securityContext = options.securityContext ?? {
103
105
  agentWorkspaceDir: options.workspaceDir,
@@ -113,16 +115,20 @@ async function readWorkspaceSkill(options, name) {
113
115
  if (truncation.truncated) {
114
116
  body += `\n\n[Truncated at ${formatSize(DEFAULT_MAX_BYTES)}. Use the read tool on ${target} to page through the rest.]`;
115
117
  }
118
+ return { name, path: target, content: body, truncated: truncation.truncated };
119
+ }
120
+ async function readWorkspaceSkill(options, name) {
121
+ const file = await loadWorkspaceSkillFile(options, name);
116
122
  // Mirrors the framing pi's own skill loader gives a model-invoked skill: the location and the
117
123
  // relative-path rule are what let the model correctly `read` a skill's references/templates
118
124
  // afterward, and are the whole reason `skill read` is worth more than a plain `read` call.
119
- const envelope = `<skill name="${name}" location="${target}">\n` +
120
- `References are relative to ${dirname(target)}.\n\n` +
121
- `${body}\n` +
125
+ const envelope = `<skill name="${file.name}" location="${file.path}">\n` +
126
+ `References are relative to ${dirname(file.path)}.\n\n` +
127
+ `${file.content}\n` +
122
128
  `</skill>`;
123
129
  return {
124
130
  content: [{ type: "text", text: envelope }],
125
- details: { action: "read", name, path: target, truncated: truncation.truncated },
131
+ details: { action: "read", name: file.name, path: file.path, truncated: file.truncated },
126
132
  };
127
133
  }
128
134
  export function createSkillTool(options) {
@@ -31,6 +31,26 @@ export function formatSize(bytes) {
31
31
  return `${(bytes / (1024 * 1024)).toFixed(1)}MB`;
32
32
  }
33
33
  }
34
+ /** Line/byte totals shared by both `truncateHead` and `truncateTail`. */
35
+ function measureContent(content) {
36
+ const totalBytes = Buffer.byteLength(content, "utf-8");
37
+ const lines = content.split("\n");
38
+ return { lines, totalLines: lines.length, totalBytes };
39
+ }
40
+ /** The "nothing to truncate" result both directions return when content already fits. */
41
+ function unclippedResult(content, totalLines, totalBytes) {
42
+ return {
43
+ content,
44
+ truncated: false,
45
+ truncatedBy: null,
46
+ totalLines,
47
+ totalBytes,
48
+ outputLines: totalLines,
49
+ outputBytes: totalBytes,
50
+ lastLinePartial: false,
51
+ firstLineExceedsLimit: false,
52
+ };
53
+ }
34
54
  /**
35
55
  * Truncate content from the head (keep first N lines/bytes).
36
56
  * Suitable for file reads where you want to see the beginning.
@@ -41,22 +61,10 @@ export function formatSize(bytes) {
41
61
  export function truncateHead(content, options = {}) {
42
62
  const maxLines = options.maxLines ?? DEFAULT_MAX_LINES;
43
63
  const maxBytes = options.maxBytes ?? DEFAULT_MAX_BYTES;
44
- const totalBytes = Buffer.byteLength(content, "utf-8");
45
- const lines = content.split("\n");
46
- const totalLines = lines.length;
64
+ const { lines, totalLines, totalBytes } = measureContent(content);
47
65
  // Check if no truncation needed
48
66
  if (totalLines <= maxLines && totalBytes <= maxBytes) {
49
- return {
50
- content,
51
- truncated: false,
52
- truncatedBy: null,
53
- totalLines,
54
- totalBytes,
55
- outputLines: totalLines,
56
- outputBytes: totalBytes,
57
- lastLinePartial: false,
58
- firstLineExceedsLimit: false,
59
- };
67
+ return unclippedResult(content, totalLines, totalBytes);
60
68
  }
61
69
  // Check if first line alone exceeds byte limit
62
70
  const firstLineBytes = Buffer.byteLength(lines[0], "utf-8");
@@ -114,22 +122,10 @@ export function truncateHead(content, options = {}) {
114
122
  export function truncateTail(content, options = {}) {
115
123
  const maxLines = options.maxLines ?? DEFAULT_MAX_LINES;
116
124
  const maxBytes = options.maxBytes ?? DEFAULT_MAX_BYTES;
117
- const totalBytes = Buffer.byteLength(content, "utf-8");
118
- const lines = content.split("\n");
119
- const totalLines = lines.length;
125
+ const { lines, totalLines, totalBytes } = measureContent(content);
120
126
  // Check if no truncation needed
121
127
  if (totalLines <= maxLines && totalBytes <= maxBytes) {
122
- return {
123
- content,
124
- truncated: false,
125
- truncatedBy: null,
126
- totalLines,
127
- totalBytes,
128
- outputLines: totalLines,
129
- outputBytes: totalBytes,
130
- lastLinePartial: false,
131
- firstLineExceedsLimit: false,
132
- };
128
+ return unclippedResult(content, totalLines, totalBytes);
133
129
  }
134
130
  // Work backwards from the end
135
131
  const outputLinesArr = [];
package/dist/tui/app.js CHANGED
@@ -7,18 +7,19 @@
7
7
  * preparation shares `prepareAppServices` with the DingTalk path.
8
8
  */
9
9
  import { userInfo } from "node:os";
10
- import { renderBuiltInHelp } from "../agent/commands.js";
11
- import { createRunner } from "../agent/index.js";
12
10
  import { channelRunningJobLines } from "../agent/job-manager.js";
11
+ import { createRunner } from "../agent/runner-factory.js";
12
+ import { ensureChannelDir } from "../channel/channel-paths.js";
13
+ import { ChannelStore } from "../channel/store.js";
14
+ import { renderBuiltInHelp } from "../commands/catalog.js";
13
15
  import * as log from "../log.js";
14
16
  import { ensureChannelMemoryFilesSync } from "../memory/files.js";
15
17
  import { BootstrapExitError, bootstrapAppHome, DEFAULT_BOOTSTRAP_PATHS, printBootstrapSummary, readCliVersion, } from "../runtime/app-home.js";
16
18
  import { prepareAppServices } from "../runtime/bootstrap.js";
17
- import { ensureChannelDir } from "../runtime/channel-paths.js";
18
19
  import { finalDeliveryOf, progressStyleOf } from "../runtime/dingtalk.js";
19
20
  import { handleEventsCommand } from "../runtime/event-commands.js";
20
21
  import { handleProjectCommand } from "../runtime/project-commands.js";
21
- import { ChannelStore } from "../runtime/store.js";
22
+ import { handleSkillsCommand } from "../runtime/skill-commands.js";
22
23
  import { handleSubagentsCommand } from "../runtime/subagent-commands.js";
23
24
  import { handleTasksCommand } from "../runtime/task-commands.js";
24
25
  import { flushSecurityLogs } from "../security/logger.js";
@@ -141,6 +142,7 @@ export async function runTuiApp(options) {
141
142
  channelId,
142
143
  }),
143
144
  runSubagents: (args) => handleSubagentsCommand({ args, channelId, discovery: runner.getSubAgentDiscoverySnapshot() }),
145
+ runSkills: (args) => handleSkillsCommand({ args, workspaceDir: paths.workspaceDir, appHomeDir: paths.appHomeDir, channelId }),
144
146
  runProject: (args) => handleProjectCommand({
145
147
  args,
146
148
  channelId,
@@ -41,6 +41,7 @@ export interface DispatchDeps {
41
41
  runTasks(args: string): Promise<string>;
42
42
  runSubagents(args: string): Promise<string>;
43
43
  runProject(args: string): Promise<string>;
44
+ runSkills(args: string): Promise<string>;
44
45
  }
45
46
  export declare function dispatch(input: string, deps: DispatchDeps): Promise<DispatchOutcome>;
46
47
  /**
@@ -13,7 +13,7 @@
13
13
  * depend on whether a turn is running, which only the app knows — so those come
14
14
  * back as intents rather than being applied here.
15
15
  */
16
- import { BUILT_IN_COMMANDS, parseBuiltInCommand, SESSION_COMMANDS } from "../agent/commands.js";
16
+ import { BUILT_IN_COMMANDS, parseBuiltInCommand, SESSION_COMMANDS } from "../commands/catalog.js";
17
17
  export async function dispatch(input, deps) {
18
18
  const trimmed = input.trim();
19
19
  if (!trimmed)
@@ -43,6 +43,8 @@ export async function dispatch(input, deps) {
43
43
  return { kind: "reply", text: await deps.runSubagents(command.args) };
44
44
  case "project":
45
45
  return { kind: "reply", text: await deps.runProject(command.args) };
46
+ case "skills":
47
+ return { kind: "reply", text: await deps.runSkills(command.args) };
46
48
  case "stop":
47
49
  return { kind: "stop" };
48
50
  case "steer":
@@ -9,8 +9,8 @@
9
9
  * - `respond` / `respondPlain` archive when `shouldLog` is set;
10
10
  * - `replaceMessage` / `deleteMessage` do not archive (they only re-render).
11
11
  */
12
- import type { ChannelContext, FinalDelivery, ProgressStyle } from "../runtime/channel-context.js";
13
- import type { ChannelStore } from "../runtime/store.js";
12
+ import type { ChannelContext, FinalDelivery, ProgressStyle } from "../channel/channel-context.js";
13
+ import type { ChannelStore } from "../channel/store.js";
14
14
  import type { TranscriptRenderer } from "./renderer.js";
15
15
  /** The minimal per-turn input the terminal context needs (no DingTalk types). */
16
16
  export interface TurnInput {
@@ -1,5 +1,5 @@
1
+ import type { MediaSender } from "../channel/channel-context.js";
1
2
  import type { BootstrapIO } from "../runtime/app-home.js";
2
- import type { MediaSender } from "../runtime/channel-context.js";
3
3
  /**
4
4
  * Terminal implementation of the `MediaSender` port. There is no chat surface to
5
5
  * push a file to, and the bytes already came from a local file, so "sending" here
@@ -7,7 +7,7 @@
7
7
  * unit-tested with fakes and a fake clock. `app.ts` builds the real ones.
8
8
  */
9
9
  import type { AgentRunner } from "../agent/types.js";
10
- import type { ChannelStore } from "../runtime/store.js";
10
+ import type { ChannelStore } from "../channel/store.js";
11
11
  import type { Frontend } from "./renderer.js";
12
12
  import { type DeliveryTraits } from "./terminal-context.js";
13
13
  export interface TurnControllerDeps {
@@ -24,6 +24,7 @@ export interface TurnControllerDeps {
24
24
  runTasks: (args: string) => Promise<string>;
25
25
  runSubagents: (args: string) => Promise<string>;
26
26
  runProject: (args: string) => Promise<string>;
27
+ runSkills: (args: string) => Promise<string>;
27
28
  /** Static bits the status renderer needs alongside the live run state. */
28
29
  statusInfo: {
29
30
  version: string;
@@ -6,8 +6,8 @@
6
6
  * Collaborators (runner, frontend, store) are injected so the machine can be
7
7
  * unit-tested with fakes and a fake clock. `app.ts` builds the real ones.
8
8
  */
9
- import { formatBusyCommandList, formatUnknownCommandMessage, isSessionCommandName, slashCommandName, } from "../agent/commands.js";
10
9
  import { renderStatus } from "../agent/status-render.js";
10
+ import { formatBusyCommandList, formatUnknownCommandMessage, isSessionCommandName, slashCommandName, } from "../commands/catalog.js";
11
11
  import * as log from "../log.js";
12
12
  import { formatLocalTime } from "../shared/local-time.js";
13
13
  import { errorMessage } from "../shared/text-utils.js";
@@ -37,6 +37,7 @@ export class TurnController {
37
37
  runTasks: deps.runTasks,
38
38
  runSubagents: deps.runSubagents,
39
39
  runProject: deps.runProject,
40
+ runSkills: deps.runSkills,
40
41
  renderContext: (args) => this.deps.runner.renderContextReport(args),
41
42
  renderStatus: () => renderStatus({
42
43
  runner: this.deps.runner,
@@ -1,7 +1,8 @@
1
+ import { clampInteger } from "../shared/numeric.js";
1
2
  export function resolveWebSearchRequest(config, query, count) {
2
3
  return {
3
4
  query: query.trim(),
4
- count: clamp(count, config.maxResults, 1, 10),
5
+ count: clampInteger(count, config.maxResults, 1, 10),
5
6
  timeoutMs: config.timeoutMs,
6
7
  };
7
8
  }
@@ -9,7 +10,7 @@ export function resolveWebFetchRequest(config, url, extractMode, maxChars) {
9
10
  return {
10
11
  url: url.trim(),
11
12
  extractMode: extractMode === "text" ? "text" : extractMode === "markdown" ? "markdown" : config.defaultExtractMode,
12
- maxChars: clamp(maxChars, config.maxChars, 100),
13
+ maxChars: clampInteger(maxChars, config.maxChars, 100),
13
14
  timeoutMs: config.timeoutMs,
14
15
  maxImageBytes: config.maxImageBytes,
15
16
  maxResponseBytes: config.maxResponseBytes,
@@ -17,16 +18,3 @@ export function resolveWebFetchRequest(config, url, extractMode, maxChars) {
17
18
  enableJinaFallback: config.enableJinaFallback,
18
19
  };
19
20
  }
20
- function clamp(value, fallback, minimum, maximum) {
21
- if (typeof value !== "number" || !Number.isFinite(value)) {
22
- return fallback;
23
- }
24
- const normalized = Math.floor(value);
25
- if (normalized < minimum) {
26
- return fallback;
27
- }
28
- if (maximum !== undefined && normalized > maximum) {
29
- return fallback;
30
- }
31
- return normalized;
32
- }
@@ -51,9 +51,9 @@ reviewer 发现的问题回流给产出角色;verifier 失败回流给 builder
51
51
  | `builder` | claude-code | `sonnet` | `write` | medium | 边界清晰、验收已定义的实现 + 单元测试 |
52
52
  | `builder-hard` | claude-code | `opus` | `write` | xhigh | builder 已失败、根因难定位或多契约耦合的实现 |
53
53
  | `reviewer` | codex-cli | `gpt-5.6-sol` | `read` | high | 与产出者分离的方案 / 代码 / 文档挑错,也可承担只读 `purpose=verify` |
54
- | `verifier` | codex-cli | `gpt-5.6-luna` | `write` | high | 实际运行系统、复现、冒烟、回归、取证 |
54
+ | `verifier` | codex-cli | `gpt-5.6-luna` | `write` | xhigh | 实际运行系统、复现、冒烟、回归、取证 |
55
55
  | `scout` | codex-cli | `gpt-5.6-luna` | `read` | medium | 大仓库里的单点事实查询 |
56
- | `worker` | codex-cli | `gpt-5.6-luna` | `write` | max | 闭环外的数据对比、指标计算、批量处理、专项报告 |
56
+ | `worker` | codex-cli | `gpt-5.6-sol` | `write` | medium | 闭环外的数据对比、指标计算、批量处理、专项报告 |
57
57
  | `documenter` | codex-cli | `gpt-5.6-luna` | `write` | high | 文档、变更记录和迁移说明;提交统一用 `git-committer` |
58
58
 
59
59
  `planner` 用 Claude 的 `--permission-mode plan`,`reviewer` / `scout` 用 Codex 的 `--sandbox read-only`;三者的 `mutates: read` 都有目标 CLI 的权限模式支撑,而不只是提示词声明。它们不占工作区写锁,但评审仍应针对稳定的 diff / commit,不要一边让 builder 改同一工作树、一边评审移动中的目标。