@abelxiaoxing/cadence 2.0.33 → 2.0.35

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.
@@ -4,6 +4,7 @@ import { createHash } from "node:crypto";
4
4
  import {
5
5
  closeSync,
6
6
  constants,
7
+ createReadStream,
7
8
  fstatSync,
8
9
  openSync,
9
10
  readFileSync,
@@ -26,8 +27,16 @@ import {
26
27
  } from "@earendil-works/pi-coding-agent";
27
28
  import { conversationResources } from "./conversation-resources.mjs";
28
29
  import { coordinatorTools } from "./coordinator-tools.mjs";
30
+ import {
31
+ decodeImageBase64,
32
+ IMAGE_LIMITS,
33
+ validateImageBytes,
34
+ } from "./image-content.mjs";
29
35
  import { researchClock, researchTools } from "./research-tools.mjs";
30
- import { WEBUI_SESSION_ENTRY } from "./session-entries.mjs";
36
+ import {
37
+ BROWSER_COMMAND_ENTRY,
38
+ WEBUI_SESSION_ENTRY,
39
+ } from "./session-entries.mjs";
31
40
  import { CaptureEmitter, SdkCapture } from "./worker-capture.mjs";
32
41
  import {
33
42
  closed,
@@ -268,6 +277,7 @@ try {
268
277
  : closed(envelope.conversation, [
269
278
  "session",
270
279
  "agentDir",
280
+ ...(Object.hasOwn(envelope.conversation, "images") ? ["images"] : []),
271
281
  ...(Object.hasOwn(envelope.conversation, "coordinator")
272
282
  ? ["coordinator"]
273
283
  : []),
@@ -561,6 +571,8 @@ try {
561
571
  if (session.agent.toolExecution !== "sequential")
562
572
  refuse("session", "capture-unsupported");
563
573
  session.agent.state.tools = ingress.wrap(session.agent.state.tools);
574
+ const initialLeaf = conversation ? manager.getLeafId() : null;
575
+ let recordedUser = null;
564
576
  unsubscribe = session.agent.subscribe(async (event) => {
565
577
  try {
566
578
  sdkEvents++;
@@ -578,6 +590,33 @@ try {
578
590
  }
579
591
  if (own(event, "type") === "message_end") {
580
592
  const message = own(event, "message");
593
+ if (
594
+ conversation &&
595
+ ["user", "assistant", "toolResult"].includes(own(message, "role"))
596
+ ) {
597
+ // Public core subscribers are awaited in registration order. The
598
+ // AgentSession's earlier subscriber has persisted this message.
599
+ // Each boundary names this worker's own prefix; a terminal append
600
+ // after it is never claimed by walking arbitrary descendants.
601
+ const entry = manager.getLeafEntry();
602
+ if (
603
+ entry?.type !== "message" ||
604
+ entry.message.role !== own(message, "role") ||
605
+ entry.id === initialLeaf
606
+ )
607
+ refuse("events", "event-projection-failed");
608
+ if (own(message, "role") === "user") {
609
+ if (recordedUser !== null)
610
+ refuse("events", "event-projection-failed");
611
+ recordedUser = entry.id;
612
+ }
613
+ if (recordedUser === null)
614
+ refuse("events", "event-projection-failed");
615
+ manager.appendCustomEntry(BROWSER_COMMAND_ENTRY, {
616
+ commandId: publicRequest.runId,
617
+ userId: recordedUser,
618
+ });
619
+ }
581
620
  if (own(message, "role") === "assistant") {
582
621
  const reason = own(message, "stopReason");
583
622
  terminalStopReason = [
@@ -620,6 +659,50 @@ try {
620
659
  });
621
660
  await capture.context(publicRequest, session.systemPrompt);
622
661
  stage = "prompt";
662
+ let images;
663
+ if (Boolean(publicRequest.imageCount) !== Boolean(conversation?.images))
664
+ throw new Error("Missing image channel");
665
+ if (conversation?.images !== undefined) {
666
+ const descriptor = closed(conversation.images, ["bytes", "sha256"]);
667
+ if (
668
+ !Number.isSafeInteger(descriptor.bytes) ||
669
+ descriptor.bytes < 1 ||
670
+ descriptor.bytes > IMAGE_LIMITS.wireBytes ||
671
+ !/^[a-f0-9]{64}$/.test(descriptor.sha256) ||
672
+ !model.input?.includes("image")
673
+ )
674
+ throw new Error("Invalid image context");
675
+ const chunks = [];
676
+ let size = 0;
677
+ for await (const chunk of createReadStream(null, { fd: 3 })) {
678
+ size += chunk.length;
679
+ if (size > descriptor.bytes)
680
+ throw new Error("Image payload exceeds bound");
681
+ chunks.push(chunk);
682
+ }
683
+ const bytes = Buffer.concat(chunks);
684
+ if (
685
+ size !== descriptor.bytes ||
686
+ createHash("sha256").update(bytes).digest("hex") !== descriptor.sha256
687
+ )
688
+ throw new Error("Incomplete image payload");
689
+ images = JSON.parse(bytes.toString("utf8"));
690
+ if (
691
+ !Array.isArray(images) ||
692
+ !images.length ||
693
+ images.length !== publicRequest.imageCount
694
+ )
695
+ throw new Error("Invalid images");
696
+ let total = 0;
697
+ for (const image of images) {
698
+ closed(image, ["type", "data", "mimeType"]);
699
+ if (image.type !== "image") throw new Error("Invalid image");
700
+ const decoded = decodeImageBase64(image.data);
701
+ validateImageBytes(decoded, image.mimeType);
702
+ total += decoded.length;
703
+ }
704
+ if (total > IMAGE_LIMITS.totalBytes) throw new Error("Images exceed bound");
705
+ }
623
706
  const suppliedPrompt = [
624
707
  publicRequest.context,
625
708
  ...(!conversation && kind !== "code"
@@ -636,6 +719,7 @@ try {
636
719
  .filter(Boolean)
637
720
  .join("\n\n");
638
721
  await session.prompt(suppliedPrompt, {
722
+ ...(images ? { images } : {}),
639
723
  expandPromptTemplates: false,
640
724
  preflightResult: (accepted) => {
641
725
  preflight = accepted ? "accepted" : "rejected";
@@ -16,6 +16,7 @@ export {
16
16
  errorStatus,
17
17
  GRAPH_SCHEMA,
18
18
  HISTORY_SCHEMA,
19
+ IMAGE_COUNT,
19
20
  integer,
20
21
  invalid,
21
22
  LIMITS,
@@ -20,7 +20,53 @@ import {
20
20
  thinkingLevels,
21
21
  } from "./domain.ts";
22
22
 
23
+ /** A conversation's identity: the Pi session id shared with the terminal. */
24
+ export function decodeSessionId(v: unknown): string {
25
+ const s = text(v, 128, true);
26
+ if (!/^[A-Za-z0-9](?:[A-Za-z0-9._-]*[A-Za-z0-9])?$/.test(s)) invalid();
27
+ return s;
28
+ }
29
+
30
+ /** A conversation location is not an execution grant or a filesystem sandbox. */
31
+ export interface ConversationLocation {
32
+ id: string;
33
+ cwd: string;
34
+ }
35
+ export interface ConversationContext extends ConversationLocation {
36
+ revision: number;
37
+ model: ModelSelector | null;
38
+ }
39
+ export interface ExecutionContext {
40
+ cwd: string;
41
+ checkoutRoot: string;
42
+ version: ChoiceVersion;
43
+ model: ModelSelection | null;
44
+ }
45
+ export function decodeConversationLocation(v: unknown): ConversationLocation {
46
+ const o = closed(v, ["id", "cwd"]);
47
+ return { id: decodeSessionId(o.id), cwd: text(o.cwd, 4096, true) };
48
+ }
49
+ export function decodeConversationContext(v: unknown): ConversationContext {
50
+ const o = closed(v, ["id", "cwd", "revision", "model"]);
51
+ return {
52
+ id: decodeSessionId(o.id),
53
+ cwd: text(o.cwd, 4096, true),
54
+ revision: integer(o.revision, 0, Number.MAX_SAFE_INTEGER - 1),
55
+ model: nullable(o.model, decodeModelSelector),
56
+ };
57
+ }
58
+ export function decodeExecutionContext(v: unknown): ExecutionContext {
59
+ const o = closed(v, ["cwd", "checkoutRoot", "version", "model"]);
60
+ return {
61
+ cwd: text(o.cwd, 4096, true),
62
+ checkoutRoot: text(o.checkoutRoot, 4096, true),
63
+ version: decodeChoiceVersion(o.version),
64
+ model: nullable(o.model, decodeModelSelection),
65
+ };
66
+ }
23
67
  export interface ChoiceVersion {
68
+ /** Omitted only by explicit low-level native default-slot requests and retained records. */
69
+ conversation?: ConversationLocation;
24
70
  epoch: string;
25
71
  accessGeneration: number;
26
72
  configRev: number;
@@ -31,6 +77,7 @@ export interface ModelChoiceState {
31
77
  selected: ModelSelection | null;
32
78
  }
33
79
  export interface ModelCandidate {
80
+ images?: boolean;
34
81
  provider: string;
35
82
  model: string;
36
83
  api: ModelSelection["api"] | null;
@@ -60,8 +107,12 @@ export function decodeChoiceVersion(value: unknown): ChoiceVersion {
60
107
  "accessGeneration",
61
108
  "configRev",
62
109
  "catalogId",
110
+ ...(Object.hasOwn(value ?? {}, "conversation") ? ["conversation"] : []),
63
111
  ]);
64
112
  return {
113
+ ...(o.conversation === undefined
114
+ ? {}
115
+ : { conversation: decodeConversationLocation(o.conversation) }),
65
116
  epoch: decodeId(o.epoch),
66
117
  accessGeneration: integer(o.accessGeneration, 1),
67
118
  configRev: integer(o.configRev, 1),
@@ -91,8 +142,10 @@ export function decodeModelCandidate(value: unknown): ModelCandidate {
91
142
  "api",
92
143
  "thinking",
93
144
  "eligibility",
145
+ ...(Object.hasOwn(value ?? {}, "images") ? ["images"] : []),
94
146
  ]);
95
147
  const candidate: ModelCandidate = {
148
+ ...(o.images === undefined ? {} : { images: bool(o.images) }),
96
149
  provider: text(o.provider, 128, true),
97
150
  model: text(o.model, 256, true),
98
151
  api: nullable(o.api, (v) => oneOf(v, modelApis)),