@jini-ai/agent-runtime 0.4.9 → 0.4.11

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,12 @@
1
+ ## 0.4.11 — 2026-10-14
2
+
3
+ - Gemini: `applyGoogleUsage` adds `input_tokens` (`promptTokenCount`) and `output_tokens` (`candidatesTokenCount` + `thoughtsTokenCount`) next to the raw `usageMetadata` fields, so usage reducers show Gemini token counts (024fe7e8).
4
+ - Gemini: a first reply with no text and no tool calls (for example thinking consumed the whole `MAX_TOKENS` budget) now emits an error carrying the finish reason and ends with `error` instead of a blank successful `stop`. Partial text cut off by `MAX_TOKENS` and tool-only turns still succeed (a80066ae).
5
+
6
+ ## 0.4.10 — 2026-10-13
7
+
8
+ - 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.
9
+
1
10
  ## 0.4.9 — 2026-10-13
2
11
 
3
12
  - `@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.
@@ -247,6 +247,7 @@ export interface GoogleStreamState {
247
247
  finishReason: string | null;
248
248
  usage: Record<string, unknown> | null;
249
249
  }
250
+ /** Adds the shared `input_tokens`/`output_tokens` fields (the only ones the chat usage reducers read) to raw Gemini `usageMetadata` and emits usage. */
250
251
  export declare function applyGoogleUsage({ state, data, onEvent }: {
251
252
  state: GoogleStreamState;
252
253
  data: Record<string, unknown>;
@@ -337,6 +338,8 @@ export declare function executeGoogleToolCalls({ executeTool, calls, onEvent }:
337
338
  * tool-execution loop when `options.executeTool` is supplied and the model
338
339
  * requests a function call. See `anthropic-messages.ts#runAnthropicToolTurn`'s
339
340
  * doc for the shared event-stream/`ended`-flag contract this mirrors.
341
+ * An initial response without text or calls emits an error with its provider finish reason,
342
+ * not a successful stop. Tool-only turns remain valid: the host may already have acted on them.
340
343
  */
341
344
  export declare function runGoogleToolTurn(requiredArgs: Pick<GoogleTurnOptions, "apiKey" | "model" | "contents" | "onEvent">, optionalArgs?: Omit<GoogleTurnOptions, "apiKey" | "model" | "contents" | "onEvent">): Promise<GoogleTurnResult>;
342
345
  export {};
@@ -151,10 +151,20 @@ function extractGoogleErrorDetail(rawText) {
151
151
  }
152
152
  return rawText.trim().slice(0, 500);
153
153
  }
154
+ /** Adds the shared `input_tokens`/`output_tokens` fields (the only ones the chat usage reducers read) to raw Gemini `usageMetadata` and emits usage. */
154
155
  export function applyGoogleUsage({ state, data, onEvent }) {
155
156
  if (!isRecord(data.usageMetadata))
156
157
  return;
157
- state.usage = data.usageMetadata;
158
+ const usage = data.usageMetadata;
159
+ const candidateTokens = typeof usage.candidatesTokenCount === 'number' ? usage.candidatesTokenCount : undefined;
160
+ const thoughtsTokens = typeof usage.thoughtsTokenCount === 'number' ? usage.thoughtsTokenCount : undefined;
161
+ state.usage = {
162
+ ...usage,
163
+ // Thoughts are reported separately from candidates; they count as output, as thinking/reasoning
164
+ // tokens already do inside Anthropic's `output_tokens` and OpenAI's `completion_tokens`.
165
+ ...(typeof usage.promptTokenCount === 'number' ? { input_tokens: usage.promptTokenCount } : {}),
166
+ ...(candidateTokens !== undefined || thoughtsTokens !== undefined ? { output_tokens: (candidateTokens ?? 0) + (thoughtsTokens ?? 0) } : {}),
167
+ };
158
168
  onEvent({ type: 'usage', usage: state.usage });
159
169
  }
160
170
  /** The frame's first candidate, unnarrowed — `processGoogleFrame` distinguishes "no candidate at all" (checks `promptFeedback` for a blocked-prompt error) from "a candidate that isn't a record" (silently skipped), so this deliberately does not collapse both into one `null`. */
@@ -468,6 +478,8 @@ export async function executeGoogleToolCalls({ executeTool, calls, onEvent }) {
468
478
  * tool-execution loop when `options.executeTool` is supplied and the model
469
479
  * requests a function call. See `anthropic-messages.ts#runAnthropicToolTurn`'s
470
480
  * doc for the shared event-stream/`ended`-flag contract this mirrors.
481
+ * An initial response without text or calls emits an error with its provider finish reason,
482
+ * not a successful stop. Tool-only turns remain valid: the host may already have acted on them.
471
483
  */
472
484
  export async function runGoogleToolTurn(requiredArgs, optionalArgs = {}) {
473
485
  const options = { ...optionalArgs, ...requiredArgs };
@@ -483,6 +495,15 @@ export async function runGoogleToolTurn(requiredArgs, optionalArgs = {}) {
483
495
  lastFinishReason = outcome.finishReason;
484
496
  if (endGuard.hasEnded())
485
497
  break;
498
+ if (toolTurns === 0 && outcome.toolCalls.length === 0 && !outcome.text.trim()) {
499
+ // Thinking can consume the entire output budget without producing any answer. Preserve
500
+ // the reason for operator diagnostics rather than turning a content-free response into stop.
501
+ options.onEvent({ type: 'error', message: redactSecrets({
502
+ input: `Google returned no text or tool calls (${outcome.finishReason ?? 'missing finish reason'})`,
503
+ }, { exactSecrets: [options.apiKey] }) });
504
+ emitEnd('error');
505
+ break;
506
+ }
486
507
  const exitReason = googleLoopExitReason({ outcome: outcome, toolTurns: toolTurns, maxToolTurns: maxToolTurns });
487
508
  if (exitReason) {
488
509
  emitEnd(exitReason);
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.11",
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": {
@@ -100,12 +100,12 @@
100
100
  "@vitest/coverage-v8": "^2.1.9",
101
101
  "@jini-ai/core": "^0.4.0",
102
102
  "@jini-ai/integrations": "^0.4.2",
103
- "@jini-ai/platform": "^0.5.6",
103
+ "@jini-ai/platform": "^0.5.7",
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.6"
109
109
  },
110
110
  "peerDependencies": {
111
111
  "@jini-ai/integrations": "^0.4.2",