@abelxiaoxing/cadence 2.0.36 → 2.0.38

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 (55) hide show
  1. package/README.de.md +4 -4
  2. package/README.es.md +4 -4
  3. package/README.fr.md +4 -4
  4. package/README.ja.md +4 -4
  5. package/README.ko.md +4 -4
  6. package/README.md +11 -9
  7. package/README.pt-BR.md +4 -4
  8. package/README.ru.md +4 -4
  9. package/README.zh-CN.md +12 -10
  10. package/THIRD_PARTY_NOTICES.md +9 -1
  11. package/agents/design-explorer.md +4 -2
  12. package/agents/diagnosis-worker.md +5 -2
  13. package/agents/implementation-worker.md +19 -12
  14. package/docs/conversation-mode.md +46 -18
  15. package/docs/reuse-and-distribution.md +1 -1
  16. package/docs/service-management.md +35 -9
  17. package/package.json +16 -8
  18. package/src/agent-browser/labeled-rule.ts +74 -0
  19. package/src/agent-browser/session-navigator.ts +214 -0
  20. package/src/agent-browser/source.ts +174 -0
  21. package/src/agent-browser/transcript-content.ts +442 -0
  22. package/src/agent-browser/transcript-pane.ts +324 -0
  23. package/src/agent-panel-cadence.ts +147 -628
  24. package/src/agent-panel-model.ts +34 -267
  25. package/src/agent-panel.ts +139 -437
  26. package/src/cadence-instructions.ts +8 -7
  27. package/src/cadence-mode.ts +30 -9
  28. package/src/change-tools.mjs +268 -0
  29. package/src/coordinator-tools.mjs +44 -16
  30. package/src/git-environment.d.mts +2 -0
  31. package/src/git-environment.mjs +24 -0
  32. package/src/image-content.mjs +7 -28
  33. package/src/index.ts +1 -1
  34. package/src/native-build.ts +1 -1
  35. package/src/native-workflow-history.ts +20 -3
  36. package/src/operator-cli.mjs +18 -11
  37. package/src/research-scan.mjs +393 -0
  38. package/src/research-tools.mjs +406 -342
  39. package/src/sdk-worker.mjs +42 -55
  40. package/src/service/contracts/core.ts +0 -1
  41. package/src/service/contracts/workbench.ts +21 -19
  42. package/src/service/contracts/workflow.ts +283 -16
  43. package/src/service/coordination.ts +7 -0
  44. package/src/service-cli.mjs +652 -149
  45. package/src/service-host.mjs +2745 -1137
  46. package/src/worker-capture.mjs +24 -1
  47. package/src/worker-public.mjs +19 -2
  48. package/src/worker-redaction.mjs +11 -0
  49. package/src/worker-toolkit.mjs +157 -0
  50. package/src/worker-workspace.d.mts +13 -0
  51. package/src/worker-workspace.mjs +48 -0
  52. package/src/workspace.ts +4 -24
  53. package/web/dist/assets/cadence.css +1 -1
  54. package/web/dist/assets/cadence.js +18 -17
  55. package/web/dist/manifest.json +7 -7
@@ -947,7 +947,9 @@ export class SdkCapture {
947
947
  const message = own(event, "message");
948
948
  const rawRole = own(message, "role");
949
949
  const role = rawRole === "toolResult" ? "tool-result" : rawRole;
950
- requireFact(["user", "assistant", "tool-result"].includes(role));
950
+ requireFact(
951
+ ["system", "user", "assistant", "tool-result"].includes(role),
952
+ );
951
953
  const matches =
952
954
  role === "tool-result"
953
955
  ? this.matches(
@@ -964,6 +966,23 @@ export class SdkCapture {
964
966
  streams: new Map(),
965
967
  declarations: new Map(),
966
968
  };
969
+ if (role === "system") {
970
+ // Pi emits prompt/section/tool-loadout changes as paired system
971
+ // messages. The initial effective prompt is already captured as
972
+ // context; these additional SDK control bodies are not chat output.
973
+ // Keep their lifecycle strict and their omitted source explicit,
974
+ // without copying tool definitions or claiming complete capture.
975
+ await this.emit({
976
+ kind: "omitted-block",
977
+ block: {
978
+ owner: { kind: "context", component: "effective-system" },
979
+ sourceType: "unsupported",
980
+ mimeType: null,
981
+ reason: "unsupported",
982
+ },
983
+ });
984
+ break;
985
+ }
967
986
  await this.emit({
968
987
  kind: "message-start",
969
988
  messageId: this.current.id,
@@ -1054,6 +1073,10 @@ export class SdkCapture {
1054
1073
  ? "tool-result"
1055
1074
  : own(message, "role")) === m.role,
1056
1075
  );
1076
+ if (m.role === "system") {
1077
+ this.current = null;
1078
+ break;
1079
+ }
1057
1080
  for (const stream of m.streams.values())
1058
1081
  await this.streamWrite(stream, "", true);
1059
1082
  const { texts, count } = await this.blocks(
@@ -2,7 +2,6 @@
2
2
  * Public types live solely in worker-public.d.mts; the TS contract paths are re-export shims.
3
3
  * Initially relocated mechanically from W1 core/domain/capture; not a generated build output. */
4
4
  /** Portable service boundary. No SDK objects, credentials, filesystem paths as IDs, or execution owner. */
5
- export const IMAGE_COUNT = 4;
6
5
  export const SERVICE_PROTOCOL = 1;
7
6
  export const WORKER_PROTOCOL = 2;
8
7
  export const GRAPH_SCHEMA = "cadence-graph/2";
@@ -939,6 +938,7 @@ export function decodeWorkerPublicRequest(v) {
939
938
  "instructions",
940
939
  "prompt",
941
940
  ...(Object.hasOwn(v ?? {}, "imageCount") ? ["imageCount"] : []),
941
+ ...(Object.hasOwn(v ?? {}, "changes") ? ["changes"] : []),
942
942
  "handoff",
943
943
  ]);
944
944
  const result = {
@@ -956,11 +956,28 @@ export function decodeWorkerPublicRequest(v) {
956
956
  prompt: text(o.prompt, 32768, o.imageCount === undefined),
957
957
  ...(o.imageCount === undefined
958
958
  ? {}
959
- : { imageCount: integer(o.imageCount, 1, IMAGE_COUNT) }),
959
+ : { imageCount: integer(o.imageCount, 1) }),
960
960
  handoff: decodeHandoff(o.handoff),
961
961
  };
962
962
  if (result.handoff.inputs.some((i) => i.assignmentId !== result.assignmentId))
963
963
  invalid();
964
+ if (o.changes !== undefined) {
965
+ const c = closed(o.changes, ["root", "base", "candidate"]);
966
+ const root = text(c.root, 4096, true);
967
+ if (
968
+ result.purpose !== "review" ||
969
+ !/^(?:\/|[A-Za-z]:[\\/]|\\\\)/u.test(root) ||
970
+ root.includes("\0")
971
+ )
972
+ throw new Error("Invalid review binding");
973
+ const oid = (value) => {
974
+ const s = text(value, 64, true);
975
+ if (!/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/u.test(s))
976
+ throw new Error("Invalid review object");
977
+ return s;
978
+ };
979
+ result.changes = { root, base: oid(c.base), candidate: oid(c.candidate) };
980
+ }
964
981
  if (
965
982
  (result.taskKind !== "code" && result.purpose === "edit") ||
966
983
  result.role.role !== roleForPurpose(result.purpose)
@@ -219,6 +219,17 @@ export class TextSanitizer {
219
219
  this.redacted ||= pos >= 0;
220
220
  this.heuristic = this.heuristic.slice(size);
221
221
  } else if (match) {
222
+ // A key/delimiter can arrive before its whitespace and value. Starting
223
+ // the skip state now would let that whitespace end it before any value
224
+ // was consumed, leaking a split value or duplicating an old marker.
225
+ // Keep only the bounded prefix until the first value character arrives.
226
+ if (!final && match.index + match[0].length === this.heuristic.length) {
227
+ output += this.heuristic.slice(0, match.index);
228
+ this.heuristic = this.heuristic.slice(match.index);
229
+ if (utf8Bytes(this.heuristic) > 8192)
230
+ throw new ContractError("oversize");
231
+ break;
232
+ }
222
233
  output += this.heuristic.slice(0, match.index) + match[0] + marker;
223
234
  this.heuristic = this.heuristic.slice(match.index + match[0].length);
224
235
  this.skipping = true;
@@ -0,0 +1,157 @@
1
+ /** Trusted capability composition. No discovery, plugin claims or model-selected
2
+ * permissions. Role prompts do not grant tools; the validated owner request does. */
3
+ import { Type } from "typebox";
4
+ import { createChangeTools } from "./change-tools.mjs";
5
+ import { createCoordinatorTools } from "./coordinator-tools.mjs";
6
+ import { createResearchTools } from "./research-tools.mjs";
7
+ import { sanitizeText } from "./worker-redaction.mjs";
8
+ import { captureBash } from "./worker-tools.mjs";
9
+
10
+ const policies = Object.freeze({
11
+ edit: Object.freeze(["files", "shell"]),
12
+ research: Object.freeze(["observation"]),
13
+ diagnosis: Object.freeze(["observation"]),
14
+ review: Object.freeze(["observation"]),
15
+ coordination: Object.freeze(["coordination"]),
16
+ });
17
+ // One reviewed registry, not a public runtime plugin interface. An observation
18
+ // bundle may add tools without teaching the SDK bootstrap another list of names.
19
+ const bundles = {
20
+ files: () => ({
21
+ names: ["read", "grep", "find", "ls", "write", "edit"],
22
+ tools: [],
23
+ }),
24
+ shell: ({ workspace, secrets, fail, createLocalBashOperations, queue }) => ({
25
+ tools: [
26
+ captureBash(
27
+ workspace.cwd,
28
+ secrets,
29
+ fail,
30
+ createLocalBashOperations,
31
+ queue,
32
+ ),
33
+ ],
34
+ }),
35
+ observation: ({ workspace }) => createResearchTools(workspace),
36
+ changes: ({ changes }) => createChangeTools(changes),
37
+ coordination: () => createCoordinatorTools(),
38
+ };
39
+
40
+ export function createWorkerToolkit(options) {
41
+ const { purpose, coordinator = false } = options;
42
+ if (
43
+ !Object.hasOwn(policies, purpose) ||
44
+ purpose === "coordination" ||
45
+ (coordinator && purpose !== "research")
46
+ )
47
+ throw new Error("Invalid worker capability selection");
48
+ if (
49
+ options.changes &&
50
+ (purpose !== "review" ||
51
+ coordinator ||
52
+ options.changes.root !== options.workspace.roots[0])
53
+ )
54
+ throw new Error("Invalid review capability binding");
55
+ const capabilities = options.changes
56
+ ? Object.freeze([...policies[purpose], "changes"])
57
+ : policies[coordinator ? "coordination" : purpose];
58
+ const owned = capabilities.map((capability) => bundles[capability](options));
59
+ const customTools = owned.flatMap((bundle) => bundle.tools);
60
+ if (options.reporting && !coordinator && purpose === "edit")
61
+ customTools.push({
62
+ name: "cadence_report",
63
+ label: "Report assignment outcome",
64
+ description:
65
+ "Submit this assignment's structured result after all work. Completed means assigned work is done, not that owner checks or review passed. Use blocked for remaining work. Then give a brief final answer; no JSON formatting is required in that answer. Any later tool call requires a new report.",
66
+ parameters: Type.Object({
67
+ status: Type.Union([
68
+ Type.Literal("completed"),
69
+ Type.Literal("blocked"),
70
+ ]),
71
+ summary: Type.String({ minLength: 1, maxLength: 8192 }),
72
+ }),
73
+ async execute(_id, input) {
74
+ if (
75
+ !input ||
76
+ !["completed", "blocked"].includes(input.status) ||
77
+ typeof input.summary !== "string" ||
78
+ !input.summary.trim() ||
79
+ Object.keys(input).some((key) => !["status", "summary"].includes(key))
80
+ )
81
+ throw new Error("Invalid assignment report");
82
+ const report = {
83
+ status: input.status,
84
+ summary: sanitizeText(input.summary, options.secrets ?? []),
85
+ };
86
+ const text = JSON.stringify(report);
87
+ if (!report.summary.trim() || Buffer.byteLength(text) > 16384)
88
+ throw new Error("Assignment report exceeds bound");
89
+ return { content: [{ type: "text", text }], details: undefined };
90
+ },
91
+ });
92
+ const names = owned.flatMap(
93
+ (bundle) => bundle.names ?? bundle.tools.map((tool) => tool.name),
94
+ );
95
+ if (options.reporting && !coordinator && purpose === "edit")
96
+ names.push("cadence_report");
97
+ if (new Set(names).size !== names.length)
98
+ throw new Error("Duplicate worker tool");
99
+ const originals = new Set();
100
+ let closed = false,
101
+ closing;
102
+ return {
103
+ capabilities,
104
+ // Explicit allowlists are required by the installed public Pi SDK. Omitting
105
+ // one would enable its defaults, not mean "only our custom capabilities".
106
+ sessionOptions: {
107
+ cwd: options.workspace.cwd,
108
+ tools: [...names],
109
+ customTools,
110
+ },
111
+ wrap(tools) {
112
+ if (closed) throw new Error("Worker tools closed");
113
+ return tools.map((tool) => {
114
+ if (!names.includes(tool.name))
115
+ throw new Error("Unexpected worker tool");
116
+ return {
117
+ ...tool,
118
+ execute: (...args) => {
119
+ if (closed) return Promise.reject(new Error("Worker tools closed"));
120
+ const original = Promise.resolve().then(() => {
121
+ if (closed) throw new Error("Worker tools closed");
122
+ if (args[2]?.aborted) throw new Error("Worker tool canceled");
123
+ return tool.execute(...args);
124
+ });
125
+ const tracked = original.finally(() => originals.delete(tracked));
126
+ originals.add(tracked);
127
+ return tracked;
128
+ },
129
+ };
130
+ });
131
+ },
132
+ close() {
133
+ if (closing) return closing;
134
+ closed = true;
135
+ // Start all owned closes, and join every original, including stock SDK
136
+ // tools. Session abort is requested separately by the runtime; a timeout
137
+ // or an observer's rejection never substitutes for actual tool settlement.
138
+ closing = (async () => {
139
+ const outcomes = await Promise.allSettled([
140
+ ...originals,
141
+ ...owned.map((bundle) =>
142
+ Promise.resolve().then(() => bundle.close?.()),
143
+ ),
144
+ ]);
145
+ // Tool execution errors belong to their original caller; only resource
146
+ // disposal errors make the toolkit's cleanup itself fail.
147
+ if (
148
+ outcomes
149
+ .slice(outcomes.length - owned.length)
150
+ .some((outcome) => outcome.status === "rejected")
151
+ )
152
+ throw new Error("Worker tool cleanup failed");
153
+ })();
154
+ return closing;
155
+ },
156
+ };
157
+ }
@@ -0,0 +1,13 @@
1
+ export interface WorkerWorkspace {
2
+ readonly cwd: string;
3
+ readonly roots: readonly string[];
4
+ }
5
+ export function withinRoot(root: string, path: string): boolean;
6
+ export function bindWorkerWorkspace(
7
+ cwd: string,
8
+ roots?: readonly string[],
9
+ ): WorkerWorkspace;
10
+ export function executionDirectory(
11
+ execution: { cwd: string; checkoutRoot: string },
12
+ tree: string,
13
+ ): string;
@@ -0,0 +1,48 @@
1
+ /** Immutable placement, not a sandbox or permission to create a workspace.
2
+ * The owner supplies paths; tools never discover a different cwd or create Git trees. */
3
+ import { isAbsolute, relative, resolve, sep } from "node:path";
4
+
5
+ export function withinRoot(root, path) {
6
+ const part = relative(root, path);
7
+ return (
8
+ part === "" ||
9
+ (!isAbsolute(part) && part !== ".." && !part.startsWith(`..${sep}`))
10
+ );
11
+ }
12
+ const absolute = (value) => {
13
+ if (typeof value !== "string" || !isAbsolute(value) || value.includes("\0"))
14
+ throw new Error("Invalid execution directory");
15
+ return resolve(value);
16
+ };
17
+
18
+ export function bindWorkerWorkspace(cwd, roots = [cwd]) {
19
+ cwd = absolute(cwd);
20
+ if (!Array.isArray(roots) || !roots.length || roots.length > 8)
21
+ throw new Error("Invalid investigation roots");
22
+ return Object.freeze({
23
+ cwd,
24
+ roots: Object.freeze(
25
+ roots.map((root) => {
26
+ if (
27
+ typeof root !== "string" ||
28
+ !root ||
29
+ root.length > 4096 ||
30
+ root.includes("\0")
31
+ )
32
+ throw new Error("Invalid investigation root");
33
+ return resolve(cwd, root);
34
+ }),
35
+ ),
36
+ });
37
+ }
38
+
39
+ /** Preserve a pinned conversation's relative cwd in an owner-selected tree.
40
+ * Filesystem validation/empty-directory preparation remain with the owner. */
41
+ export function executionDirectory(execution, tree) {
42
+ const origin = absolute(execution.checkoutRoot);
43
+ const cwd = absolute(execution.cwd);
44
+ tree = absolute(tree);
45
+ if (!withinRoot(origin, cwd))
46
+ throw new Error("Execution cwd escaped its checkout");
47
+ return resolve(tree, relative(origin, cwd));
48
+ }
package/src/workspace.ts CHANGED
@@ -1,3 +1,7 @@
1
+ import { gitArguments, gitEnvironment } from "./git-environment.mjs";
2
+
3
+ export { gitArguments, gitEnvironment } from "./git-environment.mjs";
4
+
1
5
  /** Workspace identity and bounded filesystem operations, independent of task records. */
2
6
  import { spawnSync } from "node:child_process";
3
7
  import { createHash } from "node:crypto";
@@ -158,30 +162,6 @@ export function readBounded(
158
162
  }
159
163
  }
160
164
 
161
- /** Git observations describe the physical cwd, not inherited alternate
162
- * index/worktree overrides. Root never borrows sudo's original user's trust. */
163
- export function gitEnvironment(): NodeJS.ProcessEnv {
164
- const root = process.getuid?.() === 0;
165
- return {
166
- ...Object.fromEntries(
167
- Object.entries(process.env).filter(
168
- ([name]) => !name.startsWith("GIT_") && !(root && name === "SUDO_UID"),
169
- ),
170
- ),
171
- GIT_OPTIONAL_LOCKS: "0",
172
- LC_ALL: "C",
173
- };
174
- }
175
- /** Observation is not permission to trust another account's repository.
176
- * Even with fsmonitor/textconv/ext-diff disabled, status/diff can invoke clean
177
- * or process filters. Root therefore requires Git's own ownership check, with
178
- * no safe.directory exceptions (including inherited wildcards). No config is
179
- * written and ordinary-user trust behavior stays unchanged. */
180
- export function gitArguments(args: string[]): string[] {
181
- return process.platform !== "win32" && process.getuid?.() === 0
182
- ? ["-c", "safe.directory=", "-c", "core.fsmonitor=false", ...args]
183
- : args;
184
- }
185
165
  export function resolveWorkspace(cwd: string): { root: string; cwd: string } {
186
166
  const actual = realpathSync(cwd);
187
167
  const result = spawnSync(