@jini-ai/agent-runtime 0.4.9 → 0.4.10

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 CHANGED
@@ -1,3 +1,7 @@
1
+ ## 0.4.10 — 2026-10-13
2
+
3
+ - ACP `session/request_permission` no longer fails the run. Without an injected `onPermissionRequest`, the session answers by the new `AttachAcpSessionOptions.permissionMode`: `bypass` selects `allow_once`; otherwise `reject_once`, falling back to `reject_always` or `cancelled`. It never picks an "always" approval. A handler that throws, rejects, or selects an unoffered option cancels the request. Each request emits one `status` event (`label: 'acp_permission'`) with only the tool kind and decision. `choosePermissionOutcome(options, { permissionMode })` follows the same policy.
4
+
1
5
  ## 0.4.9 — 2026-10-13
2
6
 
3
7
  - `@jini-ai/oauth` is a regular dependency, no longer an optional peer: the root imports it statically, so a consumer without its own copy (Tovu Desktop 0.1.15) crashed at load with ERR_MODULE_NOT_FOUND.
@@ -4,6 +4,7 @@
4
4
  * acp/types and acp/json; consumed by acp/session.ts and acp/models.ts.
5
5
  */
6
6
  import type { JsonRpcId, RpcWritable } from './types.js';
7
+ import type { RuntimeBuildOptions } from '../../types.js';
7
8
  /**
8
9
  * Writes a JSON-RPC 2.0 request frame to `writable` as a single newline-terminated
9
10
  * line. Used to send ACP method calls (e.g. `initialize`, `session/new`,
@@ -97,11 +98,13 @@ export interface FormattedUsage {
97
98
  export declare function formatUsage(usage: unknown): FormattedUsage | null;
98
99
  /**
99
100
  * Selects the best permission-outcome `optionId` to reply with when an ACP
100
- * agent sends a `session/request_permission` request. Prefers
101
- * `approve_for_session`, then `allow_always`, then `allow_once`.
101
+ * agent sends a `session/request_permission` request. Bypass permits only
102
+ * this invocation; otherwise reject. Never broaden approval to future calls.
102
103
  *
103
104
  * @param options - The `params.options` array from the incoming permission request.
104
- * @returns The chosen `optionId` string, or `null` when no approvable option is found.
105
+ * @param policy - The existing run permission mode; absence is conservative.
106
+ * @returns An offered `optionId`, or `null` when no safe choice exists.
107
+ * @complexity O(n) time and O(1) space for n offered options.
105
108
  */
106
- export declare function choosePermissionOutcome(options: unknown): string | null;
109
+ export declare function choosePermissionOutcome(options: unknown, policy?: Pick<RuntimeBuildOptions, 'permissionMode'>): string | null;
107
110
  //# sourceMappingURL=rpc.d.ts.map
@@ -140,23 +140,27 @@ export function formatUsage(usage) {
140
140
  }
141
141
  /**
142
142
  * Selects the best permission-outcome `optionId` to reply with when an ACP
143
- * agent sends a `session/request_permission` request. Prefers
144
- * `approve_for_session`, then `allow_always`, then `allow_once`.
143
+ * agent sends a `session/request_permission` request. Bypass permits only
144
+ * this invocation; otherwise reject. Never broaden approval to future calls.
145
145
  *
146
146
  * @param options - The `params.options` array from the incoming permission request.
147
- * @returns The chosen `optionId` string, or `null` when no approvable option is found.
147
+ * @param policy - The existing run permission mode; absence is conservative.
148
+ * @returns An offered `optionId`, or `null` when no safe choice exists.
149
+ * @complexity O(n) time and O(1) space for n offered options.
148
150
  */
149
- export function choosePermissionOutcome(options) {
151
+ export function choosePermissionOutcome(options, policy = {}) {
150
152
  const list = Array.isArray(options) ? options : [];
151
- const approveForSession = list.find((option) => option?.optionId === 'approve_for_session');
152
- if (approveForSession)
153
- return 'approve_for_session';
154
- const allowAlways = list.find((option) => option?.kind === 'allow_always');
155
- if (allowAlways?.optionId)
156
- return allowAlways.optionId;
157
- const allowOnce = list.find((option) => option?.kind === 'allow_once');
158
- if (allowOnce?.optionId)
159
- return allowOnce.optionId;
153
+ const kinds = policy.permissionMode === 'bypass'
154
+ ? ['allow_once', 'reject_once', 'reject_always']
155
+ : ['reject_once', 'reject_always'];
156
+ for (const kind of kinds) {
157
+ const option = list.find((value) => {
158
+ const record = asObject(value);
159
+ return record?.kind === kind && typeof record.optionId === 'string' && record.optionId.length > 0;
160
+ });
161
+ if (option)
162
+ return option.optionId;
163
+ }
160
164
  return null;
161
165
  }
162
166
  //# sourceMappingURL=rpc.js.map
@@ -1,4 +1,5 @@
1
1
  import type { ExecutionProfile } from './types.js';
2
+ import type { RuntimeBuildOptions } from '../../types.js';
2
3
  import { type ArtifactTextSuppressor } from './text-suppression.js';
3
4
  import type { JsonRpcId, UnknownRecord, AcpChildProcess } from './types.js';
4
5
  import { type AcpMcpServerInput } from './session-params.js';
@@ -61,11 +62,12 @@ export interface AttachAcpSessionOptions {
61
62
  }) => void;
62
63
  /**
63
64
  * Receives every native ACP tool-permission request before the agent can
64
- * execute it. Omit it only when the host intends the session to fail closed
65
- * on its first permission request; a runnable ACP host injects a policy
66
- * that records and selects an offered option.
65
+ * execute it. Omit it to answer by `permissionMode`; a handler that throws
66
+ * or picks an unoffered option cancels the request instead of failing the run.
67
67
  */
68
68
  onPermissionRequest?: AcpPermissionHandler;
69
+ /** Default policy when no handler is injected: bypass allows once; otherwise reject. */
70
+ permissionMode?: RuntimeBuildOptions['permissionMode'];
69
71
  clientName?: string;
70
72
  clientVersion?: string;
71
73
  stageTimeoutMs?: number;
@@ -19,11 +19,15 @@ import { createDsmlArtifactTextSuppressor, createToolCallTextSuppressor, } from
19
19
  import { createJsonLineStream } from '../core/index.js';
20
20
  import { ACP_PROTOCOL_VERSION, DEFAULT_STAGE_TIMEOUT_MS, ACP_ARTIFACT_ECHO_START_RE, ACP_RAW_EVENT_SHAPE_DIAGNOSTIC_LIMIT, AMR_STDERR_RETRY_TAIL_LIMIT, } from './constants.js';
21
21
  import { errorMessage, asObject, extractAcpUpdateText } from './json.js';
22
- import { sendRpc, sendRpcResult, isJsonRpcId, rpcErrorMessage, rpcErrorData, rpcErrorRetryable, promotedOpenCodeSessionErrorPayload, formatUsage, } from './rpc.js';
22
+ import { sendRpc, sendRpcResult, isJsonRpcId, rpcErrorMessage, rpcErrorData, rpcErrorRetryable, promotedOpenCodeSessionErrorPayload, formatUsage, choosePermissionOutcome, } from './rpc.js';
23
23
  import { acpRawEventShape, isAcpCompletedStatus, isAcpTerminalFailureStatus, acpToolCallId, isAcpArtifactWriteLabel, isAcpArtifactWriteUpdate, acpArtifactWritePath, promotedAmrRetryStatusPayload, promotedAmrStderrPayload, } from './updates.js';
24
24
  import { findModelConfigOption, currentModelFromSessionResult, modelSelectionErrorIsRecoverable, } from './models.js';
25
25
  import { buildAcpSessionNewParams, buildPromptBlocks } from './session-params.js';
26
26
  import { noopAccountFailureClassifier } from './account-failure.js';
27
+ /** ACP `PermissionOptionKind` values; other offered options are ignored. */
28
+ const ACP_PERMISSION_OPTION_KINDS = ['allow_once', 'allow_always', 'reject_once', 'reject_always'];
29
+ /** ACP `ToolKind` values; anything else is logged as `other`. */
30
+ const ACP_TOOL_KINDS = ['read', 'edit', 'delete', 'move', 'search', 'execute', 'think', 'fetch', 'switch_mode', 'other'];
27
31
  /** Builds a fresh {@link AcpSessionState} with every field at its initial value. */
28
32
  export function createAcpSessionState() {
29
33
  return {
@@ -477,7 +481,7 @@ function resolveAcpSessionOptionDefaults(options) {
477
481
  */
478
482
  export function attachAcpSession(requiredArgs, optionalArgs = {}) {
479
483
  const options = { ...optionalArgs, ...requiredArgs };
480
- const { child, prompt, cwd, model, mcpServers, send, modelUnavailableErrorCode, resumeSessionId, onPermissionRequest, onCliReady, onSessionInit, } = options;
484
+ const { child, prompt, cwd, model, mcpServers, send, modelUnavailableErrorCode, resumeSessionId, onPermissionRequest, permissionMode, onCliReady, onSessionInit, } = options;
481
485
  const { imagePaths, envFormat, clientName, clientVersion, stageTimeoutMs, executionProfile, accountFailureClassifier, } = resolveAcpSessionOptionDefaults(options);
482
486
  const runStartedAt = Date.now();
483
487
  const effectiveCwd = path.resolve(cwd || process.cwd());
@@ -500,7 +504,7 @@ export function attachAcpSession(requiredArgs, optionalArgs = {}) {
500
504
  let fatal = false;
501
505
  let aborted = false;
502
506
  let stageTimer = null;
503
- const pendingPermissionRequestIds = new Set();
507
+ const pendingPermissionRequests = new Map();
504
508
  const toolCallTextSuppressor = createToolCallTextSuppressor();
505
509
  let toolCallTextSuppressorLastSuppressedChars = 0;
506
510
  const artifactTextSuppressionSummary = {
@@ -818,57 +822,77 @@ export function attachAcpSession(requiredArgs, optionalArgs = {}) {
818
822
  };
819
823
  const replyPermission = (raw) => {
820
824
  const params = asObject(raw.params);
821
- if (!params || !isJsonRpcId(raw.id)) {
822
- fail(`unhandled ACP permission request: ${JSON.stringify(raw)}`);
825
+ const toolCall = asObject(params?.toolCall);
826
+ const optionRecords = Array.isArray(params?.options)
827
+ ? params.options.filter((option) => {
828
+ const record = asObject(option);
829
+ return typeof record?.optionId === 'string' && record.optionId !== '' &&
830
+ typeof record.kind === 'string' && ACP_PERMISSION_OPTION_KINDS.includes(record.kind);
831
+ })
832
+ : [];
833
+ // One status event per request. Only protocol categories leave this
834
+ // boundary: titles, names, option ids and raw arguments can contain
835
+ // commands, paths or credentials.
836
+ const logDecision = (selected) => {
837
+ try {
838
+ const tool = typeof toolCall?.kind === 'string' && ACP_TOOL_KINDS.includes(toolCall.kind) ? toolCall.kind : 'other';
839
+ send({ event: 'agent', payload: { type: 'status', label: 'acp_permission', detail: `tool=${tool} decision=${selected?.kind ?? 'cancelled'}` } });
840
+ }
841
+ catch {
842
+ // Host telemetry must not turn a handled request into a run failure.
843
+ }
844
+ };
845
+ if (!isJsonRpcId(raw.id)) {
846
+ // No response can be correlated without a valid id; drop it rather
847
+ // than failing the run.
848
+ logDecision();
823
849
  return;
824
850
  }
825
851
  const requestId = raw.id;
826
- const optionRecords = Array.isArray(params.options)
827
- ? params.options.filter((option) => Boolean(asObject(option)) && typeof asObject(option)?.optionId === 'string')
828
- : [];
829
- const request = {
830
- requestId,
831
- sessionId: typeof params.sessionId === 'string' ? params.sessionId : null,
832
- toolCall: asObject(params.toolCall) ?? null,
833
- options: optionRecords,
834
- rawParams: params,
835
- };
836
852
  const respond = (decision) => {
837
- pendingPermissionRequestIds.delete(requestId);
853
+ pendingPermissionRequests.delete(requestId);
838
854
  if (aborted || finished)
839
855
  return;
840
- if (decision.outcome === 'selected' &&
841
- !optionRecords.some((option) => option.optionId === decision.optionId)) {
842
- fail(`ACP permission handler selected an unavailable option: ${decision.optionId}`);
843
- return;
844
- }
856
+ // Anything but an offered option (including an invalid handler result) cancels.
857
+ const choice = asObject(decision);
858
+ const selected = choice?.outcome === 'selected'
859
+ ? optionRecords.find((option) => option.optionId === choice.optionId)
860
+ : undefined;
845
861
  resetStageTimer('session/request_permission');
846
862
  try {
847
863
  sendRpcResult(stdin, requestId, {
848
- outcome: decision.outcome === 'selected'
849
- ? { outcome: 'selected', optionId: decision.optionId }
850
- : { outcome: 'cancelled' },
864
+ outcome: selected ? { outcome: 'selected', optionId: selected.optionId } : { outcome: 'cancelled' },
851
865
  });
852
866
  }
853
- catch (err) {
854
- fail(`stdin write failed: ${errorMessage(err)}`);
867
+ catch {
868
+ // A broken pipe cannot carry a response; ordinary transport lifecycle
869
+ // handling still owns process failure, not the permission decision.
855
870
  }
871
+ logDecision(selected);
856
872
  };
857
- const rejectHandlerFailure = (err) => {
858
- pendingPermissionRequestIds.delete(requestId);
859
- fail(`ACP permission handler failed: ${errorMessage(err)}`);
860
- };
861
- pendingPermissionRequestIds.add(requestId);
862
- if (!onPermissionRequest) {
863
- pendingPermissionRequestIds.delete(requestId);
864
- fail('ACP permission request received without an injected permission handler');
873
+ const cancel = () => respond({ outcome: 'cancelled' });
874
+ if (!params) {
875
+ cancel();
865
876
  return;
866
877
  }
878
+ pendingPermissionRequests.set(requestId, () => logDecision());
867
879
  try {
868
- Promise.resolve(onPermissionRequest(request)).then(respond, rejectHandlerFailure);
880
+ if (!onPermissionRequest) {
881
+ const optionId = choosePermissionOutcome(optionRecords, permissionMode ? { permissionMode } : {});
882
+ respond(optionId ? { outcome: 'selected', optionId } : { outcome: 'cancelled' });
883
+ return;
884
+ }
885
+ const request = {
886
+ requestId,
887
+ sessionId: typeof params.sessionId === 'string' ? params.sessionId : null,
888
+ toolCall: toolCall ?? null,
889
+ options: optionRecords,
890
+ rawParams: params,
891
+ };
892
+ Promise.resolve(onPermissionRequest(request)).then(respond, cancel);
869
893
  }
870
- catch (err) {
871
- rejectHandlerFailure(err);
894
+ catch {
895
+ cancel();
872
896
  }
873
897
  };
874
898
  const recoverFromModelSelectionError = () => {
@@ -958,15 +982,16 @@ export function attachAcpSession(requiredArgs, optionalArgs = {}) {
958
982
  // closing stdin, which may otherwise make the response impossible to
959
983
  // deliver.
960
984
  const cancelPendingPermissionRequests = () => {
961
- for (const requestId of pendingPermissionRequestIds) {
985
+ for (const [requestId, logCancellation] of pendingPermissionRequests) {
962
986
  try {
963
987
  sendRpcResult(stdin, requestId, { outcome: { outcome: 'cancelled' } });
964
988
  }
965
989
  catch {
966
990
  // Closing stdin/process signalling below remains the fallback.
967
991
  }
992
+ logCancellation();
968
993
  }
969
- pendingPermissionRequestIds.clear();
994
+ pendingPermissionRequests.clear();
970
995
  };
971
996
  // Only cancel an established session; before session/new resolves there is
972
997
  // no sessionId to cancel, but the caller still closes stdin below.
@@ -0,0 +1,24 @@
1
+ export declare const geminiAgentDef: {
2
+ id: string;
3
+ name: string;
4
+ bin: string;
5
+ versionArgs: string[];
6
+ versionProbeTimeoutMs: number;
7
+ helpArgs: string[];
8
+ capabilityFlags: {
9
+ "--skip-trust": string;
10
+ };
11
+ fallbackModels: import("../types.js").RuntimeModelOption[];
12
+ buildArgs: ({ prompt: _prompt, imagePaths: _imagePaths }: {
13
+ prompt: string;
14
+ imagePaths: string[];
15
+ }, { extraAllowedDirs, options }?: {
16
+ extraAllowedDirs?: string[];
17
+ options?: import("../types.js").RuntimeBuildOptions;
18
+ runtimeContext?: import("../types.js").RuntimeContext;
19
+ } | undefined) => string[];
20
+ promptViaStdin: true;
21
+ streamFormat: string;
22
+ eventParser: string;
23
+ };
24
+ //# sourceMappingURL=gemini.d.ts.map
@@ -0,0 +1,81 @@
1
+ /**
2
+ * @module defs/gemini
3
+ *
4
+ * Google's Gemini CLI (`gemini`, npm `@google/gemini-cli`). Checked against an installed
5
+ * `gemini` 0.58.0 (`gemini --help` and the bundled headless code path) and the upstream headless
6
+ * docs (<https://geminicli.com/docs/cli/headless>):
7
+ *
8
+ * - Headless mode starts whenever stdin is not a TTY; the whole piped stdin becomes the prompt
9
+ * (`-p` is only needed to pass the prompt in argv, and would be "appended to input on stdin").
10
+ * So the prompt goes over stdin, like the Qwen Code fork, which avoids Windows `spawn
11
+ * ENAMETOOLONG` on large composed prompts.
12
+ * - `--output-format stream-json` emits the JSONL `init` / `message` / `tool_use` /
13
+ * `tool_result` / `error` / `result` events that `json-event-stream.ts`'s `gemini` parser
14
+ * already reads.
15
+ * - `--approval-mode yolo` auto-approves every tool (the `--yolo` alias does the same).
16
+ * - Since folder trust landed, a headless run in an untrusted directory exits with "Gemini CLI
17
+ * is not running in a trusted directory. To proceed, either use `--skip-trust`, …". The host
18
+ * already chose the run's cwd, so the def trusts it for this session only. Older builds
19
+ * reject unknown flags, so `--skip-trust` is gated on the `--help` capability probe.
20
+ * - `--include-directories` (repeatable) widens the workspace to dirs outside the cwd.
21
+ *
22
+ * Auth: since 2026-06-18 Google no longer serves Gemini CLI's "Login with Google" for free /
23
+ * Google AI Pro / Ultra individual accounts (the run dies with `IneligibleTierError: This client
24
+ * is no longer supported for Gemini Code Assist for individuals`). A Gemini API key, Vertex AI,
25
+ * or a Gemini Code Assist license still works. There is no side-effect-free auth-status
26
+ * subcommand, so no `authProbe`; `auth.ts#classifyAgentAuthFailure` turns the failure text into
27
+ * setup guidance instead.
28
+ */
29
+ import { DEFAULT_MODEL_OPTION } from './shared.js';
30
+ import { agentCapabilities } from '../capabilities.js';
31
+ const SKIP_TRUST_FLAG = '--skip-trust';
32
+ export const geminiAgentDef = {
33
+ id: 'gemini',
34
+ name: 'Gemini CLI',
35
+ bin: 'gemini',
36
+ versionArgs: ['--version'],
37
+ // A cold `gemini --version` took 4.7 s on the dev machine (warm ~2 s), past the 3 s default.
38
+ versionProbeTimeoutMs: 10_000,
39
+ helpArgs: ['--help'],
40
+ capabilityFlags: {
41
+ [SKIP_TRUST_FLAG]: 'skipTrust',
42
+ },
43
+ // No `models` subcommand. `auto` and the concrete ids below are the ones the installed
44
+ // 0.58.0 bundle and the upstream model docs name; any other id can still be typed in.
45
+ fallbackModels: [
46
+ DEFAULT_MODEL_OPTION,
47
+ { id: 'auto', label: 'auto' },
48
+ { id: 'gemini-3.1-pro-preview', label: 'gemini-3.1-pro-preview' },
49
+ { id: 'gemini-3.5-flash', label: 'gemini-3.5-flash' },
50
+ { id: 'gemini-3-pro-preview', label: 'gemini-3-pro-preview' },
51
+ { id: 'gemini-3-flash-preview', label: 'gemini-3-flash-preview' },
52
+ { id: 'gemini-2.5-pro', label: 'gemini-2.5-pro' },
53
+ { id: 'gemini-2.5-flash', label: 'gemini-2.5-flash' },
54
+ ],
55
+ buildArgs: ({ prompt: _prompt, imagePaths: _imagePaths }, { extraAllowedDirs = [], options = {} } = {}) => {
56
+ const args = ['--output-format', 'stream-json'];
57
+ if (agentCapabilities.get('gemini')?.skipTrust) {
58
+ args.push(SKIP_TRUST_FLAG);
59
+ }
60
+ // See `RuntimeBuildOptions.permissionMode`'s doc: bypass is the default (unchanged
61
+ // behavior) unless a caller explicitly opts into a restricted run.
62
+ if (options.permissionMode !== 'restricted') {
63
+ args.push('--approval-mode', 'yolo');
64
+ }
65
+ if (options.model && options.model !== 'default') {
66
+ args.push('--model', options.model);
67
+ }
68
+ const dirs = (extraAllowedDirs || []).filter((d) => typeof d === 'string' && d.length > 0);
69
+ for (const d of dirs)
70
+ args.push('--include-directories', d);
71
+ return args;
72
+ },
73
+ promptViaStdin: true,
74
+ streamFormat: 'json-event-stream',
75
+ eventParser: 'gemini',
76
+ // No `externalMcpInjection` yet: Gemini CLI reads `mcpServers` from `settings.json` (user,
77
+ // project `.gemini/settings.json`, or a system file named by
78
+ // `GEMINI_CLI_SYSTEM_SETTINGS_PATH`), with no per-run `--mcp-config` flag. A run-scoped
79
+ // system-settings file is the likely strategy, but it is not wired or verified live.
80
+ };
81
+ //# sourceMappingURL=gemini.js.map
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@jini-ai/agent-runtime",
3
- "version": "0.4.9",
3
+ "version": "0.4.10",
4
4
  "description": "Coding-agent runtime adapters: runtime registry, detection, launch, stream parsers, and the ACP/pi-rpc subprocess transport.",
5
5
  "license": "Apache-2.0",
6
6
  "repository": {
@@ -99,13 +99,13 @@
99
99
  "devDependencies": {
100
100
  "@vitest/coverage-v8": "^2.1.9",
101
101
  "@jini-ai/core": "^0.4.0",
102
- "@jini-ai/integrations": "^0.4.2",
103
102
  "@jini-ai/platform": "^0.5.6",
103
+ "@jini-ai/integrations": "^0.4.2",
104
104
  "@jini-ai/protocol": "^0.4.4"
105
105
  },
106
106
  "dependencies": {
107
- "@jini-ai/core": "^0.4.5",
108
- "@jini-ai/oauth": "^0.2.2"
107
+ "@jini-ai/oauth": "^0.2.2",
108
+ "@jini-ai/core": "^0.4.5"
109
109
  },
110
110
  "peerDependencies": {
111
111
  "@jini-ai/integrations": "^0.4.2",