agent-device 0.4.1 → 0.5.0

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 (87) hide show
  1. package/README.md +19 -20
  2. package/dist/src/797.js +1 -1
  3. package/dist/src/bin.js +32 -32
  4. package/dist/src/daemon.js +17 -17
  5. package/ios-runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests.swift +8 -2
  6. package/package.json +7 -9
  7. package/skills/agent-device/SKILL.md +22 -19
  8. package/skills/agent-device/references/permissions.md +10 -17
  9. package/skills/agent-device/references/session-management.md +3 -1
  10. package/skills/agent-device/references/snapshot-refs.md +1 -4
  11. package/dist/bin/axsnapshot +0 -0
  12. package/ios-runner/AXSnapshot/Package.swift +0 -18
  13. package/ios-runner/AXSnapshot/Sources/AXSnapshot/main.swift +0 -444
  14. package/src/__tests__/cli-help.test.ts +0 -102
  15. package/src/bin.ts +0 -3
  16. package/src/cli.ts +0 -289
  17. package/src/core/__tests__/capabilities.test.ts +0 -74
  18. package/src/core/__tests__/open-target.test.ts +0 -16
  19. package/src/core/capabilities.ts +0 -57
  20. package/src/core/dispatch.ts +0 -360
  21. package/src/core/open-target.ts +0 -13
  22. package/src/daemon/__tests__/app-state.test.ts +0 -138
  23. package/src/daemon/__tests__/is-predicates.test.ts +0 -68
  24. package/src/daemon/__tests__/selectors.test.ts +0 -261
  25. package/src/daemon/__tests__/session-routing.test.ts +0 -108
  26. package/src/daemon/__tests__/session-selector.test.ts +0 -64
  27. package/src/daemon/__tests__/session-store.test.ts +0 -142
  28. package/src/daemon/__tests__/snapshot-processing.test.ts +0 -47
  29. package/src/daemon/action-utils.ts +0 -29
  30. package/src/daemon/app-state.ts +0 -65
  31. package/src/daemon/context.ts +0 -48
  32. package/src/daemon/device-ready.ts +0 -13
  33. package/src/daemon/handlers/__tests__/find.test.ts +0 -99
  34. package/src/daemon/handlers/__tests__/interaction.test.ts +0 -22
  35. package/src/daemon/handlers/__tests__/replay-heal.test.ts +0 -509
  36. package/src/daemon/handlers/__tests__/session-reinstall.test.ts +0 -219
  37. package/src/daemon/handlers/__tests__/session.test.ts +0 -343
  38. package/src/daemon/handlers/__tests__/snapshot-handler.test.ts +0 -92
  39. package/src/daemon/handlers/__tests__/snapshot.test.ts +0 -128
  40. package/src/daemon/handlers/find.ts +0 -324
  41. package/src/daemon/handlers/interaction.ts +0 -550
  42. package/src/daemon/handlers/parse-utils.ts +0 -8
  43. package/src/daemon/handlers/record-trace.ts +0 -154
  44. package/src/daemon/handlers/session.ts +0 -1032
  45. package/src/daemon/handlers/snapshot.ts +0 -439
  46. package/src/daemon/is-predicates.ts +0 -46
  47. package/src/daemon/selectors.ts +0 -540
  48. package/src/daemon/session-routing.ts +0 -22
  49. package/src/daemon/session-selector.ts +0 -39
  50. package/src/daemon/session-store.ts +0 -298
  51. package/src/daemon/snapshot-processing.ts +0 -131
  52. package/src/daemon/types.ts +0 -56
  53. package/src/daemon-client.ts +0 -172
  54. package/src/daemon.ts +0 -295
  55. package/src/platforms/__tests__/boot-diagnostics.test.ts +0 -59
  56. package/src/platforms/android/__tests__/index.test.ts +0 -157
  57. package/src/platforms/android/devices.ts +0 -196
  58. package/src/platforms/android/index.ts +0 -754
  59. package/src/platforms/android/ui-hierarchy.ts +0 -312
  60. package/src/platforms/boot-diagnostics.ts +0 -128
  61. package/src/platforms/ios/__tests__/index.test.ts +0 -24
  62. package/src/platforms/ios/__tests__/runner-client.test.ts +0 -113
  63. package/src/platforms/ios/ax-snapshot.ts +0 -207
  64. package/src/platforms/ios/devices.ts +0 -87
  65. package/src/platforms/ios/index.ts +0 -455
  66. package/src/platforms/ios/runner-client.ts +0 -938
  67. package/src/utils/__tests__/args.test.ts +0 -221
  68. package/src/utils/__tests__/daemon-client.test.ts +0 -78
  69. package/src/utils/__tests__/exec.test.ts +0 -16
  70. package/src/utils/__tests__/finders.test.ts +0 -34
  71. package/src/utils/__tests__/keyed-lock.test.ts +0 -55
  72. package/src/utils/__tests__/process-identity.test.ts +0 -33
  73. package/src/utils/__tests__/retry.test.ts +0 -44
  74. package/src/utils/args.ts +0 -234
  75. package/src/utils/command-schema.ts +0 -629
  76. package/src/utils/device.ts +0 -84
  77. package/src/utils/errors.ts +0 -35
  78. package/src/utils/exec.ts +0 -339
  79. package/src/utils/finders.ts +0 -101
  80. package/src/utils/interactive.ts +0 -4
  81. package/src/utils/interactors.ts +0 -173
  82. package/src/utils/keyed-lock.ts +0 -14
  83. package/src/utils/output.ts +0 -204
  84. package/src/utils/process-identity.ts +0 -100
  85. package/src/utils/retry.ts +0 -180
  86. package/src/utils/snapshot.ts +0 -64
  87. package/src/utils/version.ts +0 -26
@@ -1,298 +0,0 @@
1
- import fs from 'node:fs';
2
- import os from 'node:os';
3
- import path from 'node:path';
4
- import type { CommandFlags } from '../core/dispatch.ts';
5
- import type { SessionAction, SessionState } from './types.ts';
6
- import { inferFillText } from './action-utils.ts';
7
-
8
- export class SessionStore {
9
- private readonly sessions = new Map<string, SessionState>();
10
- private readonly sessionsDir: string;
11
-
12
- constructor(sessionsDir: string) {
13
- this.sessionsDir = sessionsDir;
14
- }
15
-
16
- get(name: string): SessionState | undefined {
17
- return this.sessions.get(name);
18
- }
19
-
20
- has(name: string): boolean {
21
- return this.sessions.has(name);
22
- }
23
-
24
- set(name: string, session: SessionState): void {
25
- this.sessions.set(name, session);
26
- }
27
-
28
- delete(name: string): boolean {
29
- return this.sessions.delete(name);
30
- }
31
-
32
- values(): IterableIterator<SessionState> {
33
- return this.sessions.values();
34
- }
35
-
36
- toArray(): SessionState[] {
37
- return Array.from(this.sessions.values());
38
- }
39
-
40
- recordAction(
41
- session: SessionState,
42
- entry: {
43
- command: string;
44
- positionals: string[];
45
- flags: CommandFlags;
46
- result?: Record<string, unknown>;
47
- },
48
- ): void {
49
- if (entry.flags?.noRecord) return;
50
- if (entry.flags?.saveScript) {
51
- session.recordSession = true;
52
- if (typeof entry.flags.saveScript === 'string') {
53
- session.saveScriptPath = SessionStore.expandHome(entry.flags.saveScript);
54
- }
55
- }
56
- session.actions.push({
57
- ts: Date.now(),
58
- command: entry.command,
59
- positionals: entry.positionals,
60
- flags: sanitizeFlags(entry.flags),
61
- result: entry.result,
62
- });
63
- }
64
-
65
- writeSessionLog(session: SessionState): void {
66
- try {
67
- if (!session.recordSession) return;
68
- const scriptPath = this.resolveScriptPath(session);
69
- const scriptDir = path.dirname(scriptPath);
70
- if (!fs.existsSync(scriptDir)) fs.mkdirSync(scriptDir, { recursive: true });
71
- const script = formatScript(session, this.buildOptimizedActions(session));
72
- fs.writeFileSync(scriptPath, script);
73
- } catch {
74
- // ignore
75
- }
76
- }
77
-
78
- defaultTracePath(session: SessionState): string {
79
- const safeName = session.name.replace(/[^a-zA-Z0-9._-]/g, '_');
80
- const timestamp = new Date().toISOString().replace(/[:.]/g, '-');
81
- return path.join(this.sessionsDir, `${safeName}-${timestamp}.trace.log`);
82
- }
83
-
84
- static expandHome(filePath: string): string {
85
- if (filePath.startsWith('~/')) {
86
- return path.join(os.homedir(), filePath.slice(2));
87
- }
88
- return path.resolve(filePath);
89
- }
90
-
91
- private resolveScriptPath(session: SessionState): string {
92
- if (session.saveScriptPath) {
93
- return SessionStore.expandHome(session.saveScriptPath);
94
- }
95
- if (!fs.existsSync(this.sessionsDir)) fs.mkdirSync(this.sessionsDir, { recursive: true });
96
- const safeName = session.name.replace(/[^a-zA-Z0-9._-]/g, '_');
97
- const timestamp = new Date(session.createdAt).toISOString().replace(/[:.]/g, '-');
98
- return path.join(this.sessionsDir, `${safeName}-${timestamp}.ad`);
99
- }
100
-
101
- private buildOptimizedActions(session: SessionState): SessionAction[] {
102
- const optimized: SessionAction[] = [];
103
- for (const action of session.actions) {
104
- if (action.command === 'snapshot') {
105
- continue;
106
- }
107
- const selectorChain =
108
- Array.isArray(action.result?.selectorChain) &&
109
- action.result?.selectorChain.every((entry) => typeof entry === 'string')
110
- ? (action.result.selectorChain as string[])
111
- : [];
112
- if (selectorChain.length > 0 && (action.command === 'click' || action.command === 'fill' || action.command === 'get')) {
113
- const selectorExpr = selectorChain.join(' || ');
114
- if (action.command === 'click') {
115
- optimized.push({
116
- ...action,
117
- positionals: [selectorExpr],
118
- });
119
- continue;
120
- }
121
- if (action.command === 'fill') {
122
- const text = inferFillText(action);
123
- if (text.length > 0) {
124
- optimized.push({
125
- ...action,
126
- positionals: [selectorExpr, text],
127
- });
128
- continue;
129
- }
130
- }
131
- if (action.command === 'get') {
132
- const sub = action.positionals?.[0];
133
- if (sub === 'text' || sub === 'attrs') {
134
- optimized.push({
135
- ...action,
136
- positionals: [sub, selectorExpr],
137
- });
138
- continue;
139
- }
140
- }
141
- }
142
- if (action.command === 'click' || action.command === 'fill' || action.command === 'get') {
143
- const refLabel = action.result?.refLabel;
144
- if (typeof refLabel === 'string' && refLabel.trim().length > 0) {
145
- optimized.push({
146
- ts: action.ts,
147
- command: 'snapshot',
148
- positionals: [],
149
- flags: {
150
- platform: session.device.platform,
151
- snapshotInteractiveOnly: true,
152
- snapshotCompact: true,
153
- snapshotScope: refLabel.trim(),
154
- },
155
- result: { scope: refLabel.trim() },
156
- });
157
- }
158
- }
159
- optimized.push(action);
160
- }
161
- return optimized;
162
- }
163
- }
164
-
165
- function sanitizeFlags(flags: CommandFlags | undefined): SessionAction['flags'] {
166
- if (!flags) return {};
167
- const {
168
- platform,
169
- device,
170
- udid,
171
- serial,
172
- out,
173
- verbose,
174
- snapshotInteractiveOnly,
175
- snapshotCompact,
176
- snapshotDepth,
177
- snapshotScope,
178
- snapshotRaw,
179
- snapshotBackend,
180
- appsMetadata,
181
- relaunch,
182
- saveScript,
183
- noRecord,
184
- } = flags;
185
- return {
186
- platform,
187
- device,
188
- udid,
189
- serial,
190
- out,
191
- verbose,
192
- snapshotInteractiveOnly,
193
- snapshotCompact,
194
- snapshotDepth,
195
- snapshotScope,
196
- snapshotRaw,
197
- snapshotBackend,
198
- appsMetadata,
199
- relaunch,
200
- saveScript,
201
- noRecord,
202
- };
203
- }
204
-
205
- function formatScript(session: SessionState, actions: SessionAction[]): string {
206
- const lines: string[] = [];
207
- const deviceLabel = session.device.name.replace(/"/g, '\\"');
208
- const kind = session.device.kind ? ` kind=${session.device.kind}` : '';
209
- const theme = 'unknown';
210
- lines.push(`context platform=${session.device.platform} device="${deviceLabel}"${kind} theme=${theme}`);
211
- for (const action of actions) {
212
- if (action.flags?.noRecord) continue;
213
- lines.push(formatActionLine(action));
214
- }
215
- return `${lines.join('\n')}\n`;
216
- }
217
-
218
- function formatActionLine(action: SessionAction): string {
219
- const parts: string[] = [action.command];
220
- if (action.command === 'click') {
221
- const ref = action.positionals?.[0];
222
- if (ref) {
223
- parts.push(formatArg(ref));
224
- if (ref.startsWith('@')) {
225
- const refLabel = action.result?.refLabel;
226
- if (typeof refLabel === 'string' && refLabel.trim().length > 0) {
227
- parts.push(formatArg(refLabel));
228
- }
229
- }
230
- return parts.join(' ');
231
- }
232
- }
233
- if (action.command === 'fill') {
234
- const ref = action.positionals?.[0];
235
- if (ref && ref.startsWith('@')) {
236
- parts.push(formatArg(ref));
237
- const refLabel = action.result?.refLabel;
238
- const text = action.positionals.slice(1).join(' ');
239
- if (typeof refLabel === 'string' && refLabel.trim().length > 0) {
240
- parts.push(formatArg(refLabel));
241
- }
242
- if (text) {
243
- parts.push(formatArg(text));
244
- }
245
- return parts.join(' ');
246
- }
247
- }
248
- if (action.command === 'get') {
249
- const sub = action.positionals?.[0];
250
- const ref = action.positionals?.[1];
251
- if (sub && ref) {
252
- parts.push(formatArg(sub));
253
- parts.push(formatArg(ref));
254
- if (ref.startsWith('@')) {
255
- const refLabel = action.result?.refLabel;
256
- if (typeof refLabel === 'string' && refLabel.trim().length > 0) {
257
- parts.push(formatArg(refLabel));
258
- }
259
- }
260
- return parts.join(' ');
261
- }
262
- }
263
- if (action.command === 'snapshot') {
264
- if (action.flags?.snapshotInteractiveOnly) parts.push('-i');
265
- if (action.flags?.snapshotCompact) parts.push('-c');
266
- if (typeof action.flags?.snapshotDepth === 'number') {
267
- parts.push('-d', String(action.flags.snapshotDepth));
268
- }
269
- if (action.flags?.snapshotScope) {
270
- parts.push('-s', formatArg(action.flags.snapshotScope));
271
- }
272
- if (action.flags?.snapshotRaw) parts.push('--raw');
273
- if (action.flags?.snapshotBackend) {
274
- parts.push(`--backend`, action.flags.snapshotBackend);
275
- }
276
- return parts.join(' ');
277
- }
278
- if (action.command === 'open') {
279
- for (const positional of action.positionals ?? []) {
280
- parts.push(formatArg(positional));
281
- }
282
- if (action.flags?.relaunch) {
283
- parts.push('--relaunch');
284
- }
285
- return parts.join(' ');
286
- }
287
- for (const positional of action.positionals ?? []) {
288
- parts.push(formatArg(positional));
289
- }
290
- return parts.join(' ');
291
- }
292
-
293
- function formatArg(value: string): string {
294
- const trimmed = value.trim();
295
- if (trimmed.startsWith('@')) return trimmed;
296
- if (/^-?\d+(\.\d+)?$/.test(trimmed)) return trimmed;
297
- return JSON.stringify(trimmed);
298
- }
@@ -1,131 +0,0 @@
1
- import type { RawSnapshotNode, SnapshotState } from '../utils/snapshot.ts';
2
-
3
- export function findNodeByLabel(nodes: SnapshotState['nodes'], label: string) {
4
- const query = label.toLowerCase();
5
- return (
6
- nodes.find((node) => {
7
- const labelValue = (node.label ?? '').toLowerCase();
8
- const valueValue = (node.value ?? '').toLowerCase();
9
- const idValue = (node.identifier ?? '').toLowerCase();
10
- return labelValue.includes(query) || valueValue.includes(query) || idValue.includes(query);
11
- }) ?? null
12
- );
13
- }
14
-
15
- export function resolveRefLabel(
16
- node: SnapshotState['nodes'][number],
17
- nodes: SnapshotState['nodes'],
18
- ): string | undefined {
19
- const primary = [node.label, node.value, node.identifier]
20
- .map((value) => (typeof value === 'string' ? value.trim() : ''))
21
- .find((value) => value && value.length > 0);
22
- if (primary && isMeaningfulLabel(primary)) return primary;
23
- const fallback = findNearestMeaningfulLabel(node, nodes);
24
- return fallback ?? (primary && isMeaningfulLabel(primary) ? primary : undefined);
25
- }
26
-
27
- function isMeaningfulLabel(value: string): boolean {
28
- const trimmed = value.trim();
29
- if (!trimmed) return false;
30
- if (/^(true|false)$/i.test(trimmed)) return false;
31
- if (/^\d+$/.test(trimmed)) return false;
32
- return true;
33
- }
34
-
35
- function findNearestMeaningfulLabel(
36
- target: SnapshotState['nodes'][number],
37
- nodes: SnapshotState['nodes'],
38
- ): string | undefined {
39
- if (!target.rect) return undefined;
40
- const targetY = target.rect.y + target.rect.height / 2;
41
- let best: { label: string; distance: number } | null = null;
42
- for (const node of nodes) {
43
- if (!node.rect) continue;
44
- const label = [node.label, node.value, node.identifier]
45
- .map((value) => (typeof value === 'string' ? value.trim() : ''))
46
- .find((value) => value && value.length > 0);
47
- if (!label || !isMeaningfulLabel(label)) continue;
48
- const nodeY = node.rect.y + node.rect.height / 2;
49
- const distance = Math.abs(nodeY - targetY);
50
- if (!best || distance < best.distance) {
51
- best = { label, distance };
52
- }
53
- }
54
- return best?.label;
55
- }
56
-
57
- export function pruneGroupNodes(nodes: RawSnapshotNode[]): RawSnapshotNode[] {
58
- const skippedDepths: number[] = [];
59
- const result: RawSnapshotNode[] = [];
60
- for (const node of nodes) {
61
- const depth = node.depth ?? 0;
62
- while (skippedDepths.length > 0 && depth <= skippedDepths[skippedDepths.length - 1]) {
63
- skippedDepths.pop();
64
- }
65
- const type = normalizeType(node.type ?? '');
66
- const labelCandidate = [node.label, node.value, node.identifier]
67
- .map((value) => (typeof value === 'string' ? value.trim() : ''))
68
- .find((value) => value && value.length > 0);
69
- const hasMeaningfulLabel = labelCandidate ? isMeaningfulLabel(labelCandidate) : false;
70
- if ((type === 'group' || type === 'ioscontentgroup') && !hasMeaningfulLabel) {
71
- skippedDepths.push(depth);
72
- continue;
73
- }
74
- const adjustedDepth = Math.max(0, depth - skippedDepths.length);
75
- result.push({ ...node, depth: adjustedDepth });
76
- }
77
- return result;
78
- }
79
-
80
- export function normalizeType(type: string): string {
81
- let value = type.trim().replace(/XCUIElementType/gi, '').toLowerCase();
82
- if (value.startsWith('ax')) {
83
- value = value.replace(/^ax/, '');
84
- }
85
- const lastSeparator = Math.max(value.lastIndexOf('.'), value.lastIndexOf('/'));
86
- if (lastSeparator !== -1) {
87
- value = value.slice(lastSeparator + 1);
88
- }
89
- return value;
90
- }
91
-
92
- export function isFillableType(type: string, platform: 'ios' | 'android'): boolean {
93
- const normalized = normalizeType(type);
94
- if (!normalized) return true;
95
- if (platform === 'android') {
96
- return normalized.includes('edittext') || normalized.includes('autocompletetextview');
97
- }
98
- return (
99
- normalized.includes('textfield') ||
100
- normalized.includes('securetextfield') ||
101
- normalized.includes('searchfield') ||
102
- normalized.includes('textview') ||
103
- normalized.includes('textarea') ||
104
- normalized === 'search'
105
- );
106
- }
107
-
108
- export function findNearestHittableAncestor(
109
- nodes: SnapshotState['nodes'],
110
- node: SnapshotState['nodes'][number],
111
- ): SnapshotState['nodes'][number] | null {
112
- if (node.hittable) return node;
113
- let current = node;
114
- const visited = new Set<string>();
115
- while (current.parentIndex !== undefined) {
116
- if (visited.has(current.ref)) break;
117
- visited.add(current.ref);
118
- const parent = nodes[current.parentIndex];
119
- if (!parent) break;
120
- if (parent.hittable) return parent;
121
- current = parent;
122
- }
123
- return null;
124
- }
125
-
126
- export function extractNodeText(node: SnapshotState['nodes'][number]): string {
127
- const candidates = [node.label, node.value, node.identifier]
128
- .map((value) => (typeof value === 'string' ? value.trim() : ''))
129
- .filter((value) => value.length > 0);
130
- return candidates[0] ?? '';
131
- }
@@ -1,56 +0,0 @@
1
- import type { CommandFlags } from '../core/dispatch.ts';
2
- import type { DeviceInfo } from '../utils/device.ts';
3
- import type { ExecResult } from '../utils/exec.ts';
4
- import type { SnapshotState } from '../utils/snapshot.ts';
5
-
6
- export type DaemonRequest = {
7
- token: string;
8
- session: string;
9
- command: string;
10
- positionals: string[];
11
- flags?: CommandFlags;
12
- };
13
-
14
- export type DaemonResponse =
15
- | { ok: true; data?: Record<string, unknown> }
16
- | { ok: false; error: { code: string; message: string; details?: Record<string, unknown> } };
17
-
18
- export type SessionState = {
19
- name: string;
20
- device: DeviceInfo;
21
- createdAt: number;
22
- appBundleId?: string;
23
- appName?: string;
24
- snapshot?: SnapshotState;
25
- trace?: {
26
- outPath: string;
27
- startedAt: number;
28
- };
29
- recordSession?: boolean;
30
- saveScriptPath?: string;
31
- actions: SessionAction[];
32
- recording?: {
33
- platform: 'ios' | 'android';
34
- outPath: string;
35
- remotePath?: string;
36
- child: ReturnType<typeof import('node:child_process').spawn>;
37
- wait: Promise<ExecResult>;
38
- };
39
- };
40
-
41
- export type SessionAction = {
42
- ts: number;
43
- command: string;
44
- positionals: string[];
45
- flags: Partial<CommandFlags> & {
46
- snapshotInteractiveOnly?: boolean;
47
- snapshotCompact?: boolean;
48
- snapshotDepth?: number;
49
- snapshotScope?: string;
50
- snapshotRaw?: boolean;
51
- snapshotBackend?: 'ax' | 'xctest';
52
- saveScript?: boolean | string;
53
- noRecord?: boolean;
54
- };
55
- result?: Record<string, unknown>;
56
- };
@@ -1,172 +0,0 @@
1
- import net from 'node:net';
2
- import fs from 'node:fs';
3
- import os from 'node:os';
4
- import path from 'node:path';
5
- import { AppError } from './utils/errors.ts';
6
- import type { CommandFlags } from './core/dispatch.ts';
7
- import { runCmdDetached } from './utils/exec.ts';
8
- import { findProjectRoot, readVersion } from './utils/version.ts';
9
- import { stopProcessForTakeover } from './utils/process-identity.ts';
10
-
11
- export type DaemonRequest = {
12
- token: string;
13
- session: string;
14
- command: string;
15
- positionals: string[];
16
- flags?: CommandFlags;
17
- };
18
-
19
- export type DaemonResponse =
20
- | { ok: true; data?: Record<string, unknown> }
21
- | { ok: false; error: { code: string; message: string; details?: Record<string, unknown> } };
22
-
23
- type DaemonInfo = {
24
- port: number;
25
- token: string;
26
- pid: number;
27
- version?: string;
28
- processStartTime?: string;
29
- };
30
-
31
- const baseDir = path.join(os.homedir(), '.agent-device');
32
- const infoPath = path.join(baseDir, 'daemon.json');
33
- const REQUEST_TIMEOUT_MS = resolveDaemonRequestTimeoutMs();
34
- const DAEMON_STARTUP_TIMEOUT_MS = 5000;
35
- const DAEMON_TAKEOVER_TERM_TIMEOUT_MS = 3000;
36
- const DAEMON_TAKEOVER_KILL_TIMEOUT_MS = 1000;
37
-
38
- export async function sendToDaemon(req: Omit<DaemonRequest, 'token'>): Promise<DaemonResponse> {
39
- const info = await ensureDaemon();
40
- const request = { ...req, token: info.token };
41
- return await sendRequest(info, request);
42
- }
43
-
44
- async function ensureDaemon(): Promise<DaemonInfo> {
45
- const existing = readDaemonInfo();
46
- const localVersion = readVersion();
47
- const existingReachable = existing ? await canConnect(existing) : false;
48
- if (existing && existing.version === localVersion && existingReachable) return existing;
49
- if (existing && (existing.version !== localVersion || !existingReachable)) {
50
- await stopDaemonProcessForTakeover(existing);
51
- removeDaemonInfo();
52
- }
53
-
54
- await startDaemon();
55
-
56
- const start = Date.now();
57
- while (Date.now() - start < DAEMON_STARTUP_TIMEOUT_MS) {
58
- const info = readDaemonInfo();
59
- if (info && (await canConnect(info))) return info;
60
- await new Promise((resolve) => setTimeout(resolve, 100));
61
- }
62
-
63
- throw new AppError('COMMAND_FAILED', 'Failed to start daemon', {
64
- infoPath,
65
- hint: 'Run pnpm build, or delete ~/.agent-device/daemon.json if stale.',
66
- });
67
- }
68
-
69
- async function stopDaemonProcessForTakeover(info: DaemonInfo): Promise<void> {
70
- await stopProcessForTakeover(info.pid, {
71
- termTimeoutMs: DAEMON_TAKEOVER_TERM_TIMEOUT_MS,
72
- killTimeoutMs: DAEMON_TAKEOVER_KILL_TIMEOUT_MS,
73
- expectedStartTime: info.processStartTime,
74
- });
75
- }
76
-
77
- function readDaemonInfo(): DaemonInfo | null {
78
- if (!fs.existsSync(infoPath)) return null;
79
- try {
80
- const data = JSON.parse(fs.readFileSync(infoPath, 'utf8')) as DaemonInfo;
81
- if (!data.port || !data.token) return null;
82
- return {
83
- ...data,
84
- pid: Number.isInteger(data.pid) && data.pid > 0 ? data.pid : 0,
85
- };
86
- } catch {
87
- return null;
88
- }
89
- }
90
-
91
- function removeDaemonInfo(): void {
92
- try {
93
- if (fs.existsSync(infoPath)) fs.unlinkSync(infoPath);
94
- } catch {
95
- // Best-effort cleanup only; daemon can still overwrite this file on startup.
96
- }
97
- }
98
-
99
- async function canConnect(info: DaemonInfo): Promise<boolean> {
100
- return new Promise((resolve) => {
101
- const socket = net.createConnection({ host: '127.0.0.1', port: info.port }, () => {
102
- socket.destroy();
103
- resolve(true);
104
- });
105
- socket.on('error', () => {
106
- resolve(false);
107
- });
108
- });
109
- }
110
-
111
- async function startDaemon(): Promise<void> {
112
- const root = findProjectRoot();
113
- const distPath = path.join(root, 'dist', 'src', 'daemon.js');
114
- const srcPath = path.join(root, 'src', 'daemon.ts');
115
-
116
- const hasDist = fs.existsSync(distPath);
117
- const hasSrc = fs.existsSync(srcPath);
118
- if (!hasDist && !hasSrc) {
119
- throw new AppError('COMMAND_FAILED', 'Daemon entry not found', { distPath, srcPath });
120
- }
121
- const runningFromSource = process.execArgv.includes('--experimental-strip-types');
122
- const useSrc = runningFromSource ? hasSrc : !hasDist && hasSrc;
123
- const args = useSrc ? ['--experimental-strip-types', srcPath] : [distPath];
124
-
125
- runCmdDetached(process.execPath, args);
126
- }
127
-
128
- async function sendRequest(info: DaemonInfo, req: DaemonRequest): Promise<DaemonResponse> {
129
- return new Promise((resolve, reject) => {
130
- const socket = net.createConnection({ host: '127.0.0.1', port: info.port }, () => {
131
- socket.write(`${JSON.stringify(req)}\n`);
132
- });
133
- const timeout = setTimeout(() => {
134
- socket.destroy();
135
- reject(
136
- new AppError('COMMAND_FAILED', 'Daemon request timed out', { timeoutMs: REQUEST_TIMEOUT_MS }),
137
- );
138
- }, REQUEST_TIMEOUT_MS);
139
-
140
- let buffer = '';
141
- socket.setEncoding('utf8');
142
- socket.on('data', (chunk) => {
143
- buffer += chunk;
144
- const idx = buffer.indexOf('\n');
145
- if (idx === -1) return;
146
- const line = buffer.slice(0, idx).trim();
147
- if (!line) return;
148
- try {
149
- const response = JSON.parse(line) as DaemonResponse;
150
- socket.end();
151
- clearTimeout(timeout);
152
- resolve(response);
153
- } catch (err) {
154
- clearTimeout(timeout);
155
- reject(err);
156
- }
157
- });
158
-
159
- socket.on('error', (err) => {
160
- clearTimeout(timeout);
161
- reject(err);
162
- });
163
- });
164
- }
165
-
166
- export function resolveDaemonRequestTimeoutMs(raw: string | undefined = process.env.AGENT_DEVICE_DAEMON_TIMEOUT_MS): number {
167
- // iOS physical-device runner startup/build can exceed 60s, so use a safer default for daemon RPCs.
168
- if (!raw) return 180000;
169
- const parsed = Number(raw);
170
- if (!Number.isFinite(parsed)) return 180000;
171
- return Math.max(1000, Math.floor(parsed));
172
- }