@abelxiaoxing/cadence 2.0.35 → 2.0.37

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 (40) 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 +3 -4
  5. package/README.ko.md +4 -4
  6. package/README.md +4 -4
  7. package/README.pt-BR.md +4 -4
  8. package/README.ru.md +5 -4
  9. package/README.zh-CN.md +4 -4
  10. package/THIRD_PARTY_NOTICES.md +9 -1
  11. package/docs/conversation-mode.md +21 -2
  12. package/docs/reuse-and-distribution.md +1 -1
  13. package/docs/service-management.md +35 -9
  14. package/package.json +18 -18
  15. package/src/abort-scope.ts +47 -0
  16. package/src/agent-browser/labeled-rule.ts +74 -0
  17. package/src/agent-browser/session-navigator.ts +187 -0
  18. package/src/agent-browser/source.ts +170 -0
  19. package/src/agent-browser/transcript-content.ts +442 -0
  20. package/src/agent-browser/transcript-pane.ts +324 -0
  21. package/src/agent-panel-model.ts +4 -248
  22. package/src/agent-panel.ts +138 -432
  23. package/src/coordinator-tools.mjs +42 -14
  24. package/src/image-content.mjs +7 -28
  25. package/src/native-build.ts +1 -1
  26. package/src/research-scan.mjs +393 -0
  27. package/src/research-tools.mjs +406 -342
  28. package/src/sdk-worker.mjs +40 -55
  29. package/src/service/contracts/core.ts +0 -1
  30. package/src/service/contracts/workbench.ts +10 -16
  31. package/src/service-cli.mjs +328 -106
  32. package/src/service-host.mjs +545 -404
  33. package/src/service-http-client.ts +55 -50
  34. package/src/worker-public.mjs +1 -2
  35. package/src/worker-toolkit.mjs +110 -0
  36. package/src/worker-workspace.d.mts +13 -0
  37. package/src/worker-workspace.mjs +48 -0
  38. package/web/dist/assets/cadence.css +1 -1
  39. package/web/dist/assets/cadence.js +17 -17
  40. package/web/dist/manifest.json +7 -7
@@ -1,3 +1,4 @@
1
+ import { abortScope } from "./abort-scope.ts";
1
2
  import type {
2
3
  WorkbenchCommand,
3
4
  WorkbenchRead,
@@ -129,60 +130,64 @@ export class HttpServiceTransport implements ServiceTransport {
129
130
  write = wire.method === "POST";
130
131
  // No automatic session/preflight refresh, changed command ID, mutation retry,
131
132
  // credential query or redirect follow after an uncertain HTTP outcome.
132
- const response = await this.fetcher(
133
- `${this.origin}${this.options.project ? `/projects/${this.options.project}` : ""}${wire.path}`,
134
- {
135
- method: wire.method,
136
- headers: this.headers(write),
137
- credentials: "same-origin",
138
- redirect: "error",
139
- signal:
140
- this.options.requestTimeoutMs === undefined
141
- ? signal
142
- : AbortSignal.any([
143
- ...(signal ? [signal] : []),
144
- AbortSignal.timeout(this.options.requestTimeoutMs),
145
- ]),
146
- ...(write ? { body: wire.body } : {}),
147
- },
148
- );
149
- // Keep a known allocation even if its original response body is lost or
150
- // malformed. Without a validated CSRF challenge detach may remain blocked;
151
- // never silently forget that slot and acquire 16 replacement sessions.
152
- let sessionAttachment: string | undefined;
133
+ const scope =
134
+ this.options.requestTimeoutMs === undefined
135
+ ? undefined
136
+ : abortScope([signal], this.options.requestTimeoutMs);
137
+ const requestSignal = scope?.signal ?? signal;
153
138
  try {
154
- if (operation === "session" && response.ok) {
155
- sessionAttachment = decodeId(
156
- response.headers.get("x-cadence-attachment"),
157
- );
158
- this.attachment = sessionAttachment;
139
+ if (requestSignal?.aborted) throw requestSignal.reason;
140
+ const response = await this.fetcher(
141
+ `${this.origin}${this.options.project ? `/projects/${this.options.project}` : ""}${wire.path}`,
142
+ {
143
+ method: wire.method,
144
+ headers: this.headers(write),
145
+ credentials: "same-origin",
146
+ redirect: "error",
147
+ signal: requestSignal,
148
+ ...(write ? { body: wire.body } : {}),
149
+ },
150
+ );
151
+ // Keep a known allocation even if its original response body is lost or
152
+ // malformed. Without a validated CSRF challenge detach may remain blocked;
153
+ // never silently forget that slot and acquire 16 replacement sessions.
154
+ let sessionAttachment: string | undefined;
155
+ try {
156
+ if (operation === "session" && response.ok) {
157
+ sessionAttachment = decodeId(
158
+ response.headers.get("x-cadence-attachment"),
159
+ );
160
+ this.attachment = sessionAttachment;
161
+ }
162
+ } catch (error) {
163
+ await response.body?.cancel().catch(() => {});
164
+ throw error;
159
165
  }
160
- } catch (error) {
161
- await response.body?.cancel().catch(() => {});
162
- throw error;
163
- }
164
- const source = await boundedText(response, httpOutputLimit(operation)),
165
- parsed = parseWireJson(source);
166
- // Graph's category is known only after parsing. Count ORIGINAL wire bytes,
167
- // not a canonical re-encoding which discards padding or alternate escapes.
168
- if (utf8Bytes(source) > httpOutputLimit(operation, parsed))
169
- throw new ContractError("oversize");
170
- const result = decodeHttpOutput(operation, parsed);
171
- if (operation === "session") {
172
- const reply = decodeReply(result, decodeSessionBootstrap);
173
- if (reply.kind === "ok") {
174
- if (
175
- (reply.value.authority === "local") !==
176
- !!this.options.localCapability
177
- )
178
- throw new ContractError("forbidden");
179
- this.attachment =
180
- sessionAttachment ??
181
- decodeId(response.headers.get("x-cadence-attachment"));
182
- this.csrf = reply.value.csrf;
166
+ const source = await boundedText(response, httpOutputLimit(operation)),
167
+ parsed = parseWireJson(source);
168
+ // Graph's category is known only after parsing. Count ORIGINAL wire bytes,
169
+ // not a canonical re-encoding which discards padding or alternate escapes.
170
+ if (utf8Bytes(source) > httpOutputLimit(operation, parsed))
171
+ throw new ContractError("oversize");
172
+ const result = decodeHttpOutput(operation, parsed);
173
+ if (operation === "session") {
174
+ const reply = decodeReply(result, decodeSessionBootstrap);
175
+ if (reply.kind === "ok") {
176
+ if (
177
+ (reply.value.authority === "local") !==
178
+ !!this.options.localCapability
179
+ )
180
+ throw new ContractError("forbidden");
181
+ this.attachment =
182
+ sessionAttachment ??
183
+ decodeId(response.headers.get("x-cadence-attachment"));
184
+ this.csrf = reply.value.csrf;
185
+ }
183
186
  }
187
+ return result;
188
+ } finally {
189
+ scope?.dispose();
184
190
  }
185
- return result;
186
191
  }
187
192
  session(signal?: AbortSignal) {
188
193
  return this.request("session", null, signal);
@@ -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";
@@ -956,7 +955,7 @@ export function decodeWorkerPublicRequest(v) {
956
955
  prompt: text(o.prompt, 32768, o.imageCount === undefined),
957
956
  ...(o.imageCount === undefined
958
957
  ? {}
959
- : { imageCount: integer(o.imageCount, 1, IMAGE_COUNT) }),
958
+ : { imageCount: integer(o.imageCount, 1) }),
960
959
  handoff: decodeHandoff(o.handoff),
961
960
  };
962
961
  if (result.handoff.inputs.some((i) => i.assignmentId !== result.assignmentId))
@@ -0,0 +1,110 @@
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 { createCoordinatorTools } from "./coordinator-tools.mjs";
4
+ import { createResearchTools } from "./research-tools.mjs";
5
+ import { captureBash } from "./worker-tools.mjs";
6
+
7
+ const policies = Object.freeze({
8
+ edit: Object.freeze(["files", "shell"]),
9
+ research: Object.freeze(["observation"]),
10
+ diagnosis: Object.freeze(["observation"]),
11
+ review: Object.freeze(["observation"]),
12
+ coordination: Object.freeze(["coordination"]),
13
+ });
14
+ // One reviewed registry, not a public runtime plugin interface. An observation
15
+ // bundle may add tools without teaching the SDK bootstrap another list of names.
16
+ const bundles = {
17
+ files: () => ({
18
+ names: ["read", "grep", "find", "ls", "write", "edit"],
19
+ tools: [],
20
+ }),
21
+ shell: ({ workspace, secrets, fail, createLocalBashOperations, queue }) => ({
22
+ tools: [
23
+ captureBash(
24
+ workspace.cwd,
25
+ secrets,
26
+ fail,
27
+ createLocalBashOperations,
28
+ queue,
29
+ ),
30
+ ],
31
+ }),
32
+ observation: ({ workspace }) => createResearchTools(workspace),
33
+ coordination: () => createCoordinatorTools(),
34
+ };
35
+
36
+ export function createWorkerToolkit(options) {
37
+ const { purpose, coordinator = false } = options;
38
+ if (
39
+ !Object.hasOwn(policies, purpose) ||
40
+ purpose === "coordination" ||
41
+ (coordinator && purpose !== "research")
42
+ )
43
+ throw new Error("Invalid worker capability selection");
44
+ const capabilities = policies[coordinator ? "coordination" : purpose];
45
+ const owned = capabilities.map((capability) => bundles[capability](options));
46
+ const customTools = owned.flatMap((bundle) => bundle.tools);
47
+ const names = owned.flatMap(
48
+ (bundle) => bundle.names ?? bundle.tools.map((tool) => tool.name),
49
+ );
50
+ if (new Set(names).size !== names.length)
51
+ throw new Error("Duplicate worker tool");
52
+ const originals = new Set();
53
+ let closed = false,
54
+ closing;
55
+ return {
56
+ capabilities,
57
+ // Explicit allowlists are required by the installed public Pi SDK. Omitting
58
+ // one would enable its defaults, not mean "only our custom capabilities".
59
+ sessionOptions: {
60
+ cwd: options.workspace.cwd,
61
+ tools: [...names],
62
+ customTools,
63
+ },
64
+ wrap(tools) {
65
+ if (closed) throw new Error("Worker tools closed");
66
+ return tools.map((tool) => {
67
+ if (!names.includes(tool.name))
68
+ throw new Error("Unexpected worker tool");
69
+ return {
70
+ ...tool,
71
+ execute: (...args) => {
72
+ if (closed) return Promise.reject(new Error("Worker tools closed"));
73
+ const original = Promise.resolve().then(() => {
74
+ if (closed) throw new Error("Worker tools closed");
75
+ if (args[2]?.aborted) throw new Error("Worker tool canceled");
76
+ return tool.execute(...args);
77
+ });
78
+ const tracked = original.finally(() => originals.delete(tracked));
79
+ originals.add(tracked);
80
+ return tracked;
81
+ },
82
+ };
83
+ });
84
+ },
85
+ close() {
86
+ if (closing) return closing;
87
+ closed = true;
88
+ // Start all owned closes, and join every original, including stock SDK
89
+ // tools. Session abort is requested separately by the runtime; a timeout
90
+ // or an observer's rejection never substitutes for actual tool settlement.
91
+ closing = (async () => {
92
+ const outcomes = await Promise.allSettled([
93
+ ...originals,
94
+ ...owned.map((bundle) =>
95
+ Promise.resolve().then(() => bundle.close?.()),
96
+ ),
97
+ ]);
98
+ // Tool execution errors belong to their original caller; only resource
99
+ // disposal errors make the toolkit's cleanup itself fail.
100
+ if (
101
+ outcomes
102
+ .slice(outcomes.length - owned.length)
103
+ .some((outcome) => outcome.status === "rejected")
104
+ )
105
+ throw new Error("Worker tool cleanup failed");
106
+ })();
107
+ return closing;
108
+ },
109
+ };
110
+ }
@@ -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
+ }