@myclaw163/clawclaw-cli 0.6.54
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/README.md +440 -0
- package/bin/clawclaw-cli.mjs +4 -0
- package/package.json +48 -0
- package/personas//347/220/206/346/231/272/346/270/251/345/222/214.md +23 -0
- package/personas//350/200/201/350/260/213/346/267/261/347/256/227.md +22 -0
- package/personas//350/257/232/346/201/263/347/233/264/347/216/207.md +22 -0
- package/personas//350/275/273/346/235/276/346/264/273/346/263/274.md +22 -0
- package/personas//351/207/216/346/200/247/345/217/233/351/200/206.md +23 -0
- package/scripts/postinstall.mjs +20 -0
- package/scripts/sync-bundled-skill.mjs +245 -0
- package/scripts/sync-bundled-skill.test.mjs +152 -0
- package/skills/clawclaw/SKILL.md +240 -0
- package/skills/clawclaw/references/CHATTERBOX.md +142 -0
- package/skills/clawclaw/references/COMMANDS.md +132 -0
- package/skills/clawclaw/references/GAME-MECHANICS.md +186 -0
- package/skills/clawclaw/references/HUB.md +48 -0
- package/skills/clawclaw/references/KNOWLEDGE.md +43 -0
- package/skills/clawclaw/references/STRATEGIES.md +57 -0
- package/skills/clawclaw/references/STREAM.md +58 -0
- package/skills/clawclaw/references/TACTICS.md +65 -0
- package/src/assets/clawclaw-ascii-map.txt +40 -0
- package/src/cli.ts +153 -0
- package/src/commands/_schema.ts +109 -0
- package/src/commands/account.ts +209 -0
- package/src/commands/config.ts +30 -0
- package/src/commands/do.test.ts +37 -0
- package/src/commands/do.ts +95 -0
- package/src/commands/events.ts +22 -0
- package/src/commands/game-map.test.ts +28 -0
- package/src/commands/game-start-plan.test.ts +142 -0
- package/src/commands/game.ts +882 -0
- package/src/commands/history-player.test.ts +102 -0
- package/src/commands/history.ts +573 -0
- package/src/commands/hub.test.ts +96 -0
- package/src/commands/hub.ts +234 -0
- package/src/commands/knowledge.test.ts +19 -0
- package/src/commands/knowledge.ts +168 -0
- package/src/commands/load.test.ts +51 -0
- package/src/commands/load.ts +13 -0
- package/src/commands/meeting-history.test.ts +106 -0
- package/src/commands/memory.ts +40 -0
- package/src/commands/peek.ts +38 -0
- package/src/commands/persona.ts +57 -0
- package/src/commands/setup/codex.ts +248 -0
- package/src/commands/setup/hermes.test.ts +96 -0
- package/src/commands/setup/hermes.ts +76 -0
- package/src/commands/setup/index.ts +13 -0
- package/src/commands/setup/openclaw.test.ts +114 -0
- package/src/commands/setup/openclaw.ts +147 -0
- package/src/commands/skill.ts +128 -0
- package/src/commands/state.ts +46 -0
- package/src/commands/strategy.test.ts +135 -0
- package/src/commands/strategy.ts +189 -0
- package/src/commands/tts.ts +128 -0
- package/src/commands/upgrade.test.ts +91 -0
- package/src/commands/upgrade.ts +154 -0
- package/src/commands/watch.test.ts +973 -0
- package/src/commands/watch.ts +709 -0
- package/src/lib/auth.test.ts +59 -0
- package/src/lib/auth.ts +186 -0
- package/src/lib/command-meta.ts +37 -0
- package/src/lib/game-client.ts +391 -0
- package/src/lib/host-config-patcher.test.ts +130 -0
- package/src/lib/host-config-patcher.ts +151 -0
- package/src/lib/http-keepalive.ts +15 -0
- package/src/lib/http-transport.test.ts +42 -0
- package/src/lib/http-transport.ts +113 -0
- package/src/lib/hub-client.test.ts +56 -0
- package/src/lib/hub-client.ts +88 -0
- package/src/lib/hub-install.test.ts +98 -0
- package/src/lib/hub-install.ts +121 -0
- package/src/lib/hub-reminder.ts +75 -0
- package/src/lib/hub-unzip.test.ts +69 -0
- package/src/lib/hub-unzip.ts +62 -0
- package/src/lib/init-command.test.ts +75 -0
- package/src/lib/init-command.ts +120 -0
- package/src/lib/knowledge-store.test.ts +180 -0
- package/src/lib/knowledge-store.ts +374 -0
- package/src/lib/load-context.test.ts +52 -0
- package/src/lib/load-context.ts +52 -0
- package/src/lib/match-state.test.ts +134 -0
- package/src/lib/match-state.ts +94 -0
- package/src/lib/netease-tts.ts +83 -0
- package/src/lib/normalize.ts +42 -0
- package/src/lib/persona.test.ts +41 -0
- package/src/lib/persona.ts +72 -0
- package/src/lib/server-registry.ts +152 -0
- package/src/lib/skill-version.test.ts +48 -0
- package/src/lib/skill-version.ts +19 -0
- package/src/lib/strategy-export.test.ts +232 -0
- package/src/lib/strategy-export.ts +242 -0
- package/src/lib/tts-keys.ts +7 -0
- package/src/lib/tts-speech.test.ts +63 -0
- package/src/lib/tts-speech.ts +76 -0
- package/src/lib/workspace-argv.test.ts +49 -0
- package/src/lib/workspace-argv.ts +44 -0
- package/src/perception/player-history-store.test.ts +87 -0
- package/src/perception/player-history-store.ts +194 -0
- package/src/pipeline/event-store.ts +124 -0
- package/src/pipeline/pipeline.ts +35 -0
- package/src/runtime/auto-upgrade.test.ts +66 -0
- package/src/runtime/auto-upgrade.ts +31 -0
- package/src/runtime/daemon.ts +100 -0
- package/src/runtime/event-daemon.test.ts +28 -0
- package/src/runtime/event-daemon.ts +371 -0
- package/src/runtime/opening-mover.ts +303 -0
- package/src/runtime/raw-ws-log.test.ts +33 -0
- package/src/runtime/raw-ws-log.ts +32 -0
- package/src/runtime/runtime-logger.ts +99 -0
- package/src/runtime/ws-client.test.ts +47 -0
- package/src/runtime/ws-client.ts +272 -0
- package/src/sdk/action.ts +166 -0
- package/src/sdk/index.ts +110 -0
- package/src/sdk/types.ts +146 -0
- package/src/strategies/avoid-lone.ts +11 -0
- package/src/strategies/avoid-players.knowledge.md +20 -0
- package/src/strategies/avoid-players.ts +15 -0
- package/src/strategies/corpse-patrol.ts +22 -0
- package/src/strategies/crab-sabotage.ts +21 -0
- package/src/strategies/custom-module.test.ts +269 -0
- package/src/strategies/find-player.ts +16 -0
- package/src/strategies/game-utils.test.ts +164 -0
- package/src/strategies/game-utils.ts +721 -0
- package/src/strategies/goals/avoid-lone-top.ts +168 -0
- package/src/strategies/goals/avoid-players-top.test.ts +83 -0
- package/src/strategies/goals/avoid-players-top.ts +121 -0
- package/src/strategies/goals/conversation-goal.ts +51 -0
- package/src/strategies/goals/corpse-patrol-top.ts +91 -0
- package/src/strategies/goals/crab-octopus-reflexes.ts +93 -0
- package/src/strategies/goals/crab-sabotage-top.ts +197 -0
- package/src/strategies/goals/emergency-hunt-goal.ts +28 -0
- package/src/strategies/goals/find-player-top.ts +93 -0
- package/src/strategies/goals/flee-players-goal.ts +53 -0
- package/src/strategies/goals/goal-manager.ts +41 -0
- package/src/strategies/goals/goal-root-strategy.ts +49 -0
- package/src/strategies/goals/goal.ts +28 -0
- package/src/strategies/goals/keep-away-goal.ts +206 -0
- package/src/strategies/goals/kill-frenzy-top.ts +80 -0
- package/src/strategies/goals/kill-lone-top.ts +160 -0
- package/src/strategies/goals/kill-target-goal.ts +59 -0
- package/src/strategies/goals/kill-target-top.ts +109 -0
- package/src/strategies/goals/leaf-goal.ts +25 -0
- package/src/strategies/goals/linger-corpse-goal.ts +79 -0
- package/src/strategies/goals/lone-kill-core.ts +82 -0
- package/src/strategies/goals/lone-kill-goal.ts +24 -0
- package/src/strategies/goals/lone-kill-task-top.test.ts +85 -0
- package/src/strategies/goals/lone-kill-task-top.ts +86 -0
- package/src/strategies/goals/move-room-goal.ts +60 -0
- package/src/strategies/goals/normal-shrimp-top.test.ts +80 -0
- package/src/strategies/goals/normal-shrimp-top.ts +242 -0
- package/src/strategies/goals/paradise-fish-top.test.ts +126 -0
- package/src/strategies/goals/paradise-fish-top.ts +219 -0
- package/src/strategies/goals/patrol-top.ts +57 -0
- package/src/strategies/goals/report-patrol-top.ts +80 -0
- package/src/strategies/goals/safe-task-goal.ts +102 -0
- package/src/strategies/goals/social-task-top.ts +161 -0
- package/src/strategies/goals/task-kill-report-top.ts +163 -0
- package/src/strategies/goals/task-only-top.ts +57 -0
- package/src/strategies/goals/task-or-patrol-goal.ts +41 -0
- package/src/strategies/goals/task-report-top.ts +57 -0
- package/src/strategies/goals/wander-task-goal.ts +33 -0
- package/src/strategies/goals/warrior-shrimp-top.test.ts +86 -0
- package/src/strategies/goals/warrior-shrimp-top.ts +248 -0
- package/src/strategies/greeting.ts +53 -0
- package/src/strategies/kill-frenzy.ts +12 -0
- package/src/strategies/kill-lone.knowledge.md +20 -0
- package/src/strategies/kill-lone.ts +13 -0
- package/src/strategies/kill-target.ts +18 -0
- package/src/strategies/loader.test.ts +678 -0
- package/src/strategies/loader.ts +172 -0
- package/src/strategies/lone-kill-task.ts +21 -0
- package/src/strategies/meeting-gate.test.ts +59 -0
- package/src/strategies/meeting-gate.ts +23 -0
- package/src/strategies/move-room.ts +15 -0
- package/src/strategies/new-events-backfill.ts +98 -0
- package/src/strategies/paradise-fish.knowledge.md +20 -0
- package/src/strategies/paradise-fish.ts +25 -0
- package/src/strategies/pathfind/clawclaw-walkable.bin +0 -0
- package/src/strategies/pathfind/distance-field.ts +150 -0
- package/src/strategies/pathfind/escape-planner.test.ts +197 -0
- package/src/strategies/pathfind/escape-planner.ts +348 -0
- package/src/strategies/pathfind/walkable-grid.ts +117 -0
- package/src/strategies/patrol.ts +11 -0
- package/src/strategies/player-targets.ts +13 -0
- package/src/strategies/report-patrol.ts +11 -0
- package/src/strategies/shrimp-memory.knowledge.md +20 -0
- package/src/strategies/shrimp-memory.ts +25 -0
- package/src/strategies/social-task.test.ts +28 -0
- package/src/strategies/social-task.ts +49 -0
- package/src/strategies/spawn.ts +71 -0
- package/src/strategies/speech-module.ts +123 -0
- package/src/strategies/strategy-loop.ts +757 -0
- package/src/strategies/task-kill-report.ts +17 -0
- package/src/strategies/task-only.ts +11 -0
- package/src/strategies/task-report.ts +22 -0
- package/src/strategies/types.ts +96 -0
- package/src/strategies/warrior-memory.knowledge.md +20 -0
- package/src/strategies/warrior-memory.ts +16 -0
|
@@ -0,0 +1,130 @@
|
|
|
1
|
+
import { mkdtempSync, readFileSync, writeFileSync, existsSync, readdirSync } from 'fs';
|
|
2
|
+
import { tmpdir } from 'os';
|
|
3
|
+
import { dirname, join } from 'path';
|
|
4
|
+
import { describe, expect, it } from 'vitest';
|
|
5
|
+
import { runHostConfigSetup, unionArrayField, type HostConfigPatcher } from './host-config-patcher.js';
|
|
6
|
+
|
|
7
|
+
function tmpConfig(initial: unknown): string {
|
|
8
|
+
const dir = mkdtempSync(join(tmpdir(), 'host-cfg-'));
|
|
9
|
+
const p = join(dir, 'config.json');
|
|
10
|
+
writeFileSync(p, JSON.stringify(initial, null, 2));
|
|
11
|
+
return p;
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
const dummyHost: HostConfigPatcher<{ value: string }> = {
|
|
15
|
+
hostName: 'dummy',
|
|
16
|
+
resolveConfigPath: () => '/tmp/never-used',
|
|
17
|
+
computePatch: (current, opts) => {
|
|
18
|
+
const cur = (current as Record<string, unknown> | null) ?? {};
|
|
19
|
+
const before = (cur.values as string[] | undefined) ?? [];
|
|
20
|
+
if (before.includes(opts.value)) return { next: cur, changes: [], warnings: [] };
|
|
21
|
+
return {
|
|
22
|
+
next: { ...cur, values: [...before, opts.value] },
|
|
23
|
+
changes: [`add ${opts.value} to values`],
|
|
24
|
+
warnings: [],
|
|
25
|
+
};
|
|
26
|
+
},
|
|
27
|
+
};
|
|
28
|
+
|
|
29
|
+
describe('runHostConfigSetup', () => {
|
|
30
|
+
it('prints recommended patch in --print mode without touching disk', () => {
|
|
31
|
+
const r = runHostConfigSetup(dummyHost, { value: 'x' }, { print: true });
|
|
32
|
+
expect(r.exitCode).toBe(0);
|
|
33
|
+
expect(r.output.join('\n')).toContain('"values"');
|
|
34
|
+
});
|
|
35
|
+
|
|
36
|
+
it('reports missing config file gracefully', () => {
|
|
37
|
+
const r = runHostConfigSetup(dummyHost, { value: 'x' }, { configPath: '/no/such/file.json' });
|
|
38
|
+
expect(r.exitCode).toBe(0);
|
|
39
|
+
expect(r.output.some((l) => l.includes('not found'))).toBe(true);
|
|
40
|
+
});
|
|
41
|
+
|
|
42
|
+
it('reports malformed JSON with exit 1', () => {
|
|
43
|
+
const dir = mkdtempSync(join(tmpdir(), 'host-cfg-bad-'));
|
|
44
|
+
const p = join(dir, 'config.json');
|
|
45
|
+
writeFileSync(p, '{ not: valid json');
|
|
46
|
+
const r = runHostConfigSetup(dummyHost, { value: 'x' }, { configPath: p });
|
|
47
|
+
expect(r.exitCode).toBe(1);
|
|
48
|
+
expect(r.output.join('\n')).toMatch(/Failed to parse/);
|
|
49
|
+
});
|
|
50
|
+
|
|
51
|
+
it('returns exit 2 with diff in dry-run when changes pending', () => {
|
|
52
|
+
const p = tmpConfig({ values: ['a'] });
|
|
53
|
+
const r = runHostConfigSetup(dummyHost, { value: 'b' }, { configPath: p });
|
|
54
|
+
expect(r.exitCode).toBe(2);
|
|
55
|
+
const txt = r.output.join('\n');
|
|
56
|
+
expect(txt).toMatch(/Pending changes/);
|
|
57
|
+
expect(txt).toMatch(/Re-run with -y to apply/);
|
|
58
|
+
// file unchanged
|
|
59
|
+
expect(JSON.parse(readFileSync(p, 'utf-8'))).toEqual({ values: ['a'] });
|
|
60
|
+
});
|
|
61
|
+
|
|
62
|
+
it('returns exit 0 no-op when already up to date', () => {
|
|
63
|
+
const p = tmpConfig({ values: ['a'] });
|
|
64
|
+
const r = runHostConfigSetup(dummyHost, { value: 'a' }, { configPath: p });
|
|
65
|
+
expect(r.exitCode).toBe(0);
|
|
66
|
+
expect(r.output.join('\n')).toMatch(/already up to date/);
|
|
67
|
+
});
|
|
68
|
+
|
|
69
|
+
it('applies changes atomically with backup when -y', () => {
|
|
70
|
+
const p = tmpConfig({ values: ['a'] });
|
|
71
|
+
const r = runHostConfigSetup(dummyHost, { value: 'b' }, { configPath: p, yes: true });
|
|
72
|
+
expect(r.exitCode).toBe(0);
|
|
73
|
+
expect(JSON.parse(readFileSync(p, 'utf-8'))).toEqual({ values: ['a', 'b'] });
|
|
74
|
+
const files = readdirSync(dirname(p));
|
|
75
|
+
expect(files.some((f) => f.startsWith('config.json.bak.'))).toBe(true);
|
|
76
|
+
});
|
|
77
|
+
|
|
78
|
+
it('--no-backup skips backup file', () => {
|
|
79
|
+
const p = tmpConfig({ values: ['a'] });
|
|
80
|
+
const r = runHostConfigSetup(dummyHost, { value: 'b' }, { configPath: p, yes: true, backup: false });
|
|
81
|
+
expect(r.exitCode).toBe(0);
|
|
82
|
+
const files = readdirSync(dirname(p));
|
|
83
|
+
expect(files.some((f) => f.startsWith('config.json.bak.'))).toBe(false);
|
|
84
|
+
});
|
|
85
|
+
|
|
86
|
+
it('does not leave .tmp file behind on success', () => {
|
|
87
|
+
const p = tmpConfig({ values: ['a'] });
|
|
88
|
+
runHostConfigSetup(dummyHost, { value: 'b' }, { configPath: p, yes: true, backup: false });
|
|
89
|
+
const files = readdirSync(dirname(p));
|
|
90
|
+
expect(files.some((f) => f.includes('.tmp.'))).toBe(false);
|
|
91
|
+
});
|
|
92
|
+
|
|
93
|
+
it('preserves CRLF line endings when original file uses CRLF', () => {
|
|
94
|
+
const dir = mkdtempSync(join(tmpdir(), 'host-cfg-crlf-'));
|
|
95
|
+
const p = join(dir, 'config.json');
|
|
96
|
+
writeFileSync(p, '{\r\n "values": [\r\n "a"\r\n ]\r\n}\r\n');
|
|
97
|
+
runHostConfigSetup(dummyHost, { value: 'b' }, { configPath: p, yes: true, backup: false });
|
|
98
|
+
const after = readFileSync(p, 'utf-8');
|
|
99
|
+
expect(after.includes('\r\n')).toBe(true);
|
|
100
|
+
expect(after.replace(/\r\n/g, '<EOL>').includes('\n')).toBe(false);
|
|
101
|
+
});
|
|
102
|
+
|
|
103
|
+
it('preserves LF line endings when original file uses LF', () => {
|
|
104
|
+
const dir = mkdtempSync(join(tmpdir(), 'host-cfg-lf-'));
|
|
105
|
+
const p = join(dir, 'config.json');
|
|
106
|
+
writeFileSync(p, '{\n "values": [\n "a"\n ]\n}\n');
|
|
107
|
+
runHostConfigSetup(dummyHost, { value: 'b' }, { configPath: p, yes: true, backup: false });
|
|
108
|
+
const after = readFileSync(p, 'utf-8');
|
|
109
|
+
expect(after.includes('\r\n')).toBe(false);
|
|
110
|
+
});
|
|
111
|
+
});
|
|
112
|
+
|
|
113
|
+
describe('unionArrayField', () => {
|
|
114
|
+
it('creates new array when field missing', () => {
|
|
115
|
+
expect(unionArrayField(undefined, 'x')).toEqual({ next: ['x'], added: true });
|
|
116
|
+
});
|
|
117
|
+
|
|
118
|
+
it('returns warning when existing value is not an array', () => {
|
|
119
|
+
const r = unionArrayField('not-an-array', 'x');
|
|
120
|
+
expect(r).toEqual({ warning: 'existing value is not an array, refusing to overwrite' });
|
|
121
|
+
});
|
|
122
|
+
|
|
123
|
+
it('returns added=false when entry already present', () => {
|
|
124
|
+
expect(unionArrayField(['a', 'b'], 'a')).toEqual({ next: ['a', 'b'], added: false });
|
|
125
|
+
});
|
|
126
|
+
|
|
127
|
+
it('appends entry when missing from array', () => {
|
|
128
|
+
expect(unionArrayField(['a'], 'b')).toEqual({ next: ['a', 'b'], added: true });
|
|
129
|
+
});
|
|
130
|
+
});
|
|
@@ -0,0 +1,151 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Generic JSON-config setup runner shared by `ccl setup <host>` subcommands.
|
|
3
|
+
*
|
|
4
|
+
* Each host adapter only supplies:
|
|
5
|
+
* - resolveConfigPath(): where the host stores its global JSON config
|
|
6
|
+
* - computePatch(current, opts): pure function returning the desired next config + change/warning notes
|
|
7
|
+
*
|
|
8
|
+
* The runner handles dry-run, diff, atomic write, and timestamped backup uniformly,
|
|
9
|
+
* so adding a new host (gemini, claude-code, ...) is ~30 lines of glue.
|
|
10
|
+
*/
|
|
11
|
+
|
|
12
|
+
import { existsSync, readFileSync, renameSync, copyFileSync, writeFileSync } from 'fs';
|
|
13
|
+
|
|
14
|
+
export interface HostConfigPatcher<Opts extends object = Record<string, never>> {
|
|
15
|
+
hostName: string;
|
|
16
|
+
resolveConfigPath: () => string;
|
|
17
|
+
computePatch: (current: unknown, opts: Opts) => HostPatchResult;
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
export interface HostPatchResult {
|
|
21
|
+
next: unknown;
|
|
22
|
+
changes: string[];
|
|
23
|
+
warnings: string[];
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
export interface RunHostSetupFlags {
|
|
27
|
+
yes?: boolean;
|
|
28
|
+
print?: boolean;
|
|
29
|
+
configPath?: string;
|
|
30
|
+
backup?: boolean;
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
export interface RunHostSetupResult {
|
|
34
|
+
exitCode: number;
|
|
35
|
+
output: string[];
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
export function runHostConfigSetup<Opts extends object>(
|
|
39
|
+
patcher: HostConfigPatcher<Opts>,
|
|
40
|
+
hostOpts: Opts,
|
|
41
|
+
flags: RunHostSetupFlags,
|
|
42
|
+
): RunHostSetupResult {
|
|
43
|
+
const out: string[] = [];
|
|
44
|
+
const configPath = flags.configPath ?? patcher.resolveConfigPath();
|
|
45
|
+
|
|
46
|
+
if (flags.print) {
|
|
47
|
+
const sample = patcher.computePatch({}, hostOpts);
|
|
48
|
+
out.push(`# Recommended ${patcher.hostName} config patch:`);
|
|
49
|
+
out.push(JSON.stringify(sample.next, null, 2));
|
|
50
|
+
return { exitCode: 0, output: out };
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
if (!existsSync(configPath)) {
|
|
54
|
+
out.push(`${patcher.hostName} config not found at: ${configPath}`);
|
|
55
|
+
out.push(`Initialize it first (e.g. \`openclaw doctor\` for OpenClaw), then re-run.`);
|
|
56
|
+
return { exitCode: 0, output: out };
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
let raw: string;
|
|
60
|
+
try {
|
|
61
|
+
raw = readFileSync(configPath, 'utf-8');
|
|
62
|
+
} catch (err: any) {
|
|
63
|
+
out.push(`Failed to read ${configPath}: ${err?.message ?? err}`);
|
|
64
|
+
return { exitCode: 1, output: out };
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
let current: unknown;
|
|
68
|
+
try {
|
|
69
|
+
current = JSON.parse(raw);
|
|
70
|
+
} catch (err: any) {
|
|
71
|
+
out.push(`Failed to parse JSON at ${configPath}: ${err?.message ?? err}`);
|
|
72
|
+
out.push(`Fix the JSON manually first; this tool does not edit malformed files.`);
|
|
73
|
+
return { exitCode: 1, output: out };
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
const { next, changes, warnings } = patcher.computePatch(current, hostOpts);
|
|
77
|
+
|
|
78
|
+
for (const w of warnings) out.push(`warning: ${w}`);
|
|
79
|
+
|
|
80
|
+
if (changes.length === 0) {
|
|
81
|
+
out.push(`${patcher.hostName} config already up to date at ${configPath}.`);
|
|
82
|
+
return { exitCode: 0, output: out };
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
if (!flags.yes) {
|
|
86
|
+
out.push(`Pending changes to ${configPath}:`);
|
|
87
|
+
for (const c of changes) out.push(` - ${c}`);
|
|
88
|
+
out.push(``);
|
|
89
|
+
out.push(diffJson(current, next));
|
|
90
|
+
out.push(``);
|
|
91
|
+
out.push(`Dry-run only. Re-run with -y to apply.`);
|
|
92
|
+
return { exitCode: 2, output: out };
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
let backupPath: string | undefined;
|
|
96
|
+
if (flags.backup !== false) {
|
|
97
|
+
const ts = new Date().toISOString().replace(/[:.]/g, '-');
|
|
98
|
+
backupPath = `${configPath}.bak.${ts}`;
|
|
99
|
+
try {
|
|
100
|
+
copyFileSync(configPath, backupPath);
|
|
101
|
+
} catch (err: any) {
|
|
102
|
+
out.push(`Failed to back up ${configPath} → ${backupPath}: ${err?.message ?? err}`);
|
|
103
|
+
return { exitCode: 1, output: out };
|
|
104
|
+
}
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
const tmpPath = `${configPath}.tmp.${process.pid}`;
|
|
108
|
+
try {
|
|
109
|
+
const eol = raw.includes('\r\n') ? '\r\n' : '\n';
|
|
110
|
+
const serialized = JSON.stringify(next, null, 2).replace(/\n/g, eol) + eol;
|
|
111
|
+
writeFileSync(tmpPath, serialized, 'utf-8');
|
|
112
|
+
renameSync(tmpPath, configPath);
|
|
113
|
+
} catch (err: any) {
|
|
114
|
+
out.push(`Failed to write ${configPath}: ${err?.message ?? err}`);
|
|
115
|
+
return { exitCode: 1, output: out };
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
out.push(`Updated ${configPath}:`);
|
|
119
|
+
for (const c of changes) out.push(` - ${c}`);
|
|
120
|
+
if (backupPath) out.push(`Backup: ${backupPath}`);
|
|
121
|
+
return { exitCode: 0, output: out };
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
/** Minimal line-level JSON diff for the dry-run preview. Self-contained, zero deps. */
|
|
125
|
+
export function diffJson(before: unknown, after: unknown): string {
|
|
126
|
+
const a = JSON.stringify(before, null, 2).split('\n');
|
|
127
|
+
const b = JSON.stringify(after, null, 2).split('\n');
|
|
128
|
+
const aSet = new Set(a);
|
|
129
|
+
const bSet = new Set(b);
|
|
130
|
+
const lines: string[] = [];
|
|
131
|
+
const max = Math.max(a.length, b.length);
|
|
132
|
+
for (let i = 0; i < max; i++) {
|
|
133
|
+
const ax = a[i];
|
|
134
|
+
const bx = b[i];
|
|
135
|
+
if (ax === bx) {
|
|
136
|
+
lines.push(` ${ax ?? ''}`);
|
|
137
|
+
} else {
|
|
138
|
+
if (ax !== undefined && !bSet.has(ax)) lines.push(`- ${ax}`);
|
|
139
|
+
if (bx !== undefined && !aSet.has(bx)) lines.push(`+ ${bx}`);
|
|
140
|
+
}
|
|
141
|
+
}
|
|
142
|
+
return lines.join('\n');
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
/** Shared helper for hosts: add an entry to an array field, returning a new array (Set union). */
|
|
146
|
+
export function unionArrayField(arr: unknown, entry: string): { next: string[]; added: boolean } | { warning: string } {
|
|
147
|
+
if (arr === undefined) return { next: [entry], added: true };
|
|
148
|
+
if (!Array.isArray(arr)) return { warning: `existing value is not an array, refusing to overwrite` };
|
|
149
|
+
if (arr.includes(entry)) return { next: arr.slice() as string[], added: false };
|
|
150
|
+
return { next: [...(arr as string[]), entry], added: true };
|
|
151
|
+
}
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
import { Agent, setGlobalDispatcher } from 'undici';
|
|
2
|
+
|
|
3
|
+
let initialized = false;
|
|
4
|
+
|
|
5
|
+
export function initHttpKeepAlive(): void {
|
|
6
|
+
if (initialized) return;
|
|
7
|
+
initialized = true;
|
|
8
|
+
|
|
9
|
+
setGlobalDispatcher(new Agent({
|
|
10
|
+
keepAliveTimeout: 30_000,
|
|
11
|
+
keepAliveMaxTimeout: 120_000,
|
|
12
|
+
connections: 16,
|
|
13
|
+
pipelining: 1,
|
|
14
|
+
}));
|
|
15
|
+
}
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
// src/lib/http-transport.test.ts
|
|
2
|
+
import { describe, it, expect, vi, afterEach } from 'vitest';
|
|
3
|
+
import { HttpTransport, ApiError } from './http-transport.js';
|
|
4
|
+
|
|
5
|
+
const registry: any = { baseUrlFor: () => 'https://hub.example' };
|
|
6
|
+
|
|
7
|
+
afterEach(() => { vi.restoreAllMocks(); });
|
|
8
|
+
|
|
9
|
+
describe('HttpTransport.getBytes', () => {
|
|
10
|
+
it('returns response bytes as a Buffer', async () => {
|
|
11
|
+
const bytes = new Uint8Array([1, 2, 3, 4]);
|
|
12
|
+
vi.stubGlobal('fetch', vi.fn(async () => new Response(bytes, { status: 200 })));
|
|
13
|
+
const t = new HttpTransport('key', registry);
|
|
14
|
+
const buf = await t.getBytes('/api/v1/hub/x');
|
|
15
|
+
expect(Buffer.isBuffer(buf)).toBe(true);
|
|
16
|
+
expect([...buf]).toEqual([1, 2, 3, 4]);
|
|
17
|
+
});
|
|
18
|
+
|
|
19
|
+
it('throws ApiError on non-ok', async () => {
|
|
20
|
+
vi.stubGlobal('fetch', vi.fn(async () => new Response('nope', { status: 404 })));
|
|
21
|
+
const t = new HttpTransport('key', registry);
|
|
22
|
+
await expect(t.getBytes('/api/v1/hub/x')).rejects.toBeInstanceOf(ApiError);
|
|
23
|
+
});
|
|
24
|
+
});
|
|
25
|
+
|
|
26
|
+
describe('HttpTransport extraHeaders', () => {
|
|
27
|
+
it('merges extraHeaders into request() headers', async () => {
|
|
28
|
+
let captured: any;
|
|
29
|
+
vi.stubGlobal('fetch', vi.fn(async (_url: string, init: any) => { captured = init.headers; return new Response('{}', { status: 200 }); }));
|
|
30
|
+
const t = new HttpTransport('key', registry, { 'X-Hub-Auth-Type': 'clawkey' });
|
|
31
|
+
await t.request('GET', '/x');
|
|
32
|
+
expect(captured['X-Hub-Auth-Type']).toBe('clawkey');
|
|
33
|
+
expect(captured['Authorization']).toBe('Bearer key');
|
|
34
|
+
});
|
|
35
|
+
it('merges extraHeaders into getBytes() headers', async () => {
|
|
36
|
+
let captured: any;
|
|
37
|
+
vi.stubGlobal('fetch', vi.fn(async (_url: string, init: any) => { captured = init.headers; return new Response(new Uint8Array([1]), { status: 200 }); }));
|
|
38
|
+
const t = new HttpTransport('key', registry, { 'X-Hub-Auth-Type': 'clawkey' });
|
|
39
|
+
await t.getBytes('/x');
|
|
40
|
+
expect(captured['X-Hub-Auth-Type']).toBe('clawkey');
|
|
41
|
+
});
|
|
42
|
+
});
|
|
@@ -0,0 +1,113 @@
|
|
|
1
|
+
// src/lib/http-transport.ts
|
|
2
|
+
import type { ServerRegistry } from './server-registry.js';
|
|
3
|
+
|
|
4
|
+
export class ApiError extends Error {
|
|
5
|
+
constructor(
|
|
6
|
+
public readonly status: number,
|
|
7
|
+
public readonly body: string,
|
|
8
|
+
public readonly method: string,
|
|
9
|
+
public readonly path: string,
|
|
10
|
+
) {
|
|
11
|
+
super(`API error ${status}: ${body}`);
|
|
12
|
+
this.name = 'ApiError';
|
|
13
|
+
}
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
function parseJsonBody(body: string): any | null {
|
|
17
|
+
try {
|
|
18
|
+
return JSON.parse(body);
|
|
19
|
+
} catch {
|
|
20
|
+
return null;
|
|
21
|
+
}
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
export function formatApiError(err: ApiError): string {
|
|
25
|
+
if (err.status === 429) {
|
|
26
|
+
const data = parseJsonBody(err.body);
|
|
27
|
+
const error = data?.error ?? {};
|
|
28
|
+
const code = error?.code ?? data?.code ?? 'RATE_LIMITED';
|
|
29
|
+
const retryAfter = error?.retry_after ?? error?.['retry after'] ?? data?.retry_after ?? data?.['retry after'];
|
|
30
|
+
const hint = error?.hint ?? data?.hint;
|
|
31
|
+
const message = error?.message ?? data?.message ?? 'Too many requests.';
|
|
32
|
+
const retryText = retryAfter !== undefined ? ` Retry after ${retryAfter}s.` : '';
|
|
33
|
+
const hintText = hint ? ` Hint: ${hint}.` : '';
|
|
34
|
+
return `Rate limited (${code}). ${message}.${retryText}${hintText}`;
|
|
35
|
+
}
|
|
36
|
+
return `Request failed (${err.status}): ${err.body}`;
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
export class HttpTransport {
|
|
40
|
+
private apiKey: string;
|
|
41
|
+
private registry: ServerRegistry;
|
|
42
|
+
private extraHeaders: Record<string, string>;
|
|
43
|
+
|
|
44
|
+
constructor(apiKey: string, registry: ServerRegistry, extraHeaders: Record<string, string> = {}) {
|
|
45
|
+
this.apiKey = apiKey;
|
|
46
|
+
this.registry = registry;
|
|
47
|
+
this.extraHeaders = extraHeaders;
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
/**
|
|
51
|
+
* Generic HTTP request. Supports JSON body and FormData.
|
|
52
|
+
* Adds Authorization header when apiKey is non-empty.
|
|
53
|
+
*/
|
|
54
|
+
async request<T = any>(method: string, path: string, body?: any): Promise<T> {
|
|
55
|
+
const url = this.registry.baseUrlFor(path) + path;
|
|
56
|
+
const headers: Record<string, string> = {};
|
|
57
|
+
|
|
58
|
+
// Only add auth header if apiKey is present (register endpoint has no auth)
|
|
59
|
+
if (this.apiKey) {
|
|
60
|
+
headers['Authorization'] = `Bearer ${this.apiKey}`;
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
for (const [k, v] of Object.entries(this.extraHeaders)) headers[k] = v;
|
|
64
|
+
|
|
65
|
+
let fetchBody: BodyInit | undefined;
|
|
66
|
+
if (body !== undefined) {
|
|
67
|
+
if (body instanceof FormData) {
|
|
68
|
+
fetchBody = body;
|
|
69
|
+
// Let fetch set Content-Type with boundary for FormData
|
|
70
|
+
} else {
|
|
71
|
+
headers['Content-Type'] = 'application/json; charset=utf-8';
|
|
72
|
+
fetchBody = JSON.stringify(body);
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
const res = await fetch(url, { method, headers, body: fetchBody, signal: AbortSignal.timeout(10_000) });
|
|
77
|
+
if (!res.ok) {
|
|
78
|
+
throw new ApiError(res.status, await res.text(), method, path);
|
|
79
|
+
}
|
|
80
|
+
return res.json() as Promise<T>;
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
/** GET with one fast retry for transient network failures. */
|
|
84
|
+
async get<T = any>(path: string): Promise<T> {
|
|
85
|
+
try {
|
|
86
|
+
return await this.request<T>('GET', path);
|
|
87
|
+
} catch (err) {
|
|
88
|
+
// Only retry network errors, not HTTP errors
|
|
89
|
+
if (err instanceof ApiError) throw err;
|
|
90
|
+
await new Promise(r => setTimeout(r, 500));
|
|
91
|
+
return this.request<T>('GET', path);
|
|
92
|
+
}
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
async post<T = any>(path: string, body?: any): Promise<T> {
|
|
96
|
+
return this.request<T>('POST', path, body);
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
/** GET raw bytes (binary artifacts). Throws ApiError on non-ok. */
|
|
100
|
+
async getBytes(path: string): Promise<Buffer> {
|
|
101
|
+
const url = this.registry.baseUrlFor(path) + path;
|
|
102
|
+
const headers: Record<string, string> = {};
|
|
103
|
+
if (this.apiKey) {
|
|
104
|
+
headers['Authorization'] = `Bearer ${this.apiKey}`;
|
|
105
|
+
}
|
|
106
|
+
for (const [k, v] of Object.entries(this.extraHeaders)) headers[k] = v;
|
|
107
|
+
const res = await fetch(url, { method: 'GET', headers, signal: AbortSignal.timeout(30_000) });
|
|
108
|
+
if (!res.ok) {
|
|
109
|
+
throw new ApiError(res.status, await res.text(), 'GET', path);
|
|
110
|
+
}
|
|
111
|
+
return Buffer.from(await res.arrayBuffer());
|
|
112
|
+
}
|
|
113
|
+
}
|
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
import { describe, it, expect } from 'vitest';
|
|
2
|
+
import { HubClient, parseResourceRef } from './hub-client.js';
|
|
3
|
+
|
|
4
|
+
function fakeTransport() {
|
|
5
|
+
const calls: any[] = [];
|
|
6
|
+
const transport: any = {
|
|
7
|
+
calls,
|
|
8
|
+
async get(path: string) {
|
|
9
|
+
calls.push(['GET', path]);
|
|
10
|
+
if (path.includes('/resources/')) return { data: { id: 'abc', type: 'strategy', title: 'T' } };
|
|
11
|
+
return { data: { items: [], total: 0, pagination: { mode: 'page', page: 1, limit: 20, hasMore: false } } };
|
|
12
|
+
},
|
|
13
|
+
async getBytes(path: string) { calls.push(['GETBYTES', path]); return Buffer.from('raw'); },
|
|
14
|
+
};
|
|
15
|
+
return transport;
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
describe('parseResourceRef', () => {
|
|
19
|
+
it('splits type/id', () => {
|
|
20
|
+
expect(parseResourceRef('strategy/ab12cd')).toEqual({ type: 'strategy', id: 'ab12cd' });
|
|
21
|
+
expect(parseResourceRef('skill/xyz')).toEqual({ type: 'skill', id: 'xyz' });
|
|
22
|
+
});
|
|
23
|
+
it('rejects bad type', () => {
|
|
24
|
+
expect(() => parseResourceRef('plugin/abc')).toThrow(/invalid resource ref/);
|
|
25
|
+
});
|
|
26
|
+
it('rejects missing id', () => {
|
|
27
|
+
expect(() => parseResourceRef('strategy/')).toThrow(/invalid resource ref/);
|
|
28
|
+
});
|
|
29
|
+
});
|
|
30
|
+
|
|
31
|
+
describe('HubClient', () => {
|
|
32
|
+
it('list builds query and unwraps data', async () => {
|
|
33
|
+
const t = fakeTransport();
|
|
34
|
+
const res = await new HubClient(t).list({ type: 'skill', sort: 'downloads', q: '抢刀', limit: 10 });
|
|
35
|
+
expect(t.calls[0][1]).toBe('/api/client/v1/resources?type=skill&q=%E6%8A%A2%E5%88%80&sort=downloads&limit=10');
|
|
36
|
+
expect(res.total).toBe(0);
|
|
37
|
+
expect(res.items).toEqual([]);
|
|
38
|
+
});
|
|
39
|
+
it('list with no opts hits bare endpoint', async () => {
|
|
40
|
+
const t = fakeTransport();
|
|
41
|
+
await new HubClient(t).list();
|
|
42
|
+
expect(t.calls[0][1]).toBe('/api/client/v1/resources');
|
|
43
|
+
});
|
|
44
|
+
it('getResource builds typed path and unwraps data', async () => {
|
|
45
|
+
const t = fakeTransport();
|
|
46
|
+
const d = await new HubClient(t).getResource('strategy', 'ab12');
|
|
47
|
+
expect(t.calls[0]).toEqual(['GET', '/api/client/v1/resources/strategy/ab12']);
|
|
48
|
+
expect(d.id).toBe('abc');
|
|
49
|
+
});
|
|
50
|
+
it('downloadArtifact hits the /download endpoint (encoding id)', async () => {
|
|
51
|
+
const t = fakeTransport();
|
|
52
|
+
const buf = await new HubClient(t).downloadArtifact('skill', 'xy z');
|
|
53
|
+
expect(t.calls[0]).toEqual(['GETBYTES', '/api/client/v1/resources/skill/xy%20z/download']);
|
|
54
|
+
expect(Buffer.isBuffer(buf)).toBe(true);
|
|
55
|
+
});
|
|
56
|
+
});
|
|
@@ -0,0 +1,88 @@
|
|
|
1
|
+
// src/lib/hub-client.ts
|
|
2
|
+
import { AuthStore } from './auth.js';
|
|
3
|
+
import { ServerRegistry } from './server-registry.js';
|
|
4
|
+
import { HttpTransport } from './http-transport.js';
|
|
5
|
+
|
|
6
|
+
export type ResourceType = 'skill' | 'strategy';
|
|
7
|
+
|
|
8
|
+
export interface ResourceStats { downloadCount: number; starCount: number; commentCount: number; }
|
|
9
|
+
|
|
10
|
+
export interface ResourceSummary {
|
|
11
|
+
id: string;
|
|
12
|
+
type: ResourceType;
|
|
13
|
+
title: string;
|
|
14
|
+
description: string;
|
|
15
|
+
creator: string;
|
|
16
|
+
creatorType: string;
|
|
17
|
+
creatorDisplayName: string;
|
|
18
|
+
creatorAvatarUrl: string | null;
|
|
19
|
+
fileName: string;
|
|
20
|
+
stats: ResourceStats;
|
|
21
|
+
downloadUrl: string;
|
|
22
|
+
likedByMe: boolean;
|
|
23
|
+
createdAt: string;
|
|
24
|
+
updatedAt: string;
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
export interface ResourceDetail extends ResourceSummary {
|
|
28
|
+
artifact: { fileName: string; downloadUrl: string };
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
export interface Pagination { mode: 'page' | 'none'; page?: number; limit?: number; hasMore: boolean; }
|
|
32
|
+
export interface ResourceListResult { items: ResourceSummary[]; total: number; pagination: Pagination; }
|
|
33
|
+
|
|
34
|
+
export interface ListOptions {
|
|
35
|
+
type?: ResourceType;
|
|
36
|
+
q?: string;
|
|
37
|
+
sort?: 'latest' | 'downloads' | 'stars';
|
|
38
|
+
pagination?: 'page' | 'none';
|
|
39
|
+
page?: number;
|
|
40
|
+
limit?: number;
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
const BASE = '/api/client/v1';
|
|
44
|
+
const DEFAULT_HUB_URL = 'https://myclaw.163.com/hub';
|
|
45
|
+
|
|
46
|
+
/** Parse a `<type>/<id>` resource ref (type ∈ skill|strategy). */
|
|
47
|
+
export function parseResourceRef(ref: string): { type: ResourceType; id: string } {
|
|
48
|
+
const m = ref.match(/^(skill|strategy)\/([^/\s]+)$/);
|
|
49
|
+
if (!m) throw new Error(`invalid resource ref '${ref}' (expected <skill|strategy>/<id>)`);
|
|
50
|
+
return { type: m[1] as ResourceType, id: m[2] };
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
interface Envelope<T> { data: T; }
|
|
54
|
+
|
|
55
|
+
export class HubClient {
|
|
56
|
+
constructor(private readonly http: HttpTransport) {}
|
|
57
|
+
|
|
58
|
+
static fromAuth(opts?: { authStore?: AuthStore }): HubClient {
|
|
59
|
+
const store = opts?.authStore ?? new AuthStore();
|
|
60
|
+
const profile = store.getActive();
|
|
61
|
+
const apiKey = profile?.apiKey ?? '';
|
|
62
|
+
const hubUrl = process.env.CLAWCLAW_HUB_URL || DEFAULT_HUB_URL;
|
|
63
|
+
const registry = new ServerRegistry({ lobbyUrl: hubUrl });
|
|
64
|
+
return new HubClient(new HttpTransport(apiKey, registry, { 'X-Hub-Auth-Type': 'clawkey' }));
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
async list(opts: ListOptions = {}): Promise<ResourceListResult> {
|
|
68
|
+
const qs = new URLSearchParams();
|
|
69
|
+
if (opts.type) qs.set('type', opts.type);
|
|
70
|
+
if (opts.q) qs.set('q', opts.q);
|
|
71
|
+
if (opts.sort) qs.set('sort', opts.sort);
|
|
72
|
+
if (opts.pagination) qs.set('pagination', opts.pagination);
|
|
73
|
+
if (opts.page !== undefined) qs.set('page', String(opts.page));
|
|
74
|
+
if (opts.limit !== undefined) qs.set('limit', String(opts.limit));
|
|
75
|
+
const suffix = qs.toString() ? `?${qs.toString()}` : '';
|
|
76
|
+
const res = await this.http.get<Envelope<ResourceListResult>>(`${BASE}/resources${suffix}`);
|
|
77
|
+
return res.data;
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
async getResource(type: ResourceType, id: string): Promise<ResourceDetail> {
|
|
81
|
+
const res = await this.http.get<Envelope<ResourceDetail>>(`${BASE}/resources/${type}/${encodeURIComponent(id)}`);
|
|
82
|
+
return res.data;
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
async downloadArtifact(type: ResourceType, id: string): Promise<Buffer> {
|
|
86
|
+
return this.http.getBytes(`${BASE}/resources/${type}/${encodeURIComponent(id)}/download`);
|
|
87
|
+
}
|
|
88
|
+
}
|