@wengine-ai/ccr-provider-gemini-agy-acp 0.0.0-stage → 0.0.1
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/CHANGELOG.md +7 -0
- package/LICENSE +21 -0
- package/README.md +93 -2
- package/dist/package.json +1 -0
- package/dist/plugin.js +1 -0
- package/dist/plugin.json +6 -0
- package/dist/src/acp-config.mjs +52 -0
- package/dist/src/acp-errors.mjs +24 -0
- package/dist/src/acp-stdio.mjs +118 -0
- package/dist/src/chat.mjs +170 -0
- package/dist/src/plugin.mjs +81 -0
- package/dist/src/transport.mjs +233 -0
- package/package.json +15 -4
package/CHANGELOG.md
ADDED
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
# Changelog
|
|
2
|
+
|
|
3
|
+
## 0.0.1 — 2026-11-19
|
|
4
|
+
|
|
5
|
+
First public experimental release. Route text chat and streaming responses through a local Antigravity CLI worker using ACP and Gemini API-key authentication. The plugin requires explicit opt-in. Testing used simulated workers. Production CLI authentication remains to be verified.
|
|
6
|
+
|
|
7
|
+
首个公开实验版本。插件通过 ACP 和 Gemini API key 认证调用本地 Antigravity CLI,支持文本对话与流式响应,需显式启用。测试使用模拟进程,真实 CLI 的认证仍待验证。
|
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2025 musistudio
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,3 +1,94 @@
|
|
|
1
|
-
#
|
|
1
|
+
# gemini-agy-acp
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Experimental local provider for CCR 2.3.2433 (provider plugin API 1). A text chat request starts or reuses a local Antigravity CLI worker over ACP stdio. This provider has its own name and configuration, separate from `gemini-oauth`.
|
|
4
|
+
|
|
5
|
+
**Opt-in and billing.** Use a trusted local `agy` executable and a Gemini API key you are authorized to use. The CLI receives the prompt and may send it to Google's service. API key quotas, charges and terms apply. The CLI runs with the CCR operating system user's permissions. Treat both the executable and the operator configuration as trusted. Consumer OAuth, subscriptions, browser sign-in and account rotation are unsupported.
|
|
6
|
+
|
|
7
|
+
**启用与计费。** 本插件为实验原型,默认关闭。仅使用可信的本地 `agy` 程序和有权使用的 Gemini API 密钥。CLI 会收到对话内容,并可能将其发送到 Google 服务。调用受 API 密钥的配额、计费和使用条款约束。CLI 以 CCR 进程的系统用户身份运行。插件不支持个人订阅、浏览器 OAuth 或账号轮换。测试仅使用模拟进程,尚未验证真实账号、费用或上游服务。
|
|
8
|
+
|
|
9
|
+
## Install from npm
|
|
10
|
+
|
|
11
|
+
Run the following in the isolated CCR instance described below. Installing the package leaves the transport disabled until the operator enables it.
|
|
12
|
+
|
|
13
|
+
```sh
|
|
14
|
+
ccr plugin add @wengine-ai/ccr-provider-gemini-agy-acp@0.0.1
|
|
15
|
+
```
|
|
16
|
+
|
|
17
|
+
## Build and install locally
|
|
18
|
+
|
|
19
|
+
Use Node 20+ and this checkout's `packages/cli/dist/cli.js` (build the host with `pnpm build:cli` in a development checkout if needed). From the repository root, install into a disposable CCR configuration directory. The CLI copies the `dist` payload and records the plugin in that directory's `plugins/plugins.json`. Installing alone leaves the ACP transport disabled.
|
|
20
|
+
|
|
21
|
+
```sh
|
|
22
|
+
plugin=packages/plugins/gemini-agy-acp
|
|
23
|
+
node "$plugin/scripts/build.mjs"
|
|
24
|
+
node --test "$plugin"/test/*.test.mjs
|
|
25
|
+
export CCR_CONFIG_DIR="$(mktemp -d)"
|
|
26
|
+
node packages/cli/dist/cli.js plugin add "$plugin" --yes
|
|
27
|
+
```
|
|
28
|
+
|
|
29
|
+
The loader expects `plugin.json` and `plugin.js` in the installed plugin directory. Copy the entire built payload if inspecting it outside the CLI. Its `package.json` establishes the ESM format and `src/` contains its local module dependencies.
|
|
30
|
+
|
|
31
|
+
## Configure an isolated primary route
|
|
32
|
+
|
|
33
|
+
Place this example in the disposable `$CCR_CONFIG_DIR/config.json`. Replace `model-1` with a model selector value available to your particular CLI account. Keep the exact managed marker in `api_key` so CCR refuses ordinary HTTP dispatch if the plugin is missing. The URL fills a required host field and the ACP runtime never calls it. `test-key` is a local client-auth example.
|
|
34
|
+
|
|
35
|
+
```json
|
|
36
|
+
{
|
|
37
|
+
"HOST": "127.0.0.1",
|
|
38
|
+
"PORT": 43781,
|
|
39
|
+
"APIKEY": "test-key",
|
|
40
|
+
"ACTIVE_PROBE_ENABLED": false,
|
|
41
|
+
"Providers": [{
|
|
42
|
+
"name": "gemini-agy-acp",
|
|
43
|
+
"api_base_url": "https://example.com/unused",
|
|
44
|
+
"api_key": "ccr-managed-gemini-agy-acp",
|
|
45
|
+
"models": ["model-1"],
|
|
46
|
+
"transformer": { "use": ["gemini-agy-acp"] }
|
|
47
|
+
}],
|
|
48
|
+
"Router": { "default": "gemini-agy-acp,model-1", "enableFallback": false }
|
|
49
|
+
}
|
|
50
|
+
```
|
|
51
|
+
|
|
52
|
+
Use ACP as a **primary route** in an isolated instance with effective `Router.enableFallback` set to `false` and no project or global fallback entries. ACP disables fallback on the primary request once its transformer or dispatcher receives it. Earlier host failures, including `plugin_missing`, occur before the plugin gets the request. CCR can also continue an outer fallback chain if it reached ACP as a fallback candidate. Neither path is controlled by the plugin. Background recovery probes are disabled for this prototype.
|
|
53
|
+
|
|
54
|
+
To opt in, the local operator writes `$CCR_CONFIG_DIR/gemini-agy-acp.json` before starting the isolated host. This file is read at activation. Omission or `enabled: false` disables execution. `binary` must be an absolute path to a trusted executable (CLI 1.5.1+ with ACP). Worker limit is 1–8 (default 1) and timeout is 1–300000 ms (default 60000). Choose an unused test port and restrict access to these files and the process environment.
|
|
55
|
+
|
|
56
|
+
```json
|
|
57
|
+
{
|
|
58
|
+
"enabled": true,
|
|
59
|
+
"binary": "/absolute/path/to/agy",
|
|
60
|
+
"authMethod": "gemini-api-key",
|
|
61
|
+
"timeoutMs": 60000,
|
|
62
|
+
"maxWorkers": 1
|
|
63
|
+
}
|
|
64
|
+
```
|
|
65
|
+
|
|
66
|
+
Supply `GEMINI_API_KEY` through the isolated CCR process environment. Keep it out of request headers, JSON files, transcripts and source control. The only supported method is `gemini-api-key`. A missing key or unsupported auth method fails the request. The provider captures the API key and sidecar settings at activation. Restart the isolated CCR host with the updated environment to rotate the key for every worker.
|
|
67
|
+
|
|
68
|
+
## Text chat
|
|
69
|
+
|
|
70
|
+
Use `/v1/chat/completions` or CCR's `/v1/messages` endpoint. CCR handles Anthropic conversion. Example OpenAI request body (synthetic model ID):
|
|
71
|
+
|
|
72
|
+
```json
|
|
73
|
+
{
|
|
74
|
+
"model": "gemini-agy-acp,model-1",
|
|
75
|
+
"reasoning_effort": "high",
|
|
76
|
+
"messages": [
|
|
77
|
+
{ "role": "system", "content": "Answer in one sentence." },
|
|
78
|
+
{ "role": "user", "content": "Name a primary color." },
|
|
79
|
+
{ "role": "assistant", "content": "Blue." },
|
|
80
|
+
{ "role": "user", "content": "Name another." }
|
|
81
|
+
],
|
|
82
|
+
"stream": true
|
|
83
|
+
}
|
|
84
|
+
```
|
|
85
|
+
|
|
86
|
+
Each request gets a fresh ACP session. A single user string is passed directly. Multiple turns become an ordered JSON text transcript in one ACP prompt. Role labels in that transcript do not establish separate privileged system instructions inside the CLI. The adapter accepts `system`, `user`, `assistant` and text blocks. Tool definitions, tool calls/results, named roles and non-text content fail explicitly. The model is matched against the provider catalog and passed intact to the transport. Optional OpenAI `reasoning_effort` or CCR-normalized Anthropic effort selects an advertised thinking option. `xhigh` can match an advertised Extra tier. An unavailable explicit selection fails. Omitting effort leaves the CLI's selection unchanged.
|
|
87
|
+
|
|
88
|
+
Non-streaming requests return one OpenAI chat completion. Streaming emits role and text deltas, a finish reason, then `[DONE]` on success. Failures before the first text use HTTP errors. A failure after partial output terminates the stream with an error. The host limits output to 1 MiB of text and 8192 nonempty deltas per response. Token usage, sampling controls, caller token limits, structured output and persistent multi-turn ACP sessions are unsupported. Do not depend on token accounting or these controls in this prototype.
|
|
89
|
+
|
|
90
|
+
The protocol fixture follows Google's documented ACP v1 invocation, API-key method ID, and session selectors. This prototype handles the protocol-driven authentication method (omitted type or `agent`) and rejects other method types before opening a session. The fixture is synthetic. The exact handshake for a production CLI build still needs verification.
|
|
91
|
+
|
|
92
|
+
Local tests use synthetic text, credentials and subprocess fixtures. Live CLI authentication, model availability, actual sandbox guarantees, provider billing, production load and compatibility with other CCR versions remain unverified. CCR 2.3.2433 has no plugin shutdown callback. The transport retires idle workers and bounds each request.
|
|
93
|
+
|
|
94
|
+
[Antigravity ACP documentation](https://antigravity.google/docs/ide/extensions/acp/) · [ACP session config options](https://agentclientprotocol.com/protocol/v1/session-config-options)
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"type":"module","version":"0.0.1"}
|
package/dist/plugin.js
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export { activate } from './src/plugin.mjs';
|
package/dist/plugin.json
ADDED
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
import { AcpError } from './acp-errors.mjs';
|
|
2
|
+
|
|
3
|
+
const selectorIds = {
|
|
4
|
+
model: ['model'],
|
|
5
|
+
thought_level: ['thought_level', 'thinking', 'thinking_level'],
|
|
6
|
+
};
|
|
7
|
+
|
|
8
|
+
function select(options, category, requested) {
|
|
9
|
+
if (!Array.isArray(options)) throw new AcpError('unsupported_option');
|
|
10
|
+
const selectors = options.filter(option => option?.type === 'select' && (
|
|
11
|
+
option.category == null ? selectorIds[category].includes(option.id) : option.category === category
|
|
12
|
+
));
|
|
13
|
+
if (selectors.length !== 1) throw new AcpError('unsupported_option');
|
|
14
|
+
const [selector] = selectors;
|
|
15
|
+
if (typeof selector.id !== 'string' || !Array.isArray(selector.options)) {
|
|
16
|
+
throw new AcpError('unsupported_option');
|
|
17
|
+
}
|
|
18
|
+
const values = selector.options.flatMap(entry => entry?.options ?? [entry])
|
|
19
|
+
.filter(entry => typeof entry?.value === 'string');
|
|
20
|
+
const normalized = requested.toLowerCase();
|
|
21
|
+
const aliases = category === 'thought_level' && normalized === 'xhigh' ? ['xhigh', 'extra'] : [normalized];
|
|
22
|
+
const exact = values.filter(entry => entry.value === requested);
|
|
23
|
+
const matches = exact.length ? exact : values.filter(entry =>
|
|
24
|
+
aliases.includes(entry.value.toLowerCase()) ||
|
|
25
|
+
(typeof entry.name === 'string' && aliases.includes(entry.name.toLowerCase()))
|
|
26
|
+
);
|
|
27
|
+
if (matches.length !== 1) throw new AcpError('unsupported_option');
|
|
28
|
+
return { selector, value: matches[0].value };
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
export async function configureSession(rpc, session, model, thinking) {
|
|
32
|
+
let options = session.configOptions;
|
|
33
|
+
const selections = [['model', model]];
|
|
34
|
+
if (thinking != null) selections.push(['thought_level', thinking]);
|
|
35
|
+
const expected = new Map();
|
|
36
|
+
for (const [category, requested] of selections) {
|
|
37
|
+
const { selector, value } = select(options, category, requested);
|
|
38
|
+
expected.set(selector.id, value);
|
|
39
|
+
if (selector.currentValue !== value) {
|
|
40
|
+
const result = await rpc.request('session/set_config_option', {
|
|
41
|
+
sessionId: session.sessionId, configId: selector.id, value,
|
|
42
|
+
});
|
|
43
|
+
options = result.configOptions;
|
|
44
|
+
}
|
|
45
|
+
// Setting the model can change the available thinking levels and their wire values.
|
|
46
|
+
for (const [id, currentValue] of expected) {
|
|
47
|
+
if (!Array.isArray(options) || !options.some(option => option?.id === id && option.currentValue === currentValue)) {
|
|
48
|
+
throw new AcpError('unsupported_option');
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
}
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
const errors = {
|
|
2
|
+
invalid_config: [400, 'Invalid ACP transport configuration'],
|
|
3
|
+
invalid_request: [400, 'Invalid ACP request'],
|
|
4
|
+
input_limit: [413, 'ACP prompt exceeds the input limit'],
|
|
5
|
+
auth_required: [401, 'ACP API key authentication is required'],
|
|
6
|
+
unsupported_version: [502, 'Antigravity CLI 1.5.1 or later is required'],
|
|
7
|
+
unsupported_option: [400, 'Requested ACP session option is unavailable'],
|
|
8
|
+
busy: [503, 'ACP worker pool is full'],
|
|
9
|
+
closed: [503, 'ACP transport is closed'],
|
|
10
|
+
cancelled: [499, 'ACP request was cancelled'],
|
|
11
|
+
timeout: [504, 'ACP request timed out'],
|
|
12
|
+
worker_failed: [502, 'ACP worker failed'],
|
|
13
|
+
protocol_error: [502, 'Invalid ACP response'],
|
|
14
|
+
output_limit: [502, 'ACP output exceeds the limit'],
|
|
15
|
+
};
|
|
16
|
+
|
|
17
|
+
export class AcpError extends Error {
|
|
18
|
+
constructor(code) {
|
|
19
|
+
const [statusCode, message] = errors[code];
|
|
20
|
+
super(message);
|
|
21
|
+
this.code = `acp_${code}`;
|
|
22
|
+
this.statusCode = statusCode;
|
|
23
|
+
}
|
|
24
|
+
}
|
|
@@ -0,0 +1,118 @@
|
|
|
1
|
+
import { AcpError } from './acp-errors.mjs';
|
|
2
|
+
|
|
3
|
+
const MAX_FRAME_BYTES = 4 * 1024 * 1024;
|
|
4
|
+
const MAX_TURN_BYTES = 16 * 1024 * 1024;
|
|
5
|
+
const MAX_TURN_FRAMES = 65536;
|
|
6
|
+
const decoder = new TextDecoder('utf-8', { fatal: true });
|
|
7
|
+
|
|
8
|
+
// ACP v1 uses one UTF-8 JSON-RPC message per line. Only one outgoing request is in flight.
|
|
9
|
+
export class AcpStdio {
|
|
10
|
+
constructor(child, onFailure) {
|
|
11
|
+
this.stdin = child.stdin;
|
|
12
|
+
this.nextId = 1;
|
|
13
|
+
this.partial = Buffer.alloc(0);
|
|
14
|
+
this.partialBytes = 0;
|
|
15
|
+
this.resetBudget();
|
|
16
|
+
child.stdout.on('data', chunk => {
|
|
17
|
+
if (this.failure) return;
|
|
18
|
+
try {
|
|
19
|
+
this.read(chunk);
|
|
20
|
+
} catch (error) {
|
|
21
|
+
onFailure(error instanceof AcpError ? error : new AcpError('protocol_error'));
|
|
22
|
+
}
|
|
23
|
+
});
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
resetBudget() {
|
|
27
|
+
this.turnBytes = this.partialBytes;
|
|
28
|
+
this.turnFrames = 0;
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
read(chunk) {
|
|
32
|
+
this.turnBytes += chunk.length;
|
|
33
|
+
if (this.turnBytes > MAX_TURN_BYTES) throw new AcpError('output_limit');
|
|
34
|
+
for (let start = 0; start < chunk.length && !this.failure;) {
|
|
35
|
+
const newline = chunk.indexOf(10, start);
|
|
36
|
+
const part = chunk.subarray(start, newline === -1 ? chunk.length : newline);
|
|
37
|
+
const length = this.partialBytes + part.length;
|
|
38
|
+
if (length > MAX_FRAME_BYTES) throw new AcpError('output_limit');
|
|
39
|
+
let line = part;
|
|
40
|
+
if (newline === -1 || this.partialBytes) {
|
|
41
|
+
if (length > this.partial.length) {
|
|
42
|
+
const capacity = Math.min(MAX_FRAME_BYTES, Math.max(length, 4096, this.partial.length * 2));
|
|
43
|
+
const grown = Buffer.allocUnsafe(capacity);
|
|
44
|
+
this.partial.copy(grown, 0, 0, this.partialBytes);
|
|
45
|
+
this.partial = grown;
|
|
46
|
+
}
|
|
47
|
+
part.copy(this.partial, this.partialBytes);
|
|
48
|
+
this.partialBytes = length;
|
|
49
|
+
if (newline === -1) return;
|
|
50
|
+
line = this.partial.subarray(0, length);
|
|
51
|
+
this.partialBytes = 0;
|
|
52
|
+
}
|
|
53
|
+
if (++this.turnFrames > MAX_TURN_FRAMES) throw new AcpError('output_limit');
|
|
54
|
+
this.receive(JSON.parse(decoder.decode(line)));
|
|
55
|
+
start = newline + 1;
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
send(message) {
|
|
60
|
+
if (this.failure) throw this.failure;
|
|
61
|
+
const line = JSON.stringify({ jsonrpc: '2.0', ...message }) + '\n';
|
|
62
|
+
if (this.stdin.writableLength + Buffer.byteLength(line) > MAX_TURN_BYTES) throw new AcpError('output_limit');
|
|
63
|
+
this.stdin.write(line);
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
async request(method, params, errorCode = 'worker_failed') {
|
|
67
|
+
if (this.pending) throw new AcpError('protocol_error');
|
|
68
|
+
const id = this.nextId++;
|
|
69
|
+
this.send({ id, method, params });
|
|
70
|
+
return new Promise((resolve, reject) => { this.pending = { id, method, resolve, reject, errorCode }; });
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
receive(frame) {
|
|
74
|
+
if (frame?.jsonrpc !== '2.0' || Array.isArray(frame)) throw new AcpError('protocol_error');
|
|
75
|
+
if (Object.hasOwn(frame, 'method')) {
|
|
76
|
+
if (typeof frame.method !== 'string' || Object.hasOwn(frame, 'error') || Object.hasOwn(frame, 'result')) {
|
|
77
|
+
throw new AcpError('protocol_error');
|
|
78
|
+
}
|
|
79
|
+
if (Object.hasOwn(frame, 'id')) {
|
|
80
|
+
if (typeof frame.id !== 'string' && !Number.isSafeInteger(frame.id)) throw new AcpError('protocol_error');
|
|
81
|
+
if (frame.method === 'session/request_permission') {
|
|
82
|
+
this.send({ id: frame.id, result: { outcome: { outcome: 'cancelled' } } });
|
|
83
|
+
} else {
|
|
84
|
+
this.send({ id: frame.id, error: { code: -32601, message: 'Method not supported' } });
|
|
85
|
+
}
|
|
86
|
+
} else if (frame.method === 'session/update' && this.pending?.method === 'session/prompt' &&
|
|
87
|
+
frame.params?.sessionId === this.sessionId) {
|
|
88
|
+
const update = frame.params.update;
|
|
89
|
+
if (update?.sessionUpdate === 'agent_message_chunk' && update.content?.type === 'text') {
|
|
90
|
+
if (typeof update.content.text !== 'string') throw new AcpError('protocol_error');
|
|
91
|
+
this.onText(update.content.text);
|
|
92
|
+
}
|
|
93
|
+
}
|
|
94
|
+
return;
|
|
95
|
+
}
|
|
96
|
+
if (!Object.hasOwn(frame, 'id') || Object.hasOwn(frame, 'result') === Object.hasOwn(frame, 'error')) {
|
|
97
|
+
throw new AcpError('protocol_error');
|
|
98
|
+
}
|
|
99
|
+
if (!this.pending || frame.id !== this.pending.id) return; // stale response
|
|
100
|
+
const { resolve, reject, errorCode } = this.pending;
|
|
101
|
+
this.pending = null;
|
|
102
|
+
if (Object.hasOwn(frame, 'error')) reject(new AcpError(errorCode));
|
|
103
|
+
else if (!frame.result || typeof frame.result !== 'object' || Array.isArray(frame.result)) {
|
|
104
|
+
reject(new AcpError('protocol_error'));
|
|
105
|
+
} else resolve(frame.result);
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
stop(error) {
|
|
109
|
+
if (this.failure) return;
|
|
110
|
+
if (this.sessionId && this.pending?.method === 'session/prompt') {
|
|
111
|
+
try { this.send({ method: 'session/cancel', params: { sessionId: this.sessionId } }); } catch { /* closing */ }
|
|
112
|
+
}
|
|
113
|
+
this.failure = error;
|
|
114
|
+
this.pending?.reject(error);
|
|
115
|
+
this.pending = null;
|
|
116
|
+
this.onText = null;
|
|
117
|
+
}
|
|
118
|
+
}
|
|
@@ -0,0 +1,170 @@
|
|
|
1
|
+
import { randomUUID } from 'node:crypto';
|
|
2
|
+
|
|
3
|
+
export function failure(code, statusCode, message = code) {
|
|
4
|
+
return Object.assign(new Error(message), { code, statusCode, nonRetryable: true });
|
|
5
|
+
}
|
|
6
|
+
|
|
7
|
+
function unsupported(message) {
|
|
8
|
+
throw failure('agy_unsupported_request', 400, message);
|
|
9
|
+
}
|
|
10
|
+
|
|
11
|
+
function contentText(content) {
|
|
12
|
+
if (typeof content === 'string') return content;
|
|
13
|
+
if (Array.isArray(content) && content.length && content.every(part =>
|
|
14
|
+
part?.type === 'text' && typeof part.text === 'string')) {
|
|
15
|
+
return content.map(part => part.text).join('\n');
|
|
16
|
+
}
|
|
17
|
+
unsupported('Only text message content is supported.');
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
// Check the original Fastify body too: endpoint normalization can drop unknown
|
|
21
|
+
// roles, tool details and non-text content before the provider transformer runs.
|
|
22
|
+
export function textTurns(body) {
|
|
23
|
+
if ((body.tools !== undefined && !(Array.isArray(body.tools) && !body.tools.length)) ||
|
|
24
|
+
body.tool_choice != null || body.functions != null || body.function_call != null ||
|
|
25
|
+
body.parallel_tool_calls != null || body.audio != null ||
|
|
26
|
+
(body.modalities != null && !(Array.isArray(body.modalities) && body.modalities.length === 1 && body.modalities[0] === 'text'))) {
|
|
27
|
+
unsupported('Tools, function calling and non-text modalities are unsupported.');
|
|
28
|
+
}
|
|
29
|
+
if (!Array.isArray(body.messages) || !body.messages.length) unsupported('Expected one or more messages.');
|
|
30
|
+
const turns = [];
|
|
31
|
+
if (body.system !== undefined) turns.push({ role: 'system', content: contentText(body.system) });
|
|
32
|
+
for (const msg of body.messages) {
|
|
33
|
+
if (!['system', 'user', 'assistant'].includes(msg?.role)) unsupported('Unsupported message role.');
|
|
34
|
+
if (['tool_calls', 'tool_call_id', 'function_call', 'audio', 'refusal', 'thinking', 'name'].some(key => msg[key] != null)) {
|
|
35
|
+
unsupported('Only unnamed text messages are supported.');
|
|
36
|
+
}
|
|
37
|
+
turns.push({ role: msg.role, content: contentText(msg.content) });
|
|
38
|
+
}
|
|
39
|
+
return turns;
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
export function toPrompt(body, provider, original) {
|
|
43
|
+
const { model, reasoning, reasoning_effort } = body;
|
|
44
|
+
if (typeof model !== 'string' || !model || !Array.isArray(provider.models) || !provider.models.includes(model)) {
|
|
45
|
+
unsupported('Model is missing from the local provider catalog.');
|
|
46
|
+
}
|
|
47
|
+
// CCR normalizes Anthropic xhigh to max. The CLI advertises distinct Extra
|
|
48
|
+
// and Max tiers, so retain the original explicit effort when present.
|
|
49
|
+
const thinking = reasoning?.enabled === false ? 'none' : reasoning_effort ?? original?.output_config?.effort ?? reasoning?.effort;
|
|
50
|
+
if (thinking !== undefined && !['none', 'low', 'medium', 'high', 'extra', 'xhigh', 'max'].includes(thinking)) {
|
|
51
|
+
unsupported('Unsupported thinking effort.');
|
|
52
|
+
}
|
|
53
|
+
const turns = textTurns(body);
|
|
54
|
+
return { model, thinking, prompt: turns.length === 1 && turns[0].role === 'user' ? turns[0].content :
|
|
55
|
+
'Continue the following conversation as the assistant. Ordered text messages (JSON):\n' + JSON.stringify(turns) };
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
function safeFailure(error) {
|
|
59
|
+
// The transport contract exposes stable codes/status only. Never surface a
|
|
60
|
+
// binary path, subprocess stderr, prompts or credential values in messages.
|
|
61
|
+
const code = typeof error?.code === 'string' && /^[a-z][a-z0-9_]{0,63}$/.test(error.code)
|
|
62
|
+
? error.code : 'agy_transport_error';
|
|
63
|
+
const status = error?.statusCode;
|
|
64
|
+
return failure(code, Number.isInteger(status) && status >= 400 && status <= 599 ? status : 502);
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
function finishReason(stopReason) {
|
|
68
|
+
switch (stopReason) {
|
|
69
|
+
case 'end_turn': return 'stop';
|
|
70
|
+
case 'max_tokens': case 'max_turn_requests': return 'length';
|
|
71
|
+
case 'refusal': return 'content_filter';
|
|
72
|
+
case 'cancelled': throw failure('agy_cancelled', 499);
|
|
73
|
+
default: throw failure('agy_unknown_stop_reason', 502);
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
function clientCancellation(req, config) {
|
|
78
|
+
const controller = new AbortController();
|
|
79
|
+
const abort = () => controller.abort();
|
|
80
|
+
const raw = req?.raw;
|
|
81
|
+
const socket = raw?.socket;
|
|
82
|
+
// IncomingMessage 'close' also fires after a *successful* request upload.
|
|
83
|
+
raw?.on?.('aborted', abort);
|
|
84
|
+
socket?.on?.('close', abort);
|
|
85
|
+
const signals = [req?.signal, config?.signal].filter(s => s instanceof AbortSignal);
|
|
86
|
+
for (const signal of signals) signal.addEventListener('abort', abort, { once: true });
|
|
87
|
+
if (raw?.aborted || socket?.destroyed || signals.some(s => s.aborted)) abort();
|
|
88
|
+
return { controller, cleanup() {
|
|
89
|
+
raw?.off?.('aborted', abort);
|
|
90
|
+
socket?.off?.('close', abort);
|
|
91
|
+
for (const signal of signals) signal.removeEventListener('abort', abort);
|
|
92
|
+
} };
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
const MAX_TEXT_BYTES = 1 << 20;
|
|
96
|
+
const MAX_DELTAS = 8192;
|
|
97
|
+
|
|
98
|
+
export async function chatResponse(transport, prompt, stream, req, config) {
|
|
99
|
+
const { controller, cleanup } = clientCancellation(req, config);
|
|
100
|
+
const { signal } = controller;
|
|
101
|
+
const base = { id: `chatcmpl-${randomUUID()}`, created: Math.floor(Date.now() / 1000), model: prompt.model };
|
|
102
|
+
let bytes = 0;
|
|
103
|
+
let deltas = 0;
|
|
104
|
+
let overflow;
|
|
105
|
+
async function run(emit) {
|
|
106
|
+
try {
|
|
107
|
+
signal.throwIfAborted();
|
|
108
|
+
const result = await transport.run({ ...prompt, signal, onText(text) {
|
|
109
|
+
signal.throwIfAborted();
|
|
110
|
+
if (typeof text !== 'string') throw failure('agy_invalid_delta', 502);
|
|
111
|
+
if (!text.length) return;
|
|
112
|
+
bytes += Buffer.byteLength(text);
|
|
113
|
+
if (bytes > MAX_TEXT_BYTES || ++deltas > MAX_DELTAS) {
|
|
114
|
+
overflow = failure('agy_output_limit', 502);
|
|
115
|
+
controller.abort();
|
|
116
|
+
throw overflow;
|
|
117
|
+
}
|
|
118
|
+
emit(text);
|
|
119
|
+
} });
|
|
120
|
+
signal.throwIfAborted();
|
|
121
|
+
return finishReason(result?.stopReason);
|
|
122
|
+
} catch (error) {
|
|
123
|
+
throw overflow ?? (signal.aborted ? failure('agy_cancelled', 499) : safeFailure(error));
|
|
124
|
+
} finally {
|
|
125
|
+
cleanup();
|
|
126
|
+
}
|
|
127
|
+
}
|
|
128
|
+
if (!stream) {
|
|
129
|
+
const parts = [];
|
|
130
|
+
const finish_reason = await run(text => parts.push(text));
|
|
131
|
+
return Response.json({ ...base, object: 'chat.completion', choices: [{ index: 0,
|
|
132
|
+
message: { role: 'assistant', content: parts.join('') }, finish_reason }] });
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
// Wait for text (or a successful empty completion) before publishing headers,
|
|
136
|
+
// so spawn/auth/selector failures retain their HTTP status on stream requests.
|
|
137
|
+
let started = false;
|
|
138
|
+
let resolveReady, rejectReady;
|
|
139
|
+
const ready = new Promise((resolve, reject) => { resolveReady = resolve; rejectReady = reject; });
|
|
140
|
+
const encoder = new TextEncoder();
|
|
141
|
+
const body = new ReadableStream({
|
|
142
|
+
start(output) {
|
|
143
|
+
function event(data) { output.enqueue(encoder.encode(`data: ${JSON.stringify(data)}\n\n`)); }
|
|
144
|
+
function chunk(delta, finish_reason = null) {
|
|
145
|
+
event({ ...base, object: 'chat.completion.chunk', choices: [{ index: 0, delta, finish_reason }] });
|
|
146
|
+
}
|
|
147
|
+
function begin() {
|
|
148
|
+
if (started) return;
|
|
149
|
+
started = true;
|
|
150
|
+
chunk({ role: 'assistant' });
|
|
151
|
+
resolveReady();
|
|
152
|
+
}
|
|
153
|
+
run(text => { begin(); chunk({ content: text }); }).then(reason => {
|
|
154
|
+
begin();
|
|
155
|
+
chunk({}, reason);
|
|
156
|
+
output.enqueue(encoder.encode('data: [DONE]\n\n'));
|
|
157
|
+
output.close();
|
|
158
|
+
}).catch(error => {
|
|
159
|
+
if (!started) rejectReady(error);
|
|
160
|
+
if (started && (!signal.aborted || overflow)) {
|
|
161
|
+
event({ error: { code: error.code, message: error.message } });
|
|
162
|
+
output.close();
|
|
163
|
+
} else output.error(error);
|
|
164
|
+
});
|
|
165
|
+
},
|
|
166
|
+
cancel() { controller.abort(); },
|
|
167
|
+
});
|
|
168
|
+
await ready;
|
|
169
|
+
return new Response(body, { headers: { 'content-type': 'text/event-stream', 'cache-control': 'no-cache' } });
|
|
170
|
+
}
|
|
@@ -0,0 +1,81 @@
|
|
|
1
|
+
import { readFile } from 'node:fs/promises';
|
|
2
|
+
import { isAbsolute, join } from 'node:path';
|
|
3
|
+
import { chatResponse, failure, textTurns, toPrompt } from './chat.mjs';
|
|
4
|
+
|
|
5
|
+
const NAME = 'gemini-agy-acp';
|
|
6
|
+
const MARKER = `ccr-managed-${NAME}`;
|
|
7
|
+
|
|
8
|
+
async function readSettings(configDir) {
|
|
9
|
+
let settings;
|
|
10
|
+
try {
|
|
11
|
+
settings = JSON.parse(await readFile(join(configDir, `${NAME}.json`), 'utf8'));
|
|
12
|
+
} catch (error) {
|
|
13
|
+
if (error.code === 'ENOENT') return null;
|
|
14
|
+
throw failure('agy_config_invalid', 503);
|
|
15
|
+
}
|
|
16
|
+
if (settings?.enabled !== true) return null;
|
|
17
|
+
const { binary, authMethod, timeoutMs = 60000, maxWorkers = 1 } = settings;
|
|
18
|
+
if (typeof binary !== 'string' || !isAbsolute(binary) || binary.includes('\0') || authMethod !== 'gemini-api-key' ||
|
|
19
|
+
!Number.isSafeInteger(timeoutMs) || timeoutMs < 1 || timeoutMs > 300000 ||
|
|
20
|
+
!Number.isSafeInteger(maxWorkers) || maxWorkers < 1 || maxWorkers > 8) {
|
|
21
|
+
throw failure('agy_config_invalid', 503);
|
|
22
|
+
}
|
|
23
|
+
return { binary, authMethod, timeoutMs, maxWorkers };
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
function assertProvider(provider) {
|
|
27
|
+
if (provider?.name !== NAME || provider.apiKey !== MARKER || provider.enabled === false) {
|
|
28
|
+
throw failure('agy_provider_config_invalid', 503);
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
export async function activateWithTransport(ctx, createTransport) {
|
|
33
|
+
let transport;
|
|
34
|
+
let unavailable;
|
|
35
|
+
try {
|
|
36
|
+
const settings = await readSettings(ctx.host.configDir);
|
|
37
|
+
if (settings) transport = await createTransport(settings);
|
|
38
|
+
} catch {
|
|
39
|
+
unavailable = failure('agy_config_invalid', 503);
|
|
40
|
+
}
|
|
41
|
+
function requireTransport() {
|
|
42
|
+
if (!transport) throw unavailable ?? failure('agy_disabled', 503);
|
|
43
|
+
return transport;
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
class AgyTransformer {
|
|
47
|
+
static TransformerName = NAME;
|
|
48
|
+
name = NAME;
|
|
49
|
+
|
|
50
|
+
transformRequestIn(body, provider, context) {
|
|
51
|
+
if (provider?.name === NAME && context?.req) context.req.enableFallback = false;
|
|
52
|
+
assertProvider(provider);
|
|
53
|
+
requireTransport();
|
|
54
|
+
if (context?.req?.body) textTurns(context.req.body);
|
|
55
|
+
return { body };
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
ctx.registerTransformer(AgyTransformer);
|
|
59
|
+
ctx.registerManagedRuntime({
|
|
60
|
+
name: NAME,
|
|
61
|
+
// Claim this exact reserved name even on a malformed entry, so it fails
|
|
62
|
+
// closed instead of taking the ordinary OpenAI HTTP path.
|
|
63
|
+
isManaged: provider => provider?.name === NAME,
|
|
64
|
+
suppressDebugLog: true,
|
|
65
|
+
async signRequest() { throw failure('agy_http_disabled', 503); },
|
|
66
|
+
async probeAccountState() { return { available: false, reason: 'agy_probe_disabled' }; },
|
|
67
|
+
async probeLiveness() { return new Response(null, { status: 503 }); },
|
|
68
|
+
async dispatchRequest({ requestBody, req, config, provider }) {
|
|
69
|
+
if (req) req.enableFallback = false;
|
|
70
|
+
assertProvider(provider);
|
|
71
|
+
const local = requireTransport();
|
|
72
|
+
if (req?.body) textTurns(req.body);
|
|
73
|
+
return chatResponse(local, toPrompt(requestBody, provider, req?.body), requestBody.stream === true, req, config);
|
|
74
|
+
},
|
|
75
|
+
});
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
export function activate(ctx) {
|
|
79
|
+
// Loading and installing this prototype alone cannot start a subprocess.
|
|
80
|
+
return activateWithTransport(ctx, async options => (await import('./transport.mjs')).createTransport(options));
|
|
81
|
+
}
|
|
@@ -0,0 +1,233 @@
|
|
|
1
|
+
import { spawn } from 'node:child_process';
|
|
2
|
+
import { readFileSync } from 'node:fs';
|
|
3
|
+
import { mkdir, mkdtemp, rm } from 'node:fs/promises';
|
|
4
|
+
import { tmpdir } from 'node:os';
|
|
5
|
+
import { isAbsolute, join } from 'node:path';
|
|
6
|
+
import { configureSession } from './acp-config.mjs';
|
|
7
|
+
import { AcpError } from './acp-errors.mjs';
|
|
8
|
+
import { AcpStdio } from './acp-stdio.mjs';
|
|
9
|
+
|
|
10
|
+
const AUTH_METHOD = 'gemini-api-key';
|
|
11
|
+
const MAX_PROMPT_BYTES = 1024 * 1024;
|
|
12
|
+
const IDLE_MS = 30_000;
|
|
13
|
+
const MAX_SESSIONS = 64;
|
|
14
|
+
const STOP_REASONS = new Set(['end_turn', 'max_tokens', 'max_turn_requests', 'refusal', 'cancelled']);
|
|
15
|
+
|
|
16
|
+
function clientVersion() {
|
|
17
|
+
try {
|
|
18
|
+
return JSON.parse(readFileSync(new URL('../package.json', import.meta.url), 'utf8')).version;
|
|
19
|
+
} catch (error) {
|
|
20
|
+
if (error.code === 'ENOENT') return '0.0.0'; // standalone transport
|
|
21
|
+
throw new AcpError('invalid_config');
|
|
22
|
+
}
|
|
23
|
+
}
|
|
24
|
+
const clientInfo = { name: 'ccr-gemini-agy-acp', version: clientVersion() };
|
|
25
|
+
|
|
26
|
+
function supportedVersion(output) {
|
|
27
|
+
const versions = [...output.matchAll(/(?:^|[\s:(])v?(\d+\.\d+\.\d+(?:-[\w.-]+)?(?:\+[\w.-]+)?)(?=$|[\s,)])/gi)];
|
|
28
|
+
if (versions.length !== 1) return false;
|
|
29
|
+
const [release, prerelease] = versions[0][1].split('+')[0].split('-');
|
|
30
|
+
const [major, minor, patch] = release.split('.').map(Number);
|
|
31
|
+
return major > 1 || (major === 1 && (minor > 5 || (minor === 5 && (patch > 1 || (patch === 1 && !prerelease)))));
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
async function isolatedEnvironment(root) {
|
|
35
|
+
const dirs = Object.fromEntries(['home', 'config', 'data', 'cache', 'state', 'tmp', 'runtime', 'work']
|
|
36
|
+
.map(name => [name, join(root, name)]));
|
|
37
|
+
await Promise.all(Object.values(dirs).map(path => mkdir(path, { mode: 0o700 })));
|
|
38
|
+
const env = {
|
|
39
|
+
HOME: dirs.home, USERPROFILE: dirs.home, XDG_CONFIG_HOME: dirs.config, XDG_DATA_HOME: dirs.data,
|
|
40
|
+
XDG_CACHE_HOME: dirs.cache, XDG_STATE_HOME: dirs.state, XDG_RUNTIME_DIR: dirs.runtime,
|
|
41
|
+
APPDATA: dirs.config, LOCALAPPDATA: dirs.data, TMPDIR: dirs.tmp, TEMP: dirs.tmp, TMP: dirs.tmp,
|
|
42
|
+
PATH: '/usr/bin:/bin', LANG: 'C',
|
|
43
|
+
};
|
|
44
|
+
if (process.platform === 'win32') {
|
|
45
|
+
env.SystemRoot = process.env.SystemRoot;
|
|
46
|
+
env.PATH = join(env.SystemRoot, 'System32');
|
|
47
|
+
}
|
|
48
|
+
return { env, cwd: dirs.work };
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
class Worker {
|
|
52
|
+
constructor(binary, onRetired) {
|
|
53
|
+
this.binary = binary;
|
|
54
|
+
this.onRetired = onRetired;
|
|
55
|
+
this.sessions = new Set();
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
check() {
|
|
59
|
+
if (this.failure) throw this.failure;
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
spawnChild(args, env) {
|
|
63
|
+
this.check();
|
|
64
|
+
const child = spawn(this.binary, args, {
|
|
65
|
+
cwd: this.cwd, env, shell: false, windowsHide: true, detached: process.platform !== 'win32',
|
|
66
|
+
stdio: ['pipe', 'pipe', 'ignore'], // subprocess diagnostics may contain credentials or prompts
|
|
67
|
+
});
|
|
68
|
+
this.child = child;
|
|
69
|
+
this.childClosed = new Promise(resolve => child.once('close', resolve));
|
|
70
|
+
const fail = () => this.retire(new AcpError('worker_failed'));
|
|
71
|
+
child.on('error', fail);
|
|
72
|
+
child.stdin.on('error', fail);
|
|
73
|
+
child.stdout.on('error', fail);
|
|
74
|
+
return child;
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
async start(apiKey) {
|
|
78
|
+
this.root = await mkdtemp(join(tmpdir(), 'ccr-agy-acp-'));
|
|
79
|
+
const isolation = await isolatedEnvironment(this.root);
|
|
80
|
+
this.cwd = isolation.cwd;
|
|
81
|
+
const probe = this.spawnChild(['--version'], isolation.env);
|
|
82
|
+
let output = '';
|
|
83
|
+
let bytes = 0;
|
|
84
|
+
probe.stdout.on('data', chunk => {
|
|
85
|
+
bytes += chunk.length;
|
|
86
|
+
if (bytes > 4096) this.retire(new AcpError('output_limit'));
|
|
87
|
+
else output += chunk.toString('ascii');
|
|
88
|
+
});
|
|
89
|
+
probe.stdin.end();
|
|
90
|
+
const probeTimeout = setTimeout(() => this.retire(new AcpError('timeout')), 5000);
|
|
91
|
+
let exitCode;
|
|
92
|
+
try { exitCode = await this.childClosed; } finally { clearTimeout(probeTimeout); }
|
|
93
|
+
this.child = null;
|
|
94
|
+
this.check();
|
|
95
|
+
if (exitCode !== 0 || !supportedVersion(output)) throw new AcpError('unsupported_version');
|
|
96
|
+
|
|
97
|
+
const child = this.spawnChild(['acp', '--sandbox'], { ...isolation.env, GEMINI_API_KEY: apiKey });
|
|
98
|
+
child.once('exit', () => this.retire(new AcpError('worker_failed')));
|
|
99
|
+
child.stdout.once('end', () => this.retire(new AcpError('worker_failed')));
|
|
100
|
+
this.rpc = new AcpStdio(child, error => this.retire(error));
|
|
101
|
+
const init = await this.rpc.request('initialize', { protocolVersion: 1, clientInfo, clientCapabilities: {} });
|
|
102
|
+
if (init.protocolVersion !== 1) throw new AcpError('protocol_error');
|
|
103
|
+
if (!Array.isArray(init.authMethods) || !init.authMethods.some(method => method?.id === AUTH_METHOD &&
|
|
104
|
+
(method.type == null || method.type === 'agent'))) throw new AcpError('auth_required');
|
|
105
|
+
await this.rpc.request('authenticate', { methodId: AUTH_METHOD }, 'auth_required');
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
async turn({ model, thinking, prompt, onText }, apiKey) {
|
|
109
|
+
if (!this.rpc) await this.start(apiKey);
|
|
110
|
+
this.check();
|
|
111
|
+
const cwd = await mkdtemp(join(this.root, 'session-'));
|
|
112
|
+
try {
|
|
113
|
+
const session = await this.rpc.request('session/new', { cwd, mcpServers: [] });
|
|
114
|
+
const { sessionId } = session;
|
|
115
|
+
if (typeof sessionId !== 'string' || !sessionId || sessionId.length > 4096 || this.sessions.has(sessionId)) {
|
|
116
|
+
throw new AcpError('protocol_error');
|
|
117
|
+
}
|
|
118
|
+
this.sessions.add(sessionId);
|
|
119
|
+
await configureSession(this.rpc, session, model, thinking);
|
|
120
|
+
this.rpc.sessionId = sessionId;
|
|
121
|
+
this.rpc.onText = onText;
|
|
122
|
+
const { stopReason } = await this.rpc.request('session/prompt', { sessionId, prompt: [{ type: 'text', text: prompt }] });
|
|
123
|
+
if (!STOP_REASONS.has(stopReason)) throw new AcpError('protocol_error');
|
|
124
|
+
return { stopReason };
|
|
125
|
+
} finally {
|
|
126
|
+
this.rpc.sessionId = null;
|
|
127
|
+
this.rpc.onText = null;
|
|
128
|
+
await rm(cwd, { recursive: true, force: true });
|
|
129
|
+
}
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
async run(request, apiKey, timeoutMs) {
|
|
133
|
+
clearTimeout(this.idleTimer);
|
|
134
|
+
this.rpc?.resetBudget();
|
|
135
|
+
// A caller's deadline is independent of the OS closing the child's pipes.
|
|
136
|
+
let stopRequest;
|
|
137
|
+
const interrupted = new Promise((_, reject) => { stopRequest = reject; });
|
|
138
|
+
const interrupt = code => {
|
|
139
|
+
const error = new AcpError(code);
|
|
140
|
+
stopRequest(error);
|
|
141
|
+
this.retire(error);
|
|
142
|
+
};
|
|
143
|
+
const abort = () => interrupt('cancelled');
|
|
144
|
+
request.signal?.addEventListener('abort', abort, { once: true });
|
|
145
|
+
const timeout = setTimeout(() => interrupt('timeout'), timeoutMs);
|
|
146
|
+
this.task = this.turn(request, apiKey);
|
|
147
|
+
try {
|
|
148
|
+
const result = await Promise.race([this.task, interrupted]);
|
|
149
|
+
this.check();
|
|
150
|
+
if (this.sessions.size >= MAX_SESSIONS) this.retire(new AcpError('closed'));
|
|
151
|
+
else this.idleTimer = setTimeout(() => this.retire(new AcpError('closed')), IDLE_MS).unref();
|
|
152
|
+
return result;
|
|
153
|
+
} catch (error) {
|
|
154
|
+
const reaped = this.retire(error instanceof AcpError ? error : new AcpError('worker_failed'));
|
|
155
|
+
// Keep failed workers in the pool until retirement finishes. The caller
|
|
156
|
+
// can still time out while waiting for cleanup of an earlier error.
|
|
157
|
+
if (error?.code !== 'acp_timeout' && error?.code !== 'acp_cancelled') {
|
|
158
|
+
await Promise.race([reaped, interrupted]);
|
|
159
|
+
}
|
|
160
|
+
throw this.failure;
|
|
161
|
+
} finally {
|
|
162
|
+
this.task = null;
|
|
163
|
+
clearTimeout(timeout);
|
|
164
|
+
request.signal?.removeEventListener('abort', abort);
|
|
165
|
+
}
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
retire(error) {
|
|
169
|
+
if (this.cleanup) return this.cleanup;
|
|
170
|
+
this.failure = error;
|
|
171
|
+
clearTimeout(this.idleTimer);
|
|
172
|
+
this.rpc?.stop(error);
|
|
173
|
+
const child = this.child;
|
|
174
|
+
child?.stdin.destroy();
|
|
175
|
+
child?.stdout.destroy();
|
|
176
|
+
if (child?.pid) {
|
|
177
|
+
// POSIX workers own a fresh process group, including any CLI helpers.
|
|
178
|
+
try {
|
|
179
|
+
if (process.platform === 'win32') child.kill('SIGKILL');
|
|
180
|
+
else process.kill(-child.pid, 'SIGKILL');
|
|
181
|
+
} catch (killError) { if (killError.code !== 'ESRCH') child.kill('SIGKILL'); }
|
|
182
|
+
}
|
|
183
|
+
this.cleanup = (async () => {
|
|
184
|
+
try {
|
|
185
|
+
await this.task?.catch(() => {});
|
|
186
|
+
await this.childClosed;
|
|
187
|
+
if (this.root) await rm(this.root, { recursive: true, force: true, maxRetries: 3 });
|
|
188
|
+
} catch {
|
|
189
|
+
throw new AcpError('worker_failed');
|
|
190
|
+
} finally {
|
|
191
|
+
this.onRetired(this);
|
|
192
|
+
}
|
|
193
|
+
})();
|
|
194
|
+
// Retirement can be initiated from an idle child's exit event without a waiting run().
|
|
195
|
+
this.cleanup.catch(() => {});
|
|
196
|
+
return this.cleanup;
|
|
197
|
+
}
|
|
198
|
+
}
|
|
199
|
+
|
|
200
|
+
export function createTransport({ binary, authMethod, timeoutMs = 60_000, maxWorkers = 2 } = {}) {
|
|
201
|
+
if (typeof binary !== 'string' || !isAbsolute(binary) || binary.includes('\0') || authMethod !== AUTH_METHOD ||
|
|
202
|
+
!Number.isInteger(timeoutMs) || timeoutMs < 1 || timeoutMs > 300_000 ||
|
|
203
|
+
!Number.isInteger(maxWorkers) || maxWorkers < 1 || maxWorkers > 8) throw new AcpError('invalid_config');
|
|
204
|
+
// The host reads settings once per activation. Capture credentials at the
|
|
205
|
+
// same boundary so every worker in this pool has one billing identity.
|
|
206
|
+
const apiKey = process.env.GEMINI_API_KEY;
|
|
207
|
+
const workers = new Set();
|
|
208
|
+
let closed = false;
|
|
209
|
+
return {
|
|
210
|
+
async run(request) {
|
|
211
|
+
if (closed) throw new AcpError('closed');
|
|
212
|
+
const { model, thinking, prompt, signal, onText } = request ?? {};
|
|
213
|
+
if (signal != null && !(signal instanceof AbortSignal)) throw new AcpError('invalid_request');
|
|
214
|
+
if (signal?.aborted) throw new AcpError('cancelled');
|
|
215
|
+
if (typeof prompt !== 'string' || typeof model !== 'string' || !model || model.length > 1024 ||
|
|
216
|
+
(thinking != null && (typeof thinking !== 'string' || !thinking || thinking.length > 128)) ||
|
|
217
|
+
typeof onText !== 'function') throw new AcpError('invalid_request');
|
|
218
|
+
if (Buffer.byteLength(prompt) > MAX_PROMPT_BYTES) throw new AcpError('input_limit');
|
|
219
|
+
if (!apiKey?.trim()) throw new AcpError('auth_required');
|
|
220
|
+
let worker = [...workers].find(candidate => !candidate.task && !candidate.failure);
|
|
221
|
+
if (!worker) {
|
|
222
|
+
if (workers.size >= maxWorkers) throw new AcpError('busy');
|
|
223
|
+
worker = new Worker(binary, retired => workers.delete(retired));
|
|
224
|
+
workers.add(worker);
|
|
225
|
+
}
|
|
226
|
+
return worker.run({ model, thinking, prompt, signal, onText }, apiKey, timeoutMs);
|
|
227
|
+
},
|
|
228
|
+
async close() {
|
|
229
|
+
closed = true;
|
|
230
|
+
await Promise.all([...workers].map(worker => worker.retire(new AcpError('closed'))));
|
|
231
|
+
},
|
|
232
|
+
};
|
|
233
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,17 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@wengine-ai/ccr-provider-gemini-agy-acp",
|
|
3
|
-
"version": "0.0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.0.1",
|
|
4
|
+
"description": "Experimental text-only CCR provider for the local Antigravity CLI over ACP.",
|
|
5
|
+
"license": "MIT",
|
|
6
|
+
"keywords": ["ccr-provider-plugin", "antigravity", "acp"],
|
|
7
|
+
"publishConfig": { "access": "public" },
|
|
8
|
+
"type": "module",
|
|
9
|
+
"main": "dist/plugin.js",
|
|
10
|
+
"files": ["dist", "CHANGELOG.md"],
|
|
11
|
+
"engines": { "node": ">=20" },
|
|
12
|
+
"scripts": {
|
|
13
|
+
"build": "node scripts/build.mjs",
|
|
14
|
+
"prepack": "node scripts/build.mjs",
|
|
15
|
+
"test": "node --test test/*.test.mjs"
|
|
16
|
+
}
|
|
17
|
+
}
|