@coda-console/grok 1.6.0 → 1.7.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 CHANGED
@@ -1,3 +1,7 @@
1
1
  # Grok
2
2
 
3
3
  Grok Agent:适配运行机上 Grok CLI 的 ACP 与审批模式;资源页的「Grok」显示账号与额度,可从 Coda 安装和登录。
4
+
5
+ 不声明 `systemPrompt`;会话指令由 Coda 后端在新会话第一次非斜杠命令的用户输入前送入单独的文本块,恢复会话不再送,插件不用处理。
6
+
7
+ 入口声明 ACP 的 `session/delete`:Grok 原生没有,入口自己拦下,改跑官方命令 `grok sessions delete <id>`(15 秒超时)。命令对不存在的会话也退出 0,所以以它的输出为准:`Deleted session` 回 `{}`,`No session found` 回 -32002,其他回 -32603 并带原因。会话还开在 Grok 里时可以直接删,之后 `session/close` 和结束进程都不会把它写回来(1.0.77 实测)。这样 Coda 探测模型和模式留下的空会话能被清掉;`sessions delete` 核对于 1.0.77,更旧的 CLI 没有它时回错误,不抬高最低版本(审批模式通知只核对过 1.0.52)。
@@ -0,0 +1,27 @@
1
+ // `grok sessions delete <id>`, which is how Grok's history loses a session: ACP has no session/delete for it. It exits 0
2
+ // whether or not the session existed, so what it prints says which. Resolves null when it reports `Deleted session`, else
3
+ // the JSON-RPC error to answer with: -32002 for `No session found`, -32603 for anything else. Checked on 1.0.77: a session still open in an agent is deleted for good, and closing it
4
+ // or ending that agent afterwards writes nothing back.
5
+ import { spawn } from 'node:child_process';
6
+
7
+ const firstLine = text => text.split('\n').map(line => line.trim()).find(Boolean);
8
+
9
+ export function deleteSession(binary, sessionId, timeoutMs = 15000) {
10
+ return new Promise(resolve => {
11
+ // `--` keeps an id that starts with a dash from being read as an option.
12
+ const child = spawn(binary, ['sessions', 'delete', '--', sessionId], { stdio: ['ignore', 'pipe', 'pipe'] });
13
+ let stdout = '', stderr = '', done = false;
14
+ const finish = error => { if (done) return; done = true; clearTimeout(timer); resolve(error); };
15
+ const timer = setTimeout(() => { child.kill('SIGKILL'); finish({ code: -32603, message: '删除 Grok 会话超时' }); }, timeoutMs);
16
+ child.stdout.setEncoding('utf8').on('data', text => { stdout += text; });
17
+ child.stderr.setEncoding('utf8').on('data', text => { stderr += text; });
18
+ child.on('error', error => finish({ code: -32603, message: `无法运行 Grok CLI:${error.message}` }));
19
+ child.on('close', (code, signal) => {
20
+ if (code !== 0) return finish({ code: -32603, message: firstLine(stderr) ?? (code === null ? `grok sessions delete 被信号 ${signal} 结束` : `grok sessions delete 退出码 ${code}`) });
21
+ if (/^Deleted session /m.test(stdout)) return finish(null);
22
+ const missing = stdout.split('\n').find(line => line.startsWith('No session found with id'));
23
+ finish(missing ? { code: -32002, message: missing.trim() }
24
+ : { code: -32603, message: `grok sessions delete 没有确认删除:${firstLine(stdout) ?? '没有输出'}` });
25
+ });
26
+ });
27
+ }
package/agent/entry.mjs CHANGED
@@ -1,19 +1,24 @@
1
- // Grok 1.0.52 reports no ACP modes. Translate set_mode to the notification its own UI sends; everything else passes
2
- // through. No selected mode (the empty currentModeId) leaves the machine's configuration in charge, as before. Coda's session
3
- // instructions go in front of a new session's first prompt (instructions.mjs). Grok's questions are asked of Coda as ACP forms
4
- // (questions.mjs); Grok gives one up (its timeout, a cancelled turn) by ending the tool call alone, so that end withdraws the form.
1
+ // Grok (checked on 1.0.52) reports no ACP modes. Translate set_mode to the notification its own UI sends; everything else passes
2
+ // through. No selected mode (the empty currentModeId) leaves the machine's configuration in charge, as before.
3
+ // Grok's questions are asked of Coda as ACP forms (questions.mjs). Grok gives one up (its timeout, a cancelled turn)
4
+ // by ending the tool call alone, so that end withdraws the form.
5
+ // Grok's ACP has no session/delete, so the entry declares it and answers it with `grok sessions delete`
6
+ // (delete.mjs; checked on 1.0.77): Coda's probes (session/new, then gone) leave no empty sessions in Grok's history.
5
7
  import { spawn } from 'node:child_process';
6
8
  import { grokBinary } from '../scripts/ask.mjs';
7
- import { SessionInstructions } from './instructions.mjs';
9
+ import { deleteSession } from './delete.mjs';
8
10
  import { ASK, questionForm } from './questions.mjs';
9
11
 
10
12
  const modes = [{ id: 'auto', name: '自动审批', _meta: { coda: { shortName: '自动审批' } } },
11
13
  { id: 'always-approve', name: '全部放行', _meta: { coda: { shortName: '全部放行' } } }];
12
- const grok = spawn(grokBinary() ?? 'grok', ['agent', '--no-leader', 'stdio'], { stdio: ['pipe', 'pipe', 'inherit'] });
14
+ const binary = grokBinary() ?? 'grok';
15
+ const grok = spawn(binary, ['agent', '--no-leader', 'stdio'], { stdio: ['pipe', 'pipe', 'inherit'] });
13
16
  const send = (stream, message) => stream.write(`${JSON.stringify(message)}\n`);
14
17
  const say = message => send(process.stdout, { jsonrpc: '2.0', ...message });
15
18
  const pending = new Map();
16
- const instructions = new SessionInstructions();
19
+ // The deletes under way, by session: Coda closes a probe's session once its delete has had its few seconds, and a close
20
+ // reaching Grok while `sessions delete` still runs could write the session back.
21
+ const deleting = new Map();
17
22
  // The forms asked of Coda, by their id: Grok's request they answer, its tool call, and how the answer is given back.
18
23
  const questions = new Map();
19
24
  let sessionId, mode = '', stopping = false, asked = 0;
@@ -30,14 +35,23 @@ function read(stream, receive) {
30
35
  };
31
36
  stream.setEncoding('utf8').on('data', take).on('end', () => take('\n'));
32
37
  }
33
- read(process.stdin, said => {
34
- const question = !said.method && questions.get(said.id);
38
+ read(process.stdin, message => {
39
+ if (message.method === 'session/delete' && 'id' in message) {
40
+ const id = message.params?.sessionId;
41
+ if (typeof id !== 'string' || !id) { say({ id: message.id, error: { code: -32602, message: '缺少 sessionId' } }); return; }
42
+ deleting.set(id, deleteSession(binary, id).then(error => {
43
+ deleting.delete(id); say(error ? { id: message.id, error } : { id: message.id, result: {} });
44
+ }));
45
+ return;
46
+ }
47
+ if (message.method === 'session/close' && deleting.has(message.params?.sessionId)) {
48
+ deleting.get(message.params.sessionId).then(() => send(grok.stdin, message)); return;
49
+ }
50
+ const question = !message.method && questions.get(message.id);
35
51
  if (question) {
36
- questions.delete(said.id);
37
- send(grok.stdin, { jsonrpc: '2.0', id: question.id, result: question.answer(said.result) }); return;
52
+ questions.delete(message.id);
53
+ send(grok.stdin, { jsonrpc: '2.0', id: question.id, result: question.answer(message.result) }); return;
38
54
  }
39
- const { agent: message, coda } = instructions.fromCoda(said);
40
- if (coda) { say(coda); return; }
41
55
  if (message.method === 'session/set_mode' && 'id' in message) {
42
56
  const chosen = message.params?.modeId;
43
57
  const error = !sessionId || message.params?.sessionId !== sessionId ? 'Grok 会话不存在'
@@ -51,25 +65,28 @@ read(process.stdin, said => {
51
65
  say({ method: 'session/update', params: { sessionId, update: { sessionUpdate: 'current_mode_update', currentModeId: mode } } });
52
66
  say({ id: message.id, result: {} }); return;
53
67
  }
54
- if ('id' in message && ['session/new', 'session/load', 'session/prompt'].includes(message.method)) pending.set(message.id, message);
68
+ if ('id' in message && ['initialize', 'session/new', 'session/load', 'session/prompt'].includes(message.method)) pending.set(message.id, message);
55
69
  send(grok.stdin, message);
56
70
  });
57
- read(grok.stdout, said => {
58
- if (said.method === ASK && 'id' in said) {
59
- const id = `grok-ask-${++asked}`, { params, answer } = questionForm(said.params ?? {});
60
- questions.set(id, { id: said.id, toolCallId: params.toolCallId, answer });
71
+ read(grok.stdout, message => {
72
+ if (message.method === ASK && 'id' in message) {
73
+ const id = `grok-ask-${++asked}`, { params, answer } = questionForm(message.params ?? {});
74
+ questions.set(id, { id: message.id, toolCallId: params.toolCallId, answer });
61
75
  say({ id, method: 'elicitation/create', params }); return;
62
76
  }
63
- const update = said.method === 'session/update' ? said.params?.update : null;
77
+ const update = message.method === 'session/update' ? message.params?.update : null;
64
78
  if (update?.sessionUpdate === 'tool_call_update' && ['completed', 'failed'].includes(update.status)) {
65
79
  for (const [id, question] of questions) if (question.toolCallId === update.toolCallId) {
66
80
  questions.delete(id); say({ method: '$/cancel_request', params: { requestId: id } });
67
81
  }
68
82
  }
69
- const message = instructions.fromAgent(said), request = !message.method && pending.get(message.id);
83
+ const request = !message.method && pending.get(message.id);
70
84
  if (request) {
71
85
  pending.delete(message.id);
72
- if (message.result && request.method !== 'session/prompt') {
86
+ if (message.result && request.method === 'initialize') {
87
+ const capabilities = message.result.agentCapabilities ??= {};
88
+ capabilities.sessionCapabilities = { ...capabilities.sessionCapabilities, delete: {} };
89
+ } else if (message.result && request.method !== 'session/prompt') {
73
90
  sessionId = message.result.sessionId ?? request.params.sessionId;
74
91
  mode = request.params?._meta?.yoloMode ? 'always-approve' : request.params?._meta?.autoMode ? 'auto' : '';
75
92
  message.result.modes = { currentModeId: mode, availableModes: modes };
package/package.json CHANGED
@@ -3,7 +3,7 @@
3
3
  "id": "grok",
4
4
  "displayName": "Grok",
5
5
  "description": "用 Grok CLI 跑会话",
6
- "version": "1.6.0",
6
+ "version": "1.7.0",
7
7
  "categories": [
8
8
  "Agent"
9
9
  ],
package/scripts/setup.mjs CHANGED
@@ -1,6 +1,7 @@
1
1
  // The plugin's setup (`contributes.setup`), which Coda runs on each machine when the user installs or updates the plugin: it
2
2
  // ends well once the machine can run the agent. Without a Grok CLI that runs, or with one older than MINIMUM (the CLI whose
3
- // `agent --no-leader stdio` and `_x.ai/yolo_mode_changed` the agent entry was checked against), Grok's own installer puts
3
+ // `agent --no-leader stdio` and `_x.ai/yolo_mode_changed` the agent entry was checked against: 1.0.52). `sessions delete`
4
+ // was checked on 1.0.77; on an older CLI that does not have it, the entry answers session/delete with its error. Grok's own installer puts
4
5
  // the latest in ~/.grok/bin, where the agent looks first, as the「Grok」type's install does; a newer one is kept. Why the
5
6
  // machine is not ready is said in one line on standard error.
6
7
  import { spawnSync } from 'node:child_process';
@@ -1,68 +0,0 @@
1
- // Coda's session instructions (docs/agent-protocol.md「会话指令」) for an agent whose own ACP does not take `systemPrompt`: the
2
- // entry declares that it does, keeps the parameter from the agent, and puts the text in front of the first prompt of a
3
- // session the agent opened new, as a part of its own; a session it loaded has had them. A slash command is the agent's to
4
- // read as one: the instructions wait for the next prompt. Kept the same in every plugin that relays a CLI's ACP.
5
- const record = value => value && typeof value === 'object' && !Array.isArray(value);
6
-
7
- // ACP's `systemPrompt`: its text, '' when there is none; throws on anything but text appended to the agent's own.
8
- export function sessionInstructions(systemPrompt) {
9
- if (systemPrompt === undefined || systemPrompt === null) return '';
10
- if (systemPrompt.mode !== 'append') throw new Error('会话指令只支持 append 模式');
11
- const { content } = systemPrompt;
12
- if (!Array.isArray(content) || content.some(block => block?.type !== 'text' || typeof block.text !== 'string')) throw new Error('会话指令只接受文本块');
13
- return content.map(block => block.text).join('\n\n');
14
- }
15
-
16
- // The part in front of the user's input: delimited, and said to be the client's, not the user's.
17
- const OPENING = '<coda-session-instructions>';
18
- export const instructionsBlock = text => ({ type: 'text', text: `${OPENING}\n`
19
- + 'Instructions from Coda, the client this session runs in, for the whole session. They are not part of the user\'s message.\n\n'
20
- + `${text}\n</coda-session-instructions>\n` });
21
-
22
- export class SessionInstructions {
23
- // Coda's requests whose answers are read here, by id; the instructions of a session yet to have its first prompt.
24
- constructor() { this.asked = new Map(); this.waiting = new Map(); }
25
- // What Coda says: `agent`, what the agent is told, or `coda`, Coda's answer given here instead.
26
- fromCoda(message) {
27
- const { id, method, params } = message;
28
- if (!record(params)) return { agent: message };
29
- if (method === 'initialize' && id !== undefined) this.asked.set(id, { initialize: true });
30
- if (method === 'session/new' || method === 'session/load') {
31
- let text;
32
- try { text = sessionInstructions(params.systemPrompt); }
33
- catch (error) { return { coda: { jsonrpc: '2.0', id, error: { code: -32602, message: error.message } } }; }
34
- const { systemPrompt, ...rest } = params;
35
- if (method === 'session/new' && text && id !== undefined) this.asked.set(id, { text });
36
- return { agent: { ...message, params: rest } };
37
- }
38
- if (method === 'session/prompt' && Array.isArray(params.prompt) && this.waiting.has(params.sessionId)) {
39
- const first = params.prompt.find(block => block?.type === 'text');
40
- if (typeof first?.text === 'string' && first.text.trimStart().startsWith('/')) return { agent: message };
41
- const text = this.waiting.get(params.sessionId);
42
- this.waiting.delete(params.sessionId);
43
- return { agent: { ...message, params: { ...params, prompt: [instructionsBlock(text), ...params.prompt] } } };
44
- }
45
- return { agent: message };
46
- }
47
- // What the agent says, as said to Coda. A title the agent took from the first prompt's text begins with the instructions,
48
- // not with what the user asked: it is left out, and the session keeps the title Coda gives it.
49
- fromAgent(message) {
50
- const update = message?.method === 'session/update' && record(message.params) ? message.params.update : null;
51
- if (record(update) && update.sessionUpdate === 'session_info_update' && typeof update.title === 'string' && update.title.trimStart().startsWith(OPENING)) {
52
- const { title, ...rest } = update;
53
- return { ...message, params: { ...message.params, update: rest } };
54
- }
55
- if (!record(message) || !('id' in message) || 'method' in message) return message;
56
- const asked = this.asked.get(message.id);
57
- if (!asked) return message;
58
- this.asked.delete(message.id);
59
- if (!record(message.result)) return message;
60
- if (asked.text) {
61
- if (typeof message.result.sessionId === 'string') this.waiting.set(message.result.sessionId, asked.text);
62
- return message;
63
- }
64
- const capabilities = record(message.result.agentCapabilities) ? message.result.agentCapabilities : {};
65
- const sessions = record(capabilities.sessionCapabilities) ? capabilities.sessionCapabilities : {};
66
- return { ...message, result: { ...message.result, agentCapabilities: { ...capabilities, sessionCapabilities: { ...sessions, systemPrompt: {} } } } };
67
- }
68
- }