peachsim 0.1.2406 → 0.1.2409

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 (107) hide show
  1. package/cli/agent-note.ts +231 -0
  2. package/cli/cloud-client.ts +8 -3
  3. package/cli/cloud-dispatch.ts +1 -1
  4. package/cli/command-agent.ts +122 -0
  5. package/cli/commands/agent.ts +29 -26
  6. package/cli/commands/stream.ts +11 -7
  7. package/cli/main.ts +16 -2
  8. package/cli/outbound-endpoints.ts +15 -0
  9. package/cli/ws-bridge.ts +4 -1
  10. package/dist-lib/agent-daemon-client.cjs +23 -3
  11. package/dist-lib/agent-events.cjs +1 -1
  12. package/dist-lib/attached-projects.cjs +1 -1
  13. package/dist-lib/auth/shared-session.cjs +1 -1
  14. package/dist-lib/backend-origin.cjs +1 -1
  15. package/dist-lib/beta.cjs +1 -1
  16. package/dist-lib/beta.mjs +1 -1
  17. package/dist-lib/bridge-constants.cjs +1 -1
  18. package/dist-lib/bridge-contract-input.cjs +1 -1
  19. package/dist-lib/bridge-contract-input.mjs +1 -1
  20. package/dist-lib/bridge-contract.cjs +1 -1
  21. package/dist-lib/bridge-contract.mjs +1 -1
  22. package/dist-lib/bundle-channel.cjs +205 -62
  23. package/dist-lib/capture-contract.cjs +1 -1
  24. package/dist-lib/capture-contract.mjs +1 -1
  25. package/dist-lib/cloud-contract.cjs +20 -1
  26. package/dist-lib/cloud-contract.mjs +18 -1
  27. package/dist-lib/cloud-test-args.cjs +1 -1
  28. package/dist-lib/cloud-test-args.mjs +1 -1
  29. package/dist-lib/cloud.cjs +1 -1
  30. package/dist-lib/cloud.mjs +1 -1
  31. package/dist-lib/config.cjs +1 -1
  32. package/dist-lib/config.mjs +1 -1
  33. package/dist-lib/detox/index.cjs +1630 -1513
  34. package/dist-lib/dev-bundle-resolution.cjs +1 -1
  35. package/dist-lib/expo-swift-bundle.cjs +203 -60
  36. package/dist-lib/expo-swift-metadata.cjs +1 -1
  37. package/dist-lib/expo-swift-metadata.mjs +1 -1
  38. package/dist-lib/home-paths.cjs +1 -1
  39. package/dist-lib/host/bridge-host.cjs +394 -102
  40. package/dist-lib/host/fetch-proxy-handler.cjs +5 -5
  41. package/dist-lib/host/fetch-proxy-overrides.cjs +1 -1
  42. package/dist-lib/host/fetch-proxy-overrides.mjs +1 -1
  43. package/dist-lib/host/replacement-module-handler.cjs +1 -1
  44. package/dist-lib/host/websocket-proxy.cjs +1 -1
  45. package/dist-lib/index.cjs +392 -272
  46. package/dist-lib/jump-to-source-babel.cjs +1 -1
  47. package/dist-lib/jump-to-source-native.cjs +1 -1
  48. package/dist-lib/kotlin-host.cjs +1 -1
  49. package/dist-lib/menu.cjs +1 -1
  50. package/dist-lib/menu.mjs +1 -1
  51. package/dist-lib/metro-fingerprint-registry.cjs +1 -1
  52. package/dist-lib/metro-fingerprint-registry.mjs +1 -1
  53. package/dist-lib/metro-production-bundle.cjs +1 -1
  54. package/dist-lib/metro-production-bundle.mjs +1 -1
  55. package/dist-lib/metro.cjs +5 -5
  56. package/dist-lib/native-app-identity-project.cjs +3 -3
  57. package/dist-lib/native-app-identity-project.mjs +3 -3
  58. package/dist-lib/native-app-identity.cjs +1 -1
  59. package/dist-lib/native-app-identity.mjs +1 -1
  60. package/dist-lib/native-firebase-metadata.cjs +1 -1
  61. package/dist-lib/native-firebase-metadata.mjs +1 -1
  62. package/dist-lib/pdfium-raster.cjs +1 -1
  63. package/dist-lib/pdfium-raster.mjs +1 -1
  64. package/dist-lib/plist.cjs +1 -1
  65. package/dist-lib/plist.mjs +1 -1
  66. package/dist-lib/profiles.cjs +1 -1
  67. package/dist-lib/public-brand.cjs +1 -1
  68. package/dist-lib/public-origins-lib-esm.json +24 -24
  69. package/dist-lib/public-origins-lib.json +70 -60
  70. package/dist-lib/react-native-host-modules.cjs +1 -1
  71. package/dist-lib/react-native-host-modules.mjs +1 -1
  72. package/dist-lib/reap-browser.cjs +1 -1
  73. package/dist-lib/scripts/dev-server-scanner.cjs +1 -1
  74. package/dist-lib/sdk.cjs +1 -1
  75. package/dist-lib/sdk.mjs +1 -1
  76. package/dist-lib/skills.cjs +1199 -821
  77. package/dist-lib/swift-compile.cjs +197 -55
  78. package/dist-lib/swift-compile.mjs +197 -55
  79. package/dist-lib/swift-package.cjs +1 -1
  80. package/dist-lib/swift-package.mjs +1 -1
  81. package/dist-lib/swift-submit.cjs +1 -1
  82. package/dist-lib/swift-submit.mjs +1 -1
  83. package/dist-lib/swift-toolchain.cjs +1 -1
  84. package/dist-lib/swift.cjs +1 -1
  85. package/dist-lib/vite-swift.cjs +213 -58
  86. package/dist-lib/vite.cjs +5 -5
  87. package/dist-lib/worklet-executable.cjs +1 -1
  88. package/dist-lib/worklet-executable.mjs +1 -1
  89. package/dist-types/packages/peach-engine/src/remote-stream/cloud-display.d.ts +2 -2
  90. package/dist-types/packages/peach-globals/src/index.d.ts +1 -1
  91. package/dist-types/packages/peach-globals/src/replayBridgeContract.d.ts +7 -0
  92. package/kotlin/sdk.tar.gz +0 -0
  93. package/package.json +1 -1
  94. package/runtime-companion.json +1 -1
  95. package/skills/peach-setup/SKILL.md +8 -3
  96. package/src/agent-daemon-client.ts +35 -2
  97. package/src/agent-prompt.ts +68 -0
  98. package/src/bridge-contract.ts +4 -0
  99. package/src/canvas-agent-note-delivery.ts +83 -0
  100. package/src/cloud-contract.ts +30 -0
  101. package/src/host/agent-host.ts +128 -18
  102. package/src/swift-compile.ts +124 -66
  103. package/src/swift-host.ts +2 -1
  104. package/src/swift-objc-import.ts +99 -0
  105. package/src/swift-packages.ts +1 -0
  106. package/src/swift-shared-sdk.ts +2 -1
  107. package/src/xcode-header-search.ts +33 -0
@@ -0,0 +1,231 @@
1
+ import { mkdirSync, writeFileSync } from 'node:fs'
2
+ import { tmpdir } from 'node:os'
3
+ import { join } from 'node:path'
4
+ import { AgentDaemonClient, connectToDaemon } from '../src/agent-daemon-client'
5
+ import {
6
+ CANVAS_AGENT_ID_MAX_CHARS,
7
+ readCanvasAgentId,
8
+ type AgentInspectMessage,
9
+ } from '../src/agent-prompt'
10
+ import { cloudCanvasAgentNoteUrl } from '../src/canvas-agent-note-delivery'
11
+ import { rnxPublicBrand } from '../src/public-brand'
12
+ import { authHeaderValue, resolveCliAuth } from './auth'
13
+ import { resolveCloudSessionForParsed } from './cloud-client'
14
+ import { readLocalStreamRecord } from './commands/stream'
15
+ import { getCliIdentity, readCurrentTarget } from './current-sim'
16
+ import { CliUsageError } from './usage-error'
17
+ import { parseBridgeCliArgs } from './ws-bridge'
18
+
19
+ export function inspectArtifactDirectory(messageId: string): string {
20
+ if (!/^inspect-[a-f0-9-]+$/.test(messageId))
21
+ throw new Error('invalid inspect message id')
22
+ return join(tmpdir(), 'peach-inspect', messageId)
23
+ }
24
+
25
+ export function saveCanvasNoteArtifacts(message: AgentInspectMessage) {
26
+ const dir = inspectArtifactDirectory(message.id)
27
+ const crop = message.crop
28
+ const prefix = /^data:image\/(webp|png);base64,/.exec(crop ?? '')
29
+ if (!prefix || !crop) throw new Error('inspect message crop is missing')
30
+ const cropPath = join(dir, `crop.${prefix[1]}`)
31
+ const inspectPath = join(dir, 'inspect.json')
32
+ const describePath = join(dir, 'describe.txt')
33
+ mkdirSync(dir, { recursive: true, mode: 0o700 })
34
+ writeFileSync(cropPath, Buffer.from(crop.slice(prefix[0].length), 'base64'), {
35
+ mode: 0o600,
36
+ })
37
+ const { crop: _crop, ...metadata } = message
38
+ writeFileSync(inspectPath, JSON.stringify(metadata, null, 2) + '\n', { mode: 0o600 })
39
+ writeFileSync(
40
+ describePath,
41
+ [message.prompt.inspectSummary, message.prompt.inspectTrace]
42
+ .filter(Boolean)
43
+ .join('\n') + '\n',
44
+ { mode: 0o600 },
45
+ )
46
+ return { cropPath, inspectPath, describePath, screenshotPath: null }
47
+ }
48
+
49
+ export function canvasNoteSource(message: AgentInspectMessage): string | undefined {
50
+ return [message.prompt.inspectSummary, message.prompt.inspectTrace]
51
+ .flatMap((value) => value?.split('\n') ?? [])
52
+ .find((line) => /^# source\b/i.test(line.trim()))
53
+ ?.trim()
54
+ }
55
+
56
+ function inboxTarget(args: string[], port?: number) {
57
+ const parsed = parseBridgeCliArgs(args, { port })
58
+ const identity = getCliIdentity()
59
+ const recipientId = identity.stable
60
+ ? readCanvasAgentId(
61
+ identity.key.length > CANVAS_AGENT_ID_MAX_CHARS
62
+ ? `${identity.key.slice(0, CANVAS_AGENT_ID_MAX_CHARS - 1)}…`
63
+ : identity.key,
64
+ )
65
+ : undefined
66
+ const cloud = resolveCloudSessionForParsed(parsed)
67
+ const simId = cloud?.service === 'box' ? cloud.boxId : (cloud?.simId ?? parsed.simId)
68
+ const stream = !cloud && simId ? readLocalStreamRecord(simId) : null
69
+ const pin = readCurrentTarget()
70
+ const local =
71
+ !cloud && simId
72
+ ? {
73
+ simId,
74
+ port: parsed.explicitPort
75
+ ? parsed.wsPort
76
+ : ((pin?.simId === simId ? pin.bridgePort : undefined) ?? parsed.wsPort),
77
+ }
78
+ : null
79
+ const externalId = cloud
80
+ ? simId
81
+ : stream
82
+ ? new URL(stream.watchUrl).pathname.split('/').at(-1)
83
+ : null
84
+ const auth = externalId ? resolveCliAuth() : null
85
+ const origin =
86
+ stream?.origin ??
87
+ (process.env.PEACH_API_ORIGIN?.trim() ||
88
+ (auth?.kind === 'session' ? auth.origin : rnxPublicBrand.origin))
89
+ const remote =
90
+ externalId && auth
91
+ ? {
92
+ url: cloudCanvasAgentNoteUrl(origin, {
93
+ kind: cloud?.service === 'box' ? 'box' : 'sim',
94
+ externalId,
95
+ }),
96
+ authorization: authHeaderValue(auth),
97
+ }
98
+ : null
99
+ return { local, remote, simId, recipientId }
100
+ }
101
+
102
+ type CloudInbox = NonNullable<ReturnType<typeof inboxTarget>['remote']>
103
+
104
+ async function requestCloudNote<T>(
105
+ remote: CloudInbox,
106
+ recipientId: string,
107
+ action: 'wait' | 'take',
108
+ wait: boolean,
109
+ signal?: AbortSignal,
110
+ ): Promise<T> {
111
+ const timeout = AbortSignal.timeout(wait ? 25_000 : 2_000)
112
+ const response = await fetch(remote.url, {
113
+ method: 'POST',
114
+ headers: { authorization: remote.authorization, 'content-type': 'application/json' },
115
+ body: JSON.stringify({ action, recipientId, wait }),
116
+ signal: signal ? AbortSignal.any([signal, timeout]) : timeout,
117
+ })
118
+ if (!response.ok) throw new CliUsageError(`note inbox returned HTTP ${response.status}`)
119
+ return response.json()
120
+ }
121
+
122
+ async function takeCloudNote(remote: CloudInbox, recipientId: string, wait: boolean) {
123
+ const { message } = await requestCloudNote<{ message: AgentInspectMessage | null }>(
124
+ remote,
125
+ recipientId,
126
+ 'take',
127
+ wait,
128
+ )
129
+ return message
130
+ }
131
+
132
+ async function listenToStreamNotes(
133
+ client: AgentDaemonClient,
134
+ simId: string,
135
+ remote: CloudInbox,
136
+ recipientId: string,
137
+ ): Promise<AgentInspectMessage> {
138
+ while (true) {
139
+ const stop = new AbortController()
140
+ const local = client.listenForInspect(simId, recipientId)
141
+ const waitForCloud = async () => {
142
+ while (!stop.signal.aborted) {
143
+ const { pending } = await requestCloudNote<{ pending: boolean }>(
144
+ remote,
145
+ recipientId,
146
+ 'wait',
147
+ true,
148
+ stop.signal,
149
+ )
150
+ if (pending) break
151
+ }
152
+ return null
153
+ }
154
+ try {
155
+ const delivery = await Promise.race([local, waitForCloud()])
156
+ if (delivery) return delivery
157
+ if (!(await client.cancelInspectListener(simId))) return await local
158
+ const cloud = await takeCloudNote(remote, recipientId, false)
159
+ if (cloud) return cloud
160
+ } finally {
161
+ stop.abort()
162
+ }
163
+ }
164
+ }
165
+
166
+ export async function listenForAgentInspect(args: string[], port?: number) {
167
+ const { local, remote, simId, recipientId } = inboxTarget(args, port)
168
+ if (remote && !local) {
169
+ if (!recipientId)
170
+ throw new CliUsageError(
171
+ 'Set PEACH_CLI_IDENTITY to the identity driving the simulator.',
172
+ )
173
+ while (true) {
174
+ const message = await takeCloudNote(remote, recipientId, true)
175
+ if (message) return message
176
+ }
177
+ }
178
+ if (!local) {
179
+ throw new CliUsageError(
180
+ simId
181
+ ? 'Sign in to receive notes for the remote simulator.'
182
+ : 'No current simulator. Run peach use <id> or pass --sim <id>.',
183
+ )
184
+ }
185
+ const client = await connectToDaemon({
186
+ port: local.port,
187
+ commandTimeoutMs: 0,
188
+ clientLabel: 'peach-agent-listen',
189
+ })
190
+ try {
191
+ if (remote && recipientId)
192
+ return await listenToStreamNotes(client, local.simId, remote, recipientId)
193
+ return await client.listenForInspect(local.simId, recipientId)
194
+ } finally {
195
+ client.close()
196
+ }
197
+ }
198
+
199
+ export async function printPendingCanvasNote(args: string[], port?: number) {
200
+ const { local, remote, recipientId } = inboxTarget(args, port)
201
+ if (!recipientId) return
202
+ let message: AgentInspectMessage | null = null
203
+ if (local) {
204
+ const client = new AgentDaemonClient({
205
+ port: local.port,
206
+ connectTimeoutMs: 250,
207
+ commandTimeoutMs: 500,
208
+ })
209
+ try {
210
+ message = await client
211
+ .takeInspectMessage(local.simId, recipientId)
212
+ .catch(() => null)
213
+ } finally {
214
+ client.close()
215
+ }
216
+ }
217
+ if (!message && remote) message = await takeCloudNote(remote, recipientId, false)
218
+ if (!message) return
219
+ const artifacts = saveCanvasNoteArtifacts(message)
220
+ const line = [
221
+ message.prompt.text,
222
+ message.prompt.inspectSummary,
223
+ canvasNoteSource(message),
224
+ ]
225
+ .filter(Boolean)
226
+ .map((part) => JSON.stringify(part?.replace(/[\p{Cc}\p{Zl}\p{Zp}]/gu, ' ')))
227
+ .join(' ')
228
+ process.stderr.write(
229
+ `PEACH INSPECT ${message.id} ${line} Crop: ${artifacts.cropPath}\n`,
230
+ )
231
+ }
@@ -57,8 +57,10 @@ import {
57
57
  type CloudSimSession,
58
58
  type RemotePlatform,
59
59
  } from './cloud-session.ts'
60
+ import { commandAgent } from './command-agent.ts'
60
61
  import { detectProject } from './commands/detect.ts'
61
62
  import { resolveCheckoutRepo } from './run-registry.ts'
63
+ import type { WsBridgeCommand } from '../src/bridge-contract.ts'
62
64
  import type {
63
65
  BridgeClaimResult,
64
66
  BridgeSimInfo,
@@ -1526,15 +1528,16 @@ class CloudBridge implements WsBridge {
1526
1528
  ) {}
1527
1529
 
1528
1530
  async send(
1529
- command: { type: string; [key: string]: unknown },
1531
+ command: WsBridgeCommand,
1530
1532
  options?: { timeoutMs?: number; defaultTimeoutMs?: number },
1531
1533
  ): Promise<unknown> {
1532
1534
  const timeoutMs =
1533
1535
  options?.timeoutMs ?? this.explicitTimeoutMs ?? options?.defaultTimeoutMs
1536
+ const agent = commandAgent(command)
1534
1537
  const body: CloudCommandEnvelope = {
1535
1538
  id: randomUUID(),
1536
1539
  claimId: this.session.claimId,
1537
- command: cloudCommand(command),
1540
+ command: cloudCommand(agent ? { ...command, agent } : command),
1538
1541
  }
1539
1542
  let response: Response
1540
1543
  try {
@@ -1612,7 +1615,7 @@ export class CloudBoxBridge implements WsBridge {
1612
1615
  ) {}
1613
1616
 
1614
1617
  async send(
1615
- command: { type: string; [key: string]: unknown },
1618
+ command: WsBridgeCommand,
1616
1619
  options?: { timeoutMs?: number; defaultTimeoutMs?: number },
1617
1620
  ): Promise<unknown> {
1618
1621
  const timeoutMs =
@@ -1624,6 +1627,8 @@ export class CloudBoxBridge implements WsBridge {
1624
1627
  for (const [key, value] of Object.entries(command)) {
1625
1628
  if (key !== 'id' && key !== 'simId') payload[key] = value
1626
1629
  }
1630
+ const agent = commandAgent(command)
1631
+ if (agent) payload.agent = agent
1627
1632
  let response: Response
1628
1633
  try {
1629
1634
  response = await fetch(
@@ -5,7 +5,7 @@ interface CloudBoundaryInvocation {
5
5
 
6
6
  export type CloudBoundaryResult = { handled: false } | { handled: true; code: number }
7
7
 
8
- const CLOUD_TARGET_COMMANDS = new Set([
8
+ export const CLOUD_TARGET_COMMANDS = new Set([
9
9
  'assert',
10
10
  'camera',
11
11
  'claim',
@@ -0,0 +1,122 @@
1
+ // who is driving a command and what it is doing, so the people watching a sim
2
+ // see the agent and its step beside each action. a cli whose identity is not
3
+ // stable is anonymous and names nobody, and a command that drives nothing
4
+ // carries no agent.
5
+
6
+ import { hostname } from 'os'
7
+ import { formatLockOwner } from '../../peach-kit/src/agent-identity'
8
+ import { AGENT_IDENTITY_MAX_CHARS } from '../src/cloud-contract'
9
+ import { getCliIdentity, readAgentId } from './current-sim'
10
+ import type { PerformStep, WsBridgeCommand } from '../src/bridge-contract'
11
+ import type { SootSimAgentIdentity, SootSimReplayTarget } from '@peach/globals'
12
+
13
+ function clip(text: string): string {
14
+ return text.length > AGENT_IDENTITY_MAX_CHARS
15
+ ? `${text.slice(0, AGENT_IDENTITY_MAX_CHARS - 1)}…`
16
+ : text
17
+ }
18
+
19
+ function targetName(target: SootSimReplayTarget | undefined): string | null {
20
+ const name = target?.text?.trim() || target?.testID?.trim() || target?.id?.trim()
21
+ return name ? name.replace(/\s+/g, ' ') : null
22
+ }
23
+
24
+ function verb(action: string, target: string | null): string {
25
+ return target ? `${action} ${target}` : action
26
+ }
27
+
28
+ // typed text never appears here: a step reaches every person watching, and
29
+ // the text could be a password.
30
+ function describeStep(step: PerformStep): string | null {
31
+ switch (step.type) {
32
+ case 'tap':
33
+ return verb('Tapping', targetName(step.target))
34
+ case 'tapId':
35
+ return verb('Tapping', step.id)
36
+ case 'doubleTap':
37
+ return 'Double tapping'
38
+ case 'longPress':
39
+ return verb('Long pressing', targetName(step.target))
40
+ case 'drag':
41
+ return 'Dragging'
42
+ case 'pinch':
43
+ return 'Pinching'
44
+ case 'scroll':
45
+ return verb('Scrolling', step.id)
46
+ case 'touchDown':
47
+ case 'touchMove':
48
+ case 'touchUp':
49
+ case 'touchCancel':
50
+ return 'Touching the screen'
51
+ case 'type':
52
+ case 'typeInto':
53
+ case 'setElementValue':
54
+ return 'Typing'
55
+ case 'key':
56
+ case 'keyDown':
57
+ case 'keyUp':
58
+ return 'Pressing a key'
59
+ case 'dismissKeyboard':
60
+ case 'toggleKeyboard':
61
+ return 'Using the keyboard'
62
+ case 'openUrl':
63
+ return 'Opening a link'
64
+ case 'setOrientation':
65
+ return `Rotating to ${step.orientation}`
66
+ case 'incrementElement':
67
+ case 'decrementElement':
68
+ return verb('Adjusting', step.id)
69
+ case 'buttonDown':
70
+ case 'buttonUp':
71
+ case 'wait':
72
+ case 'waitFor':
73
+ case 'deviceInfo':
74
+ case 'discoverStoreKitConfig':
75
+ case 'clearStoreKitConfig':
76
+ return null
77
+ }
78
+ }
79
+
80
+ function describeCommand(command: WsBridgeCommand): string | null {
81
+ switch (command.type) {
82
+ case 'tap':
83
+ return verb('Tapping', targetName(command.target))
84
+ case 'longPress':
85
+ return verb('Long pressing', targetName(command.target))
86
+ case 'keyboard':
87
+ return command.action === 'dismiss'
88
+ ? 'Dismissing the keyboard'
89
+ : command.action === 'press' || command.action === 'dispatchKey'
90
+ ? 'Pressing a key'
91
+ : 'Typing'
92
+ case 'screenshot':
93
+ return 'Taking a screenshot'
94
+ case 'perform': {
95
+ const labels = (command.steps ?? []).flatMap((step) => describeStep(step) ?? [])
96
+ const [first] = labels
97
+ if (!first) return null
98
+ return labels.length === 1 ? first : `${first}, then ${labels.length - 1} more`
99
+ }
100
+ default:
101
+ return null
102
+ }
103
+ }
104
+
105
+ /** the identity a command carries to the sim, or undefined when it names nobody. */
106
+ export function commandAgent(command: WsBridgeCommand): SootSimAgentIdentity | undefined {
107
+ const step = describeCommand(command)
108
+ if (!step) return undefined
109
+ const identity = getCliIdentity()
110
+ if (!identity.stable) return undefined
111
+ const machine = hostname().split('.')[0]
112
+ if (!machine) return undefined
113
+ return {
114
+ id: clip(identity.key),
115
+ name: clip(
116
+ readAgentId() ??
117
+ (process.env.PEACH_AGENT_ID?.trim() || formatLockOwner(identity.key)),
118
+ ),
119
+ machine: clip(machine),
120
+ step: clip(step),
121
+ }
122
+ }
@@ -12,7 +12,6 @@
12
12
  // wrapper is live.
13
13
 
14
14
  import fs from 'node:fs'
15
- import os from 'node:os'
16
15
  import path from 'node:path'
17
16
  import {
18
17
  AgentDaemonError,
@@ -29,7 +28,12 @@ import {
29
28
  listSessions,
30
29
  upsertProject,
31
30
  } from '../../src/attached-projects'
32
- import { readCurrentSimId } from '../current-sim'
31
+ import {
32
+ canvasNoteSource,
33
+ inspectArtifactDirectory,
34
+ listenForAgentInspect,
35
+ saveCanvasNoteArtifacts,
36
+ } from '../agent-note'
33
37
  import { printCommandHelp } from '../help'
34
38
  import { createBridge, resolveDefaultBridgePort } from '../ws-bridge'
35
39
  import { inspectDescribe } from './inspect/core'
@@ -70,7 +74,7 @@ export async function runAgentCommand(
70
74
  case 'watch':
71
75
  return await cmdWatch(rest)
72
76
  case 'listen':
73
- return await cmdListen(rest)
77
+ return await cmdListen(rest, opts.port)
74
78
  case 'info':
75
79
  return await cmdInfo(rest)
76
80
  case 'transcript':
@@ -341,26 +345,13 @@ async function cmdWatch(argv: string[]): Promise<number> {
341
345
  return exit
342
346
  }
343
347
 
344
- async function cmdListen(argv: string[]): Promise<number> {
345
- const { flags } = parseFlags(argv, { '--sim': 'value' })
346
- const simId = ((flags['--sim'] as string) || readCurrentSimId() || '').trim()
347
- if (!simId) {
348
- process.stderr.write('no current sim. run `peach use <id>` or pass `--sim <id>`.\n')
349
- return 1
350
- }
351
- const client = await connectToDaemon({
352
- port: daemonPort,
353
- commandTimeoutMs: 0,
354
- clientLabel: 'peach-agent-listen',
355
- })
356
- try {
357
- const message = await client.listenForInspect(simId)
358
- const artifacts = await saveInspectArtifacts(message)
359
- printInspectMessage(message, artifacts)
360
- return 0
361
- } finally {
362
- client.close()
363
- }
348
+ async function cmdListen(argv: string[], port?: number): Promise<number> {
349
+ const message = await listenForAgentInspect(argv, port)
350
+ const artifacts = message.crop
351
+ ? saveCanvasNoteArtifacts(message)
352
+ : await saveInspectArtifacts(message)
353
+ printInspectMessage(message, artifacts)
354
+ return 0
364
355
  }
365
356
 
366
357
  async function saveInspectArtifacts(message: AgentInspectMessage): Promise<{
@@ -368,7 +359,7 @@ async function saveInspectArtifacts(message: AgentInspectMessage): Promise<{
368
359
  describePath: string
369
360
  screenshotPath: string | null
370
361
  }> {
371
- const dir = path.join(os.tmpdir(), 'peach-inspect', message.id)
362
+ const dir = inspectArtifactDirectory(message.id)
372
363
  fs.mkdirSync(dir, { recursive: true, mode: 0o700 })
373
364
  const inspectPath = path.join(dir, 'inspect.json')
374
365
  const describePath = path.join(dir, 'describe.txt')
@@ -424,7 +415,12 @@ async function saveInspectArtifacts(message: AgentInspectMessage): Promise<{
424
415
 
425
416
  function printInspectMessage(
426
417
  message: AgentInspectMessage,
427
- artifacts: { inspectPath: string; describePath: string; screenshotPath: string | null },
418
+ artifacts: {
419
+ inspectPath: string
420
+ describePath: string
421
+ screenshotPath: string | null
422
+ cropPath?: string
423
+ },
428
424
  ): void {
429
425
  const request = message.prompt.displayText ?? message.prompt.text
430
426
  const context = [
@@ -434,14 +430,17 @@ function printInspectMessage(
434
430
  .map((line) => line.trim())
435
431
  .filter((line, index, lines) => line && lines.indexOf(line) === index)
436
432
  .slice(0, 4)
433
+ const source = message.crop ? canvasNoteSource(message) : undefined
437
434
  const lines = [
438
435
  `PEACH INSPECT ${message.id}`,
439
436
  `Request: ${request}`,
440
437
  `Sim: ${message.simId}`,
441
438
  ...context.map((line, index) => `${index === 0 ? 'Target' : 'Context'}: ${line}`),
439
+ ...(source && !context.includes(source) ? [`Context: ${source}`] : []),
442
440
  `Describe: ${artifacts.describePath}`,
443
441
  `Inspect: ${artifacts.inspectPath}`,
444
442
  ...(artifacts.screenshotPath ? [`Screenshot: ${artifacts.screenshotPath}`] : []),
443
+ ...(artifacts.cropPath ? [`Crop: ${artifacts.cropPath}`] : []),
445
444
  `More: peach agent info ${message.id}`,
446
445
  ]
447
446
  process.stdout.write(lines.join('\n') + '\n')
@@ -453,7 +452,7 @@ async function cmdInfo(argv: string[]): Promise<number> {
453
452
  process.stderr.write('usage: peach agent info <message-id>\n')
454
453
  return 2
455
454
  }
456
- const dir = path.join(os.tmpdir(), 'peach-inspect', messageId)
455
+ const dir = inspectArtifactDirectory(messageId)
457
456
  const inspectPath = path.join(dir, 'inspect.json')
458
457
  if (!fs.existsSync(inspectPath)) {
459
458
  process.stderr.write(`inspect message not found: ${messageId}\n`)
@@ -470,6 +469,10 @@ async function cmdInfo(argv: string[]): Promise<number> {
470
469
  screenshot: fs.existsSync(path.join(dir, 'screenshot.png'))
471
470
  ? path.join(dir, 'screenshot.png')
472
471
  : null,
472
+ crop:
473
+ ['crop.webp', 'crop.png']
474
+ .map((file) => path.join(dir, file))
475
+ .find((file) => fs.existsSync(file)) ?? null,
473
476
  },
474
477
  },
475
478
  null,
@@ -21,6 +21,16 @@ const recordSchema = z.object({
21
21
  watchUrl: z.string(),
22
22
  })
23
23
 
24
+ export function readLocalStreamRecord(simId: string) {
25
+ const file = join(rnxHomeDir(), 'streams', `${encodeURIComponent(simId)}.json`)
26
+ try {
27
+ return recordSchema.parse(JSON.parse(readFileSync(file, 'utf8')))
28
+ } catch (error) {
29
+ if (error instanceof Error && 'code' in error && error.code === 'ENOENT') return null
30
+ throw error
31
+ }
32
+ }
33
+
24
34
  export async function runStreamCommand(
25
35
  args: string[],
26
36
  opts: { port?: number } = {},
@@ -64,13 +74,7 @@ export async function runStreamCommand(
64
74
  }
65
75
  if (action === 'stop') {
66
76
  await callInBridge(bridge, 'SootSim.bridges.videoStream.stop')
67
- let record: z.infer<typeof recordSchema> | null = null
68
- try {
69
- record = recordSchema.parse(JSON.parse(readFileSync(file, 'utf8')))
70
- } catch (error) {
71
- if (!(error instanceof Error && 'code' in error && error.code === 'ENOENT'))
72
- throw error
73
- }
77
+ const record = readLocalStreamRecord(simId)
74
78
  if (record) await stopSession(record)
75
79
  rmSync(file, { force: true })
76
80
  console.log(' stream: off')
package/cli/main.ts CHANGED
@@ -426,7 +426,17 @@ if (
426
426
  }
427
427
  }
428
428
 
429
- const { dispatchCloudBoundary } = await import('./cloud-dispatch')
429
+ const { CLOUD_TARGET_COMMANDS, dispatchCloudBoundary } = await import('./cloud-dispatch')
430
+ if (
431
+ !isReadOnlyInvocation &&
432
+ !redact &&
433
+ (TOP_LEVEL_RUNTIME_COMMANDS.has(command) ||
434
+ CLOUD_TARGET_COMMANDS.has(command) ||
435
+ command === 'canvas')
436
+ ) {
437
+ const { printPendingCanvasNote } = await import('./agent-note')
438
+ await printPendingCanvasNote(commandArgsWithSim, port).catch(() => {})
439
+ }
430
440
  const cloudBoundary = await dispatchCloudBoundary({
431
441
  command,
432
442
  args: commandArgsWithSim,
@@ -805,7 +815,11 @@ try {
805
815
 
806
816
  case 'agent': {
807
817
  const { runAgentCommand } = await import('./commands/agent')
808
- const code = await runAgentCommand(parsed.commandArgs, { port })
818
+ const args =
819
+ parsed.commandArgs[0] === 'listen' && globalSimTarget
820
+ ? ['listen', '--sim', globalSimTarget, ...parsed.commandArgs.slice(1)]
821
+ : parsed.commandArgs
822
+ const code = await runAgentCommand(args, { port })
809
823
  await exitWithFlush(code)
810
824
  }
811
825
 
@@ -99,6 +99,13 @@ export const OUTBOUND_ENDPOINTS: Record<string, OutboundEndpointDeclaration> = {
99
99
  payload:
100
100
  "explicit auth, billing, preview, issue report, test, generated-flow or stream request; a stream registration names the checkout's GitHub owner/repo; a stored login may refresh auth/subscription state",
101
101
  },
102
+ peach_canvas_notes: {
103
+ category: 'explicit-user-action',
104
+ destination: 'configured product API origin, /api/account/rnx-cloud/agent-notes/<id>',
105
+ preConsent: false,
106
+ payload:
107
+ 'a note sent from a running canvas item carries text, element or mark context, source and crop; receipt checks send the note id, and a signed-in CLI requests notes for its own driving identity',
108
+ },
102
109
  cli_delivery: {
103
110
  category: 'explicit-user-action',
104
111
  destination:
@@ -333,6 +340,14 @@ export interface OutboundCallDeclaration {
333
340
  // a new fetch, websocket, node HTTP request, or TCP connection has no entry and
334
341
  // fails scripts/check/outbound-endpoints.ts until its destination and consent behavior are declared.
335
342
  export const DECLARED_OUTBOUND_CALLS: Record<string, OutboundCallDeclaration> = {
343
+ 'packages/peachsim/cli/agent-note.ts :: fetch :: remote.url': {
344
+ category: 'peach_canvas_notes',
345
+ count: 1,
346
+ },
347
+ 'packages/peachsim/src/canvas-agent-note-delivery.ts :: fetch-alias :: endpoint': {
348
+ category: 'peach_canvas_notes',
349
+ count: 1,
350
+ },
336
351
  'packages/peach-engine/src/guest/tcp-relay.ts :: websocket :: url': {
337
352
  category: 'guest_app_network',
338
353
  count: 1,
package/cli/ws-bridge.ts CHANGED
@@ -29,6 +29,7 @@ import {
29
29
  type DevBridgeLockfile,
30
30
  } from '../src/home-paths'
31
31
  import { createCloudBridgeForParsed } from './cloud-client'
32
+ import { commandAgent } from './command-agent'
32
33
  import {
33
34
  getCliIdentity,
34
35
  getOwnerProcessGroupId,
@@ -831,6 +832,8 @@ export function createBridge(wsPort: number, opts: WsBridgeOptions = {}): WsBrid
831
832
  callOpts?.timeoutMs ??
832
833
  (opts.explicitTimeout ? commandTimeoutMs : callOpts?.defaultTimeoutMs) ??
833
834
  commandTimeoutMs
835
+ const agent = commandAgent(cmd)
836
+ const sent = agent ? { ...cmd, agent } : cmd
834
837
  const sendOnce = async (
835
838
  defaultSimId?: string,
836
839
  cmdOverride?: Record<string, any>,
@@ -839,7 +842,7 @@ export function createBridge(wsPort: number, opts: WsBridgeOptions = {}): WsBrid
839
842
  if (terminalError) throw terminalError
840
843
  const id = nextId++
841
844
  return new Promise((resolve, reject) => {
842
- const payload = { ...(cmdOverride ?? cmd), id } as Record<string, any>
845
+ const payload = { ...(cmdOverride ?? sent), id } as Record<string, any>
843
846
  if (payload.simId === undefined && defaultSimId) {
844
847
  payload.simId = defaultSimId
845
848
  }