@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.
- package/README.md +91 -2
- package/lib/chat-host.d.ts +60 -0
- package/lib/chat-host.js +2 -0
- package/lib/chat-host.js.map +1 -0
- package/lib/chats.d.ts +36 -0
- package/lib/chats.js +163 -0
- package/lib/chats.js.map +1 -0
- package/lib/client.js +11 -0
- package/lib/client.js.map +1 -0
- package/lib/client.packages.json +6 -0
- package/lib/controller.d.ts +32 -0
- package/lib/controller.js +238 -0
- package/lib/controller.js.map +1 -0
- package/lib/download.d.ts +9 -0
- package/lib/download.js +84 -0
- package/lib/download.js.map +1 -0
- package/lib/index.d.ts +22 -0
- package/lib/index.js +93 -0
- package/lib/index.js.map +1 -0
- package/lib/remote.d.ts +19 -0
- package/lib/remote.js +64 -0
- package/lib/runner.d.ts +12 -0
- package/lib/runner.js +143 -0
- package/lib/runner.js.map +1 -0
- package/lib/types.d.ts +27 -0
- package/lib/types.js +2 -0
- package/lib/types.js.map +1 -0
- package/locale/en.json +1 -0
- package/locale/zh-CN.json +1 -0
- package/package.json +56 -4
package/README.md
CHANGED
|
@@ -1,3 +1,92 @@
|
|
|
1
|
-
#
|
|
1
|
+
# Ft Bot for FtAi Desktop
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
An installable FtAi Desktop plugin (`@ftai/ftai-plugin-ft-bot`) that connects the **cloud WeCom bot** to this computer. Its English/Chinese settings page downloads and verifies the native runner, pairs it, shows connection and desktop permission status, and lets the user disconnect, reconnect, or update.
|
|
4
|
+
|
|
5
|
+
Version 0.1.0 requires [FtAi plugin contract 2.1](https://ftai.chat/desktop/docs/plugins/) and Ft Bot runner protocol 4. The cloud bot keeps its `run_command`, file/browser tools and `desktop` tool, and gains `local_chat` to create, resume, read and cancel persistent chats in FtAi through `ctx.agents`. Commands retain cancellation, secret redaction and replay protection. The plugin does not register duplicate tools in FtAi's own chats.
|
|
6
|
+
|
|
7
|
+
## Use
|
|
8
|
+
|
|
9
|
+
1. Use an FtAi Desktop build supporting contract 2.1 and install `@ftai/ftai-plugin-ft-bot@0.1.0` in its plugin settings. The package must be published to an npm registry first; see **Build and verify** below.
|
|
10
|
+
2. Open the plugin's settings. Ask the WeCom bot to connect this computer, paste its one-use pairing code, and choose **Pair and connect**. The plugin uses `https://ftai.chat/ft-bot/api` by default, downloads and verifies the runner, and connects.
|
|
11
|
+
3. Ask the bot to use this computer now, make it the default for future runs, or both. A current-run switch affects subsequent operations immediately; already-started operations keep their original computer. Pairing alone does not select it.
|
|
12
|
+
4. On macOS, use **Request macOS permissions**, then allow the runner in Screen & System Audio Recording and Accessibility. Disconnect/reconnect after changing grants. On Windows, keep the interactive user logged in and the desktop unlocked.
|
|
13
|
+
|
|
14
|
+
For a self-hosted deployment, change **Advanced → Server URL** to the URL returned by your bot. Leaving it blank uses the default; saved custom URLs are retained. Deploy the matching gateway and runner release together using the existing runner publication pipeline: all runners must use protocol 4, and the plugin requires stdio bridge version 2.
|
|
15
|
+
|
|
16
|
+
Commands run on Windows (PowerShell), macOS and Linux (Bash). Desktop control supports Windows/macOS: display discovery, screenshots, clicks, double/right clicks, mouse movement, dragging, scrolling, Unicode text and key chords. Linux retains command/file/browser access without native desktop control. UAC/secure desktops and macOS permission restrictions still apply.
|
|
17
|
+
|
|
18
|
+
## Local chats
|
|
19
|
+
|
|
20
|
+
After selecting this computer, ask the WeCom bot to create a local FtAi chat in a project directory, continue a saved chat by its session ID, or check its replies. The `local_chat` tool accepts an `action` with these fields:
|
|
21
|
+
|
|
22
|
+
| Type | Fields | Result |
|
|
23
|
+
| --- | --- | --- |
|
|
24
|
+
| `create` | `prompt`, `cwd` (absolute local path or null) | Creates a saved chat through `ctx.agents.create`, queues its first turn, returns `session_id`, `message_id` and `next_seq`. |
|
|
25
|
+
| `resume` | `session_id`, `prompt` (text or null) | Attaches through `ctx.agents.resume`; null sends nothing, text queues a new turn. |
|
|
26
|
+
| `read` | `session_id`, `after_seq` | Reads user/assistant text and turn outcomes; returns `next_seq`, `has_more` and `status`. Use zero to read from the start. |
|
|
27
|
+
| `cancel` | `session_id` | Cancels the current turn and drops queued input. |
|
|
28
|
+
| `list` | None | Lists currently loaded chats with ID, working directory, status and whether this plugin holds them. Saved chats that are unloaded are not listed. |
|
|
29
|
+
|
|
30
|
+
Create/resume return after submitting, without waiting for the model. A prompt is always a new turn, including when another turn is running. Prompts allow at most 64 KiB of UTF-8 text. Chats use FtAi's configured default model and permissions; approvals and questions must be handled locally in FtAi. The tool does not approve actions or answer those questions automatically. Chat text sent to the bot is untrusted content, not authority to take further actions.
|
|
31
|
+
|
|
32
|
+
Read/cancel require a chat attached by create/resume in the current plugin connection. Reads cover up to 256 event sequence positions and 65,536 text characters per response. Follow `next_seq` while `has_more` is true. Oversized messages are marked `truncated`; their omitted text remains in the local history. Reasoning, tool payloads and attachments are not returned. A turn-end entry distinguishes completion, cancellation and model errors; `idle` alone does not prove success. An attached chat is saved in FtAi but is not automatically added to a workspace.
|
|
33
|
+
|
|
34
|
+
Runner operation IDs prevent transport retries from duplicating prompts. After an unknown outcome, resume the returned session ID with a null prompt and inspect its log before deciding whether to resend. Never automatically repeat a prompt after a timeout or disconnect. The plugin keeps attached chats alive between calls. Disconnect, access revocation, gateway restart, runner update and graceful shutdown release them and stop their current turns; queued input and history remain. Resume with null after reconnecting. This also applies to existing active chats attached by the plugin. A plugin crash may leave a chat running; inspect it locally or reattach before continuing.
|
|
35
|
+
|
|
36
|
+
## Connection and storage
|
|
37
|
+
|
|
38
|
+
- Pairing connects immediately and remembers the enabled state. The runner reconnects while the plugin and FtAi **host** are running, including when the host continues in the background after the window closes. **Disconnect** persists across host restarts.
|
|
39
|
+
- Disabling/uninstalling the plugin or stopping/crashing its host closes the runner's stdin. The runner then cancels supervised work and exits. No login service or inbound listening port is installed. Completed actions cannot be undone.
|
|
40
|
+
- The runner has the OS account's access to files, credentials, tools, apps and networking. Tool output, screenshots and requested local chat text reach the cloud bot; attachments use its existing storage. FtAi's local-chat permissions apply to local chat turns; they do not govern commands and desktop input performed directly by the cloud bot.
|
|
41
|
+
- This plugin has its own pairing/state directory: `~/.local/share/ft-bot-desktop-plugin` on macOS/Linux, `%LOCALAPPDATA%\ft-bot-desktop-plugin` on Windows. Credentials and the replay journal are in its `runner` subdirectory, protected by the native runner's permissions/ACLs. `config.json` contains the gateway, executable path and enabled preference, never the pairing code or bearer token.
|
|
42
|
+
- Each pairing code can be redeemed once. The gateway issues the bearer token and stores only its hash. If the response is lost or the token cannot be saved, request a new code and revoke any unused computer entry through the bot. A paired instance belongs to one gateway. To change gateways, disconnect, revoke the old computer through the bot, and remove this plugin's `runner/credentials.json` and `config.json` while the plugin is disabled. Work files are retained. Uninstalling does not delete local state.
|
|
43
|
+
- **Download update** stops current work, verifies the gateway's current binary, checks its plugin interface and resumes if enabled. Failed downloads leave the previous executable intact. Old revision directories remain available; macOS may need permission grants for a new executable path.
|
|
44
|
+
- Downloads stay on the configured gateway, require HTTPS (loopback HTTP is allowed for development), reject redirects, and verify the expected platform filename, size and checksum.
|
|
45
|
+
|
|
46
|
+
## Build and verify
|
|
47
|
+
|
|
48
|
+
Requires Node.js 22.12+ and pnpm. The lockfile fixes development dependencies; the installed plugin has **no third-party runtime dependencies or installation scripts**. FtAi supplies its SDK, Cordis and shared React runtime.
|
|
49
|
+
|
|
50
|
+
The supplied FtAi checkout exposes contract 2.1, but `@ftai/plugin-sdk@2.1.0` is not yet published to npm. Build tools therefore use the published 2.0 SDK with a small, type-only snapshot of the needed 2.1 agent interfaces in `src/chat-host.ts`. The runtime still requires 2.1; there is no fallback for older hosts. The snapshot and actual source runtime can be checked without modifying the FtAi checkout or calling a model:
|
|
51
|
+
|
|
52
|
+
```sh
|
|
53
|
+
# After pnpm build, from desktop-plugin:
|
|
54
|
+
node scripts/check-host-api.mjs /path/to/ft-ai-desktop
|
|
55
|
+
```
|
|
56
|
+
|
|
57
|
+
```sh
|
|
58
|
+
cd desktop-plugin
|
|
59
|
+
pnpm install --frozen-lockfile
|
|
60
|
+
pnpm build
|
|
61
|
+
pnpm test
|
|
62
|
+
pnpm pack
|
|
63
|
+
```
|
|
64
|
+
|
|
65
|
+
The archive contains `lib/index.js`, `lib/client.js`, `lib/remote.js`, shared declarations and both locale files. Publishing is a separate operator action:
|
|
66
|
+
|
|
67
|
+
```sh
|
|
68
|
+
pnpm publish --access public
|
|
69
|
+
```
|
|
70
|
+
|
|
71
|
+
Integration tests use the real native runner, an isolated loopback mock gateway and a recorded FtAi agent service. They require no MySQL, model credentials or GUI input and cover pairing, authentication, commands, desktop status, cancellation, host crash cleanup, connection preferences, local chat creation/resumption/reading, prompt replay protection and ownership cleanup:
|
|
72
|
+
|
|
73
|
+
```sh
|
|
74
|
+
# From the repository root:
|
|
75
|
+
cargo build --locked --package ft-bot-runner
|
|
76
|
+
cargo test --locked --package ft-bot-runner --test runner_plugin
|
|
77
|
+
cd desktop-plugin
|
|
78
|
+
FT_BOT_TEST_RUNNER="$(pwd)/../target/debug/ft-bot-runner" pnpm test:integration
|
|
79
|
+
```
|
|
80
|
+
|
|
81
|
+
If `CARGO_TARGET_DIR` is set, use its absolute binary path instead. Windows uses `ft-bot-runner.exe` and `$env:FT_BOT_TEST_RUNNER`. `pnpm build` must precede both JavaScript test commands. CI builds the native runner, runs these checks and retains the npm archive; it does not publish the plugin to a registry.
|
|
82
|
+
|
|
83
|
+
## Local FtAi installation
|
|
84
|
+
|
|
85
|
+
Use the [official local-registry workflow](https://ftai.chat/desktop/docs/plugins/quickstart). Start Verdaccio on loopback, build and publish this package there, and start an **isolated** FtAi instance with `FTAI_PLUGIN_REGISTRY` pointing to that registry. Keep upstream npm proxying enabled so the application can resolve other plugins. Install the exact package version through the plugin UI.
|
|
86
|
+
|
|
87
|
+
For development, set these environment variables **before starting the FtAi host**:
|
|
88
|
+
|
|
89
|
+
- `FT_BOT_PLUGIN_HOME`: an absolute, isolated plugin state directory; use a separate one for each test instance.
|
|
90
|
+
- `FT_BOT_RUNNER_BINARY`: an absolute path to the freshly built runner; skips download while preserving pairing and all lifecycle behavior.
|
|
91
|
+
|
|
92
|
+
Verify a pair/connect/disconnect cycle, plugin disable/re-enable, host exit, and macOS permission grants in that instance. Create a chat, read its reply, resume its session ID with another prompt, and check local approval handling and cancellation. Real chat turns require a configured model; recorded host tests do not establish model or provider availability. Real screenshot/input validation needs an unlocked desktop and the OS permissions; automated tests do not click or type into your applications.
|
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The public 2.1 agent contract used by this plugin, checked against
|
|
3
|
+
* ft-ai-desktop/packages/plugin-host-api/src/{index,sessions,session-events}.ts.
|
|
4
|
+
* npm currently publishes SDK 2.0 only; build tools stay pinned there while the
|
|
5
|
+
* manifest requires a 2.1 host. This is types only, with no runtime fallback.
|
|
6
|
+
*/
|
|
7
|
+
export interface ChatMessage {
|
|
8
|
+
readonly id: string;
|
|
9
|
+
readonly role: 'user';
|
|
10
|
+
readonly content: {
|
|
11
|
+
type: 'text';
|
|
12
|
+
text: string;
|
|
13
|
+
}[];
|
|
14
|
+
readonly source: {
|
|
15
|
+
kind: string;
|
|
16
|
+
};
|
|
17
|
+
}
|
|
18
|
+
export interface ChatEvent {
|
|
19
|
+
readonly type: string;
|
|
20
|
+
readonly seq: number;
|
|
21
|
+
readonly time: number;
|
|
22
|
+
readonly data: unknown;
|
|
23
|
+
}
|
|
24
|
+
export interface ChatAgent {
|
|
25
|
+
readonly id: string;
|
|
26
|
+
readonly status: Promise<'idle' | 'running'>;
|
|
27
|
+
readonly session: {
|
|
28
|
+
readonly header: {
|
|
29
|
+
readonly cwd?: string;
|
|
30
|
+
};
|
|
31
|
+
readSeq(): Promise<number>;
|
|
32
|
+
readEvents(range?: {
|
|
33
|
+
readonly fromSeq?: number;
|
|
34
|
+
readonly toSeq?: number;
|
|
35
|
+
}): Promise<readonly ChatEvent[]>;
|
|
36
|
+
};
|
|
37
|
+
followup(message: ChatMessage): Promise<void>;
|
|
38
|
+
cancel(cause: {
|
|
39
|
+
kind: 'hook';
|
|
40
|
+
reason: string;
|
|
41
|
+
}): Promise<void>;
|
|
42
|
+
}
|
|
43
|
+
export interface OwnedChat {
|
|
44
|
+
readonly agent: ChatAgent;
|
|
45
|
+
dispose(): Promise<void>;
|
|
46
|
+
}
|
|
47
|
+
export interface ChatAgents {
|
|
48
|
+
create(options?: {
|
|
49
|
+
readonly sessionId?: string;
|
|
50
|
+
readonly meta?: {
|
|
51
|
+
readonly cwd?: string;
|
|
52
|
+
};
|
|
53
|
+
readonly signal?: AbortSignal;
|
|
54
|
+
}): Promise<OwnedChat>;
|
|
55
|
+
resume(options: {
|
|
56
|
+
readonly resumeSessionId: string;
|
|
57
|
+
readonly signal?: AbortSignal;
|
|
58
|
+
}): Promise<OwnedChat>;
|
|
59
|
+
list(): Promise<ChatAgent[]>;
|
|
60
|
+
}
|
package/lib/chat-host.js
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"chat-host.js","sourceRoot":"","sources":["../src/chat-host.ts"],"names":[],"mappings":""}
|
package/lib/chats.d.ts
ADDED
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
import type { ChatAgents } from './chat-host.ts';
|
|
2
|
+
export type ChatAction = {
|
|
3
|
+
type: 'create';
|
|
4
|
+
prompt: string;
|
|
5
|
+
cwd: string | null;
|
|
6
|
+
} | {
|
|
7
|
+
type: 'resume';
|
|
8
|
+
session_id: string;
|
|
9
|
+
prompt: string | null;
|
|
10
|
+
} | {
|
|
11
|
+
type: 'read';
|
|
12
|
+
session_id: string;
|
|
13
|
+
after_seq: number;
|
|
14
|
+
} | {
|
|
15
|
+
type: 'cancel';
|
|
16
|
+
session_id: string;
|
|
17
|
+
} | {
|
|
18
|
+
type: 'list';
|
|
19
|
+
};
|
|
20
|
+
export interface ChatPort {
|
|
21
|
+
request(id: string, action: ChatAction, signal: AbortSignal): Promise<unknown>;
|
|
22
|
+
stop(): Promise<void>;
|
|
23
|
+
}
|
|
24
|
+
export declare class Chats implements ChatPort {
|
|
25
|
+
private readonly agents;
|
|
26
|
+
private readonly owned;
|
|
27
|
+
private readonly busy;
|
|
28
|
+
private readonly requests;
|
|
29
|
+
private lifetime;
|
|
30
|
+
private stopping;
|
|
31
|
+
constructor(agents: ChatAgents);
|
|
32
|
+
request(id: string, action: ChatAction, signal: AbortSignal): Promise<unknown>;
|
|
33
|
+
private execute;
|
|
34
|
+
private attached;
|
|
35
|
+
stop(): Promise<void>;
|
|
36
|
+
}
|
package/lib/chats.js
ADDED
|
@@ -0,0 +1,163 @@
|
|
|
1
|
+
import { isAbsolute } from 'node:path';
|
|
2
|
+
function prompt(value) {
|
|
3
|
+
if (typeof value !== 'string' || !value.trim() || Buffer.byteLength(value) > 65536 || value.includes('\0')) {
|
|
4
|
+
throw new Error('Prompt must contain 1..65536 UTF-8 bytes without NUL.');
|
|
5
|
+
}
|
|
6
|
+
}
|
|
7
|
+
export class Chats {
|
|
8
|
+
agents;
|
|
9
|
+
owned = new Map();
|
|
10
|
+
busy = new Set();
|
|
11
|
+
requests = new Set();
|
|
12
|
+
lifetime = new AbortController();
|
|
13
|
+
stopping;
|
|
14
|
+
constructor(agents) {
|
|
15
|
+
this.agents = agents;
|
|
16
|
+
}
|
|
17
|
+
async request(id, action, signal) {
|
|
18
|
+
if (this.stopping)
|
|
19
|
+
await this.stopping;
|
|
20
|
+
signal.throwIfAborted();
|
|
21
|
+
const scope = AbortSignal.any([signal, this.lifetime.signal]);
|
|
22
|
+
const task = this.execute(id, action, scope);
|
|
23
|
+
this.requests.add(task);
|
|
24
|
+
try {
|
|
25
|
+
return await task;
|
|
26
|
+
}
|
|
27
|
+
finally {
|
|
28
|
+
this.requests.delete(task);
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
async execute(id, action, signal) {
|
|
32
|
+
if (!/^[\w-]{21}$/.test(id))
|
|
33
|
+
throw new Error('Invalid local chat request ID.');
|
|
34
|
+
signal.throwIfAborted();
|
|
35
|
+
if (action.type === 'list') {
|
|
36
|
+
const agents = await this.agents.list();
|
|
37
|
+
return { scope: 'loaded', chats: await Promise.all(agents.map(async (agent) => ({
|
|
38
|
+
session_id: agent.id, cwd: agent.session.header.cwd ?? null,
|
|
39
|
+
status: await agent.status, attached: this.owned.has(agent.id),
|
|
40
|
+
}))) };
|
|
41
|
+
}
|
|
42
|
+
const sessionId = action.type === 'create' ? `session-ft-bot-${id}` : action.session_id;
|
|
43
|
+
if (typeof sessionId !== 'string' || !/^[\w-]{1,256}$/.test(sessionId))
|
|
44
|
+
throw new Error('Invalid FtAi session ID.');
|
|
45
|
+
if (this.busy.has(sessionId))
|
|
46
|
+
throw new Error('Another request is still updating this local chat.');
|
|
47
|
+
this.busy.add(sessionId);
|
|
48
|
+
let acquired;
|
|
49
|
+
let submitted = false;
|
|
50
|
+
try {
|
|
51
|
+
if (action.type === 'create' || action.type === 'resume') {
|
|
52
|
+
if (action.prompt !== null)
|
|
53
|
+
prompt(action.prompt);
|
|
54
|
+
if (action.type === 'create' && action.cwd !== null && (!isAbsolute(action.cwd) || action.cwd.includes('\0'))) {
|
|
55
|
+
throw new Error('The chat working directory must be an absolute local path.');
|
|
56
|
+
}
|
|
57
|
+
signal.throwIfAborted();
|
|
58
|
+
if (action.type === 'create') {
|
|
59
|
+
acquired = await this.agents.create({ sessionId, ...(action.cwd === null ? {} : { meta: { cwd: action.cwd } }), signal });
|
|
60
|
+
}
|
|
61
|
+
else if (!this.owned.has(sessionId)) {
|
|
62
|
+
acquired = await this.agents.resume({ resumeSessionId: sessionId, signal });
|
|
63
|
+
}
|
|
64
|
+
signal.throwIfAborted();
|
|
65
|
+
if (acquired)
|
|
66
|
+
this.owned.set(sessionId, acquired);
|
|
67
|
+
const agent = this.attached(sessionId);
|
|
68
|
+
const nextSeq = await agent.session.readSeq();
|
|
69
|
+
signal.throwIfAborted();
|
|
70
|
+
if (action.prompt !== null) {
|
|
71
|
+
// The runner operation ID identifies the submitted message. It can be
|
|
72
|
+
// found in the local log after an uncertain transport outcome.
|
|
73
|
+
submitted = true;
|
|
74
|
+
await agent.followup({ id: `ft-bot-${id}`, role: 'user', source: { kind: 'user' }, content: [{ type: 'text', text: action.prompt }] });
|
|
75
|
+
}
|
|
76
|
+
signal.throwIfAborted();
|
|
77
|
+
return { session_id: sessionId, message_id: action.prompt === null ? null : `ft-bot-${id}`,
|
|
78
|
+
status: action.prompt === null ? await agent.status : 'submitted', next_seq: nextSeq };
|
|
79
|
+
}
|
|
80
|
+
const agent = this.attached(sessionId);
|
|
81
|
+
if (action.type === 'cancel') {
|
|
82
|
+
await agent.cancel({ kind: 'hook', reason: 'ft-bot-cancelled' });
|
|
83
|
+
return { session_id: sessionId, cancellation_requested: true };
|
|
84
|
+
}
|
|
85
|
+
if (!Number.isSafeInteger(action.after_seq) || action.after_seq < 0)
|
|
86
|
+
throw new Error('Invalid chat cursor.');
|
|
87
|
+
const end = await agent.session.readSeq();
|
|
88
|
+
if (action.after_seq > end)
|
|
89
|
+
throw new Error('Chat cursor is beyond the current log.');
|
|
90
|
+
const to = Math.min(end, action.after_seq + 256);
|
|
91
|
+
const events = to === action.after_seq ? [] : await agent.session.readEvents({ fromSeq: action.after_seq, toSeq: to - 1 });
|
|
92
|
+
let budget = 64 * 1024;
|
|
93
|
+
const entries = [];
|
|
94
|
+
let nextSeq = action.after_seq;
|
|
95
|
+
let truncated = false;
|
|
96
|
+
for (const event of events) {
|
|
97
|
+
if (budget <= 0)
|
|
98
|
+
break;
|
|
99
|
+
nextSeq = event.seq + 1;
|
|
100
|
+
const data = event.data;
|
|
101
|
+
if (event.type === 'assistant/message' || event.type === 'user/message') {
|
|
102
|
+
const message = event.type === 'assistant/message' ? data.message : data;
|
|
103
|
+
const text = message.content
|
|
104
|
+
.filter(block => block.type === 'text').map(block => block.text ?? '').join('\n');
|
|
105
|
+
const clipped = text.length > budget;
|
|
106
|
+
entries.push({ seq: event.seq, time: event.time, role: event.type === 'user/message' ? 'user' : 'assistant',
|
|
107
|
+
message_id: message.id, text: text.slice(0, budget), truncated: clipped });
|
|
108
|
+
truncated ||= clipped;
|
|
109
|
+
budget -= Math.min(text.length, budget);
|
|
110
|
+
}
|
|
111
|
+
else if (event.type === 'turn/end') {
|
|
112
|
+
entries.push({ seq: event.seq, time: event.time, turn: data.turn, reason: data.reason?.kind,
|
|
113
|
+
error: typeof data.reason?.error?.message === 'string' ? data.reason.error.message.slice(0, 2000) : null });
|
|
114
|
+
budget -= 2000;
|
|
115
|
+
}
|
|
116
|
+
}
|
|
117
|
+
// Events can be sparse in test/custom session stores; the queried range is consumed.
|
|
118
|
+
if (budget > 0)
|
|
119
|
+
nextSeq = to;
|
|
120
|
+
return { session_id: sessionId, status: await agent.status, entries,
|
|
121
|
+
next_seq: nextSeq, has_more: nextSeq < end, truncated };
|
|
122
|
+
}
|
|
123
|
+
catch (error) {
|
|
124
|
+
try {
|
|
125
|
+
if (signal.aborted && submitted) {
|
|
126
|
+
await this.owned.get(sessionId)?.agent.cancel({ kind: 'hook', reason: 'ft-bot-request-interrupted' });
|
|
127
|
+
}
|
|
128
|
+
}
|
|
129
|
+
finally {
|
|
130
|
+
if (acquired) {
|
|
131
|
+
this.owned.delete(sessionId);
|
|
132
|
+
await acquired.dispose();
|
|
133
|
+
}
|
|
134
|
+
}
|
|
135
|
+
throw error;
|
|
136
|
+
}
|
|
137
|
+
finally {
|
|
138
|
+
this.busy.delete(sessionId);
|
|
139
|
+
}
|
|
140
|
+
}
|
|
141
|
+
attached(id) {
|
|
142
|
+
const owned = this.owned.get(id);
|
|
143
|
+
if (!owned)
|
|
144
|
+
throw new Error('Attach this chat with resume and a null prompt before reading or cancelling it.');
|
|
145
|
+
return owned.agent;
|
|
146
|
+
}
|
|
147
|
+
stop() {
|
|
148
|
+
if (this.stopping)
|
|
149
|
+
return this.stopping;
|
|
150
|
+
this.lifetime.abort();
|
|
151
|
+
this.stopping = (async () => {
|
|
152
|
+
await Promise.allSettled([...this.requests]);
|
|
153
|
+
const owned = [...this.owned.values()];
|
|
154
|
+
this.owned.clear();
|
|
155
|
+
const results = await Promise.allSettled(owned.map(chat => chat.dispose()));
|
|
156
|
+
const failure = results.find(result => result.status === 'rejected');
|
|
157
|
+
if (failure?.status === 'rejected')
|
|
158
|
+
throw failure.reason;
|
|
159
|
+
})().finally(() => { this.lifetime = new AbortController(); this.stopping = undefined; });
|
|
160
|
+
return this.stopping;
|
|
161
|
+
}
|
|
162
|
+
}
|
|
163
|
+
//# sourceMappingURL=chats.js.map
|
package/lib/chats.js.map
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"chats.js","sourceRoot":"","sources":["../src/chats.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,MAAM,WAAW,CAAA;AAetC,SAAS,MAAM,CAAC,KAAa;IAC3B,IAAI,OAAO,KAAK,KAAK,QAAQ,IAAI,CAAC,KAAK,CAAC,IAAI,EAAE,IAAI,MAAM,CAAC,UAAU,CAAC,KAAK,CAAC,GAAG,KAAK,IAAI,KAAK,CAAC,QAAQ,CAAC,IAAI,CAAC,EAAE,CAAC;QAC3G,MAAM,IAAI,KAAK,CAAC,uDAAuD,CAAC,CAAA;IAC1E,CAAC;AACH,CAAC;AAED,MAAM,OAAO,KAAK;IAOa;IANZ,KAAK,GAAG,IAAI,GAAG,EAAqB,CAAA;IACpC,IAAI,GAAG,IAAI,GAAG,EAAU,CAAA;IACxB,QAAQ,GAAG,IAAI,GAAG,EAAoB,CAAA;IAC/C,QAAQ,GAAG,IAAI,eAAe,EAAE,CAAA;IAChC,QAAQ,CAA2B;IAE3C,YAA6B,MAAkB;QAAlB,WAAM,GAAN,MAAM,CAAY;IAAG,CAAC;IAEnD,KAAK,CAAC,OAAO,CAAC,EAAU,EAAE,MAAkB,EAAE,MAAmB;QAC/D,IAAI,IAAI,CAAC,QAAQ;YAAE,MAAM,IAAI,CAAC,QAAQ,CAAA;QACtC,MAAM,CAAC,c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AAE,CAAC,CAAC,IAAI,CAAC,QAAQ,GAAG,SAAS,CAAA,CAAC,CAAC,CAAC,CAAA;QACxF,OAAO,IAAI,CAAC,QAAQ,CAAA;IACtB,CAAC;CACF"}
|
package/lib/client.js
ADDED
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
window.__ModuleLoader__.load({ id: "@ftai/ftai-plugin-ft-bot", factory: (require) => { var module = { exports: {} }; var exports = module.exports;
|
|
2
|
+
Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});let e=require("react"),t=require("@ftai/client-app"),n=require("react/jsx-runtime");var r={outline:{xmlns:`http://www.w3.org/2000/svg`,width:24,height:24,viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:2,strokeLinecap:`round`,strokeLinejoin:`round`},filled:{xmlns:`http://www.w3.org/2000/svg`,width:24,height:24,viewBox:`0 0 24 24`,fill:`currentColor`,stroke:`none`}},i=((t,n,i,a)=>{let o=(0,e.forwardRef)(({color:i=`currentColor`,size:o=24,stroke:s=2,title:c,className:l,children:u,...d},f)=>(0,e.createElement)(`svg`,{ref:f,...r[t],width:o,height:o,className:[`tabler-icon`,`tabler-icon-${n}`,l].join(` `),strokeWidth:s,stroke:i,...d},[c&&(0,e.createElement)(`title`,{key:`svg-title`},c),...a.map(([t,n])=>(0,e.createElement)(t,n)),...Array.isArray(u)?u:[u]]));return o.displayName=`${i}`,o})(`outline`,`device-desktop`,`DeviceDesktop`,[[`path`,{d:`M3 5a1 1 0 0 1 1 -1h16a1 1 0 0 1 1 1v10a1 1 0 0 1 -1 1h-16a1 1 0 0 1 -1 -1v-10`,key:`svg-0`}],[`path`,{d:`M7 20h10`,key:`svg-1`}],[`path`,{d:`M9 16v4`,key:`svg-2`}],[`path`,{d:`M15 16v4`,key:`svg-3`}]]);function a(r,i){return function(){let{t:a}=(0,t.useMessages)(r),[o,s]=(0,e.useState)(null),[c,l]=(0,e.useState)(null),[u,d]=(0,e.useState)(``),[f,p]=(0,e.useState)(!1),[m,h]=(0,e.useState)(null),g=(0,e.useRef)(!1),_=(0,e.useRef)(0),v=(0,e.useRef)(!1);(0,e.useEffect)(()=>{g.current=!0;let e=!1,t=async()=>{if(v.current||e)return;e=!0;let t=_.current;try{let e=await i.status();if(!g.current||t!==_.current)return;e.ok?s(e.value):h(e.error.message)}catch(e){g.current&&t===_.current&&h(String(e))}finally{e=!1}};t();let n=setInterval(()=>{t()},2e3);return()=>{g.current=!1,_.current++,clearInterval(n)}},[]);let y=async e=>{if(v.current)return;v.current=!0;let t=++_.current;p(!0),h(null);try{let n=await e();if(!g.current||t!==_.current)return;n.ok?s(n.value):h(n.error.message)}catch(e){g.current&&t===_.current&&h(String(e))}finally{v.current=!1,g.current&&t===_.current&&p(!1)}},b=f||!o||o.busy,x=!!o?.computer?.device_id,S=o?.enabled&&(o.connection===`error`||o.connection===`stopped`),C=m||o?.error;return(0,n.jsxs)(t.SettingsPage,{title:a(`title`),description:a(`description`),children:[(0,n.jsx)(`p`,{className:`ft-bot-note`,children:a(`access`)}),!o&&(0,n.jsx)(`p`,{role:`status`,children:a(`waiting`)}),C&&(0,n.jsxs)(`div`,{className:`ft-bot-error`,role:`alert`,children:[(0,n.jsx)(`p`,{children:a(`failed`)}),(0,n.jsx)(`pre`,{children:C})]}),!x&&(0,n.jsx)(t.SettingsGroup,{children:(0,n.jsx)(t.SettingsRow,{title:a(`pairing`),description:a(`instructions`),children:(0,n.jsxs)(`form`,{className:`ft-bot-form`,onSubmit:e=>{e.preventDefault();let t=u;d(``),y(()=>i.pair((c??o?.server??``).trim(),t))},children:[(0,n.jsxs)(`label`,{children:[a(`code`),(0,n.jsx)(t.Input,{type:`password`,value:u,autoComplete:`off`,onChange:e=>d(e.target.value),required:!0,disabled:b,maxLength:256})]}),(0,n.jsxs)(`details`,{className:`ft-bot-advanced`,children:[(0,n.jsx)(`summary`,{children:a(`advanced`)}),(0,n.jsxs)(`label`,{children:[a(`gateway`),(0,n.jsx)(t.Input,{type:`url`,value:c??o?.server??`https://ftai.chat/ft-bot/api`,placeholder:`https://ftai.chat/ft-bot/api`,onChange:e=>l(e.target.value),disabled:b})]}),(0,n.jsx)(`p`,{className:`ft-bot-note`,children:a(`gatewayHelp`)})]}),(0,n.jsx)(t.Button,{type:`submit`,disabled:b||!u.trim(),children:a(f?`pairingBusy`:`pair`)})]})})}),x&&(0,n.jsx)(t.SettingsGroup,{children:(0,n.jsxs)(t.SettingsRow,{title:a(`connection`),description:a(`lifetime`),action:(0,n.jsx)(t.Button,{variant:`outline`,size:`sm`,disabled:b,onClick:()=>{y(()=>i.setEnabled(S||!o?.enabled))},children:S?a(`retry`):o?.enabled?a(`disconnect`):a(`connect`)}),children:[(0,n.jsx)(`p`,{role:`status`,children:a(`state.${o.connection}`)}),(0,n.jsxs)(`p`,{className:`ft-bot-note`,children:[a(`computer`),`: `,(0,n.jsx)(`code`,{children:o.computer.device_id})]}),(0,n.jsx)(`p`,{className:`ft-bot-note`,children:a(`select`)})]})}),o?.installed&&(0,n.jsxs)(t.SettingsGroup,{children:[(0,n.jsx)(t.SettingsRow,{title:a(`chats`),description:a(`chatsHelp`)}),(0,n.jsxs)(t.SettingsRow,{title:a(`desktop`),description:a(`desktopHelp`),action:(0,n.jsx)(t.Button,{variant:`outline`,size:`sm`,disabled:b,onClick:()=>{y(()=>i.refresh())},children:a(`diagnostics`)}),children:[o.computer?.platform===`macos`&&(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)(`p`,{className:`ft-bot-note`,children:a(`permissionsHelp`)}),(0,n.jsx)(t.Button,{variant:`outline`,size:`sm`,disabled:b,onClick:()=>{y(()=>i.requestPermissions())},children:a(`permissions`)})]}),(0,n.jsxs)(`details`,{className:`ft-bot-diagnostics`,children:[(0,n.jsx)(`summary`,{children:a(`details`)}),(0,n.jsx)(`pre`,{children:JSON.stringify(o.computer?.desktop??{},null,2)})]})]}),(0,n.jsx)(t.SettingsRow,{title:a(`update`),description:a(`updateHelp`),action:(0,n.jsx)(t.Button,{variant:`outline`,size:`sm`,disabled:b||!o.server,onClick:()=>{y(()=>i.updateRunner())},children:a(f?`working`:`updateAction`)})})]})]})}}var o={title:`Ft Bot`,description:`Connect your WeCom bot to this computer.`,access:`The bot runs with your OS account’s file, credential, app and network access. Command output, screenshots and requested local chat text are sent to the cloud bot. Disconnect here or disable this plugin to stop access.`,pairing:`Pair this computer`,instructions:`Ask your bot to connect this computer, then paste its one-use pairing code here.`,advanced:`Advanced`,gateway:`Server URL`,gatewayHelp:`Change this only if your bot uses a different server. Leave blank to use the default.`,code:`One-use pairing code`,pair:`Pair and connect`,pairingBusy:`Downloading and pairing…`,connection:`Connection`,lifetime:`Reconnects while this plugin is enabled and the FtAi host is running, including in the background. Disconnect is remembered across restarts.`,connect:`Connect`,disconnect:`Disconnect`,retry:`Reconnect`,state:{stopped:`Disconnected`,connecting:`Connecting…`,connected:`Connected`,reconnecting:`Reconnecting — check the gateway and access in the bot`,error:`Connection failed`},computer:`Computer ID`,select:`Ask the bot to select this computer. New bot conversations then use it; existing jobs keep their current computer.`,chats:`Local FtAi chats`,chatsHelp:`Ask the bot to create a local chat, resume one by its session ID, or read its replies. Chats use FtAi’s default model and permissions; answer approvals and questions in FtAi. Disconnecting releases attached chats and stops their current turns. Their history stays saved.`,desktop:`Desktop access`,desktopHelp:`Windows and macOS support screenshots, clicks, dragging, scrolling, typing and keyboard shortcuts. Keep the account logged in and the desktop unlocked. Native desktop control is unavailable on Linux.`,permissions:`Request macOS permissions`,permissionsHelp:`Allow the runner in System Settings → Privacy & Security → Screen & System Audio Recording and Accessibility. After changing permissions, disconnect and reconnect.`,diagnostics:`Refresh diagnostics`,details:`Desktop diagnostics`,update:`Update runner`,updateHelp:`Downloads the gateway’s current runner and verifies its SHA-256. Updating temporarily stops active work. macOS may require granting desktop permissions again.`,updateAction:`Download update`,waiting:`Waiting for the plugin host…`,failed:`The operation failed. Check the details below.`,working:`Working…`},s={title:`Ft Bot`,description:`将企业微信中的机器人连接到这台电脑。`,access:`机器人以当前系统账户的权限访问文件、凭据、应用和网络。命令输出、截图及请求读取的本地会话文本会发送给云端机器人。可在这里断开连接,或停用插件来停止访问。`,pairing:`配对这台电脑`,instructions:`请机器人连接这台电脑,然后在这里粘贴它提供的一次性配对码。`,advanced:`高级设置`,gateway:`服务器地址`,gatewayHelp:`仅当机器人使用其他服务器时修改。留空则使用默认地址。`,code:`一次性配对码`,pair:`配对并连接`,pairingBusy:`正在下载并配对…`,connection:`连接`,lifetime:`插件启用且 FtAi 宿主运行时(包括后台运行)会自动重连。主动断开后,重启也不会自动连接。`,connect:`连接`,disconnect:`断开连接`,retry:`重新连接`,state:{stopped:`已断开`,connecting:`正在连接…`,connected:`已连接`,reconnecting:`正在重连,请检查网关及机器人中的访问权限`,error:`连接失败`},computer:`电脑 ID`,select:`请机器人选择这台电脑。新的机器人会话将使用它,已有任务继续使用原来的电脑。`,chats:`本地 FtAi 会话`,chatsHelp:`请机器人创建本地会话、通过会话 ID 继续已有会话,或读取回复。会话使用 FtAi 的默认模型和权限;请在 FtAi 中处理审批和提问。断开连接会释放已连接的会话并停止其当前轮次,历史记录仍会保留。`,desktop:`桌面访问`,desktopHelp:`Windows 和 macOS 支持截图、点击、拖拽、滚动、输入文字和快捷键。请保持账户登录及桌面解锁。Linux 不支持原生桌面控制。`,permissions:`请求 macOS 权限`,permissionsHelp:`在系统设置 → 隐私与安全性 → 屏幕与系统录音、辅助功能中允许运行程序。修改权限后,请断开并重新连接。`,diagnostics:`刷新诊断`,details:`桌面诊断信息`,update:`更新运行程序`,updateHelp:`下载网关当前版本并校验 SHA-256。更新会暂时停止当前工作,macOS 更新后可能需要重新授予桌面权限。`,updateAction:`下载更新`,waiting:`正在等待插件宿主…`,failed:`操作失败,请查看下方详情。`,working:`正在处理…`},c={meta:{title:`Ft Bot`,description:`Local computer access for your WeCom bot.`}},l={meta:{title:`Ft Bot`,description:`让企业微信中的机器人访问本地电脑。`}},u=`@ftai/ftai-plugin-ft-bot`,d=[`ftaiFeatures`,`remote`];function f(e){let t=e.ftaiFeatures.createMessageScope({"en-US":o,"zh-CN":s});e.inject([`remote.ftBot`],e=>{let n=a(t,e.remote.ftBot),r=()=>(t.locale()===`zh-CN`?l:c).meta;e.ftaiFeatures.register({id:`ft-bot`,name:()=>r().title,description:()=>r().description,settings:{label:()=>r().title,icon:i,group:`integrations`,order:90,component:n}})})}exports.apply=f,exports.inject=d,exports.name=u;
|
|
3
|
+
if (typeof document !== "undefined") {
|
|
4
|
+
const style = document.createElement("style");
|
|
5
|
+
style.setAttribute("data-plugin", "@ftai/ftai-plugin-ft-bot");
|
|
6
|
+
style.setAttribute("data-plugin-css", "@ftai/ftai-plugin-ft-bot");
|
|
7
|
+
style.textContent = ".ft-bot-note{color:var(--muted-foreground);overflow-wrap:anywhere;font-size:14px}.ft-bot-form{gap:16px;max-width:460px;margin-top:16px;display:grid}.ft-bot-form label{gap:8px;font-size:14px;display:grid}.ft-bot-advanced summary{cursor:pointer;font-size:14px}.ft-bot-advanced label{margin-top:12px}.ft-bot-error{color:var(--destructive)}.ft-bot-error pre,.ft-bot-diagnostics pre{white-space:pre-wrap;overflow-wrap:anywhere;font-size:12px}.ft-bot-diagnostics{margin-top:16px}.ft-bot-diagnostics summary{cursor:pointer;font-size:14px}\n/*$vite$:1*/";
|
|
8
|
+
document.head.append(style);
|
|
9
|
+
}
|
|
10
|
+
return module.exports; } });
|
|
11
|
+
//# sourceMappingURL=client.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"client.js","names":["forwardRef","createElement","useMessages","useState","useRef","SettingsPage","SettingsGroup","SettingsRow","Input","Button","_Fragment","meta","enUS","zhCN","zhMeta","enMeta","react","_ftai_client_app","react_jsx_runtime","defaultAttributes","IconDeviceDesktop","Component","rest","type","size","iconName","className","stroke","color","title","iconNode","tag","attrs","children","iconNamePascal","\"d\"","\"key\"","createSettings","messages","status","setStatus","server","setServer","code","setCode","pending","setPending","error","setError","active","generation","inFlight","polling","poll","owner","result","remote","timer","run","call","busy","paired","retry","failure","t","event","pairingCode","en_US_default","zh_CN_default$1","en_default","\"title\"","\"description\"","zh_CN_default","name","inject","apply","ctx","Page","scoped","meta"],"sources":["../node_modules/.pnpm/@tabler+icons-react@3.46.0_react@18.3.1/node_modules/@tabler/icons-react/dist/esm/defaultAttributes.mjs","../node_modules/.pnpm/@tabler+icons-react@3.46.0_react@18.3.1/node_modules/@tabler/icons-react/dist/esm/createReactComponent.mjs","../node_modules/.pnpm/@tabler+icons-react@3.46.0_react@18.3.1/node_modules/@tabler/icons-react/dist/esm/icons/IconDeviceDesktop.mjs","../src/types.ts","../src/client/Settings.tsx","../src/client/i18n/en-US.ts","../src/client/i18n/zh-CN.ts","../locale/en.json","../locale/zh-CN.json","../src/client/index.ts"],"sourcesContent":["/**\n * @license @tabler/icons-react v3.46.0 - MIT\n *\n * This source code is licensed under the MIT license.\n * See the LICENSE file in the root directory of this source tree.\n */\n\nvar defaultAttributes = {\n outline: {\n xmlns: \"http://www.w3.org/2000/svg\",\n width: 24,\n height: 24,\n viewBox: \"0 0 24 24\",\n fill: \"none\",\n stroke: \"currentColor\",\n strokeWidth: 2,\n strokeLinecap: \"round\",\n strokeLinejoin: \"round\"\n },\n filled: {\n xmlns: \"http://www.w3.org/2000/svg\",\n width: 24,\n height: 24,\n viewBox: \"0 0 24 24\",\n fill: \"currentColor\",\n stroke: \"none\"\n }\n};\n\nexport { defaultAttributes as default };\n//# sourceMappingURL=defaultAttributes.mjs.map\n","/**\n * @license @tabler/icons-react v3.46.0 - MIT\n *\n * This source code is licensed under the MIT license.\n * See the LICENSE file in the root directory of this source tree.\n */\n\nimport { forwardRef, createElement } from 'react';\nimport defaultAttributes from './defaultAttributes.mjs';\n\nconst createReactComponent = (type, iconName, iconNamePascal, iconNode) => {\n const Component = forwardRef(\n ({ color = \"currentColor\", size = 24, stroke = 2, title, className, children, ...rest }, ref) => createElement(\n \"svg\",\n {\n ref,\n ...defaultAttributes[type],\n width: size,\n height: size,\n className: [`tabler-icon`, `tabler-icon-${iconName}`, className].join(\" \"),\n ...type === \"filled\" ? {\n fill: color\n } : {\n strokeWidth: stroke,\n stroke: color\n },\n ...rest\n },\n [\n title && createElement(\"title\", { key: \"svg-title\" }, title),\n ...iconNode.map(([tag, attrs]) => createElement(tag, attrs)),\n ...Array.isArray(children) ? children : [children]\n ]\n )\n );\n Component.displayName = `${iconNamePascal}`;\n return Component;\n};\n\nexport { createReactComponent as default };\n//# sourceMappingURL=createReactComponent.mjs.map\n","/**\n * @license @tabler/icons-react v3.46.0 - MIT\n *\n * This source code is licensed under the MIT license.\n * See the LICENSE file in the root directory of this source tree.\n */\n\nimport createReactComponent from '../createReactComponent.mjs';\n\nconst __iconNode = [[\"path\", { \"d\": \"M3 5a1 1 0 0 1 1 -1h16a1 1 0 0 1 1 1v10a1 1 0 0 1 -1 1h-16a1 1 0 0 1 -1 -1v-10\", \"key\": \"svg-0\" }], [\"path\", { \"d\": \"M7 20h10\", \"key\": \"svg-1\" }], [\"path\", { \"d\": \"M9 16v4\", \"key\": \"svg-2\" }], [\"path\", { \"d\": \"M15 16v4\", \"key\": \"svg-3\" }]];\nconst IconDeviceDesktop = createReactComponent(\"outline\", \"device-desktop\", \"DeviceDesktop\", __iconNode);\n\nexport { __iconNode, IconDeviceDesktop as default };\n//# sourceMappingURL=IconDeviceDesktop.mjs.map\n","export const DEFAULT_GATEWAY = 'https://ftai.chat/ft-bot/api'\n\nexport type Connection = 'stopped' | 'connecting' | 'connected' | 'reconnecting' | 'error'\n\nexport interface ComputerStatus {\n bridge: number\n protocol: number\n platform: string\n arch: string\n server: string | null\n device_id: string | null\n desktop: Record<string, unknown>\n}\n\nexport interface PluginStatus {\n server: string\n installed: boolean\n enabled: boolean\n busy: boolean\n connection: Connection\n computer: ComputerStatus | null\n error: string | null\n}\n\nimport type {} from '@ftai/plugin-sdk/host'\n\ndeclare module '@ftai/plugin-sdk/host' {\n interface RemoteErrorDetailsMap {\n 'ft-bot/operation-failed': { reason: string }\n }\n}\n","import { useEffect, useRef, useState } from 'react'\nimport { Button, Input, SettingsGroup, SettingsPage, SettingsRow, useMessages } from '@ftai/plugin-sdk/app'\nimport type { MessageScope } from '@ftai/plugin-sdk/features'\nimport type { RemoteNamespaceMap, RemoteResult } from '@ftai/plugin-sdk/remote'\nimport type {} from '@ftai/ftai-plugin-ft-bot/remote'\nimport { DEFAULT_GATEWAY, type PluginStatus } from '../types.ts'\n\nexport function createSettings(messages: MessageScope, remote: RemoteNamespaceMap['ftBot']) {\n return function Settings() {\n const { t } = useMessages(messages)\n const [status, setStatus] = useState<PluginStatus | null>(null)\n const [server, setServer] = useState<string | null>(null)\n const [code, setCode] = useState('')\n const [pending, setPending] = useState(false)\n const [error, setError] = useState<string | null>(null)\n const active = useRef(false)\n const generation = useRef(0)\n const inFlight = useRef(false)\n\n useEffect(() => {\n active.current = true\n let polling = false\n const poll = async () => {\n if (inFlight.current || polling) return\n polling = true\n const owner = generation.current\n try {\n const result = await remote.status()\n if (!active.current || owner !== generation.current) return\n if (result.ok) setStatus(result.value)\n else setError(result.error.message)\n } catch (error) {\n if (active.current && owner === generation.current) setError(String(error))\n } finally { polling = false }\n }\n void poll()\n const timer = setInterval(() => { void poll() }, 2000)\n return () => { active.current = false; generation.current++; clearInterval(timer) }\n }, [])\n\n const run = async (call: () => Promise<RemoteResult<PluginStatus>>) => {\n if (inFlight.current) return\n inFlight.current = true\n const owner = ++generation.current\n setPending(true)\n setError(null)\n try {\n const result = await call()\n if (!active.current || owner !== generation.current) return\n if (result.ok) setStatus(result.value)\n else setError(result.error.message)\n } catch (error) {\n if (active.current && owner === generation.current) setError(String(error))\n } finally {\n inFlight.current = false\n if (active.current && owner === generation.current) setPending(false)\n }\n }\n\n const busy = pending || !status || status.busy\n const paired = Boolean(status?.computer?.device_id)\n const retry = status?.enabled && (status.connection === 'error' || status.connection === 'stopped')\n const failure = error || status?.error\n return <SettingsPage title={t('title')} description={t('description')}>\n <p className=\"ft-bot-note\">{t('access')}</p>\n {!status && <p role=\"status\">{t('waiting')}</p>}\n {failure && <div className=\"ft-bot-error\" role=\"alert\"><p>{t('failed')}</p><pre>{failure}</pre></div>}\n {!paired && <SettingsGroup>\n <SettingsRow title={t('pairing')} description={t('instructions')}>\n <form className=\"ft-bot-form\" onSubmit={event => {\n event.preventDefault()\n const pairingCode = code\n setCode('')\n void run(() => remote.pair((server ?? status?.server ?? '').trim(), pairingCode))\n }}>\n <label>{t('code')}<Input type=\"password\" value={code} autoComplete=\"off\"\n onChange={event => setCode(event.target.value)} required disabled={busy} maxLength={256} /></label>\n <details className=\"ft-bot-advanced\">\n <summary>{t('advanced')}</summary>\n <label>{t('gateway')}<Input type=\"url\" value={server ?? status?.server ?? DEFAULT_GATEWAY}\n placeholder={DEFAULT_GATEWAY} onChange={event => setServer(event.target.value)} disabled={busy} /></label>\n <p className=\"ft-bot-note\">{t('gatewayHelp')}</p>\n </details>\n <Button type=\"submit\" disabled={busy || !code.trim()}>{pending ? t('pairingBusy') : t('pair')}</Button>\n </form>\n </SettingsRow>\n </SettingsGroup>}\n {paired && <SettingsGroup>\n <SettingsRow title={t('connection')} description={t('lifetime')}\n action={<Button variant=\"outline\" size=\"sm\" disabled={busy}\n onClick={() => { void run(() => remote.setEnabled(retry || !status?.enabled)) }}>\n {retry ? t('retry') : status?.enabled ? t('disconnect') : t('connect')}\n </Button>}>\n <p role=\"status\">{t(`state.${status!.connection}`)}</p>\n <p className=\"ft-bot-note\">{t('computer')}: <code>{status!.computer!.device_id}</code></p>\n <p className=\"ft-bot-note\">{t('select')}</p>\n </SettingsRow>\n </SettingsGroup>}\n {status?.installed && <SettingsGroup>\n <SettingsRow title={t('chats')} description={t('chatsHelp')} />\n <SettingsRow title={t('desktop')} description={t('desktopHelp')}\n action={<Button variant=\"outline\" size=\"sm\" disabled={busy}\n onClick={() => { void run(() => remote.refresh()) }}>{t('diagnostics')}</Button>}>\n {status.computer?.platform === 'macos' && <>\n <p className=\"ft-bot-note\">{t('permissionsHelp')}</p>\n <Button variant=\"outline\" size=\"sm\" disabled={busy}\n onClick={() => { void run(() => remote.requestPermissions()) }}>{t('permissions')}</Button>\n </>}\n <details className=\"ft-bot-diagnostics\"><summary>{t('details')}</summary>\n <pre>{JSON.stringify(status.computer?.desktop ?? {}, null, 2)}</pre>\n </details>\n </SettingsRow>\n <SettingsRow title={t('update')} description={t('updateHelp')}\n action={<Button variant=\"outline\" size=\"sm\" disabled={busy || !status.server}\n onClick={() => { void run(() => remote.updateRunner()) }}>{pending ? t('working') : t('updateAction')}</Button>} />\n </SettingsGroup>}\n </SettingsPage>\n }\n}\n","export default {\n title: 'Ft Bot',\n description: 'Connect your WeCom bot to this computer.',\n access: 'The bot runs with your OS account’s file, credential, app and network access. Command output, screenshots and requested local chat text are sent to the cloud bot. Disconnect here or disable this plugin to stop access.',\n pairing: 'Pair this computer',\n instructions: 'Ask your bot to connect this computer, then paste its one-use pairing code here.',\n advanced: 'Advanced',\n gateway: 'Server URL',\n gatewayHelp: 'Change this only if your bot uses a different server. Leave blank to use the default.',\n code: 'One-use pairing code',\n pair: 'Pair and connect',\n pairingBusy: 'Downloading and pairing…',\n connection: 'Connection',\n lifetime: 'Reconnects while this plugin is enabled and the FtAi host is running, including in the background. Disconnect is remembered across restarts.',\n connect: 'Connect', disconnect: 'Disconnect', retry: 'Reconnect',\n state: {\n stopped: 'Disconnected', connecting: 'Connecting…', connected: 'Connected',\n reconnecting: 'Reconnecting — check the gateway and access in the bot', error: 'Connection failed',\n },\n computer: 'Computer ID',\n select: 'Ask the bot to select this computer. New bot conversations then use it; existing jobs keep their current computer.',\n chats: 'Local FtAi chats',\n chatsHelp: 'Ask the bot to create a local chat, resume one by its session ID, or read its replies. Chats use FtAi’s default model and permissions; answer approvals and questions in FtAi. Disconnecting releases attached chats and stops their current turns. Their history stays saved.',\n desktop: 'Desktop access',\n desktopHelp: 'Windows and macOS support screenshots, clicks, dragging, scrolling, typing and keyboard shortcuts. Keep the account logged in and the desktop unlocked. Native desktop control is unavailable on Linux.',\n permissions: 'Request macOS permissions',\n permissionsHelp: 'Allow the runner in System Settings → Privacy & Security → Screen & System Audio Recording and Accessibility. After changing permissions, disconnect and reconnect.',\n diagnostics: 'Refresh diagnostics',\n details: 'Desktop diagnostics',\n update: 'Update runner',\n updateHelp: 'Downloads the gateway’s current runner and verifies its SHA-256. Updating temporarily stops active work. macOS may require granting desktop permissions again.',\n updateAction: 'Download update',\n waiting: 'Waiting for the plugin host…',\n failed: 'The operation failed. Check the details below.',\n working: 'Working…',\n}\n","export default {\n title: 'Ft Bot',\n description: '将企业微信中的机器人连接到这台电脑。',\n access: '机器人以当前系统账户的权限访问文件、凭据、应用和网络。命令输出、截图及请求读取的本地会话文本会发送给云端机器人。可在这里断开连接,或停用插件来停止访问。',\n pairing: '配对这台电脑',\n instructions: '请机器人连接这台电脑,然后在这里粘贴它提供的一次性配对码。',\n advanced: '高级设置',\n gateway: '服务器地址',\n gatewayHelp: '仅当机器人使用其他服务器时修改。留空则使用默认地址。',\n code: '一次性配对码',\n pair: '配对并连接',\n pairingBusy: '正在下载并配对…',\n connection: '连接',\n lifetime: '插件启用且 FtAi 宿主运行时(包括后台运行)会自动重连。主动断开后,重启也不会自动连接。',\n connect: '连接', disconnect: '断开连接', retry: '重新连接',\n state: {\n stopped: '已断开', connecting: '正在连接…', connected: '已连接',\n reconnecting: '正在重连,请检查网关及机器人中的访问权限', error: '连接失败',\n },\n computer: '电脑 ID',\n select: '请机器人选择这台电脑。新的机器人会话将使用它,已有任务继续使用原来的电脑。',\n chats: '本地 FtAi 会话',\n chatsHelp: '请机器人创建本地会话、通过会话 ID 继续已有会话,或读取回复。会话使用 FtAi 的默认模型和权限;请在 FtAi 中处理审批和提问。断开连接会释放已连接的会话并停止其当前轮次,历史记录仍会保留。',\n desktop: '桌面访问',\n desktopHelp: 'Windows 和 macOS 支持截图、点击、拖拽、滚动、输入文字和快捷键。请保持账户登录及桌面解锁。Linux 不支持原生桌面控制。',\n permissions: '请求 macOS 权限',\n permissionsHelp: '在系统设置 → 隐私与安全性 → 屏幕与系统录音、辅助功能中允许运行程序。修改权限后,请断开并重新连接。',\n diagnostics: '刷新诊断',\n details: '桌面诊断信息',\n update: '更新运行程序',\n updateHelp: '下载网关当前版本并校验 SHA-256。更新会暂时停止当前工作,macOS 更新后可能需要重新授予桌面权限。',\n updateAction: '下载更新',\n waiting: '正在等待插件宿主…',\n failed: '操作失败,请查看下方详情。',\n working: '正在处理…',\n}\n","{ \"meta\": { \"title\": \"Ft Bot\", \"description\": \"Local computer access for your WeCom bot.\" } }\n","{ \"meta\": { \"title\": \"Ft Bot\", \"description\": \"让企业微信中的机器人访问本地电脑。\" } }\n","import type { Context } from 'cordis'\nimport type {} from '@ftai/plugin-sdk/features'\nimport type {} from '@ftai/plugin-sdk/remote'\nimport type {} from '@ftai/ftai-plugin-ft-bot/remote'\nimport { IconDeviceDesktop } from '@tabler/icons-react'\nimport { createSettings } from './Settings.tsx'\nimport enUS from './i18n/en-US.ts'\nimport zhCN from './i18n/zh-CN.ts'\nimport enMeta from '../../locale/en.json'\nimport zhMeta from '../../locale/zh-CN.json'\nimport './style.css'\n\nexport const name = '@ftai/ftai-plugin-ft-bot'\nexport const inject = ['ftaiFeatures', 'remote']\n\nexport function apply(ctx: Context) {\n const messages = ctx.ftaiFeatures.createMessageScope({ 'en-US': enUS, 'zh-CN': zhCN })\n ctx.inject(['remote.ftBot'], scoped => {\n const Page = createSettings(messages, scoped.remote.ftBot)\n const meta = () => (messages.locale() === 'zh-CN' ? zhMeta : enMeta).meta\n scoped.ftaiFeatures.register({\n id: 'ft-bot', name: () => meta().title, description: () => meta().description,\n settings: { label: () => meta().title, icon: IconDeviceDesktop, group: 'integrations', order: 90, component: Page },\n })\n })\n}\n"],"ignoreList":[0,1,2],"mappings":";A,uJAOA,IAAImB,EAAoB,CACtB,QAAS,CACP,MAAO,6BACP,MAAO,GACP,OAAQ,GACR,QAAS,YACT,KAAM,OACN,OAAQ,eACR,YAAa,EACb,cAAe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EAAmB,MAAO,eAAgB,MAAO,GAAI,UAAWyD,CAAK,CACpH,CAAC,CACH,CAAC,CACH,C"}
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
import { type PluginStatus } from './types.ts';
|
|
2
|
+
import type { ChatPort } from './chats.ts';
|
|
3
|
+
export declare function stateDirectory(): string;
|
|
4
|
+
export declare class Controller {
|
|
5
|
+
private readonly directory;
|
|
6
|
+
private readonly override;
|
|
7
|
+
private readonly chats?;
|
|
8
|
+
private config;
|
|
9
|
+
private snapshot;
|
|
10
|
+
private readonly abort;
|
|
11
|
+
private readonly children;
|
|
12
|
+
private running;
|
|
13
|
+
private readonly ready;
|
|
14
|
+
constructor(directory: string, override?: string | undefined, chats?: ChatPort | undefined);
|
|
15
|
+
getStatus(): PluginStatus;
|
|
16
|
+
private alive;
|
|
17
|
+
private executable;
|
|
18
|
+
private load;
|
|
19
|
+
private save;
|
|
20
|
+
private request;
|
|
21
|
+
private inspect;
|
|
22
|
+
private startRunner;
|
|
23
|
+
private stopRunner;
|
|
24
|
+
private operate;
|
|
25
|
+
pair(server: string, code: string): Promise<PluginStatus>;
|
|
26
|
+
private download;
|
|
27
|
+
updateRunner(): Promise<PluginStatus>;
|
|
28
|
+
setEnabled(enabled: boolean): Promise<PluginStatus>;
|
|
29
|
+
refresh(): Promise<PluginStatus>;
|
|
30
|
+
requestPermissions(): Promise<PluginStatus>;
|
|
31
|
+
dispose(): Promise<void>;
|
|
32
|
+
}
|