@yu_robotics/remote-cli 1.6.231 → 1.6.232
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.
- package/dist/client/MessageHandler.d.ts +14 -0
- package/dist/client/MessageHandler.d.ts.map +1 -1
- package/dist/client/MessageHandler.js +230 -0
- package/dist/client/MessageHandler.js.map +1 -1
- package/dist/client/WebSocketClient.d.ts +4 -1
- package/dist/client/WebSocketClient.d.ts.map +1 -1
- package/dist/client/WebSocketClient.js +37 -3
- package/dist/client/WebSocketClient.js.map +1 -1
- package/dist/maintenance/release-notes.json +1 -1
- package/dist/scheduling/ClaudeNativeScheduleProvider.d.ts +19 -0
- package/dist/scheduling/ClaudeNativeScheduleProvider.d.ts.map +1 -0
- package/dist/scheduling/ClaudeNativeScheduleProvider.js +570 -0
- package/dist/scheduling/ClaudeNativeScheduleProvider.js.map +1 -0
- package/dist/scheduling/DshNativeScheduleProvider.d.ts +19 -0
- package/dist/scheduling/DshNativeScheduleProvider.d.ts.map +1 -0
- package/dist/scheduling/DshNativeScheduleProvider.js +470 -0
- package/dist/scheduling/DshNativeScheduleProvider.js.map +1 -0
- package/dist/scheduling/ScheduleCapabilities.d.ts +53 -0
- package/dist/scheduling/ScheduleCapabilities.d.ts.map +1 -0
- package/dist/scheduling/ScheduleCapabilities.js +65 -0
- package/dist/scheduling/ScheduleCapabilities.js.map +1 -0
- package/dist/scheduling/ScheduleCommand.d.ts +27 -0
- package/dist/scheduling/ScheduleCommand.d.ts.map +1 -0
- package/dist/scheduling/ScheduleCommand.js +173 -0
- package/dist/scheduling/ScheduleCommand.js.map +1 -0
- package/dist/scheduling/ScheduleDeliveryClient.d.ts +17 -0
- package/dist/scheduling/ScheduleDeliveryClient.d.ts.map +1 -0
- package/dist/scheduling/ScheduleDeliveryClient.js +109 -0
- package/dist/scheduling/ScheduleDeliveryClient.js.map +1 -0
- package/dist/scheduling/ScheduleService.d.ts +73 -0
- package/dist/scheduling/ScheduleService.d.ts.map +1 -0
- package/dist/scheduling/ScheduleService.js +742 -0
- package/dist/scheduling/ScheduleService.js.map +1 -0
- package/dist/scheduling/claude/rules.d.ts +8 -0
- package/dist/scheduling/claude/rules.d.ts.map +1 -0
- package/dist/scheduling/claude/rules.js +46 -0
- package/dist/scheduling/claude/rules.js.map +1 -0
- package/dist/scheduling/dsh/HostBridge.d.ts +96 -0
- package/dist/scheduling/dsh/HostBridge.d.ts.map +1 -0
- package/dist/scheduling/dsh/HostBridge.js +364 -0
- package/dist/scheduling/dsh/HostBridge.js.map +1 -0
- package/dist/scheduling/dsh/ScopePlugin.d.ts +9 -0
- package/dist/scheduling/dsh/ScopePlugin.d.ts.map +1 -0
- package/dist/scheduling/dsh/ScopePlugin.js +13 -0
- package/dist/scheduling/dsh/ScopePlugin.js.map +1 -0
- package/dist/scheduling/dsh/launch.d.ts +13 -0
- package/dist/scheduling/dsh/launch.d.ts.map +1 -0
- package/dist/scheduling/dsh/launch.js +58 -0
- package/dist/scheduling/dsh/launch.js.map +1 -0
- package/dist/scheduling/dsh/protocol.d.ts +28 -0
- package/dist/scheduling/dsh/protocol.d.ts.map +1 -0
- package/dist/scheduling/dsh/protocol.js +142 -0
- package/dist/scheduling/dsh/protocol.js.map +1 -0
- package/dist/scheduling/types.d.ts +79 -0
- package/dist/scheduling/types.d.ts.map +1 -0
- package/dist/scheduling/types.js +13 -0
- package/dist/scheduling/types.js.map +1 -0
- package/dist/types/index.d.ts +4 -0
- package/dist/types/index.d.ts.map +1 -1
- package/native/prebuilds/darwin-arm64/managed_native.node +0 -0
- package/native/prebuilds/darwin-arm64/manifest.json +1 -1
- package/native/prebuilds/darwin-x64/managed_native.node +0 -0
- package/native/prebuilds/darwin-x64/manifest.json +1 -1
- package/native/prebuilds/win32-arm64/managed_native.node +0 -0
- package/native/prebuilds/win32-arm64/manifest.json +1 -1
- package/native/prebuilds/win32-x64/managed_native.node +0 -0
- package/native/prebuilds/win32-x64/manifest.json +1 -1
- package/package.json +1 -1
|
@@ -0,0 +1,742 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
|
|
3
|
+
if (k2 === undefined) k2 = k;
|
|
4
|
+
var desc = Object.getOwnPropertyDescriptor(m, k);
|
|
5
|
+
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
|
|
6
|
+
desc = { enumerable: true, get: function() { return m[k]; } };
|
|
7
|
+
}
|
|
8
|
+
Object.defineProperty(o, k2, desc);
|
|
9
|
+
}) : (function(o, m, k, k2) {
|
|
10
|
+
if (k2 === undefined) k2 = k;
|
|
11
|
+
o[k2] = m[k];
|
|
12
|
+
}));
|
|
13
|
+
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
|
|
14
|
+
Object.defineProperty(o, "default", { enumerable: true, value: v });
|
|
15
|
+
}) : function(o, v) {
|
|
16
|
+
o["default"] = v;
|
|
17
|
+
});
|
|
18
|
+
var __importStar = (this && this.__importStar) || (function () {
|
|
19
|
+
var ownKeys = function(o) {
|
|
20
|
+
ownKeys = Object.getOwnPropertyNames || function (o) {
|
|
21
|
+
var ar = [];
|
|
22
|
+
for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
|
|
23
|
+
return ar;
|
|
24
|
+
};
|
|
25
|
+
return ownKeys(o);
|
|
26
|
+
};
|
|
27
|
+
return function (mod) {
|
|
28
|
+
if (mod && mod.__esModule) return mod;
|
|
29
|
+
var result = {};
|
|
30
|
+
if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
|
|
31
|
+
__setModuleDefault(result, mod);
|
|
32
|
+
return result;
|
|
33
|
+
};
|
|
34
|
+
})();
|
|
35
|
+
var __importDefault = (this && this.__importDefault) || function (mod) {
|
|
36
|
+
return (mod && mod.__esModule) ? mod : { "default": mod };
|
|
37
|
+
};
|
|
38
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
39
|
+
exports.ScheduleService = exports.SCHEDULE_CATALOG_FILE = void 0;
|
|
40
|
+
const node_fs_1 = require("node:fs");
|
|
41
|
+
const fs = __importStar(require("node:fs/promises"));
|
|
42
|
+
const node_path_1 = __importDefault(require("node:path"));
|
|
43
|
+
const node_crypto_1 = require("node:crypto");
|
|
44
|
+
const ScheduleCommand_1 = require("./ScheduleCommand");
|
|
45
|
+
const types_1 = require("./types");
|
|
46
|
+
const ScheduleCapabilities_1 = require("./ScheduleCapabilities");
|
|
47
|
+
exports.SCHEDULE_CATALOG_FILE = 'schedule-catalog.json';
|
|
48
|
+
const OUTPUT_BYTES = 16 * 1024;
|
|
49
|
+
const ERROR_BYTES = 4096;
|
|
50
|
+
const LIVE = new Set(['creating', 'active', 'running']);
|
|
51
|
+
const STATES = new Set([...LIVE, 'completed', 'cancelled', 'interrupted', 'failed']);
|
|
52
|
+
const RESTART_REASON = 'Native schedule interrupted by service restart; not recreated or resumed.';
|
|
53
|
+
function bounded(value, limit) {
|
|
54
|
+
if (Buffer.byteLength(value, 'utf8') <= limit)
|
|
55
|
+
return value;
|
|
56
|
+
const marker = '\n[Truncated]';
|
|
57
|
+
return Buffer.from(value).subarray(0, limit - Buffer.byteLength(marker)).toString('utf8').replace(/\uFFFD$/, '') + marker;
|
|
58
|
+
}
|
|
59
|
+
function errorText(error) {
|
|
60
|
+
return bounded(error instanceof Error ? error.message : 'Native schedule operation failed.', ERROR_BYTES);
|
|
61
|
+
}
|
|
62
|
+
function object(value, keys) {
|
|
63
|
+
if (!value || typeof value !== 'object' || Array.isArray(value)
|
|
64
|
+
|| Object.keys(value).some(key => !keys.includes(key)))
|
|
65
|
+
throw new Error('Invalid schedule catalog object.');
|
|
66
|
+
return value;
|
|
67
|
+
}
|
|
68
|
+
function text(value, max = 256) {
|
|
69
|
+
if (typeof value !== 'string' || !value.trim() || /[\x00-\x1f\x7f]/.test(value)
|
|
70
|
+
|| Buffer.byteLength(value) > max)
|
|
71
|
+
throw new Error('Invalid schedule identifier or path.');
|
|
72
|
+
}
|
|
73
|
+
function ownerOf(record) {
|
|
74
|
+
return { threadId: record.threadId, openId: record.openId, generation: record.generation };
|
|
75
|
+
}
|
|
76
|
+
function validateOwner(owner) {
|
|
77
|
+
if (!owner || typeof owner !== 'object')
|
|
78
|
+
throw new Error('Invalid schedule owner.');
|
|
79
|
+
text(owner.threadId);
|
|
80
|
+
text(owner.openId);
|
|
81
|
+
text(owner.generation);
|
|
82
|
+
}
|
|
83
|
+
function sameOwner(left, right) {
|
|
84
|
+
return left.threadId === right.threadId && left.openId === right.openId && left.generation === right.generation;
|
|
85
|
+
}
|
|
86
|
+
function deliveryId(scheduleId, occurrenceId) {
|
|
87
|
+
return `${scheduleId}:${occurrenceId}`;
|
|
88
|
+
}
|
|
89
|
+
/**
|
|
90
|
+
* Single service instance per directory. Native processes, never this service, own timing.
|
|
91
|
+
* Delivery is fenced immediately before invoking the callback; an external send already
|
|
92
|
+
* in flight cannot be revoked. A crash between sending and persisting acknowledgement
|
|
93
|
+
* can replay an outbox entry after explicit reconnect. Consumers receive a stable ID.
|
|
94
|
+
*/
|
|
95
|
+
class ScheduleService {
|
|
96
|
+
options;
|
|
97
|
+
maxLive;
|
|
98
|
+
maxRecords;
|
|
99
|
+
maxPending;
|
|
100
|
+
maxOccurrences;
|
|
101
|
+
now;
|
|
102
|
+
records = new Map();
|
|
103
|
+
pending = new Map();
|
|
104
|
+
runtimes = new Map();
|
|
105
|
+
tail = Promise.resolve();
|
|
106
|
+
deliveryTail = Promise.resolve();
|
|
107
|
+
tasks = new Set();
|
|
108
|
+
operations = new Set();
|
|
109
|
+
initialization;
|
|
110
|
+
initialized = false;
|
|
111
|
+
closing = false;
|
|
112
|
+
destruction;
|
|
113
|
+
fault;
|
|
114
|
+
catalogPath = '';
|
|
115
|
+
constructor(options) {
|
|
116
|
+
this.options = { ...options };
|
|
117
|
+
this.now = options.now ?? Date.now;
|
|
118
|
+
const limit = (value, fallback, ceiling) => {
|
|
119
|
+
const result = value ?? fallback;
|
|
120
|
+
if (!Number.isInteger(result) || result < 1 || result > ceiling)
|
|
121
|
+
throw new Error('Invalid schedule capacity.');
|
|
122
|
+
return result;
|
|
123
|
+
};
|
|
124
|
+
this.maxLive = limit(options.maxLiveSchedules, 5, 5);
|
|
125
|
+
this.maxRecords = limit(options.maxRecords, 100, 1000);
|
|
126
|
+
this.maxPending = limit(options.maxPendingDeliveries, 100, 1000);
|
|
127
|
+
this.maxOccurrences = limit(options.maxOccurrencesPerSchedule, 1000, 10_000);
|
|
128
|
+
}
|
|
129
|
+
initialize() {
|
|
130
|
+
if (this.closing)
|
|
131
|
+
return Promise.reject(new Error('Schedule service is closed.'));
|
|
132
|
+
return this.initialization ??= this.serial(async () => {
|
|
133
|
+
await fs.mkdir(this.options.directory, { recursive: true, mode: 0o700 });
|
|
134
|
+
const directory = await fs.realpath(this.options.directory);
|
|
135
|
+
this.catalogPath = node_path_1.default.join(directory, exports.SCHEDULE_CATALOG_FILE);
|
|
136
|
+
const data = await this.readCatalog();
|
|
137
|
+
if (data !== undefined)
|
|
138
|
+
this.load(data);
|
|
139
|
+
let changed = false;
|
|
140
|
+
for (const record of this.records.values()) {
|
|
141
|
+
if (LIVE.has(record.state)) {
|
|
142
|
+
record.state = 'interrupted';
|
|
143
|
+
record.error = RESTART_REASON;
|
|
144
|
+
changed = true;
|
|
145
|
+
}
|
|
146
|
+
}
|
|
147
|
+
for (const [id, delivery] of this.pending) {
|
|
148
|
+
const record = this.records.get(delivery.scheduleId);
|
|
149
|
+
if (record.state === 'cancelled' || !this.current(record)) {
|
|
150
|
+
this.pending.delete(id);
|
|
151
|
+
changed = true;
|
|
152
|
+
}
|
|
153
|
+
}
|
|
154
|
+
if (changed || data === undefined)
|
|
155
|
+
await this.persist();
|
|
156
|
+
this.initialized = true;
|
|
157
|
+
});
|
|
158
|
+
}
|
|
159
|
+
create(owner, input) {
|
|
160
|
+
return this.operation(this.createSchedule(owner, input));
|
|
161
|
+
}
|
|
162
|
+
async createSchedule(owner, input) {
|
|
163
|
+
this.checkReady();
|
|
164
|
+
const backend = input.backend === undefined ? 'claude' : input.backend;
|
|
165
|
+
(0, ScheduleCapabilities_1.assertNativeScheduleBackend)(backend);
|
|
166
|
+
const createdAt = this.now();
|
|
167
|
+
if (!Number.isSafeInteger(createdAt) || createdAt < 0)
|
|
168
|
+
throw new Error('Invalid schedule clock.');
|
|
169
|
+
validateOwner(owner);
|
|
170
|
+
(0, ScheduleCommand_1.validateScheduleId)(input.id);
|
|
171
|
+
(0, ScheduleCommand_1.validateSchedulePrompt)(input.prompt);
|
|
172
|
+
(0, ScheduleCommand_1.validateScheduleRule)(input.rule, createdAt);
|
|
173
|
+
text(input.cwd, 4096);
|
|
174
|
+
if (!node_path_1.default.isAbsolute(input.cwd))
|
|
175
|
+
throw new Error('Schedule working directory must be absolute.');
|
|
176
|
+
const originalOwner = ownerOf(owner);
|
|
177
|
+
const nativeInput = { ...structuredClone(input), backend };
|
|
178
|
+
const runtime = this.newRuntime();
|
|
179
|
+
await this.serial(async () => {
|
|
180
|
+
this.checkReady();
|
|
181
|
+
if (!this.current(originalOwner))
|
|
182
|
+
throw new Error('Schedule owner is no longer current.');
|
|
183
|
+
if (this.records.has(nativeInput.id))
|
|
184
|
+
throw new Error('Schedule ID already exists.');
|
|
185
|
+
if (this.records.size >= this.maxRecords)
|
|
186
|
+
throw new Error('Schedule catalog is full; history was not pruned.');
|
|
187
|
+
const liveCount = [...this.records.values()].filter(record => LIVE.has(record.state)
|
|
188
|
+
|| (this.runtimes.has(record.id) && !this.runtimes.get(record.id).stopped)).length;
|
|
189
|
+
if (liveCount >= this.maxLive)
|
|
190
|
+
throw new Error('Live native schedule limit reached.');
|
|
191
|
+
this.records.set(nativeInput.id, { ...originalOwner, id: nativeInput.id, backend,
|
|
192
|
+
cwd: nativeInput.cwd, prompt: nativeInput.prompt, rule: structuredClone(nativeInput.rule),
|
|
193
|
+
createdAt, state: 'creating' });
|
|
194
|
+
await this.persist();
|
|
195
|
+
this.runtimes.set(nativeInput.id, runtime);
|
|
196
|
+
});
|
|
197
|
+
try {
|
|
198
|
+
const handle = await this.options.provider.create(structuredClone(nativeInput), event => {
|
|
199
|
+
const task = this.onEvent(nativeInput.id, structuredClone(event));
|
|
200
|
+
this.track(task);
|
|
201
|
+
});
|
|
202
|
+
runtime.handle = handle;
|
|
203
|
+
runtime.resolveReady(handle);
|
|
204
|
+
text(handle.nativeId);
|
|
205
|
+
await this.serial(async () => {
|
|
206
|
+
const record = this.records.get(nativeInput.id);
|
|
207
|
+
record.nativeId = handle.nativeId;
|
|
208
|
+
const ownerCurrent = this.current(originalOwner);
|
|
209
|
+
if (this.closing || !ownerCurrent) {
|
|
210
|
+
if (LIVE.has(record.state)) {
|
|
211
|
+
record.state = 'interrupted';
|
|
212
|
+
record.error = 'Schedule owner or service retired during creation.';
|
|
213
|
+
}
|
|
214
|
+
if (!ownerCurrent)
|
|
215
|
+
this.dropPending(record.id);
|
|
216
|
+
}
|
|
217
|
+
else if (record.state === 'creating')
|
|
218
|
+
record.state = 'active';
|
|
219
|
+
await this.persist();
|
|
220
|
+
});
|
|
221
|
+
const record = this.records.get(nativeInput.id);
|
|
222
|
+
if (!LIVE.has(record.state) && !runtime.cancelling)
|
|
223
|
+
await this.stop(nativeInput.id, runtime);
|
|
224
|
+
return structuredClone(this.records.get(nativeInput.id));
|
|
225
|
+
}
|
|
226
|
+
catch (error) {
|
|
227
|
+
if (error instanceof types_1.NativeScheduleCleanupError)
|
|
228
|
+
runtime.handle = error.handle;
|
|
229
|
+
runtime.resolveReady(runtime.handle);
|
|
230
|
+
await this.serial(async () => {
|
|
231
|
+
const record = this.records.get(nativeInput.id);
|
|
232
|
+
if (LIVE.has(record.state)) {
|
|
233
|
+
record.state = 'failed';
|
|
234
|
+
record.error = errorText(error);
|
|
235
|
+
}
|
|
236
|
+
if (!this.fault)
|
|
237
|
+
await this.persist();
|
|
238
|
+
});
|
|
239
|
+
if (runtime.handle)
|
|
240
|
+
await this.stop(nativeInput.id, runtime).catch(() => { });
|
|
241
|
+
else
|
|
242
|
+
runtime.stopped = true;
|
|
243
|
+
throw error;
|
|
244
|
+
}
|
|
245
|
+
}
|
|
246
|
+
/** Catalog lookup only; this does not probe or recreate native jobs. */
|
|
247
|
+
async list(owner) {
|
|
248
|
+
this.checkReady();
|
|
249
|
+
validateOwner(owner);
|
|
250
|
+
return this.serial(async () => [...this.records.values()].filter(record => sameOwner(record, owner)).map(record => structuredClone(record)));
|
|
251
|
+
}
|
|
252
|
+
/** Includes terminal jobs whose native process exit is still unconfirmed. */
|
|
253
|
+
hasActiveSchedules(threadId) {
|
|
254
|
+
return [...this.records.values()].some(record => (!threadId || record.threadId === threadId)
|
|
255
|
+
&& (LIVE.has(record.state) || (this.runtimes.has(record.id) && !this.runtimes.get(record.id).stopped)));
|
|
256
|
+
}
|
|
257
|
+
/** User-requested native reconciliation only; no background polling is installed. */
|
|
258
|
+
refresh(owner) {
|
|
259
|
+
return this.operation(this.refreshNative(owner));
|
|
260
|
+
}
|
|
261
|
+
async refreshNative(owner) {
|
|
262
|
+
this.checkReady();
|
|
263
|
+
validateOwner(owner);
|
|
264
|
+
const candidates = await this.serial(async () => [...this.records.values()]
|
|
265
|
+
.filter(record => sameOwner(record, owner)).map(record => record.id));
|
|
266
|
+
await Promise.all(candidates.map(async (id) => {
|
|
267
|
+
const runtime = this.runtimes.get(id);
|
|
268
|
+
if (!runtime?.handle || runtime.stopped || runtime.cancelling || runtime.running.size || !this.current(owner))
|
|
269
|
+
return;
|
|
270
|
+
if (!LIVE.has(this.records.get(id).state)) {
|
|
271
|
+
await this.stop(id, runtime);
|
|
272
|
+
return;
|
|
273
|
+
}
|
|
274
|
+
try {
|
|
275
|
+
const present = await runtime.handle.list();
|
|
276
|
+
if (present)
|
|
277
|
+
return;
|
|
278
|
+
await this.serial(async () => {
|
|
279
|
+
const record = this.records.get(id);
|
|
280
|
+
if (LIVE.has(record.state)) {
|
|
281
|
+
record.state = 'interrupted';
|
|
282
|
+
record.error = 'Native schedule is no longer listed; execution completion is not confirmed.';
|
|
283
|
+
await this.persist();
|
|
284
|
+
}
|
|
285
|
+
});
|
|
286
|
+
await this.stop(id, runtime);
|
|
287
|
+
}
|
|
288
|
+
catch (error) {
|
|
289
|
+
await this.serial(async () => {
|
|
290
|
+
const record = this.records.get(id);
|
|
291
|
+
if (LIVE.has(record.state))
|
|
292
|
+
record.state = 'interrupted';
|
|
293
|
+
record.error = errorText(error);
|
|
294
|
+
if (!this.fault)
|
|
295
|
+
await this.persist();
|
|
296
|
+
});
|
|
297
|
+
await this.stop(id, runtime);
|
|
298
|
+
}
|
|
299
|
+
}));
|
|
300
|
+
}
|
|
301
|
+
cancel(owner, id) {
|
|
302
|
+
return this.operation(this.cancelSchedule(owner, id));
|
|
303
|
+
}
|
|
304
|
+
async cancelSchedule(owner, id) {
|
|
305
|
+
this.checkReady();
|
|
306
|
+
validateOwner(owner);
|
|
307
|
+
(0, ScheduleCommand_1.validateScheduleId)(id);
|
|
308
|
+
let runtime;
|
|
309
|
+
let existing;
|
|
310
|
+
let operation;
|
|
311
|
+
await this.serial(async () => {
|
|
312
|
+
const record = this.owned(owner, id);
|
|
313
|
+
runtime = this.runtimes.get(id);
|
|
314
|
+
if (runtime?.cancelPromise) {
|
|
315
|
+
existing = runtime.cancelPromise;
|
|
316
|
+
return;
|
|
317
|
+
}
|
|
318
|
+
if (!LIVE.has(record.state) && !runtime?.cancelling && (!runtime || runtime.stopped)) {
|
|
319
|
+
this.dropPending(id);
|
|
320
|
+
await this.persist();
|
|
321
|
+
operation = Promise.resolve(structuredClone(record));
|
|
322
|
+
return;
|
|
323
|
+
}
|
|
324
|
+
if (!runtime)
|
|
325
|
+
throw new Error('Native schedule handle is unavailable.');
|
|
326
|
+
runtime.cancelling = true;
|
|
327
|
+
// Starting outside the state queue also permits synchronous provider callbacks.
|
|
328
|
+
operation = Promise.resolve().then(() => this.cancelNative(id, runtime));
|
|
329
|
+
runtime.cancelPromise = operation;
|
|
330
|
+
});
|
|
331
|
+
return (existing ?? operation);
|
|
332
|
+
}
|
|
333
|
+
/** Explicit reconnect retry. No timer or periodic retry is installed. */
|
|
334
|
+
async retryDeliveries() {
|
|
335
|
+
this.checkReady();
|
|
336
|
+
const ids = await this.serial(async () => [...this.pending.keys()]);
|
|
337
|
+
await this.attemptDeliveries(ids);
|
|
338
|
+
}
|
|
339
|
+
destroy() {
|
|
340
|
+
if (this.destruction)
|
|
341
|
+
return this.destruction;
|
|
342
|
+
this.closing = true;
|
|
343
|
+
return this.destruction = (async () => {
|
|
344
|
+
await this.initialization?.catch(() => { });
|
|
345
|
+
let failure;
|
|
346
|
+
await this.serial(async () => {
|
|
347
|
+
for (const record of this.records.values()) {
|
|
348
|
+
if (LIVE.has(record.state)) {
|
|
349
|
+
record.state = 'interrupted';
|
|
350
|
+
record.error = 'Native schedule interrupted by service shutdown.';
|
|
351
|
+
}
|
|
352
|
+
}
|
|
353
|
+
if (this.initialized && !this.fault)
|
|
354
|
+
await this.persist();
|
|
355
|
+
}).catch(error => { failure = error; });
|
|
356
|
+
const stops = await Promise.allSettled([...this.runtimes].map(([id, runtime]) => this.stop(id, runtime)));
|
|
357
|
+
while (this.operations.size)
|
|
358
|
+
await Promise.allSettled([...this.operations]);
|
|
359
|
+
while (this.tasks.size)
|
|
360
|
+
await Promise.allSettled([...this.tasks]);
|
|
361
|
+
await this.deliveryTail;
|
|
362
|
+
await this.tail;
|
|
363
|
+
const rejected = stops.find((result) => result.status === 'rejected');
|
|
364
|
+
if (failure || rejected || this.fault)
|
|
365
|
+
throw failure ?? rejected?.reason ?? this.fault;
|
|
366
|
+
})().catch(error => {
|
|
367
|
+
// Keep admission closed and retain handles, but allow explicit cleanup retries.
|
|
368
|
+
this.destruction = undefined;
|
|
369
|
+
throw error;
|
|
370
|
+
});
|
|
371
|
+
}
|
|
372
|
+
async cancelNative(id, runtime) {
|
|
373
|
+
try {
|
|
374
|
+
const handle = await runtime.ready;
|
|
375
|
+
if (handle && !runtime.stopped) {
|
|
376
|
+
if (LIVE.has(this.records.get(id).state))
|
|
377
|
+
await handle.cancel();
|
|
378
|
+
else
|
|
379
|
+
await this.stop(id, runtime);
|
|
380
|
+
}
|
|
381
|
+
await this.serial(async () => {
|
|
382
|
+
const record = this.records.get(id);
|
|
383
|
+
record.state = 'cancelled';
|
|
384
|
+
delete record.error;
|
|
385
|
+
this.dropPending(id);
|
|
386
|
+
await this.persist();
|
|
387
|
+
});
|
|
388
|
+
runtime.cancelling = false;
|
|
389
|
+
runtime.heldDeliveries.clear();
|
|
390
|
+
await this.stop(id, runtime);
|
|
391
|
+
return structuredClone(this.records.get(id));
|
|
392
|
+
}
|
|
393
|
+
catch (error) {
|
|
394
|
+
runtime.cancelling = false;
|
|
395
|
+
await this.serial(async () => {
|
|
396
|
+
this.records.get(id).error = errorText(error);
|
|
397
|
+
if (!this.fault)
|
|
398
|
+
await this.persist();
|
|
399
|
+
});
|
|
400
|
+
if (!LIVE.has(this.records.get(id).state))
|
|
401
|
+
await this.stop(id, runtime).catch(() => { });
|
|
402
|
+
const ids = [...runtime.heldDeliveries];
|
|
403
|
+
runtime.heldDeliveries.clear();
|
|
404
|
+
await this.attemptDeliveries(ids, true);
|
|
405
|
+
throw error;
|
|
406
|
+
}
|
|
407
|
+
finally {
|
|
408
|
+
runtime.cancelPromise = undefined;
|
|
409
|
+
}
|
|
410
|
+
}
|
|
411
|
+
async onEvent(id, event) {
|
|
412
|
+
let delivery;
|
|
413
|
+
let cleanup = false;
|
|
414
|
+
const runtime = this.runtimes.get(id);
|
|
415
|
+
await this.serial(async () => {
|
|
416
|
+
if (this.fault)
|
|
417
|
+
throw this.fault;
|
|
418
|
+
const record = this.records.get(id);
|
|
419
|
+
// Process exit evidence is independent of task state, including late exit
|
|
420
|
+
// after a failed cancellation cleanup. Never downgrade confirmed exit.
|
|
421
|
+
if (event.type === 'stopped' && event.exitConfirmed !== false) {
|
|
422
|
+
runtime.stopped = true;
|
|
423
|
+
if (record.error?.startsWith('Native process exit unconfirmed:')) {
|
|
424
|
+
delete record.error;
|
|
425
|
+
await this.persist();
|
|
426
|
+
}
|
|
427
|
+
}
|
|
428
|
+
const ownerCurrent = this.current(record);
|
|
429
|
+
if (this.closing || !ownerCurrent) {
|
|
430
|
+
if (LIVE.has(record.state)) {
|
|
431
|
+
record.state = 'interrupted';
|
|
432
|
+
record.error = 'Schedule owner or service is no longer current.';
|
|
433
|
+
}
|
|
434
|
+
// Native stop notifications during shutdown must preserve completed outbox
|
|
435
|
+
// entries for restart. Only actual ownership invalidation discards them.
|
|
436
|
+
if (!ownerCurrent)
|
|
437
|
+
this.dropPending(id);
|
|
438
|
+
cleanup = true;
|
|
439
|
+
await this.persist();
|
|
440
|
+
return;
|
|
441
|
+
}
|
|
442
|
+
if (record.state === 'cancelled' || record.state === 'failed' || record.state === 'completed')
|
|
443
|
+
return;
|
|
444
|
+
if (event.type === 'stopped') {
|
|
445
|
+
if (LIVE.has(record.state)) {
|
|
446
|
+
record.state = 'interrupted';
|
|
447
|
+
record.error = bounded(event.reason, ERROR_BYTES);
|
|
448
|
+
}
|
|
449
|
+
}
|
|
450
|
+
else {
|
|
451
|
+
text(event.occurrenceId);
|
|
452
|
+
if (runtime.completed.has(event.occurrenceId))
|
|
453
|
+
return;
|
|
454
|
+
if (record.state === 'interrupted' && (event.type !== 'completed' || !runtime.running.has(event.occurrenceId)))
|
|
455
|
+
return;
|
|
456
|
+
if (runtime.completed.size + runtime.running.size >= this.maxOccurrences && !runtime.running.has(event.occurrenceId)) {
|
|
457
|
+
record.state = 'interrupted';
|
|
458
|
+
record.error = 'Occurrence tracking limit reached; native schedule stopped.';
|
|
459
|
+
cleanup = true;
|
|
460
|
+
}
|
|
461
|
+
else if (event.type === 'started') {
|
|
462
|
+
runtime.running.add(event.occurrenceId);
|
|
463
|
+
record.state = 'running';
|
|
464
|
+
}
|
|
465
|
+
else if (event.type === 'completed') {
|
|
466
|
+
if (typeof event.success !== 'boolean')
|
|
467
|
+
throw new Error('Invalid native completion event.');
|
|
468
|
+
runtime.running.delete(event.occurrenceId);
|
|
469
|
+
runtime.completed.add(event.occurrenceId);
|
|
470
|
+
if (this.pending.size >= this.maxPending) {
|
|
471
|
+
record.state = 'interrupted';
|
|
472
|
+
record.error = 'Delivery outbox is full; latest result could not be retained. Native schedule stopped.';
|
|
473
|
+
cleanup = true;
|
|
474
|
+
}
|
|
475
|
+
else {
|
|
476
|
+
delivery = deliveryId(id, event.occurrenceId);
|
|
477
|
+
this.pending.set(delivery, { id: delivery, scheduleId: id, occurrenceId: event.occurrenceId,
|
|
478
|
+
success: event.success, ...(event.output !== undefined && { output: bounded(event.output, OUTPUT_BYTES) }),
|
|
479
|
+
...(event.error !== undefined && { error: bounded(event.error, ERROR_BYTES) }) });
|
|
480
|
+
if (record.rule.kind === 'once') {
|
|
481
|
+
record.state = 'completed';
|
|
482
|
+
cleanup = true;
|
|
483
|
+
}
|
|
484
|
+
else if (record.state !== 'interrupted')
|
|
485
|
+
record.state = runtime.running.size ? 'running' : 'active';
|
|
486
|
+
}
|
|
487
|
+
}
|
|
488
|
+
else
|
|
489
|
+
throw new Error('Invalid native schedule event.');
|
|
490
|
+
}
|
|
491
|
+
await this.persist();
|
|
492
|
+
});
|
|
493
|
+
// Do not wait for a create handle before recording or delivering an early result.
|
|
494
|
+
// stop() records retryable exit failures itself. A cleanup timeout must not
|
|
495
|
+
// fault the entire service or prevent a later explicit cancellation retry.
|
|
496
|
+
// Persistence failures still set the service fault inside persist().
|
|
497
|
+
if (cleanup && !runtime.cancelling)
|
|
498
|
+
this.track(this.stop(id, runtime).catch(() => { }));
|
|
499
|
+
if (delivery)
|
|
500
|
+
await this.attemptDeliveries([delivery], true);
|
|
501
|
+
}
|
|
502
|
+
attemptDeliveries(ids, firstAttempt = false) {
|
|
503
|
+
const run = this.deliveryTail.then(async () => {
|
|
504
|
+
for (const id of ids) {
|
|
505
|
+
let delivery;
|
|
506
|
+
await this.serial(async () => {
|
|
507
|
+
if (this.closing || this.fault)
|
|
508
|
+
return;
|
|
509
|
+
const pending = this.pending.get(id);
|
|
510
|
+
if (!pending)
|
|
511
|
+
return;
|
|
512
|
+
const record = this.records.get(pending.scheduleId);
|
|
513
|
+
if (!this.current(record) || record.state === 'cancelled') {
|
|
514
|
+
this.pending.delete(id);
|
|
515
|
+
await this.persist();
|
|
516
|
+
return;
|
|
517
|
+
}
|
|
518
|
+
const runtime = this.runtimes.get(record.id);
|
|
519
|
+
if (runtime?.cancelling) {
|
|
520
|
+
if (firstAttempt)
|
|
521
|
+
runtime.heldDeliveries.add(id);
|
|
522
|
+
return;
|
|
523
|
+
}
|
|
524
|
+
delivery = { id, schedule: structuredClone(record), occurrenceId: pending.occurrenceId,
|
|
525
|
+
success: pending.success, ...(pending.output !== undefined && { output: pending.output }),
|
|
526
|
+
...(pending.error !== undefined && { error: pending.error }) };
|
|
527
|
+
});
|
|
528
|
+
if (!delivery || this.closing || !this.current(delivery.schedule) || !this.pending.has(id))
|
|
529
|
+
continue;
|
|
530
|
+
const runtime = this.runtimes.get(delivery.schedule.id);
|
|
531
|
+
if (runtime?.cancelling) {
|
|
532
|
+
if (firstAttempt)
|
|
533
|
+
runtime.heldDeliveries.add(id);
|
|
534
|
+
continue;
|
|
535
|
+
}
|
|
536
|
+
try {
|
|
537
|
+
await this.options.deliver(delivery);
|
|
538
|
+
}
|
|
539
|
+
catch {
|
|
540
|
+
continue;
|
|
541
|
+
} // Keep the persisted outbox; only explicit reconnect retries it.
|
|
542
|
+
await this.serial(async () => { this.pending.delete(id); await this.persist(); });
|
|
543
|
+
}
|
|
544
|
+
});
|
|
545
|
+
this.deliveryTail = run.catch(() => { });
|
|
546
|
+
return run;
|
|
547
|
+
}
|
|
548
|
+
stop(id, runtime) {
|
|
549
|
+
if (runtime.stopped)
|
|
550
|
+
return Promise.resolve();
|
|
551
|
+
if (runtime.stopPromise)
|
|
552
|
+
return runtime.stopPromise;
|
|
553
|
+
const operation = (async () => {
|
|
554
|
+
try {
|
|
555
|
+
const handle = await runtime.ready;
|
|
556
|
+
if (handle && !runtime.stopped)
|
|
557
|
+
await handle.stop();
|
|
558
|
+
runtime.stopped = true;
|
|
559
|
+
}
|
|
560
|
+
catch (error) {
|
|
561
|
+
await this.serial(async () => {
|
|
562
|
+
this.records.get(id).error = `Native process exit unconfirmed: ${errorText(error)}`.slice(0, ERROR_BYTES / 4);
|
|
563
|
+
if (!this.fault)
|
|
564
|
+
await this.persist();
|
|
565
|
+
});
|
|
566
|
+
throw error;
|
|
567
|
+
}
|
|
568
|
+
})();
|
|
569
|
+
runtime.stopPromise = operation;
|
|
570
|
+
void operation.catch(() => { runtime.stopPromise = undefined; });
|
|
571
|
+
return operation;
|
|
572
|
+
}
|
|
573
|
+
newRuntime() {
|
|
574
|
+
let resolveReady;
|
|
575
|
+
const ready = new Promise(resolve => { resolveReady = resolve; });
|
|
576
|
+
return { ready, resolveReady, running: new Set(), completed: new Set(), heldDeliveries: new Set(), cancelling: false, stopped: false };
|
|
577
|
+
}
|
|
578
|
+
track(task) {
|
|
579
|
+
this.tasks.add(task);
|
|
580
|
+
void task.catch(error => {
|
|
581
|
+
// Persistence/protocol failures fail closed and stop native producers.
|
|
582
|
+
this.fault ??= error instanceof Error ? error : new Error('Schedule service failed.');
|
|
583
|
+
for (const [id, runtime] of this.runtimes)
|
|
584
|
+
void this.stop(id, runtime).catch(() => { });
|
|
585
|
+
}).finally(() => this.tasks.delete(task));
|
|
586
|
+
}
|
|
587
|
+
operation(task) {
|
|
588
|
+
this.operations.add(task);
|
|
589
|
+
void task.finally(() => this.operations.delete(task)).catch(() => { });
|
|
590
|
+
return task;
|
|
591
|
+
}
|
|
592
|
+
current(owner) {
|
|
593
|
+
try {
|
|
594
|
+
return this.options.isOwnerCurrent(ownerOf(owner)) === true;
|
|
595
|
+
}
|
|
596
|
+
catch {
|
|
597
|
+
return false;
|
|
598
|
+
}
|
|
599
|
+
}
|
|
600
|
+
owned(owner, id) {
|
|
601
|
+
const record = this.records.get(id);
|
|
602
|
+
if (!record || !sameOwner(record, owner))
|
|
603
|
+
throw new Error('Schedule not found for this owner.');
|
|
604
|
+
return record;
|
|
605
|
+
}
|
|
606
|
+
dropPending(id) {
|
|
607
|
+
for (const [key, item] of this.pending)
|
|
608
|
+
if (item.scheduleId === id)
|
|
609
|
+
this.pending.delete(key);
|
|
610
|
+
}
|
|
611
|
+
checkReady() {
|
|
612
|
+
if (this.fault)
|
|
613
|
+
throw this.fault;
|
|
614
|
+
if (!this.initialized || this.closing)
|
|
615
|
+
throw new Error('Schedule service is not initialized or is closed.');
|
|
616
|
+
}
|
|
617
|
+
serial(operation) {
|
|
618
|
+
const task = this.tail.then(operation);
|
|
619
|
+
this.tail = task.catch(() => { });
|
|
620
|
+
return task;
|
|
621
|
+
}
|
|
622
|
+
async readCatalog() {
|
|
623
|
+
let handle;
|
|
624
|
+
try {
|
|
625
|
+
const stat = await fs.lstat(this.catalogPath);
|
|
626
|
+
if (!stat.isFile() || stat.isSymbolicLink())
|
|
627
|
+
throw new Error('Schedule catalog must be a regular file, not a symlink.');
|
|
628
|
+
handle = await fs.open(this.catalogPath, node_fs_1.constants.O_RDONLY | (node_fs_1.constants.O_NOFOLLOW ?? 0));
|
|
629
|
+
}
|
|
630
|
+
catch (error) {
|
|
631
|
+
if (error.code === 'ENOENT')
|
|
632
|
+
return undefined;
|
|
633
|
+
throw error;
|
|
634
|
+
}
|
|
635
|
+
try {
|
|
636
|
+
// JSON can expand one control byte to six bytes (for example, "\\u0001").
|
|
637
|
+
const maxBytes = (this.maxRecords + this.maxPending) * (160 * 1024) + 4096;
|
|
638
|
+
const size = (await handle.stat()).size;
|
|
639
|
+
if (size > maxBytes)
|
|
640
|
+
throw new Error('Schedule catalog exceeds its size limit.');
|
|
641
|
+
const buffer = Buffer.alloc(size + 1);
|
|
642
|
+
let length = 0;
|
|
643
|
+
while (length < buffer.length) {
|
|
644
|
+
const { bytesRead } = await handle.read(buffer, length, buffer.length - length, null);
|
|
645
|
+
if (!bytesRead)
|
|
646
|
+
break;
|
|
647
|
+
length += bytesRead;
|
|
648
|
+
}
|
|
649
|
+
if (length > maxBytes)
|
|
650
|
+
throw new Error('Schedule catalog exceeds its size limit.');
|
|
651
|
+
return JSON.parse(buffer.subarray(0, length).toString('utf8'), (key, value) => {
|
|
652
|
+
if (['__proto__', 'constructor', 'prototype'].includes(key))
|
|
653
|
+
throw new Error('Unsafe schedule catalog key.');
|
|
654
|
+
return value;
|
|
655
|
+
});
|
|
656
|
+
}
|
|
657
|
+
finally {
|
|
658
|
+
await handle.close();
|
|
659
|
+
}
|
|
660
|
+
}
|
|
661
|
+
load(data) {
|
|
662
|
+
const catalog = object(data, ['version', 'records', 'pending']);
|
|
663
|
+
if (catalog.version !== 1 || !Array.isArray(catalog.records) || catalog.records.length > this.maxRecords
|
|
664
|
+
|| !Array.isArray(catalog.pending) || catalog.pending.length > this.maxPending)
|
|
665
|
+
throw new Error('Invalid schedule catalog envelope.');
|
|
666
|
+
const records = new Map();
|
|
667
|
+
const pending = new Map();
|
|
668
|
+
for (const value of catalog.records) {
|
|
669
|
+
const record = object(value, ['id', 'backend', 'cwd', 'prompt', 'rule', 'createdAt', 'nativeId', 'state', 'error', 'threadId', 'openId', 'generation']);
|
|
670
|
+
(0, ScheduleCommand_1.validateScheduleId)(record.id);
|
|
671
|
+
validateOwner(record);
|
|
672
|
+
(0, ScheduleCommand_1.validateSchedulePrompt)(record.prompt);
|
|
673
|
+
text(record.cwd, 4096);
|
|
674
|
+
if (!node_path_1.default.isAbsolute(record.cwd) || !(0, ScheduleCapabilities_1.isNativeScheduleBackend)(record.backend) || !STATES.has(record.state)
|
|
675
|
+
|| typeof record.createdAt !== 'number' || !Number.isSafeInteger(record.createdAt) || record.createdAt < 0
|
|
676
|
+
|| records.has(record.id))
|
|
677
|
+
throw new Error('Invalid schedule catalog record.');
|
|
678
|
+
if (record.nativeId !== undefined)
|
|
679
|
+
text(record.nativeId);
|
|
680
|
+
if (record.error !== undefined && (typeof record.error !== 'string' || Buffer.byteLength(record.error) > ERROR_BYTES))
|
|
681
|
+
throw new Error('Invalid schedule error.');
|
|
682
|
+
const rule = object(record.rule, ['kind', 'at', 'expression', 'timezone']);
|
|
683
|
+
if (rule.kind === 'once')
|
|
684
|
+
object(rule, ['kind', 'at']);
|
|
685
|
+
else
|
|
686
|
+
object(rule, ['kind', 'expression', 'timezone']);
|
|
687
|
+
(0, ScheduleCommand_1.validateScheduleRule)(rule);
|
|
688
|
+
records.set(record.id, structuredClone(record));
|
|
689
|
+
}
|
|
690
|
+
for (const value of catalog.pending) {
|
|
691
|
+
const item = object(value, ['id', 'scheduleId', 'occurrenceId', 'success', 'output', 'error']);
|
|
692
|
+
(0, ScheduleCommand_1.validateScheduleId)(item.scheduleId);
|
|
693
|
+
text(item.occurrenceId);
|
|
694
|
+
if (item.id !== deliveryId(item.scheduleId, item.occurrenceId) || !records.has(item.scheduleId)
|
|
695
|
+
|| pending.has(item.id) || typeof item.success !== 'boolean')
|
|
696
|
+
throw new Error('Invalid pending schedule delivery.');
|
|
697
|
+
for (const [field, limit] of [['output', OUTPUT_BYTES], ['error', ERROR_BYTES]]) {
|
|
698
|
+
if (item[field] !== undefined && (typeof item[field] !== 'string' || Buffer.byteLength(item[field]) > limit))
|
|
699
|
+
throw new Error('Invalid delivery text.');
|
|
700
|
+
}
|
|
701
|
+
pending.set(item.id, structuredClone(item));
|
|
702
|
+
}
|
|
703
|
+
this.records = records;
|
|
704
|
+
this.pending = pending;
|
|
705
|
+
}
|
|
706
|
+
async persist() {
|
|
707
|
+
if (this.fault)
|
|
708
|
+
throw this.fault;
|
|
709
|
+
const temporary = node_path_1.default.join(node_path_1.default.dirname(this.catalogPath), `.schedule-${(0, node_crypto_1.randomUUID)()}.tmp`);
|
|
710
|
+
try {
|
|
711
|
+
try {
|
|
712
|
+
const stat = await fs.lstat(this.catalogPath);
|
|
713
|
+
if (!stat.isFile() || stat.isSymbolicLink())
|
|
714
|
+
throw new Error('Schedule catalog is not a regular file.');
|
|
715
|
+
}
|
|
716
|
+
catch (error) {
|
|
717
|
+
if (error.code !== 'ENOENT')
|
|
718
|
+
throw error;
|
|
719
|
+
}
|
|
720
|
+
const handle = await fs.open(temporary, 'wx', 0o600);
|
|
721
|
+
try {
|
|
722
|
+
await handle.writeFile(JSON.stringify({ version: 1, records: [...this.records.values()], pending: [...this.pending.values()] }), 'utf8');
|
|
723
|
+
await handle.sync();
|
|
724
|
+
}
|
|
725
|
+
finally {
|
|
726
|
+
await handle.close();
|
|
727
|
+
}
|
|
728
|
+
await fs.rename(temporary, this.catalogPath);
|
|
729
|
+
}
|
|
730
|
+
catch (error) {
|
|
731
|
+
this.fault = error instanceof Error ? error : new Error('Schedule catalog write failed.');
|
|
732
|
+
for (const [id, runtime] of this.runtimes)
|
|
733
|
+
void this.stop(id, runtime).catch(() => { });
|
|
734
|
+
throw this.fault;
|
|
735
|
+
}
|
|
736
|
+
finally {
|
|
737
|
+
await fs.unlink(temporary).catch(() => { });
|
|
738
|
+
}
|
|
739
|
+
}
|
|
740
|
+
}
|
|
741
|
+
exports.ScheduleService = ScheduleService;
|
|
742
|
+
//# sourceMappingURL=ScheduleService.js.map
|