@myagentroam/marctl 0.11.3 → 0.11.5

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.
@@ -0,0 +1,247 @@
1
+ import { MarctlError } from './errors.mjs';
2
+ import { createTranslator } from './i18n/index.mjs';
3
+ import { sessionTarget } from './session-target.mjs';
4
+
5
+ const commands = {
6
+ current: [],
7
+ list: ['cursor', 'limit', 'query', 'parent', 'scope', 'agent', 'runner'],
8
+ graph: ['limit'],
9
+ show: [],
10
+ view: ['cursor', 'limit', 'history'],
11
+ history: ['cursor', 'limit'],
12
+ start: [
13
+ 'runner',
14
+ 'model',
15
+ 'effort',
16
+ 'title',
17
+ 'message',
18
+ 'message-file',
19
+ 'image',
20
+ 'client-message-id',
21
+ 'parent',
22
+ 'goal',
23
+ 'clear-goal'
24
+ ],
25
+ config: ['model', 'effort'],
26
+ rename: ['title'],
27
+ 'prompt.get': [],
28
+ 'prompt.set': ['message', 'message-file'],
29
+ 'prompt.clear': [],
30
+ 'approval.decide': ['run', 'approval', 'decision'],
31
+ 'schedule.list': ['cursor', 'limit'],
32
+ 'schedule.get': [],
33
+ 'schedule.create': ['cron', 'message', 'message-file'],
34
+ 'schedule.update': ['cron', 'message', 'message-file', 'expected-revision'],
35
+ send: [
36
+ 'message',
37
+ 'message-file',
38
+ 'image',
39
+ 'steer',
40
+ 'queue',
41
+ 'client-message-id',
42
+ 'goal',
43
+ 'clear-goal',
44
+ 'approval',
45
+ 'decision'
46
+ ],
47
+ stop: ['execution'],
48
+ 'goal.get': [],
49
+ 'goal.set': ['message', 'message-file'],
50
+ 'goal.clear': [],
51
+ wait: ['timeout', 'wait-for', 'mode', 'agent', 'run', 'until']
52
+ };
53
+ const fieldNames = {
54
+ parent: 'parentSessionId',
55
+ 'expected-revision': 'expectedRevision',
56
+ 'message-file': 'messageFile',
57
+ 'client-message-id': 'clientMessageId',
58
+ run: 'runId',
59
+ approval: 'approvalId',
60
+ timeout: 'timeoutMs',
61
+ execution: 'executionId',
62
+ 'wait-for': 'waitFor',
63
+ 'clear-goal': 'clearGoal',
64
+ image: 'images'
65
+ };
66
+
67
+ export function parseSessionArgs(argv, translate = createTranslator()) {
68
+ const invalid = (key = 'errors.invalidArguments', details) =>
69
+ new MarctlError(translate(key), {
70
+ code: 'MARCTL_SESSION_INPUT_INVALID',
71
+ details:
72
+ details ??
73
+ (argv[0] === 'prompt'
74
+ ? 'Use prompt get|clear [session-id], or prompt set [session-id] with exactly one of -m/--message or --message-file.'
75
+ : argv[0] === 'approval'
76
+ ? 'Use approval decide <session-id> --run <run-id> --approval <approval-id> --decision approve|reject.'
77
+ : undefined)
78
+ });
79
+ if (
80
+ argv.length === 0 ||
81
+ argv.some(
82
+ (value, index) =>
83
+ (value === '--help' || value === '-h') && !['-m', '--message'].includes(argv[index - 1])
84
+ )
85
+ )
86
+ return { command: 'agents', help: true };
87
+ const input = [...argv];
88
+ let action = input.shift();
89
+ if (['goal', 'schedule', 'prompt', 'approval'].includes(action)) action += '.' + input.shift();
90
+ if (!Object.hasOwn(commands, action)) throw invalid();
91
+ const args = { command: 'agents', action };
92
+ if (sessionTarget[action] !== 'workspace') {
93
+ if (
94
+ (input[0] === undefined || input[0].startsWith('-')) &&
95
+ sessionTarget[action] === 'explicit'
96
+ )
97
+ throw invalid();
98
+ if (input[0] !== undefined && !input[0].startsWith('-')) {
99
+ const sessionId = input.shift();
100
+ if (!sessionId || sessionId.length > 512) throw invalid();
101
+ args.sessionId = sessionId;
102
+ }
103
+ }
104
+ while (input.length > 0) {
105
+ const rawFlag = input.shift();
106
+ const flag = rawFlag === '-m' ? '--message' : rawFlag;
107
+ if (flag === '--json' && args.json === undefined) {
108
+ args.json = true;
109
+ continue;
110
+ }
111
+ if (action === 'send' && (flag === '--steer' || flag === '--queue')) {
112
+ const key = flag.slice(2);
113
+ if (Object.hasOwn(args, key)) throw invalid();
114
+ args[key] = true;
115
+ continue;
116
+ }
117
+ if (
118
+ (flag === '--clear-goal' && ['start', 'send'].includes(action)) ||
119
+ (flag === '--history' && action === 'view')
120
+ ) {
121
+ const key = flag === '--history' ? 'history' : 'clearGoal';
122
+ if (Object.hasOwn(args, key)) throw invalid();
123
+ args[key] = true;
124
+ continue;
125
+ }
126
+ const name = flag.startsWith('--') ? flag.slice(2) : '';
127
+ const key = fieldNames[name] ?? name;
128
+ if (
129
+ !commands[action].includes(name) ||
130
+ (name !== 'image' && !(name === 'agent' && action === 'wait') && Object.hasOwn(args, key))
131
+ )
132
+ throw invalid();
133
+ const value = input.shift();
134
+ if (
135
+ value === undefined ||
136
+ (value === '' && name !== 'effort') ||
137
+ (name !== 'message' && value.startsWith('--'))
138
+ )
139
+ throw invalid();
140
+ if (name === 'agent' && action === 'wait') {
141
+ (args.agentIds ??= []).push(value);
142
+ if (args.agentIds.length > 8) throw invalid();
143
+ } else if (name === 'image') {
144
+ (args.images ??= []).push(value);
145
+ if (args.images.length > 5) throw invalid();
146
+ } else if (name === 'limit' || name === 'expected-revision') {
147
+ if (
148
+ !/^[1-9][0-9]*$/u.test(value) ||
149
+ !Number.isSafeInteger(Number(value)) ||
150
+ (name === 'limit' && Number(value) > 100)
151
+ )
152
+ throw invalid();
153
+ args[key] = Number(value);
154
+ } else if (name === 'timeout') {
155
+ const match = /^(0|[1-9][0-9]*)(ms|s|m)$/u.exec(value);
156
+ const ms = match === null ? 0 : Number(match[1]) * { ms: 1, s: 1000, m: 60000 }[match[2]];
157
+ if (match === null || !Number.isSafeInteger(ms) || ms > 300000) throw invalid();
158
+ args[key] = ms;
159
+ } else args[key] = value;
160
+ }
161
+ if (action === 'send' && args.steer === true && args.queue === true)
162
+ throw invalid('errors.sessionDeliveryRequired');
163
+ if (
164
+ action === 'send' &&
165
+ ((args.approvalId === undefined) !== (args.decision === undefined) ||
166
+ (args.decision !== undefined && !['approve', 'reject'].includes(args.decision)))
167
+ )
168
+ throw invalid();
169
+ if (args.goal !== undefined && (args.clearGoal || !args.goal.trim() || args.goal.length > 20000))
170
+ throw invalid();
171
+ if (args.message !== undefined && args.messageFile !== undefined) throw invalid();
172
+ if (
173
+ ['start', 'send', 'goal.set', 'schedule.create', 'prompt.set'].includes(action) &&
174
+ args.messageFile === undefined &&
175
+ args.message === undefined &&
176
+ !args.images?.length &&
177
+ !(
178
+ action === 'send' &&
179
+ (args.goal !== undefined || args.clearGoal || args.approvalId !== undefined)
180
+ )
181
+ )
182
+ throw invalid();
183
+ if (
184
+ action === 'start' &&
185
+ args.runner !== undefined &&
186
+ !['mar-agent', 'codex', 'claude-code', 'opencode'].includes(args.runner)
187
+ )
188
+ throw invalid();
189
+ if (action === 'stop' && !args.executionId) throw invalid();
190
+ if (action === 'wait' && args.sessionId && args.agentIds?.length) throw invalid();
191
+ if (
192
+ args.until !== undefined &&
193
+ (args.until !== 'approval' ||
194
+ !args.sessionId ||
195
+ !args.runId ||
196
+ !args.timeoutMs ||
197
+ args.agentIds?.length)
198
+ )
199
+ throw invalid();
200
+ if (
201
+ action === 'wait' &&
202
+ args.runId !== undefined &&
203
+ (!args.sessionId ||
204
+ args.timeoutMs === 0 ||
205
+ args.agentIds?.length ||
206
+ args.mode !== undefined ||
207
+ args.waitFor !== undefined)
208
+ )
209
+ throw invalid();
210
+ if (args.waitFor !== undefined && !['message', 'completion'].includes(args.waitFor))
211
+ throw invalid();
212
+ if (args.mode !== undefined && !['any', 'all'].includes(args.mode)) throw invalid();
213
+ if (
214
+ args.scope !== undefined &&
215
+ !['children', 'descendants', 'workspace', 'profile'].includes(args.scope)
216
+ )
217
+ throw invalid();
218
+ if (
219
+ action === 'approval.decide' &&
220
+ (!args.runId || !args.approvalId || !['approve', 'reject'].includes(args.decision))
221
+ )
222
+ throw invalid(
223
+ undefined,
224
+ 'Approval decisions require --run, --approval and --decision approve|reject.'
225
+ );
226
+ if (action === 'rename' && args.title !== undefined) args.title = args.title.trim();
227
+ if (args.title !== undefined && args.title.length > 160) throw invalid();
228
+ if (args.model !== undefined && (args.model.trim().length === 0 || args.model.length > 120))
229
+ throw invalid();
230
+ if (args.effort !== undefined && args.effort.length > 120) throw invalid();
231
+ if (action === 'config' && args.model === undefined && args.effort === undefined) throw invalid();
232
+ if (action === 'rename') {
233
+ if (args.title === undefined || args.title.trim().length === 0) throw invalid();
234
+ }
235
+ if (action === 'schedule.create' && args.cron === undefined) throw invalid();
236
+ if (args.cron !== undefined && (args.cron.trim().length === 0 || args.cron.length > 512))
237
+ throw invalid();
238
+ if (
239
+ action === 'schedule.update' &&
240
+ (args.expectedRevision === undefined ||
241
+ (args.cron === undefined && args.message === undefined && args.messageFile === undefined))
242
+ )
243
+ throw invalid();
244
+ if (args.query !== undefined && args.query.length > 160) throw invalid();
245
+ if (args.parentSessionId !== undefined && args.parentSessionId.length > 512) throw invalid();
246
+ return args;
247
+ }
@@ -0,0 +1,88 @@
1
+ import { open } from 'node:fs/promises';
2
+ import { basename } from 'node:path';
3
+ import { MarctlError } from './errors.mjs';
4
+
5
+ export async function messageContent(
6
+ { message, messageFile: path },
7
+ stdin,
8
+ limit,
9
+ translate,
10
+ diagnostic = false
11
+ ) {
12
+ let file;
13
+ try {
14
+ let content = message;
15
+ if (content === undefined) {
16
+ const input =
17
+ path === '-'
18
+ ? stdin
19
+ : (file = await open(path, 'r')).createReadStream({ autoClose: false });
20
+ const parts = [];
21
+ let bytes = 0;
22
+ for await (const part of input) {
23
+ const chunk = Buffer.from(part);
24
+ bytes += chunk.length;
25
+ if (bytes > limit * 4) throw new Error('MESSAGE_TOO_LONG');
26
+ parts.push(chunk);
27
+ }
28
+ content = new TextDecoder('utf-8', { fatal: true }).decode(Buffer.concat(parts));
29
+ }
30
+ if (content.trim().length === 0 || content.length > limit) throw new Error('MESSAGE_INVALID');
31
+ return content;
32
+ } catch (error) {
33
+ throw new MarctlError(translate('errors.sessionMessageInvalid'), {
34
+ code: 'MARCTL_SESSION_INPUT_INVALID',
35
+ ...(diagnostic
36
+ ? {
37
+ details: `${path === undefined ? 'message' : path === '-' ? 'stdin' : 'message-file'}: provide non-blank UTF-8 text of at most ${limit} characters.${typeof error.code === 'string' && /^[A-Z_]+$/u.test(error.code) ? ' File error: ' + error.code + '.' : ''}`
38
+ }
39
+ : {})
40
+ });
41
+ } finally {
42
+ await file?.close();
43
+ }
44
+ }
45
+
46
+ export async function imageAttachments(paths, translate) {
47
+ const attachments = [];
48
+ let total = 0;
49
+ for (const path of paths) {
50
+ let file;
51
+ try {
52
+ file = await open(path, 'r');
53
+ const info = await file.stat();
54
+ if (!info.isFile() || info.size === 0 || info.size > 5 * 1024 * 1024)
55
+ throw new Error('IMAGE_INVALID');
56
+ const parts = [];
57
+ let size = 0;
58
+ for await (const part of file.createReadStream({ autoClose: false })) {
59
+ size += part.length;
60
+ total += part.length;
61
+ if (size > 5 * 1024 * 1024 || total > 10 * 1024 * 1024) throw new Error('IMAGE_TOO_LARGE');
62
+ parts.push(part);
63
+ }
64
+ const data = Buffer.concat(parts);
65
+ const mime = imageMime(data);
66
+ if (mime === undefined) throw new Error('IMAGE_INVALID');
67
+ attachments.push({ name: basename(path), mime, dataBase64: data.toString('base64') });
68
+ } catch {
69
+ throw new MarctlError(translate('errors.sessionImageInvalid'), {
70
+ code: 'MARCTL_SESSION_INPUT_INVALID'
71
+ });
72
+ } finally {
73
+ await file?.close();
74
+ }
75
+ }
76
+ return attachments;
77
+ }
78
+
79
+ function imageMime(data) {
80
+ if (data.subarray(0, 8).equals(Buffer.from('89504e470d0a1a0a', 'hex'))) return 'image/png';
81
+ if (data[0] === 0xff && data[1] === 0xd8 && data[2] === 0xff) return 'image/jpeg';
82
+ if (['GIF87a', 'GIF89a'].includes(data.subarray(0, 6).toString('ascii'))) return 'image/gif';
83
+ if (
84
+ data.subarray(0, 4).toString('ascii') === 'RIFF' &&
85
+ data.subarray(8, 12).toString('ascii') === 'WEBP'
86
+ )
87
+ return 'image/webp';
88
+ }
@@ -0,0 +1,99 @@
1
+ import { randomUUID } from 'node:crypto';
2
+ import { messageContent, imageAttachments } from './session-input.mjs';
3
+
4
+ const networkActions = new Set(['start', 'send', 'wait', 'stop', 'list', 'view']);
5
+
6
+ /** Adapt CLI syntax to the same Node Agent Network command used by native tools. */
7
+ export async function prepareAgentNetworkRequest({ args, stdin, translate, sessionId }) {
8
+ const input = {};
9
+ for (const name of [
10
+ 'runner',
11
+ 'model',
12
+ 'effort',
13
+ 'title',
14
+ 'cursor',
15
+ 'limit',
16
+ 'query',
17
+ 'parentSessionId',
18
+ 'scope',
19
+ 'waitFor',
20
+ 'mode',
21
+ 'executionId'
22
+ ])
23
+ if (args[name] !== undefined) input[name] = args[name];
24
+ if (args.action === 'list' && input.parentSessionId !== undefined) {
25
+ input.parent = input.parentSessionId;
26
+ delete input.parentSessionId;
27
+ }
28
+ if (args.action === 'list' && args.agent !== undefined) input.agentId = args.agent;
29
+ if (['send', 'stop', 'view', 'wait'].includes(args.action) && sessionId)
30
+ input.agentId = sessionId;
31
+ if (args.action === 'wait' && args.agentIds?.length) input.agentIds = args.agentIds;
32
+ if (args.action === 'wait' && args.timeoutMs !== undefined) input.waitMs = args.timeoutMs;
33
+ if (args.action === 'view' && args.history) input.includeHistory = true;
34
+ if (args.message !== undefined || args.messageFile !== undefined)
35
+ input.content = await messageContent(args, stdin, 100000, translate);
36
+ if (args.images?.length) input.attachments = await imageAttachments(args.images, translate);
37
+ if (args.goal !== undefined) input.goal = { objective: args.goal.trim() };
38
+ if (args.clearGoal) input.goal = { clear: true };
39
+ if (args.action === 'send' && args.approvalId !== undefined)
40
+ input.approval = { approvalId: args.approvalId, decision: args.decision };
41
+ if (args.action === 'start' || args.action === 'send')
42
+ input.clientMessageId = args.clientMessageId ?? randomUUID();
43
+ if (args.action === 'send')
44
+ input.deliveryIntent = args.steer ? 'REPLACE_CURRENT' : args.queue ? 'QUEUE' : 'SEND';
45
+ return { action: 'network', command: { operation: args.action, input } };
46
+ }
47
+
48
+ export function isAgentNetworkAction(action) {
49
+ return networkActions.has(action);
50
+ }
51
+
52
+ export async function prepareSessionRequest({ args, env, stdin, translate, sessionId, targeted }) {
53
+ const body = { action: args.action };
54
+ for (const name of [
55
+ 'sessionId',
56
+ 'parentSessionId',
57
+ 'runner',
58
+ 'model',
59
+ 'effort',
60
+ 'title',
61
+ 'cursor',
62
+ 'limit',
63
+ 'query',
64
+ 'runId',
65
+ 'approvalId',
66
+ 'cron',
67
+ 'expectedRevision'
68
+ ])
69
+ if (args[name] !== undefined) body[name] = args[name];
70
+ if (targeted) body.sessionId = sessionId;
71
+ if (args.action === 'current' && env.MAR_CTL_SESSION_ID) body.sessionId = env.MAR_CTL_SESSION_ID;
72
+ if (args.action === 'start' && env.MAR_CTL_SESSION_ID)
73
+ body.parentSessionId = env.MAR_CTL_SESSION_ID;
74
+ if (['start', 'send'].includes(args.action) && env.MAR_CTL_SESSION_ID)
75
+ body.sourceSessionId = env.MAR_CTL_SESSION_ID;
76
+ if (args.messageFile !== undefined || args.message !== undefined)
77
+ body.content = await messageContent(
78
+ args,
79
+ stdin,
80
+ args.action === 'goal.set' ||
81
+ args.action.startsWith('schedule.') ||
82
+ args.action === 'prompt.set'
83
+ ? 20000
84
+ : 100000,
85
+ translate,
86
+ args.action === 'prompt.set'
87
+ );
88
+ if (args.action === 'approval.decide')
89
+ body.decision = args.decision === 'approve' ? 'APPROVED' : 'REJECTED';
90
+ if (args.images !== undefined) {
91
+ body.attachments = await imageAttachments(args.images, translate);
92
+ body.content ??= '';
93
+ }
94
+ if (args.action === 'start' || args.action === 'send')
95
+ body.clientMessageId = args.clientMessageId ?? randomUUID();
96
+ if (args.action === 'send')
97
+ body.deliveryIntent = args.steer === true ? 'REPLACE_CURRENT' : 'QUEUE';
98
+ return Object.freeze(body);
99
+ }
@@ -0,0 +1,26 @@
1
+ // Scope is a command property, independent of input or the remote session state.
2
+ export const sessionTarget = Object.freeze({
3
+ current: 'workspace',
4
+ list: 'workspace',
5
+ start: 'workspace',
6
+ 'schedule.list': 'workspace',
7
+ show: 'current',
8
+ view: 'current',
9
+ config: 'current',
10
+ history: 'current',
11
+ graph: 'current',
12
+ rename: 'current',
13
+ 'prompt.get': 'current',
14
+ 'prompt.set': 'current',
15
+ 'prompt.clear': 'current',
16
+ 'schedule.get': 'current',
17
+ 'schedule.create': 'current',
18
+ 'schedule.update': 'current',
19
+ send: 'explicit',
20
+ stop: 'explicit',
21
+ wait: 'optional',
22
+ 'approval.decide': 'explicit',
23
+ 'goal.get': 'explicit',
24
+ 'goal.set': 'explicit',
25
+ 'goal.clear': 'explicit'
26
+ });
@@ -0,0 +1,232 @@
1
+ import { randomUUID } from 'node:crypto';
2
+ import { MarctlError } from './errors.mjs';
3
+ import { createTranslator } from './i18n/index.mjs';
4
+
5
+ const terminal = new Set(['SUCCEEDED', 'FAILED', 'CANCELLED', 'INTERRUPTED']);
6
+
7
+ /** One CLI-owned Workbench connection and one existing Session Watch, never history polling. */
8
+ export async function waitForSessionRun({
9
+ client,
10
+ sessionId,
11
+ runId,
12
+ timeoutMs,
13
+ until,
14
+ WebSocketClass,
15
+ translate = createTranslator(),
16
+ signal
17
+ }) {
18
+ let socket;
19
+ const watchId = randomUUID();
20
+ let connectionId;
21
+ let renewal;
22
+ let settled = false;
23
+ let subscribed = false;
24
+ let progress;
25
+ let accept;
26
+ let rejectResult;
27
+ const result = new Promise((resolve, fail) => {
28
+ accept = resolve;
29
+ rejectResult = fail;
30
+ });
31
+ const reject = (error, stage) => {
32
+ if (settled) return;
33
+ settled = true;
34
+ Object.assign(error, { sessionId, runId, stage });
35
+ rejectResult(error);
36
+ };
37
+ const fail = (code, key, { stage, upstreamCode, ...options } = {}) => {
38
+ const error = new MarctlError(translate(key), { ...options, code });
39
+ if (upstreamCode !== undefined) error.upstreamCode = upstreamCode;
40
+ if (stage === 'timeout' && progress !== undefined) error.progress = progress;
41
+ reject(error, stage);
42
+ };
43
+ const unknown = (stage, detail, source) =>
44
+ fail('MARCTL_WAIT_UNKNOWN', 'errors.sessionWaitUnknown', {
45
+ stage,
46
+ upstreamCode:
47
+ typeof source?.code === 'string' && /^[A-Za-z][A-Za-z0-9_]{0,127}$/u.test(source.code)
48
+ ? source.code
49
+ : undefined,
50
+ requestId: typeof source?.requestId === 'string' ? source.requestId.slice(0, 160) : undefined,
51
+ upstreamRequestId:
52
+ typeof source?.upstreamRequestId === 'string'
53
+ ? source.upstreamRequestId.slice(0, 160)
54
+ : undefined,
55
+ details: [detail, source?.message, source?.details]
56
+ .filter((value) => typeof value === 'string')
57
+ .join(' ')
58
+ .slice(0, 4000)
59
+ });
60
+ const command = (mode) =>
61
+ client.sessionCommand({
62
+ action: 'watch',
63
+ sessionId,
64
+ workbenchConnectionId: connectionId,
65
+ watchId,
66
+ mode
67
+ });
68
+ const scheduleRenewal = (expiresAt) => {
69
+ clearTimeout(renewal);
70
+ const remaining = expiresAt - Date.now();
71
+ if (!Number.isFinite(remaining) || remaining <= 0) {
72
+ unknown('lease', 'The Watch lease is missing or expired.');
73
+ return;
74
+ }
75
+ renewal = setTimeout(
76
+ () => {
77
+ command('renew')
78
+ .then((ack) => {
79
+ if (!settled) scheduleRenewal(ack?.expiresAt);
80
+ })
81
+ .catch((error) => {
82
+ if ([401, 403].includes(error.statusCode)) reject(error, 'renew');
83
+ else
84
+ unknown(
85
+ 'renew',
86
+ 'The Watch lease could not be renewed.',
87
+ error instanceof MarctlError ? error : undefined
88
+ );
89
+ });
90
+ },
91
+ Math.max(50, Math.floor(remaining / 2))
92
+ );
93
+ };
94
+ const check = (run) => {
95
+ if (run?.id === runId && run.sessionId === sessionId && terminal.has(run.status) && !settled) {
96
+ settled = true;
97
+ accept({ run });
98
+ }
99
+ };
100
+ const checkApproval = () => {
101
+ if (settled || until !== 'approval' || progress === undefined) return;
102
+ if (!Array.isArray(progress.pendingApprovals)) {
103
+ fail('NODE_OPERATION_UNSUPPORTED', 'errors.sessionApprovalUnsupported', {
104
+ stage: 'approval'
105
+ });
106
+ return;
107
+ }
108
+ const pendingApprovals = progress.pendingApprovals.filter(
109
+ (approval) => approval.runId === runId
110
+ );
111
+ if (pendingApprovals.length === 0) return;
112
+ settled = true;
113
+ accept({
114
+ sessionId,
115
+ runId,
116
+ stopReason: 'APPROVAL_REQUIRED',
117
+ pendingApprovals,
118
+ ...(progress.pendingApprovalsTruncated ? { pendingApprovalsTruncated: true } : {})
119
+ });
120
+ };
121
+ const onMessage = (raw) => {
122
+ if (settled) return;
123
+ let message;
124
+ try {
125
+ message = JSON.parse(String(raw));
126
+ } catch {
127
+ return;
128
+ }
129
+ if (message?.type === 'watch.event') message = message.event;
130
+ if (!message || typeof message !== 'object') return;
131
+ if (
132
+ message.type === 'workbench.ready' &&
133
+ connectionId === undefined &&
134
+ typeof message.workbenchConnectionId === 'string'
135
+ ) {
136
+ connectionId = message.workbenchConnectionId;
137
+ subscribed = true;
138
+ command('initial').catch((error) => reject(error, 'subscribe'));
139
+ }
140
+ if (message.watchId !== watchId) return;
141
+ if (message.type === 'watch.failed') {
142
+ unknown('watch', 'The Session Watch failed.', message);
143
+ return;
144
+ }
145
+ if (message.type === 'watch.session.snapshot') {
146
+ const runs = message.payload?.runs;
147
+ if (!Array.isArray(runs)) {
148
+ unknown('snapshot', 'The Watch snapshot did not contain a Run list.');
149
+ return;
150
+ }
151
+ const run = runs.find((value) => value?.id === runId && value.sessionId === sessionId);
152
+ if (run === undefined) {
153
+ unknown('snapshot', 'The requested Run was absent from the Watch snapshot.');
154
+ return;
155
+ }
156
+ if (message.payload?.session?.id === sessionId && message.payload?.progress?.runId === runId)
157
+ progress = message.payload.progress;
158
+ check(run);
159
+ if (!settled && until === 'approval' && progress === undefined) {
160
+ fail('NODE_OPERATION_UNSUPPORTED', 'errors.sessionApprovalUnsupported', {
161
+ stage: 'approval'
162
+ });
163
+ }
164
+ checkApproval();
165
+ } else if (message.type === 'watch.session.event') {
166
+ const payload = message.event?.payload;
167
+ if (
168
+ (payload?.sessionId ?? payload?.run?.sessionId) === sessionId &&
169
+ payload?.progress?.runId === runId
170
+ )
171
+ progress = payload.progress;
172
+ check(payload?.run);
173
+ checkApproval();
174
+ }
175
+ if (!settled && message.expiresAt !== undefined) scheduleRenewal(message.expiresAt);
176
+ };
177
+ const onClose = (code, reason) => {
178
+ if (code === 1008 && String(reason) === 'UNAUTHENTICATED')
179
+ fail('UNAUTHENTICATED', 'errors.userContextUnavailable', {
180
+ statusCode: 401,
181
+ stage: 'connection'
182
+ });
183
+ else
184
+ unknown(
185
+ 'connection',
186
+ Number.isInteger(code)
187
+ ? `The Watch connection closed (code ${code}).`
188
+ : 'The Watch connection closed.'
189
+ );
190
+ };
191
+ const onError = (error) =>
192
+ unknown('connection', 'The Watch connection failed.', { code: error?.code });
193
+ const onOpen = () => {
194
+ try {
195
+ socket.send(JSON.stringify({ type: 'resume' }));
196
+ } catch (error) {
197
+ onError(error);
198
+ }
199
+ };
200
+ const onAbort = () =>
201
+ fail('MARCTL_WAIT_CANCELLED', 'errors.sessionWaitCancelled', { stage: 'cancel' });
202
+ try {
203
+ socket = client.openWorkbenchWebSocket(WebSocketClass ?? (await import('ws')).default);
204
+ } catch (error) {
205
+ if (error instanceof MarctlError) reject(error, 'connection');
206
+ else unknown('connection', 'The Watch connection could not be opened.');
207
+ return await result;
208
+ }
209
+ const timer = setTimeout(
210
+ () => fail('MARCTL_WAIT_TIMEOUT', 'errors.sessionWaitTimeout', { stage: 'timeout' }),
211
+ timeoutMs
212
+ );
213
+ socket.on('open', onOpen);
214
+ socket.on('message', onMessage);
215
+ socket.on('error', onError);
216
+ socket.on('close', onClose);
217
+ signal?.addEventListener('abort', onAbort, { once: true });
218
+ if (signal?.aborted) onAbort();
219
+ try {
220
+ return await result;
221
+ } finally {
222
+ settled = true;
223
+ clearTimeout(timer);
224
+ clearTimeout(renewal);
225
+ signal?.removeEventListener('abort', onAbort);
226
+ if (subscribed) await command('stop').catch(() => undefined);
227
+ socket.off('open', onOpen);
228
+ socket.off('message', onMessage);
229
+ socket.off('close', onClose);
230
+ socket.close();
231
+ }
232
+ }