@myclaw163/clawclaw-cli 0.8.34 → 0.8.36
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/docs/configuration.md +19 -0
- package/docs/runtime/owner-lifecycle-and-observability.md +2 -2
- package/package.json +2 -1
- package/skills/clawclaw/SKILL.md +5 -1
- package/skills/clawclaw/references/COMMANDS.md +3 -1
- package/skills/clawclaw/references/STREAM.md +2 -0
- package/src/commands/load.ts +6 -0
- package/src/lib/agent-workspace-skills.ts +4 -0
- package/src/lib/auth.ts +25 -9
- package/src/lib/workspace-runtime-lock.ts +47 -0
- package/src/runtime/clawclaw/behavior-input.ts +5 -3
- package/src/runtime/clawclaw/notifications.ts +16 -0
- package/src/runtime/clawclaw/owner-lock-error.ts +25 -0
- package/src/runtime/clawclaw/owner-lock.ts +221 -0
- package/src/runtime/clawclaw/owner.ts +30 -225
- package/src/runtime/clawclaw/plugins/action/action-plugin.ts +64 -0
- package/src/runtime/clawclaw/plugins/derived-event/reminder-plugin.ts +3 -1
- package/src/runtime/clawclaw/plugins/game-query/game-query-plugin.ts +3 -1
- package/src/runtime/clawclaw/runtime-state.ts +4 -2
- package/src/runtime/clawclaw/starting-owner-control.ts +26 -0
- package/src/runtime/clawclaw/task-choice-projection.ts +93 -0
- package/src/runtime/owner-control.ts +10 -0
- package/src/runtime/process-identity.ts +72 -0
- package/src/sdk/module-input/index.ts +1 -0
|
@@ -1,9 +1,9 @@
|
|
|
1
1
|
import { randomUUID } from 'node:crypto';
|
|
2
|
-
import {
|
|
2
|
+
import { acquireOwnerLock, type OwnerLock } from './owner-lock.js';
|
|
3
|
+
import { createStartingOwnerControl } from './starting-owner-control.js';
|
|
4
|
+
export { acquireOwnerLock, type OwnerLock, type OwnerLockOperations } from './owner-lock.js';
|
|
3
5
|
import {
|
|
4
6
|
chmodSync,
|
|
5
|
-
closeSync,
|
|
6
|
-
openSync,
|
|
7
7
|
readFileSync,
|
|
8
8
|
renameSync,
|
|
9
9
|
unlinkSync,
|
|
@@ -43,7 +43,6 @@ import {
|
|
|
43
43
|
import {
|
|
44
44
|
gameStartRuntimePath,
|
|
45
45
|
readGameStartRuntime,
|
|
46
|
-
sendProfileOwnerControlRequest,
|
|
47
46
|
startOwnerControlServer,
|
|
48
47
|
type OwnerControlServer,
|
|
49
48
|
} from '../owner-control.js';
|
|
@@ -251,9 +250,6 @@ export function deriveClawclawOwnerRuntimeStart(
|
|
|
251
250
|
};
|
|
252
251
|
}
|
|
253
252
|
|
|
254
|
-
export interface OwnerLock {
|
|
255
|
-
release(): void;
|
|
256
|
-
}
|
|
257
253
|
|
|
258
254
|
interface OwnerRuntimePointer {
|
|
259
255
|
release(): void;
|
|
@@ -263,10 +259,6 @@ const MAILBOX_DRAIN_TIMEOUT_MS = 2_000;
|
|
|
263
259
|
const DESKTOP_RESOURCE_LOCALE = 'zh-CN';
|
|
264
260
|
const EVENTS_QUERY_BARRIER_TIMEOUT_MS = 10_000;
|
|
265
261
|
const LOCAL_STOP_FORCE_EXIT_MS = 10_000;
|
|
266
|
-
const FORCE_STOP_GRACE_MS = 1_500;
|
|
267
|
-
const FORCE_STOP_TERM_MS = 1_500;
|
|
268
|
-
const FORCE_STOP_KILL_MS = 2_000;
|
|
269
|
-
const FORCE_STOP_POLL_MS = 50;
|
|
270
262
|
|
|
271
263
|
type ConfigurationWarning = (code: string, details: Readonly<Record<string, unknown>>) => void;
|
|
272
264
|
|
|
@@ -428,206 +420,17 @@ async function waitForMailboxDrain(
|
|
|
428
420
|
return true;
|
|
429
421
|
}
|
|
430
422
|
|
|
431
|
-
function processAlive(pid: number): boolean {
|
|
432
|
-
if (!Number.isSafeInteger(pid) || pid <= 0) return false;
|
|
433
|
-
try {
|
|
434
|
-
process.kill(pid, 0);
|
|
435
|
-
return true;
|
|
436
|
-
} catch {
|
|
437
|
-
return false;
|
|
438
|
-
}
|
|
439
|
-
}
|
|
440
|
-
|
|
441
|
-
function terminateRuntimeProcessTree(pid: number, signal: NodeJS.Signals): boolean {
|
|
442
|
-
if (!Number.isSafeInteger(pid) || pid <= 0 || pid === process.pid) return false;
|
|
443
|
-
if (process.platform === 'win32') {
|
|
444
|
-
const systemRoot = process.env.SystemRoot ?? process.env.SYSTEMROOT ?? 'C:\\Windows';
|
|
445
|
-
const result = spawnSync(join(systemRoot, 'System32', 'taskkill.exe'), [
|
|
446
|
-
'/PID',
|
|
447
|
-
String(pid),
|
|
448
|
-
'/T',
|
|
449
|
-
'/F',
|
|
450
|
-
], {
|
|
451
|
-
stdio: 'ignore',
|
|
452
|
-
windowsHide: true,
|
|
453
|
-
timeout: FORCE_STOP_TERM_MS,
|
|
454
|
-
});
|
|
455
|
-
return result.status === 0 || !processAlive(pid);
|
|
456
|
-
}
|
|
457
|
-
|
|
458
|
-
const childSignal = signal === 'SIGKILL' ? '-KILL' : '-TERM';
|
|
459
|
-
try {
|
|
460
|
-
spawnSync('pkill', [childSignal, '-P', String(pid)], {
|
|
461
|
-
stdio: 'ignore',
|
|
462
|
-
timeout: FORCE_STOP_TERM_MS,
|
|
463
|
-
});
|
|
464
|
-
} catch {}
|
|
465
|
-
try {
|
|
466
|
-
process.kill(pid, signal);
|
|
467
|
-
return true;
|
|
468
|
-
} catch {
|
|
469
|
-
return !processAlive(pid);
|
|
470
|
-
}
|
|
471
|
-
}
|
|
472
|
-
|
|
473
|
-
async function waitForProcessExit(
|
|
474
|
-
pid: number,
|
|
475
|
-
timeoutMs: number,
|
|
476
|
-
isAlive = processAlive,
|
|
477
|
-
): Promise<boolean> {
|
|
478
|
-
const deadline = Date.now() + timeoutMs;
|
|
479
|
-
while (Date.now() < deadline) {
|
|
480
|
-
if (!isAlive(pid)) return true;
|
|
481
|
-
await new Promise((resolve) => setTimeout(resolve, FORCE_STOP_POLL_MS));
|
|
482
|
-
}
|
|
483
|
-
return !isAlive(pid);
|
|
484
|
-
}
|
|
485
|
-
|
|
486
|
-
export interface OwnerLockOperations {
|
|
487
|
-
processAlive(pid: number): boolean;
|
|
488
|
-
requestStop(
|
|
489
|
-
profile: Pick<AuthProfile, 'apiKey' | 'runtimeAccountId'>,
|
|
490
|
-
expectedPid: number,
|
|
491
|
-
): Promise<void>;
|
|
492
|
-
terminateProcessTree(pid: number, signal: NodeJS.Signals): boolean;
|
|
493
|
-
waitForExit(pid: number, timeoutMs: number): Promise<boolean>;
|
|
494
|
-
}
|
|
495
|
-
|
|
496
|
-
const defaultOwnerLockOperations: OwnerLockOperations = {
|
|
497
|
-
processAlive,
|
|
498
|
-
requestStop: async (profile, expectedPid) => {
|
|
499
|
-
const stateDir = getProfileRuntimeStateDir(profile);
|
|
500
|
-
const pointer = readGameStartRuntime(stateDir);
|
|
501
|
-
const pointerPid = Number(pointer?.owner_pid ?? pointer?.pid);
|
|
502
|
-
if (pointerPid !== expectedPid) return;
|
|
503
|
-
try {
|
|
504
|
-
await sendProfileOwnerControlRequest(profile, 'stop');
|
|
505
|
-
} catch {}
|
|
506
|
-
},
|
|
507
|
-
terminateProcessTree: terminateRuntimeProcessTree,
|
|
508
|
-
waitForExit: (pid, timeoutMs) => waitForProcessExit(pid, timeoutMs),
|
|
509
|
-
};
|
|
510
|
-
|
|
511
|
-
function readOwnerLockPid(path: string): number | null {
|
|
512
|
-
try {
|
|
513
|
-
const pid = Number((JSON.parse(readFileSync(path, 'utf8')) as { pid?: number }).pid);
|
|
514
|
-
return Number.isSafeInteger(pid) && pid > 0 ? pid : null;
|
|
515
|
-
} catch {
|
|
516
|
-
return null;
|
|
517
|
-
}
|
|
518
|
-
}
|
|
519
|
-
|
|
520
|
-
function removeOwnerLockForPid(path: string, pid: number): boolean {
|
|
521
|
-
try {
|
|
522
|
-
if (readOwnerLockPid(path) !== pid) return false;
|
|
523
|
-
unlinkSync(path);
|
|
524
|
-
return true;
|
|
525
|
-
} catch {
|
|
526
|
-
return false;
|
|
527
|
-
}
|
|
528
|
-
}
|
|
529
|
-
|
|
530
|
-
function removeRuntimePointerForPid(stateDir: string, pid: number): void {
|
|
531
|
-
const pointer = readGameStartRuntime(stateDir);
|
|
532
|
-
const pointerPid = Number(pointer?.owner_pid ?? pointer?.pid);
|
|
533
|
-
if (pointerPid !== pid) return;
|
|
534
|
-
const controlPath = typeof pointer?.control?.path === 'string' ? pointer.control.path : '';
|
|
535
|
-
try { unlinkSync(gameStartRuntimePath(stateDir)); } catch {}
|
|
536
|
-
if (process.platform !== 'win32' && controlPath) {
|
|
537
|
-
try { unlinkSync(controlPath); } catch {}
|
|
538
|
-
}
|
|
539
|
-
}
|
|
540
|
-
|
|
541
|
-
async function stopExistingRuntime(
|
|
542
|
-
profile: Pick<AuthProfile, 'apiKey' | 'runtimeAccountId'>,
|
|
543
|
-
pid: number,
|
|
544
|
-
operations: OwnerLockOperations,
|
|
545
|
-
): Promise<void> {
|
|
546
|
-
try { await operations.requestStop(profile, pid); } catch {}
|
|
547
|
-
if (await operations.waitForExit(pid, FORCE_STOP_GRACE_MS)) return;
|
|
548
|
-
|
|
549
|
-
operations.terminateProcessTree(pid, 'SIGTERM');
|
|
550
|
-
if (await operations.waitForExit(pid, FORCE_STOP_TERM_MS)) return;
|
|
551
|
-
|
|
552
|
-
operations.terminateProcessTree(pid, 'SIGKILL');
|
|
553
|
-
if (await operations.waitForExit(pid, FORCE_STOP_KILL_MS)) return;
|
|
554
|
-
|
|
555
|
-
throw new Error(`Unable to replace the running ClawClaw runtime (pid ${pid}).`);
|
|
556
|
-
}
|
|
557
|
-
|
|
558
|
-
export async function acquireOwnerLock(
|
|
559
|
-
profile: Pick<AuthProfile, 'apiKey' | 'runtimeAccountId'>,
|
|
560
|
-
options: {
|
|
561
|
-
force?: boolean;
|
|
562
|
-
operations?: OwnerLockOperations;
|
|
563
|
-
} = {},
|
|
564
|
-
): Promise<OwnerLock> {
|
|
565
|
-
const stateDir = getProfileRuntimeStateDir(profile);
|
|
566
|
-
const path = join(stateDir, 'owner.lock');
|
|
567
|
-
const operations = options.operations ?? defaultOwnerLockOperations;
|
|
568
|
-
let replacementPid: number | undefined;
|
|
569
|
-
for (let attempt = 0; attempt < 4; attempt += 1) {
|
|
570
|
-
try {
|
|
571
|
-
const fd = openSync(path, 'wx');
|
|
572
|
-
writeFileSync(fd, JSON.stringify({ pid: process.pid, started_at: new Date().toISOString() }));
|
|
573
|
-
closeSync(fd);
|
|
574
|
-
let released = false;
|
|
575
|
-
return {
|
|
576
|
-
release: () => {
|
|
577
|
-
if (released) return;
|
|
578
|
-
released = true;
|
|
579
|
-
try {
|
|
580
|
-
const current = JSON.parse(readFileSync(path, 'utf8')) as { pid?: number };
|
|
581
|
-
if (current.pid === process.pid) unlinkSync(path);
|
|
582
|
-
} catch {}
|
|
583
|
-
},
|
|
584
|
-
};
|
|
585
|
-
} catch (error: any) {
|
|
586
|
-
if (error?.code !== 'EEXIST') throw error;
|
|
587
|
-
const ownerPid = readOwnerLockPid(path);
|
|
588
|
-
if (ownerPid === null) {
|
|
589
|
-
try { unlinkSync(path); } catch {}
|
|
590
|
-
continue;
|
|
591
|
-
}
|
|
592
|
-
if (!operations.processAlive(ownerPid)) {
|
|
593
|
-
removeRuntimePointerForPid(stateDir, ownerPid);
|
|
594
|
-
removeOwnerLockForPid(path, ownerPid);
|
|
595
|
-
continue;
|
|
596
|
-
}
|
|
597
|
-
if (!options.force) {
|
|
598
|
-
throw new Error(
|
|
599
|
-
`A ClawClaw runtime is already running (pid ${ownerPid}). Re-run with --force to replace it.`,
|
|
600
|
-
);
|
|
601
|
-
}
|
|
602
|
-
if (ownerPid === process.pid) {
|
|
603
|
-
throw new Error('Refusing to replace the current ClawClaw runtime process.');
|
|
604
|
-
}
|
|
605
|
-
if (replacementPid !== undefined && replacementPid !== ownerPid) {
|
|
606
|
-
throw new Error(
|
|
607
|
-
`The active ClawClaw runtime changed from pid ${replacementPid} to pid ${ownerPid}; refusing to replace the new process.`,
|
|
608
|
-
);
|
|
609
|
-
}
|
|
610
|
-
replacementPid = ownerPid;
|
|
611
|
-
await stopExistingRuntime(profile, ownerPid, operations);
|
|
612
|
-
if (operations.processAlive(ownerPid)) {
|
|
613
|
-
throw new Error(`Unable to replace the running ClawClaw runtime (pid ${ownerPid}).`);
|
|
614
|
-
}
|
|
615
|
-
removeRuntimePointerForPid(stateDir, ownerPid);
|
|
616
|
-
removeOwnerLockForPid(path, ownerPid);
|
|
617
|
-
}
|
|
618
|
-
}
|
|
619
|
-
throw new Error('Unable to acquire the ClawClaw runtime owner lock.');
|
|
620
|
-
}
|
|
621
|
-
|
|
622
423
|
export function publishOwnerRuntimePointer(
|
|
623
424
|
stateDir: string,
|
|
624
425
|
control: OwnerControlServer,
|
|
426
|
+
instanceId?: string,
|
|
625
427
|
): OwnerRuntimePointer {
|
|
626
428
|
const path = gameStartRuntimePath(stateDir);
|
|
627
429
|
const tempPath = `${path}.${process.pid}.tmp`;
|
|
628
430
|
const value = {
|
|
629
431
|
schema: 'clawclaw.owner.v1',
|
|
630
432
|
owner_pid: process.pid,
|
|
433
|
+
...(instanceId ? { instance_id: instanceId } : {}),
|
|
631
434
|
started_at: new Date().toISOString(),
|
|
632
435
|
control: control.control,
|
|
633
436
|
control_token: control.token,
|
|
@@ -683,6 +486,7 @@ export async function runClawclawOwner(
|
|
|
683
486
|
let mailboxBroker: MailboxRelayBroker | undefined;
|
|
684
487
|
let ownerControl: OwnerControlServer | undefined;
|
|
685
488
|
let runtimePointer: OwnerRuntimePointer | undefined;
|
|
489
|
+
let startingControl: ReturnType<typeof createStartingOwnerControl> | undefined;
|
|
686
490
|
let relayAlive = false;
|
|
687
491
|
let relayAbort: AbortController | undefined;
|
|
688
492
|
let relayPromise: Promise<void> | undefined;
|
|
@@ -695,6 +499,7 @@ export async function runClawclawOwner(
|
|
|
695
499
|
const requestLocalStop = (): void => {
|
|
696
500
|
if (localStopRequested) return;
|
|
697
501
|
localStopRequested = true;
|
|
502
|
+
try { lock?.setPhase('stopping'); } catch {}
|
|
698
503
|
forceExitTimer = setTimeout(() => process.exit(1), LOCAL_STOP_FORCE_EXIT_MS);
|
|
699
504
|
forceExitTimer.unref?.();
|
|
700
505
|
void source?.submitIntent({ kind: 'stop' }).catch(() => {});
|
|
@@ -705,7 +510,26 @@ export async function runClawclawOwner(
|
|
|
705
510
|
lock = await acquireOwnerLock(options.profile, {
|
|
706
511
|
force: options.forceExistingRuntime === true,
|
|
707
512
|
});
|
|
513
|
+
startingControl = createStartingOwnerControl(lock.instanceId, requestLocalStop);
|
|
514
|
+
ownerControl = await startOwnerControlServer(
|
|
515
|
+
getProfileRuntimeStateDir(options.profile), startingControl.handle,
|
|
516
|
+
{ get observability() { return telemetry; } },
|
|
517
|
+
);
|
|
518
|
+
runtimePointer = publishOwnerRuntimePointer(
|
|
519
|
+
getProfileRuntimeStateDir(options.profile), ownerControl, lock.instanceId,
|
|
520
|
+
);
|
|
521
|
+
parentWatch = watchParentProcess(() => {
|
|
522
|
+
runtime?.diagnostic('runtime.owner.parent_exited', {
|
|
523
|
+
parent_pid: parentWatch?.parentPid ?? process.ppid,
|
|
524
|
+
}, 'warn');
|
|
525
|
+
requestLocalStop();
|
|
526
|
+
});
|
|
527
|
+
process.on('SIGINT', onSignal);
|
|
528
|
+
process.on('SIGTERM', onSignal);
|
|
708
529
|
telemetry = createOwnerTelemetryRecorder(options.profile);
|
|
530
|
+
telemetry.log('info', 'owner.control.started', { transport: ownerControl.control.kind }, {
|
|
531
|
+
component: 'runtime.owner_control',
|
|
532
|
+
});
|
|
709
533
|
const fullDiagnosticsEnabled = resolveOwnerObservabilityLevel() === 'full';
|
|
710
534
|
if (fullDiagnosticsEnabled) {
|
|
711
535
|
const retention = observabilityRetention();
|
|
@@ -1112,9 +936,7 @@ export async function runClawclawOwner(
|
|
|
1112
936
|
}, 'error');
|
|
1113
937
|
});
|
|
1114
938
|
}
|
|
1115
|
-
|
|
1116
|
-
getProfileRuntimeStateDir(options.profile),
|
|
1117
|
-
async (request, context) => {
|
|
939
|
+
startingControl.setHandler(async (request, context) => {
|
|
1118
940
|
if (context.principal === 'host_relay') {
|
|
1119
941
|
if (request.type === 'mailbox_claim') mailboxService?.prepareMonitor();
|
|
1120
942
|
return mailboxBroker?.handle(request) ?? { ok: false, error: 'mailbox_monitor_unavailable' };
|
|
@@ -1429,10 +1251,7 @@ export async function runClawclawOwner(
|
|
|
1429
1251
|
config: latest.triggers[request.trigger] ?? null,
|
|
1430
1252
|
};
|
|
1431
1253
|
}
|
|
1432
|
-
|
|
1433
|
-
requestLocalStop();
|
|
1434
|
-
return { ok: true, type: request.type };
|
|
1435
|
-
}
|
|
1254
|
+
|
|
1436
1255
|
if (request.type === 'quit' || request.type === 'leave') {
|
|
1437
1256
|
await ownerSource.submitIntent({ kind: 'leave' });
|
|
1438
1257
|
return { ok: true, type: request.type };
|
|
@@ -1462,27 +1281,13 @@ export async function runClawclawOwner(
|
|
|
1462
1281
|
return { ok: true, type: request.type, result };
|
|
1463
1282
|
}
|
|
1464
1283
|
return { ok: false, error: 'owner_request_not_supported' };
|
|
1465
|
-
},
|
|
1466
|
-
{
|
|
1467
|
-
observability: telemetry,
|
|
1468
|
-
},
|
|
1469
|
-
);
|
|
1470
|
-
runtimePointer = publishOwnerRuntimePointer(
|
|
1471
|
-
getProfileRuntimeStateDir(options.profile),
|
|
1472
|
-
ownerControl,
|
|
1473
|
-
);
|
|
1474
|
-
parentWatch = watchParentProcess(() => {
|
|
1475
|
-
runtime?.diagnostic('runtime.owner.parent_exited', {
|
|
1476
|
-
parent_pid: parentWatch?.parentPid ?? process.ppid,
|
|
1477
|
-
}, 'warn');
|
|
1478
|
-
requestLocalStop();
|
|
1479
1284
|
});
|
|
1480
|
-
|
|
1481
|
-
process.on('SIGTERM', onSignal);
|
|
1285
|
+
if (localStopRequested) return { reason: 'stopped' };
|
|
1482
1286
|
await runtime.startSourcePlugin(ownerSource);
|
|
1483
1287
|
await desktopEventPump?.flush();
|
|
1484
1288
|
await channelEventPump?.flush();
|
|
1485
1289
|
if (localStopRequested) await ownerSource.submitIntent({ kind: 'stop' });
|
|
1290
|
+
if (!localStopRequested) lock.setPhase('ready');
|
|
1486
1291
|
options.notificationHost?.markMailboxReady();
|
|
1487
1292
|
const completion = await source.waitForCompletion();
|
|
1488
1293
|
await runtime.flush();
|
|
@@ -21,6 +21,7 @@ import type {
|
|
|
21
21
|
RuntimeEpochPluginResult,
|
|
22
22
|
} from '../../../framework/plugins/index.js';
|
|
23
23
|
import { isClawclawRuntimeState, type ClawclawRuntimeStage } from '../../runtime-state.js';
|
|
24
|
+
import { sabotageTaskActionBlocked } from '../../task-choice-projection.js';
|
|
24
25
|
|
|
25
26
|
export const CLAWCLAW_ACTION_PLUGIN_ID = 'clawclaw.action';
|
|
26
27
|
export const CLAWCLAW_ACTION_CAPABILITY = 'clawclaw.action';
|
|
@@ -271,6 +272,11 @@ export class ClawclawActionPlugin implements RuntimeEpochPlugin<Record<string, a
|
|
|
271
272
|
private connection: 'connected' | 'reconnecting' | 'disconnected' = 'disconnected';
|
|
272
273
|
private noteAgentActivity?: () => void;
|
|
273
274
|
private diagnostic?: RuntimeEpochPluginContext<Record<string, any>>['diagnostic'];
|
|
275
|
+
private latestTaskGameState?: {
|
|
276
|
+
scopeKey: string;
|
|
277
|
+
epochSeq: number;
|
|
278
|
+
state: Record<string, any>;
|
|
279
|
+
};
|
|
274
280
|
private readonly ownedSettlements = new Map<string, Promise<ActionResult>>();
|
|
275
281
|
/**
|
|
276
282
|
* Automated callers may receive a queued receipt before HTTP settlement.
|
|
@@ -290,6 +296,7 @@ export class ClawclawActionPlugin implements RuntimeEpochPlugin<Record<string, a
|
|
|
290
296
|
|
|
291
297
|
start(context: RuntimeEpochPluginContext<Record<string, any>>): void {
|
|
292
298
|
if (this.unregister) throw new Error('Clawclaw Action Plugin is already started.');
|
|
299
|
+
this.latestTaskGameState = undefined;
|
|
293
300
|
this.stage = context.currentSegment().kind === 'room_lobby' ? 'room' : 'matching';
|
|
294
301
|
this.diagnostic = context.diagnostic;
|
|
295
302
|
this.detailCapture = new DetailCapture('actions', context.diagnostic);
|
|
@@ -303,9 +310,14 @@ export class ClawclawActionPlugin implements RuntimeEpochPlugin<Record<string, a
|
|
|
303
310
|
}
|
|
304
311
|
|
|
305
312
|
update(input: RuntimeEpochPluginInput<Record<string, any>>): RuntimeEpochPluginResult {
|
|
313
|
+
const scopeKey = this.automatedProviderQueueKey(input.epoch.scope);
|
|
314
|
+
if (this.latestTaskGameState?.scopeKey !== scopeKey) this.latestTaskGameState = undefined;
|
|
306
315
|
if (isClawclawRuntimeState(input.epoch.state)) {
|
|
307
316
|
this.stage = input.epoch.state.stage;
|
|
308
317
|
this.connection = input.epoch.state.connection;
|
|
318
|
+
if (input.epoch.state.game_snapshot.status === 'fresh') {
|
|
319
|
+
this.rememberTaskGameState(input.epoch.scope, input.epoch.epochSeq, input.epoch.state.game_snapshot.state);
|
|
320
|
+
}
|
|
309
321
|
}
|
|
310
322
|
return { outcome: 'noop', reason: 'no_action_request' };
|
|
311
323
|
}
|
|
@@ -314,6 +326,7 @@ export class ClawclawActionPlugin implements RuntimeEpochPlugin<Record<string, a
|
|
|
314
326
|
this.unregister?.();
|
|
315
327
|
this.unregister = undefined;
|
|
316
328
|
this.diagnostic = undefined;
|
|
329
|
+
this.latestTaskGameState = undefined;
|
|
317
330
|
this.automatedProviderStarts.clear();
|
|
318
331
|
this.automatedProviderQueueDepths.clear();
|
|
319
332
|
}
|
|
@@ -322,6 +335,53 @@ export class ClawclawActionPlugin implements RuntimeEpochPlugin<Record<string, a
|
|
|
322
335
|
return `${scope.sessionId}:${scope.segmentId}`;
|
|
323
336
|
}
|
|
324
337
|
|
|
338
|
+
private rememberTaskGameState(scope: ScopeRef, epochSeq: number, state: Record<string, any>): void {
|
|
339
|
+
const scopeKey = this.automatedProviderQueueKey(scope);
|
|
340
|
+
if (this.latestTaskGameState?.scopeKey === scopeKey
|
|
341
|
+
&& this.latestTaskGameState.epochSeq > epochSeq) return;
|
|
342
|
+
this.latestTaskGameState = { scopeKey, epochSeq, state: structuredClone(state) };
|
|
343
|
+
}
|
|
344
|
+
|
|
345
|
+
private taskAdmissionRejection(
|
|
346
|
+
request: ClawclawActionRequest,
|
|
347
|
+
scope: ScopeRef,
|
|
348
|
+
actionId: string,
|
|
349
|
+
context: ActionExecutionContext,
|
|
350
|
+
): ActionResult | undefined {
|
|
351
|
+
if (request.action.action !== 'task') return undefined;
|
|
352
|
+
const scopeKey = this.automatedProviderQueueKey(scope);
|
|
353
|
+
if (this.latestTaskGameState?.scopeKey !== scopeKey) this.latestTaskGameState = undefined;
|
|
354
|
+
const latest = context.latestAcceptedState();
|
|
355
|
+
const runtimeState = latest?.state;
|
|
356
|
+
let game: Record<string, any> | undefined;
|
|
357
|
+
if (isClawclawRuntimeState(runtimeState)) {
|
|
358
|
+
if (runtimeState.game_snapshot.status === 'fresh') {
|
|
359
|
+
game = runtimeState.game_snapshot.state;
|
|
360
|
+
this.rememberTaskGameState(scope, latest!.epochSeq, game);
|
|
361
|
+
} else if (runtimeState.game_snapshot.status === 'not_updated'
|
|
362
|
+
&& runtimeState.connection === 'connected') {
|
|
363
|
+
// Control-only epochs retain the last authoritative game observation.
|
|
364
|
+
game = this.latestTaskGameState?.state;
|
|
365
|
+
}
|
|
366
|
+
if (runtimeState.connection !== 'connected') game = undefined;
|
|
367
|
+
} else if (runtimeState) {
|
|
368
|
+
game = runtimeState;
|
|
369
|
+
this.rememberTaskGameState(scope, latest!.epochSeq, game);
|
|
370
|
+
}
|
|
371
|
+
// An unavailable snapshot may retain task identity for rejection, but can
|
|
372
|
+
// never borrow a previous ready status to authorize sabotage.
|
|
373
|
+
if (!game && this.latestTaskGameState) {
|
|
374
|
+
game = { ...this.latestTaskGameState.state, crab_sabotage: undefined };
|
|
375
|
+
}
|
|
376
|
+
if (!sabotageTaskActionBlocked(game, request.action.task_name)) return undefined;
|
|
377
|
+
return actionResult(scope, actionId, 'failure', undefined, {
|
|
378
|
+
error: {
|
|
379
|
+
code: 'SABOTAGE_NOT_READY',
|
|
380
|
+
message: 'The sabotage task requires the current shared sabotage state to be ready.',
|
|
381
|
+
},
|
|
382
|
+
}, { source: 'local', actionOutcome: 'not_submitted' });
|
|
383
|
+
}
|
|
384
|
+
|
|
325
385
|
private enqueueAutomatedSubmission(
|
|
326
386
|
request: ClawclawActionRequest,
|
|
327
387
|
scope: ScopeRef,
|
|
@@ -472,6 +532,8 @@ export class ClawclawActionPlugin implements RuntimeEpochPlugin<Record<string, a
|
|
|
472
532
|
): ActionResult | undefined {
|
|
473
533
|
const stale = this.automationSafetyRejection(request, scope, actionId, caller, context);
|
|
474
534
|
if (stale) return stale;
|
|
535
|
+
const taskRejected = this.taskAdmissionRejection(request, scope, actionId, context);
|
|
536
|
+
if (taskRejected) return taskRejected;
|
|
475
537
|
if (caller.kind === 'behavior') {
|
|
476
538
|
// A queued Behavior Action is owned by its exact activation controller
|
|
477
539
|
// until the endpoint starts. Suspension, replacement, or restart must
|
|
@@ -519,6 +581,8 @@ export class ClawclawActionPlugin implements RuntimeEpochPlugin<Record<string, a
|
|
|
519
581
|
}, { source: 'local', actionOutcome: 'not_submitted' });
|
|
520
582
|
}
|
|
521
583
|
} else {
|
|
584
|
+
const taskRejected = this.taskAdmissionRejection(request, scope, actionId, context);
|
|
585
|
+
if (taskRejected) return taskRejected;
|
|
522
586
|
const targetPreparation = prepareActionTarget(action);
|
|
523
587
|
if ('failure' in targetPreparation) {
|
|
524
588
|
return actionResult(scope, actionId, 'failure', undefined, {
|
|
@@ -4,6 +4,7 @@ import type { ReminderInput, ReminderResult, ReminderTopic, ReminderTaskChange }
|
|
|
4
4
|
import type { ResolvedClawclawPerceptionSource } from '../perception/perception-source.js';
|
|
5
5
|
import { freshClawclawGameState } from '../../runtime-state.js';
|
|
6
6
|
import { createCanonicalGameState } from '../../behavior-input.js';
|
|
7
|
+
import { projectTaskChoiceEventPayload } from '../../task-choice-projection.js';
|
|
7
8
|
import { ObservationFrameProjector } from '../../observation-frame-projector.js';
|
|
8
9
|
import { REMINDER_EVENT_TYPES, REMINDER_EVENT_TYPE_BY_TOPIC, REMINDER_FACT_TYPES, REMINDER_TOPICS } from './reminder-rules.js';
|
|
9
10
|
import { ReminderRunner } from './reminder-runner.js';
|
|
@@ -90,7 +91,8 @@ export class ClawclawReminderPlugin implements RuntimeEpochPlugin<Record<string,
|
|
|
90
91
|
next.previousTick = undefined; next.previousConnectionId = undefined;
|
|
91
92
|
}
|
|
92
93
|
next.previousConnectionId = input.epoch.connectionId;
|
|
93
|
-
const facts = input.pendingEvents
|
|
94
|
+
const facts = input.pendingEvents.map(event => ({ ...event,
|
|
95
|
+
payload: projectTaskChoiceEventPayload(game, event.type, event.payload) }));
|
|
94
96
|
const events: RuntimeEventProposal[] = [];
|
|
95
97
|
const taskChanges: ReminderTaskChange[] = facts.filter(e => e.type === 'tasks_changed').flatMap(e => {
|
|
96
98
|
const delta = Array.isArray(e.payload.delta) ? e.payload.delta : [];
|
|
@@ -11,6 +11,7 @@ import type {
|
|
|
11
11
|
RuntimeEpochPluginResult,
|
|
12
12
|
} from '../../../framework/plugins/index.js';
|
|
13
13
|
import { isClawclawRuntimeState } from '../../runtime-state.js';
|
|
14
|
+
import { projectTaskChoices, projectTaskChoiceLocations } from '../../task-choice-projection.js';
|
|
14
15
|
import {
|
|
15
16
|
CLAWCLAW_MAP_CAPABILITY,
|
|
16
17
|
CLAWCLAW_PATH_DISTANCE_CAPABILITY,
|
|
@@ -63,7 +64,7 @@ export function clawclawTasksFromGameState(
|
|
|
63
64
|
gameState: Record<string, any> | null | undefined,
|
|
64
65
|
): readonly Record<string, any>[] | null {
|
|
65
66
|
const tasks = gameState?.you?.tasks;
|
|
66
|
-
return Array.isArray(tasks) ? structuredClone(tasks) : null;
|
|
67
|
+
return Array.isArray(tasks) ? structuredClone(projectTaskChoices(gameState, tasks)) : null;
|
|
67
68
|
}
|
|
68
69
|
|
|
69
70
|
function clawclawPlayersFromGameState(
|
|
@@ -84,6 +85,7 @@ export function clawclawMapFromGameState(
|
|
|
84
85
|
const tasks = clawclawTasksFromGameState(gameState);
|
|
85
86
|
return {
|
|
86
87
|
...structuredClone(PACKAGED_MAP),
|
|
88
|
+
all_task_locations: structuredClone(projectTaskChoiceLocations(gameState, PACKAGED_MAP.all_task_locations)),
|
|
87
89
|
all_players: clawclawPlayersFromGameState(gameState),
|
|
88
90
|
...(tasks === null ? {} : { your_tasks: tasks }),
|
|
89
91
|
};
|
|
@@ -1,3 +1,5 @@
|
|
|
1
|
+
import { projectTaskChoiceGameState } from './task-choice-projection.js';
|
|
2
|
+
|
|
1
3
|
export type ClawclawRuntimeStage =
|
|
2
4
|
| 'matching'
|
|
3
5
|
| 'room'
|
|
@@ -80,9 +82,9 @@ export function isClawclawRuntimeState(value: unknown): value is ClawclawRuntime
|
|
|
80
82
|
export function projectClawclawCurrentState(
|
|
81
83
|
state: Record<string, any>,
|
|
82
84
|
): Record<string, any> | null {
|
|
83
|
-
if (!isClawclawRuntimeState(state)) return state;
|
|
85
|
+
if (!isClawclawRuntimeState(state)) return projectTaskChoiceGameState(state);
|
|
84
86
|
if (state.connection !== 'connected') return null;
|
|
85
|
-
if (state.game_snapshot.status === 'fresh') return
|
|
87
|
+
if (state.game_snapshot.status === 'fresh') return projectTaskChoiceGameState(state.game_snapshot.state);
|
|
86
88
|
if (state.stage === 'room' && state.room) return structuredClone(state.room);
|
|
87
89
|
if (state.stage === 'matching' && state.queue) return structuredClone(state.queue);
|
|
88
90
|
return null;
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
import type { OwnerControlRequest, OwnerControlRequestContext, OwnerControlResponse } from '../owner-control.js';
|
|
2
|
+
|
|
3
|
+
type OwnerRequestHandler = (
|
|
4
|
+
request: OwnerControlRequest, context: OwnerControlRequestContext,
|
|
5
|
+
) => OwnerControlResponse | Promise<OwnerControlResponse>;
|
|
6
|
+
|
|
7
|
+
/** Stop works before modules, persistence, or backend transports initialize. */
|
|
8
|
+
export function createStartingOwnerControl(instanceId: string, requestStop: () => void) {
|
|
9
|
+
let handler: OwnerRequestHandler | undefined;
|
|
10
|
+
return {
|
|
11
|
+
setHandler(value: OwnerRequestHandler) { handler = value; },
|
|
12
|
+
handle: ((request, context) => {
|
|
13
|
+
if (context.principal === 'master' && request.type === 'stop') {
|
|
14
|
+
if (request.instance_id !== undefined && request.instance_id !== instanceId) {
|
|
15
|
+
return { ok: false, error: 'owner_instance_changed', instance_id: instanceId };
|
|
16
|
+
}
|
|
17
|
+
requestStop();
|
|
18
|
+
return { ok: true, type: 'stop', instance_id: instanceId };
|
|
19
|
+
}
|
|
20
|
+
if (!handler) {
|
|
21
|
+
return { ok: false, error: 'runtime_starting', retryable: true, instance_id: instanceId, pid: process.pid };
|
|
22
|
+
}
|
|
23
|
+
return handler(request, context);
|
|
24
|
+
}) satisfies OwnerRequestHandler,
|
|
25
|
+
};
|
|
26
|
+
}
|
|
@@ -0,0 +1,93 @@
|
|
|
1
|
+
import { loadClawclawMapAsset } from '../../lib/game-context.js';
|
|
2
|
+
|
|
3
|
+
type RecordValue = Readonly<Record<string, any>>;
|
|
4
|
+
const record = (value: unknown): RecordValue => value && typeof value === 'object' && !Array.isArray(value)
|
|
5
|
+
? value as RecordValue : {};
|
|
6
|
+
const label = (value: unknown): string => typeof value === 'string' ? value.trim().normalize('NFC').toLocaleLowerCase() : '';
|
|
7
|
+
const taskName = (task: RecordValue): string => label(task.name ?? task.task_name);
|
|
8
|
+
const catalog = (loadClawclawMapAsset().tasks ?? []) as readonly RecordValue[];
|
|
9
|
+
|
|
10
|
+
export function isCrabPlayer(game: unknown): boolean {
|
|
11
|
+
const self = record(record(game).you);
|
|
12
|
+
return self.faction === 'crab' || self.role === 'crab_generic';
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
export function crabSabotageReady(game: unknown): boolean {
|
|
16
|
+
const state = record(game), sabotage = record(state.crab_sabotage);
|
|
17
|
+
return sabotage.status === 'ready' && record(state.emergency).active !== true
|
|
18
|
+
&& !(typeof sabotage.cooldown_remaining_secs === 'number' && sabotage.cooldown_remaining_secs > 0);
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
function staticTaskType(task: RecordValue): number | undefined {
|
|
22
|
+
const name = taskName(task);
|
|
23
|
+
if (!name) return undefined;
|
|
24
|
+
const matches = catalog.filter(candidate => label(candidate.name) === name);
|
|
25
|
+
const room = label(task.room);
|
|
26
|
+
const selected = matches.find(candidate => room && label(candidate.room) === room) ?? (matches.length === 1 ? matches[0] : undefined);
|
|
27
|
+
return selected ? Number(selected.task_type) : undefined;
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
/** Classify this player's task, not another player's role or a shared coordinate. */
|
|
31
|
+
export function isSabotageTask(game: unknown, value: unknown): boolean {
|
|
32
|
+
if (!isCrabPlayer(game)) return false;
|
|
33
|
+
const task = record(value), emergency = record(record(game).emergency);
|
|
34
|
+
if (task.is_fake_shrimp === true) return false;
|
|
35
|
+
if (emergency.active === true && taskName(task) && taskName(task) === label(emergency.task_name)) return false;
|
|
36
|
+
const type = staticTaskType(task);
|
|
37
|
+
if (type === 0 || type === 2) return false;
|
|
38
|
+
if (type === 1 || task.faction === 'crab' || task.task_type === 1) return true;
|
|
39
|
+
// GameSync's crab assignments are sabotage or fake shrimp, plus active repair.
|
|
40
|
+
// The false marker also covers renamed/localized sabotage names absent from the packaged map.
|
|
41
|
+
return task.is_fake_shrimp === false;
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
function ongoingTask(game: unknown, task: RecordValue): boolean {
|
|
45
|
+
const activity = record(record(record(game).you).activity);
|
|
46
|
+
return activity.kind === 'task' && taskName(task) && taskName(task) === label(activity.task_name) ? true : false;
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
/** Keep execution/completion facts; omit unstarted sabotage choices until authoritative readiness. */
|
|
50
|
+
export function projectTaskChoices<T extends RecordValue>(game: unknown, tasks: readonly T[]): T[] {
|
|
51
|
+
return tasks.flatMap(task => {
|
|
52
|
+
if (!isSabotageTask(game, task) || crabSabotageReady(game)) return [task];
|
|
53
|
+
if (task.status === 'completed' || task.status === 'in_progress') return [task];
|
|
54
|
+
// Activity is an authoritative execution fact even if its task-status update lags.
|
|
55
|
+
if (ongoingTask(game, task)) return [{ ...task, status: 'in_progress' } as T];
|
|
56
|
+
return [];
|
|
57
|
+
});
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
/** A public projection only. Persisted Source snapshots and task-change history remain untouched. */
|
|
61
|
+
export function projectTaskChoiceGameState<T extends Record<string, any>>(source: T): T {
|
|
62
|
+
const game: Record<string, any> = structuredClone(source);
|
|
63
|
+
if (Array.isArray(game.you?.tasks)) game.you.tasks = projectTaskChoices(source, game.you.tasks);
|
|
64
|
+
return game as T;
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
/** Map task locations are not assignments, but must not recreate blocked sabotage choices. */
|
|
68
|
+
export function projectTaskChoiceLocations<T extends RecordValue>(game: unknown, locations: readonly T[]): T[] {
|
|
69
|
+
return locations.filter(task => !isSabotageTask(game, task) || crabSabotageReady(game));
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
/** Current assignment arrays in module input follow the same policy; occurrence facts survive. */
|
|
73
|
+
export function projectTaskChoiceEventPayload(game: unknown, type: string, payload: RecordValue): Record<string, any> {
|
|
74
|
+
const result: Record<string, any> = structuredClone(payload);
|
|
75
|
+
if (type === 'tasks_changed') {
|
|
76
|
+
if (Array.isArray(result.tasks)) result.tasks = projectTaskChoices(game, result.tasks);
|
|
77
|
+
if (Array.isArray(result.delta)) result.delta = result.delta.filter(change =>
|
|
78
|
+
change.change === 'removed' || projectTaskChoices(game, [record(change.task)]).length > 0);
|
|
79
|
+
}
|
|
80
|
+
if (result.newly_assigned_task && projectTaskChoices(game, [record(result.newly_assigned_task)]).length === 0) {
|
|
81
|
+
delete result.newly_assigned_task;
|
|
82
|
+
}
|
|
83
|
+
return result;
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
/** Also reject stale/remembered task names at the Action boundary, before HTTP submission. */
|
|
87
|
+
export function sabotageTaskActionBlocked(game: unknown, name: unknown): boolean {
|
|
88
|
+
if (!isCrabPlayer(game) || crabSabotageReady(game) || !label(name)) return false;
|
|
89
|
+
const state = record(game), tasks = record(state.you).tasks;
|
|
90
|
+
const assigned = Array.isArray(tasks) ? tasks.filter(task => taskName(record(task)) === label(name)) : [];
|
|
91
|
+
if (assigned.length) return assigned.some(task => isSabotageTask(game, task));
|
|
92
|
+
return isSabotageTask(game, { name });
|
|
93
|
+
}
|
|
@@ -282,6 +282,16 @@ export function sendOwnerControlRequest(
|
|
|
282
282
|
timeoutMs = OWNER_CONTROL_TIMEOUT_MS,
|
|
283
283
|
): Promise<OwnerControlResponse | null> {
|
|
284
284
|
const info = readGameStartRuntime(stateDir);
|
|
285
|
+
return sendOwnerControlRequestTo(info, type, payload, timeoutMs);
|
|
286
|
+
}
|
|
287
|
+
|
|
288
|
+
/** Use a captured endpoint when replacing an owner; do not re-read a newer pointer. */
|
|
289
|
+
export function sendOwnerControlRequestTo(
|
|
290
|
+
info: Record<string, any> | null,
|
|
291
|
+
type: OwnerControlType,
|
|
292
|
+
payload: Record<string, any> = {},
|
|
293
|
+
timeoutMs = OWNER_CONTROL_TIMEOUT_MS,
|
|
294
|
+
): Promise<OwnerControlResponse | null> {
|
|
285
295
|
const path = typeof info?.control?.path === 'string' ? info.control.path : '';
|
|
286
296
|
const token = typeof info?.control_token === 'string' ? info.control_token : '';
|
|
287
297
|
if (!path || !token) return Promise.resolve(null);
|