@ftai/ftai-plugin-ft-bot 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,238 @@
1
+ import { homedir } from 'node:os';
2
+ import { isAbsolute, join } from 'node:path';
3
+ import { chmod, mkdir, readFile, rename, writeFile } from 'node:fs/promises';
4
+ import { randomUUID } from 'node:crypto';
5
+ import { downloadRunner, gateway } from "./download.js";
6
+ import { computerStatus, launchRunner } from "./runner.js";
7
+ import { DEFAULT_GATEWAY } from "./types.js";
8
+ export function stateDirectory() {
9
+ if (process.env.FT_BOT_PLUGIN_HOME)
10
+ return process.env.FT_BOT_PLUGIN_HOME;
11
+ if (process.platform === 'win32') {
12
+ if (!process.env.LOCALAPPDATA)
13
+ throw new Error('LOCALAPPDATA is not set.');
14
+ return join(process.env.LOCALAPPDATA, 'ft-bot-desktop-plugin');
15
+ }
16
+ return join(homedir(), '.local', 'share', 'ft-bot-desktop-plugin');
17
+ }
18
+ export class Controller {
19
+ directory;
20
+ override;
21
+ chats;
22
+ config = { server: '', executable: null, enabled: false };
23
+ snapshot = {
24
+ server: DEFAULT_GATEWAY, installed: false, enabled: false, busy: true, connection: 'stopped', computer: null, error: null,
25
+ };
26
+ abort = new AbortController();
27
+ children = new Set();
28
+ running;
29
+ ready;
30
+ constructor(directory, override = process.env.FT_BOT_RUNNER_BINARY, chats) {
31
+ this.directory = directory;
32
+ this.override = override;
33
+ this.chats = chats;
34
+ this.ready = this.load().catch(error => {
35
+ this.snapshot.error = String(error.message);
36
+ if (this.config.enabled)
37
+ this.snapshot.connection = 'error';
38
+ }).finally(() => { this.snapshot.busy = false; });
39
+ }
40
+ getStatus() { return { ...this.snapshot }; }
41
+ alive() {
42
+ if (this.abort.signal.aborted)
43
+ throw new Error('The plugin has stopped.');
44
+ }
45
+ executable() {
46
+ const executable = this.override || this.config.executable;
47
+ if (!executable || !isAbsolute(executable))
48
+ throw new Error('Download the runner first.');
49
+ return executable;
50
+ }
51
+ async load() {
52
+ if (!isAbsolute(this.directory))
53
+ throw new Error('Plugin state directory must be absolute.');
54
+ await mkdir(this.directory, { recursive: true, mode: 0o700 });
55
+ if (process.platform !== 'win32')
56
+ await chmod(this.directory, 0o700);
57
+ try {
58
+ const config = JSON.parse(await readFile(join(this.directory, 'config.json'), 'utf8'));
59
+ if (typeof config.enabled !== 'boolean' || typeof config.server !== 'string'
60
+ || !(config.executable === null || (typeof config.executable === 'string' && isAbsolute(config.executable)))) {
61
+ throw new Error('Invalid plugin configuration.');
62
+ }
63
+ this.config = { server: config.server ? gateway(config.server) : '', executable: config.executable, enabled: config.enabled };
64
+ }
65
+ catch (error) {
66
+ if (error.code !== 'ENOENT')
67
+ throw error;
68
+ }
69
+ this.alive();
70
+ this.snapshot.server = this.config.server || DEFAULT_GATEWAY;
71
+ this.snapshot.enabled = this.config.enabled;
72
+ this.snapshot.installed = Boolean(this.override || this.config.executable);
73
+ if (this.snapshot.installed) {
74
+ await this.inspect();
75
+ if (this.config.enabled)
76
+ this.startRunner();
77
+ }
78
+ }
79
+ async save(config) {
80
+ this.alive();
81
+ const temporary = join(this.directory, `.config-${randomUUID()}`);
82
+ await writeFile(temporary, JSON.stringify(config), { mode: 0o600, flag: 'wx' });
83
+ await rename(temporary, join(this.directory, 'config.json'));
84
+ this.config = config;
85
+ this.snapshot.server = config.server || DEFAULT_GATEWAY;
86
+ this.snapshot.enabled = config.enabled;
87
+ this.snapshot.installed = Boolean(this.override || config.executable);
88
+ }
89
+ async request(request) {
90
+ this.alive();
91
+ const runner = launchRunner(this.executable(), join(this.directory, 'runner'), request);
92
+ this.children.add(runner);
93
+ let timedOut = false;
94
+ const timer = setTimeout(() => { timedOut = true; void runner.stop(); }, 30_000);
95
+ try {
96
+ const result = await runner.done;
97
+ this.alive();
98
+ if (timedOut)
99
+ throw new Error('Runner request timed out.');
100
+ return computerStatus(result);
101
+ }
102
+ finally {
103
+ clearTimeout(timer);
104
+ this.children.delete(runner);
105
+ }
106
+ }
107
+ async inspect() {
108
+ this.snapshot.computer = await this.request({ type: 'status' });
109
+ const server = this.snapshot.computer.server;
110
+ if (this.snapshot.computer.device_id && server && this.config.server && gateway(server) !== this.config.server) {
111
+ throw new Error('Saved pairing belongs to another gateway.');
112
+ }
113
+ }
114
+ startRunner() {
115
+ this.alive();
116
+ if (this.running)
117
+ return;
118
+ if (!this.snapshot.computer?.device_id)
119
+ throw new Error('Pair this computer first.');
120
+ this.snapshot.connection = 'connecting';
121
+ const runner = launchRunner(this.executable(), join(this.directory, 'runner'), { type: 'run' }, status => {
122
+ if (this.running === runner)
123
+ this.snapshot.connection = status;
124
+ }, this.chats);
125
+ this.running = runner;
126
+ this.children.add(runner);
127
+ void runner.done.then(() => {
128
+ if (this.running === runner)
129
+ this.snapshot.connection = 'stopped';
130
+ }, error => {
131
+ if (this.running === runner) {
132
+ this.snapshot.connection = 'error';
133
+ this.snapshot.error = error.message;
134
+ }
135
+ }).finally(() => {
136
+ this.children.delete(runner);
137
+ if (this.running === runner)
138
+ this.running = undefined;
139
+ });
140
+ }
141
+ async stopRunner() {
142
+ const runner = this.running;
143
+ this.running = undefined;
144
+ if (runner)
145
+ await runner.stop();
146
+ this.snapshot.connection = 'stopped';
147
+ }
148
+ async operate(work) {
149
+ await this.ready;
150
+ this.alive();
151
+ if (this.snapshot.busy)
152
+ throw new Error('Another operation is still running.');
153
+ this.snapshot.busy = true;
154
+ this.snapshot.error = null;
155
+ try {
156
+ await work();
157
+ }
158
+ catch (error) {
159
+ this.snapshot.error = error.message;
160
+ throw error;
161
+ }
162
+ finally {
163
+ this.snapshot.busy = false;
164
+ }
165
+ return this.getStatus();
166
+ }
167
+ async pair(server, code) {
168
+ return this.operate(async () => {
169
+ server = gateway(server.trim() || DEFAULT_GATEWAY);
170
+ if (typeof code !== 'string' || !code.trim() || code.length > 256)
171
+ throw new Error('Enter the pairing code from the bot.');
172
+ if (this.snapshot.computer?.device_id)
173
+ throw new Error('This computer is already paired.');
174
+ if (!this.snapshot.installed)
175
+ await this.download(server);
176
+ this.snapshot.computer = await this.request({ type: 'pair', server, code });
177
+ await this.save({ ...this.config, server, enabled: true });
178
+ this.startRunner();
179
+ });
180
+ }
181
+ async download(server) {
182
+ const executable = this.override || await downloadRunner(server, join(this.directory, 'bin'), AbortSignal.any([this.abort.signal, AbortSignal.timeout(180_000)]));
183
+ this.alive();
184
+ // Probe the stdio contract before selecting a release. Failed upgrades keep the old path.
185
+ const previous = this.config;
186
+ this.config = { ...previous, executable };
187
+ try {
188
+ await this.inspect();
189
+ }
190
+ catch (error) {
191
+ this.config = previous;
192
+ throw error;
193
+ }
194
+ await this.save({ ...this.config, server });
195
+ }
196
+ async updateRunner() {
197
+ return this.operate(async () => {
198
+ if (!this.config.server)
199
+ throw new Error('Pair with a gateway first.');
200
+ await this.stopRunner();
201
+ try {
202
+ await this.download(this.config.server);
203
+ }
204
+ finally {
205
+ if (this.config.enabled)
206
+ this.startRunner();
207
+ }
208
+ });
209
+ }
210
+ async setEnabled(enabled) {
211
+ return this.operate(async () => {
212
+ if (typeof enabled !== 'boolean')
213
+ throw new Error('Invalid connection setting.');
214
+ if (enabled) {
215
+ await this.inspect();
216
+ if (!this.snapshot.computer?.device_id)
217
+ throw new Error('Pair this computer first.');
218
+ }
219
+ await this.save({ ...this.config, enabled });
220
+ if (enabled)
221
+ this.startRunner();
222
+ else
223
+ await this.stopRunner();
224
+ });
225
+ }
226
+ async refresh() { return this.operate(() => this.inspect()); }
227
+ async requestPermissions() {
228
+ return this.operate(async () => {
229
+ this.snapshot.computer = await this.request({ type: 'permissions' });
230
+ });
231
+ }
232
+ async dispose() {
233
+ this.abort.abort();
234
+ this.running = undefined;
235
+ await Promise.all([...this.children].map(runner => runner.stop()));
236
+ }
237
+ }
238
+ //# sourceMappingURL=controller.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"controller.js","sourceRoot":"","sources":["../src/controller.ts"],"names":[],"mappings":"AAAA,OAAO,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AAC,CAAA;IACJ,CAAC;IAED,KAAK,CAAC,OAAO,KAAK,OAAO,IAAI,CAAC,OAAO,CAAC,GAAG,EAAE,CAAC,IAAI,CAAC,OAAO,EAAE,CAAC,CAAA,CAAC,CAAC;IAE7D,KAAK,CAAC,kBAAkB;QACtB,OAAO,IAAI,CAAC,OAAO,CAAC,KAAK,IAAI,EAAE;YAC7B,IAAI,CAAC,QAAQ,CAAC,QAAQ,GAAG,MAAM,IAAI,CAAC,OAAO,CAAC,EAAE,IAAI,EAAE,aAAa,EAAE,CAAC,CAAA;QACtE,CAAC,CAAC,CAAA;IACJ,CAAC;IAED,KAAK,CAAC,OAAO;QACX,IAAI,CAAC,KAAK,CAAC,KAAK,EAAE,CAAA;QAClB,IAAI,CAAC,OAAO,GAAG,SAAS,CAAA;QACxB,MAAM,OAAO,CAAC,GAAG,CAAC,CAAC,GAAG,IAAI,CAAC,QAAQ,CAAC,CAAC,GAAG,CAAC,MAAM,CAAC,EAAE,CAAC,MAAM,CAAC,IAAI,EAAE,CAAC,CAAC,CAAA;IACpE,CAAC;CACF"}
@@ -0,0 +1,9 @@
1
+ export declare const PROTOCOL = 4;
2
+ export declare function gateway(value: string): string;
3
+ export declare function artifactFor(manifest: unknown, platform?: NodeJS.Platform, arch?: NodeJS.Architecture): {
4
+ revision: string;
5
+ filename: string;
6
+ sha256: string;
7
+ bytes: number;
8
+ };
9
+ export declare function downloadRunner(server: string, directory: string, signal: AbortSignal): Promise<string>;
@@ -0,0 +1,84 @@
1
+ import { createHash, randomUUID } from 'node:crypto';
2
+ import { mkdir, open, rename, rm } from 'node:fs/promises';
3
+ import { join } from 'node:path';
4
+ export const PROTOCOL = 4;
5
+ export function gateway(value) {
6
+ const url = new URL(value.trim());
7
+ if ((url.protocol !== 'https:' && !(url.protocol === 'http:' && ['localhost', '127.0.0.1', '[::1]'].includes(url.hostname)))
8
+ || url.username || url.password || url.search || url.hash) {
9
+ throw new Error('Use an HTTPS gateway URL without credentials, query or fragment (HTTP is allowed on loopback).');
10
+ }
11
+ return url.href.replace(/\/+$/, '');
12
+ }
13
+ const targets = {
14
+ 'darwin-arm64': 'aarch64-apple-darwin', 'darwin-x64': 'x86_64-apple-darwin',
15
+ 'win32-arm64': 'aarch64-pc-windows-msvc', 'win32-x64': 'x86_64-pc-windows-msvc',
16
+ 'linux-arm64': 'aarch64-unknown-linux-musl', 'linux-x64': 'x86_64-unknown-linux-musl',
17
+ };
18
+ export function artifactFor(manifest, platform = process.platform, arch = process.arch) {
19
+ const target = targets[`${platform}-${arch}`];
20
+ if (!target)
21
+ throw new Error(`Unsupported computer: ${platform}/${arch}`);
22
+ const data = manifest;
23
+ if (!data || typeof data.revision !== 'string' || !/^[a-f0-9]{40}$/.test(data.revision)
24
+ || data.protocol !== PROTOCOL || !Array.isArray(data.artifacts)) {
25
+ throw new Error('The gateway must publish runner protocol 4 binaries.');
26
+ }
27
+ const filename = `ft-bot-runner-${target}${platform === 'win32' ? '.exe' : ''}`;
28
+ const matches = data.artifacts.filter((item) => item?.target === target);
29
+ const artifact = matches[0];
30
+ if (matches.length !== 1 || artifact.filename !== filename || typeof artifact.sha256 !== 'string'
31
+ || !/^[a-f0-9]{64}$/.test(artifact.sha256) || !Number.isSafeInteger(artifact.bytes)
32
+ || artifact.bytes <= 0 || artifact.bytes > 256 * 1024 * 1024) {
33
+ throw new Error('Invalid runner download metadata.');
34
+ }
35
+ return { revision: data.revision, filename, sha256: artifact.sha256, bytes: artifact.bytes };
36
+ }
37
+ async function fetchFile(url, signal) {
38
+ // Keep downloads on the selected HTTPS gateway; never follow a downgrade or redirect.
39
+ const response = await fetch(url, { signal, redirect: 'error' });
40
+ if (!response.ok || !response.body)
41
+ throw new Error(`Runner download failed (HTTP ${response.status}).`);
42
+ return response;
43
+ }
44
+ export async function downloadRunner(server, directory, signal) {
45
+ const base = `${gateway(server)}/runner/downloads`;
46
+ const response = await fetchFile(`${base}/latest.json`, signal);
47
+ const chunks = [];
48
+ let size = 0;
49
+ for await (const chunk of response.body) {
50
+ size += chunk.length;
51
+ if (size > 64 * 1024)
52
+ throw new Error('Runner manifest is too large.');
53
+ chunks.push(chunk);
54
+ }
55
+ const artifact = artifactFor(JSON.parse(Buffer.concat(chunks).toString('utf8')));
56
+ const folder = join(directory, artifact.revision);
57
+ await mkdir(folder, { recursive: true, mode: 0o700 });
58
+ const temporary = join(folder, `.download-${randomUUID()}`);
59
+ const destination = join(folder, artifact.filename);
60
+ const file = await open(temporary, 'wx', 0o700);
61
+ try {
62
+ const binary = await fetchFile(`${base}/${artifact.revision}/${artifact.filename}`, signal);
63
+ const hash = createHash('sha256');
64
+ let bytes = 0;
65
+ for await (const chunk of binary.body) {
66
+ bytes += chunk.length;
67
+ if (bytes > artifact.bytes)
68
+ throw new Error('Runner download exceeds its declared size.');
69
+ hash.update(chunk);
70
+ await file.writeFile(chunk);
71
+ }
72
+ if (bytes !== artifact.bytes || hash.digest('hex') !== artifact.sha256)
73
+ throw new Error('Runner checksum mismatch.');
74
+ await file.sync();
75
+ await file.close();
76
+ await rename(temporary, destination);
77
+ return destination;
78
+ }
79
+ finally {
80
+ await file.close();
81
+ await rm(temporary, { force: true });
82
+ }
83
+ }
84
+ //# sourceMappingURL=download.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"download.js","sourceRoot":"","sources":["../src/download.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,UAAU,EAAE,MAAM,aAAa,CAAA;AACpD,OAAO,EAAE,KAAK,EAAE,IAAI,EAAE,MAAM,EAAE,EAAE,EAAE,MAAM,kBAAkB,CAAA;AAC1D,OAAO,EAAE,IAAI,EAAE,MAAM,WAAW,CAAA;AAEhC,MAAM,CAAC,MAAM,QAAQ,GAAG,CAAC,CAAA;AAEzB,MAAM,UAAU,OAAO,CAAC,KAAa;IACnC,MAAM,GAAG,GAAG,IAAI,GAAG,CAAC,KAAK,CAAC,IAAI,EAAE,CAAC,CAAA;IACjC,IAAI,CAAC,GAAG,CAAC,QAAQ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ACH,MAAM,MAAM,GAAG,MAAM,SAAS,CAAC,GAAG,IAAI,IAAI,QAAQ,CAAC,QAAQ,IAAI,QAAQ,CAAC,QAAQ,EAAE,EAAE,MAAM,CAAC,CAAA;QAC3F,MAAM,IAAI,GAAG,UAAU,CAAC,QAAQ,CAAC,CAAA;QACjC,IAAI,KAAK,GAAG,CAAC,CAAA;QACb,IAAI,KAAK,EAAE,MAAM,KAAK,IAAI,MAAM,CAAC,IAAK,EAAE,CAAC;YACvC,KAAK,IAAI,KAAK,CAAC,MAAM,CAAA;YACrB,IAAI,KAAK,GAAG,QAAQ,CAAC,KAAK;gBAAE,MAAM,IAAI,KAAK,CAAC,4CAA4C,CAAC,CAAA;YACzF,IAAI,CAAC,MAAM,CAAC,KAAK,CAAC,CAAA;YAClB,MAAM,IAAI,CAAC,SAAS,CAAC,KAAK,CAAC,CAAA;QAC7B,CAAC;QACD,IAAI,KAAK,KAAK,QAAQ,CAAC,KAAK,IAAI,IAAI,CAAC,MAAM,CAAC,KAAK,CAAC,KAAK,QAAQ,CAAC,MAAM;YAAE,MAAM,IAAI,KAAK,CAAC,2BAA2B,CAAC,CAAA;QACpH,MAAM,IAAI,CAAC,IAAI,EAAE,CAAA;QACjB,MAAM,IAAI,CAAC,KAAK,EAAE,CAAA;QAClB,MAAM,MAAM,CAAC,SAAS,EAAE,WAAW,CAAC,CAAA;QACpC,OAAO,WAAW,CAAA;IACpB,CAAC;YAAS,CAAC;QACT,MAAM,IAAI,CAAC,KAAK,EAAE,CAAA;QAClB,MAAM,EAAE,CAAC,SAAS,EAAE,EAAE,KAAK,EAAE,IAAI,EAAE,CAAC,CAAA;IACtC,CAAC;AACH,CAAC"}
package/lib/index.d.ts ADDED
@@ -0,0 +1,22 @@
1
+ import type { Context } from 'cordis';
2
+ import { TypertRemoteService } from '@ftai/plugin-sdk/host';
3
+ import type { PluginStatus } from './types.ts';
4
+ export type * from './types.ts';
5
+ declare module 'cordis' {
6
+ interface Context {
7
+ ftBot: FtBot;
8
+ }
9
+ }
10
+ export declare class FtBot extends TypertRemoteService {
11
+ static inject: string[];
12
+ private controller;
13
+ constructor(ctx: Context);
14
+ private perform;
15
+ status(): PluginStatus;
16
+ pair(server: string, code: string): Promise<PluginStatus>;
17
+ setEnabled(enabled: boolean): Promise<PluginStatus>;
18
+ updateRunner(): Promise<PluginStatus>;
19
+ refresh(): Promise<PluginStatus>;
20
+ requestPermissions(): Promise<PluginStatus>;
21
+ }
22
+ export default FtBot;
package/lib/index.js ADDED
@@ -0,0 +1,93 @@
1
+ var __runInitializers = (this && this.__runInitializers) || function (thisArg, initializers, value) {
2
+ var useValue = arguments.length > 2;
3
+ for (var i = 0; i < initializers.length; i++) {
4
+ value = useValue ? initializers[i].call(thisArg, value) : initializers[i].call(thisArg);
5
+ }
6
+ return useValue ? value : void 0;
7
+ };
8
+ var __esDecorate = (this && this.__esDecorate) || function (ctor, descriptorIn, decorators, contextIn, initializers, extraInitializers) {
9
+ function accept(f) { if (f !== void 0 && typeof f !== "function") throw new TypeError("Function expected"); return f; }
10
+ var kind = contextIn.kind, key = kind === "getter" ? "get" : kind === "setter" ? "set" : "value";
11
+ var target = !descriptorIn && ctor ? contextIn["static"] ? ctor : ctor.prototype : null;
12
+ var descriptor = descriptorIn || (target ? Object.getOwnPropertyDescriptor(target, contextIn.name) : {});
13
+ var _, done = false;
14
+ for (var i = decorators.length - 1; i >= 0; i--) {
15
+ var context = {};
16
+ for (var p in contextIn) context[p] = p === "access" ? {} : contextIn[p];
17
+ for (var p in contextIn.access) context.access[p] = contextIn.access[p];
18
+ context.addInitializer = function (f) { if (done) throw new TypeError("Cannot add initializers after decoration has completed"); extraInitializers.push(accept(f || null)); };
19
+ var result = (0, decorators[i])(kind === "accessor" ? { get: descriptor.get, set: descriptor.set } : descriptor[key], context);
20
+ if (kind === "accessor") {
21
+ if (result === void 0) continue;
22
+ if (result === null || typeof result !== "object") throw new TypeError("Object expected");
23
+ if (_ = accept(result.get)) descriptor.get = _;
24
+ if (_ = accept(result.set)) descriptor.set = _;
25
+ if (_ = accept(result.init)) initializers.unshift(_);
26
+ }
27
+ else if (_ = accept(result)) {
28
+ if (kind === "field") initializers.unshift(_);
29
+ else descriptor[key] = _;
30
+ }
31
+ }
32
+ if (target) Object.defineProperty(target, contextIn.name, descriptor);
33
+ done = true;
34
+ };
35
+ import { Remote, RemoteError, TypertRemoteService } from '@ftai/plugin-sdk/host';
36
+ import { Controller, stateDirectory } from "./controller.js";
37
+ import { Chats } from "./chats.js";
38
+ let FtBot = (() => {
39
+ let _classSuper = TypertRemoteService;
40
+ let _instanceExtraInitializers = [];
41
+ let _status_decorators;
42
+ let _pair_decorators;
43
+ let _setEnabled_decorators;
44
+ let _updateRunner_decorators;
45
+ let _refresh_decorators;
46
+ let _requestPermissions_decorators;
47
+ return class FtBot extends _classSuper {
48
+ static {
49
+ const _metadata = typeof Symbol === "function" && Symbol.metadata ? Object.create(_classSuper[Symbol.metadata] ?? null) : void 0;
50
+ _status_decorators = [Remote];
51
+ _pair_decorators = [Remote];
52
+ _setEnabled_decorators = [Remote];
53
+ _updateRunner_decorators = [Remote];
54
+ _refresh_decorators = [Remote];
55
+ _requestPermissions_decorators = [Remote];
56
+ __esDecorate(this, null, _status_decorators, { kind: "method", name: "status", static: false, private: false, access: { has: obj => "status" in obj, get: obj => obj.status }, metadata: _metadata }, null, _instanceExtraInitializers);
57
+ __esDecorate(this, null, _pair_decorators, { kind: "method", name: "pair", static: false, private: false, access: { has: obj => "pair" in obj, get: obj => obj.pair }, metadata: _metadata }, null, _instanceExtraInitializers);
58
+ __esDecorate(this, null, _setEnabled_decorators, { kind: "method", name: "setEnabled", static: false, private: false, access: { has: obj => "setEnabled" in obj, get: obj => obj.setEnabled }, metadata: _metadata }, null, _instanceExtraInitializers);
59
+ __esDecorate(this, null, _updateRunner_decorators, { kind: "method", name: "updateRunner", static: false, private: false, access: { has: obj => "updateRunner" in obj, get: obj => obj.updateRunner }, metadata: _metadata }, null, _instanceExtraInitializers);
60
+ __esDecorate(this, null, _refresh_decorators, { kind: "method", name: "refresh", static: false, private: false, access: { has: obj => "refresh" in obj, get: obj => obj.refresh }, metadata: _metadata }, null, _instanceExtraInitializers);
61
+ __esDecorate(this, null, _requestPermissions_decorators, { kind: "method", name: "requestPermissions", static: false, private: false, access: { has: obj => "requestPermissions" in obj, get: obj => obj.requestPermissions }, metadata: _metadata }, null, _instanceExtraInitializers);
62
+ if (_metadata) Object.defineProperty(this, Symbol.metadata, { enumerable: true, configurable: true, writable: true, value: _metadata });
63
+ }
64
+ static inject = ['agents'];
65
+ controller = __runInitializers(this, _instanceExtraInitializers);
66
+ constructor(ctx) {
67
+ super(ctx, 'ftBot');
68
+ ctx.effect(() => {
69
+ const chats = new Chats(ctx.agents);
70
+ this.controller = new Controller(stateDirectory(), undefined, chats);
71
+ return () => this.controller.dispose();
72
+ }, 'ft-bot: runner lifetime');
73
+ }
74
+ async perform(work) {
75
+ try {
76
+ return await work();
77
+ }
78
+ catch (error) {
79
+ const reason = error.message;
80
+ throw new RemoteError('ft-bot/operation-failed', reason, { reason });
81
+ }
82
+ }
83
+ status() { return this.controller.getStatus(); }
84
+ pair(server, code) { return this.perform(() => this.controller.pair(server, code)); }
85
+ setEnabled(enabled) { return this.perform(() => this.controller.setEnabled(enabled)); }
86
+ updateRunner() { return this.perform(() => this.controller.updateRunner()); }
87
+ refresh() { return this.perform(() => this.controller.refresh()); }
88
+ requestPermissions() { return this.perform(() => this.controller.requestPermissions()); }
89
+ };
90
+ })();
91
+ export { FtBot };
92
+ export default FtBot;
93
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AACA,OAAO,EAAE,MAAM,EAAE,WAAW,EAAE,mBAAmB,EAAE,MAAM,uBAAuB,CAAA;AAChF,OAAO,EAAE,UAAU,EAAE,cAAc,EAAE,MAAM,iBA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EAAE,CAAA,CAAC,CAAC;QAG7D,IAAI,CAAC,MAAc,EAAE,IAAY,IAA2B,OAAO,IAAI,CAAC,OAAO,CAAC,GAAG,EAAE,CAAC,IAAI,CAAC,UAAU,CAAC,IAAI,CAAC,MAAM,EAAE,IAAI,CAAC,CAAC,CAAA,CAAC,CAAC;QAG3H,UAAU,CAAC,OAAgB,IAA2B,OAAO,IAAI,CAAC,OAAO,CAAC,GAAG,EAAE,CAAC,IAAI,CAAC,UAAU,CAAC,UAAU,CAAC,OAAO,CAAC,CAAC,CAAA,CAAC,CAAC;QAGtH,YAAY,KAA4B,OAAO,IAAI,CAAC,OAAO,CAAC,GAAG,EAAE,CAAC,IAAI,CAAC,UAAU,CAAC,YAAY,EAAE,CAAC,CAAA,CAAC,CAAC;QAGnG,OAAO,KAA4B,OAAO,IAAI,CAAC,OAAO,CAAC,GAAG,EAAE,CAAC,IAAI,CAAC,UAAU,CAAC,OAAO,EAAE,CAAC,CAAA,CAAC,CAAC;QAGzF,kBAAkB,KAA4B,OAAO,IAAI,CAAC,OAAO,CAAC,GAAG,EAAE,CAAC,IAAI,CAAC,UAAU,CAAC,kBAAkB,EAAE,CAAC,CAAA,CAAC,CAAC;;;SArCpG,KAAK;AAwClB,eAAe,KAAK,CAAA"}
@@ -0,0 +1,19 @@
1
+ /* 由 @ftai/plugin-sdk 的 ftai-plugin-remote 生成,不要手改。 */
2
+ import type { RemoteResult, RemoteStream } from '@ftai/plugin-sdk/remote'
3
+ import type { FtBot } from './index.js'
4
+
5
+ /** 去掉最后一个 `signal: AbortSignal` 参数:宿主替插件传它,插件前端可另给自己的取消信号。 */
6
+ type Args<F> = F extends (...args: infer A) => unknown ? (A extends [...infer Head, AbortSignal] ? Head : A) : never
7
+ type Value<F> = F extends (...args: never[]) => infer R ? Awaited<R> : never
8
+ type Item<F> = F extends (...args: never[]) => infer R ? (R extends AsyncIterable<infer I> | Iterable<infer I> ? I : never) : never
9
+ type Call<F> = ((...args: Args<F>) => Promise<RemoteResult<Value<F>>>) & ((...args: [...Args<F>, AbortSignal | undefined]) => Promise<RemoteResult<Value<F>>>)
10
+ type Stream<F> = ((...args: Args<F>) => RemoteStream<Item<F>>) & ((...args: [...Args<F>, AbortSignal | undefined]) => RemoteStream<Item<F>>)
11
+
12
+ declare module '@ftai/plugin-sdk/remote' {
13
+ interface RemoteNamespaceMap {
14
+ 'ftBot': { status: Call<FtBot['status']>; pair: Call<FtBot['pair']>; setEnabled: Call<FtBot['setEnabled']>; updateRunner: Call<FtBot['updateRunner']>; refresh: Call<FtBot['refresh']>; requestPermissions: Call<FtBot['requestPermissions']> }
15
+ }
16
+ }
17
+
18
+ declare const REMOTE: { readonly package: string; readonly namespaces: readonly { readonly namespace: string; readonly methods: readonly { readonly name: string; readonly stream: boolean; readonly params?: readonly { readonly name: string; readonly optional: boolean; readonly schema: unknown }[] }[] }[] }
19
+ export default REMOTE
package/lib/remote.js ADDED
@@ -0,0 +1,64 @@
1
+ /* 由 @ftai/plugin-sdk 的 ftai-plugin-remote 生成,不要手改。 */
2
+ export default Object.freeze({
3
+ "package": "@ftai/ftai-plugin-ft-bot",
4
+ "namespaces": [
5
+ {
6
+ "namespace": "ftBot",
7
+ "methods": [
8
+ {
9
+ "name": "status",
10
+ "stream": false,
11
+ "params": []
12
+ },
13
+ {
14
+ "name": "pair",
15
+ "stream": false,
16
+ "params": [
17
+ {
18
+ "name": "server",
19
+ "optional": false,
20
+ "schema": {
21
+ "type": "string"
22
+ }
23
+ },
24
+ {
25
+ "name": "code",
26
+ "optional": false,
27
+ "schema": {
28
+ "type": "string"
29
+ }
30
+ }
31
+ ]
32
+ },
33
+ {
34
+ "name": "setEnabled",
35
+ "stream": false,
36
+ "params": [
37
+ {
38
+ "name": "enabled",
39
+ "optional": false,
40
+ "schema": {
41
+ "type": "boolean"
42
+ }
43
+ }
44
+ ]
45
+ },
46
+ {
47
+ "name": "updateRunner",
48
+ "stream": false,
49
+ "params": []
50
+ },
51
+ {
52
+ "name": "refresh",
53
+ "stream": false,
54
+ "params": []
55
+ },
56
+ {
57
+ "name": "requestPermissions",
58
+ "stream": false,
59
+ "params": []
60
+ }
61
+ ]
62
+ }
63
+ ]
64
+ })
@@ -0,0 +1,12 @@
1
+ import type { ComputerStatus, Connection } from './types.ts';
2
+ import type { ChatPort } from './chats.ts';
3
+ export interface RunnerRequest {
4
+ type: 'status' | 'pair' | 'permissions' | 'run';
5
+ server?: string;
6
+ code?: string;
7
+ }
8
+ export declare function launchRunner(executable: string, state: string, request: RunnerRequest, onConnection?: (status: Connection) => void, chats?: ChatPort): {
9
+ done: Promise<unknown>;
10
+ stop(): Promise<void>;
11
+ };
12
+ export declare function computerStatus(value: unknown): ComputerStatus;