@jini-ai/agent-runtime 0.6.22 → 0.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/CHANGELOG.md +32 -0
- package/dist/agent-protocol/acp/models.js +1 -1
- package/dist/agent-protocol/acp/session.js +1 -1
- package/dist/agent-protocol/core/json-line-stream.d.ts +10 -20
- package/dist/agent-protocol/core/json-line-stream.js +39 -27
- package/dist/agent-protocol/pi-rpc/session.js +1 -1
- package/dist/auth.js +1 -1
- package/dist/claude-stream.js +8 -19
- package/dist/core/bounded-line-stream.d.ts +17 -0
- package/dist/core/bounded-line-stream.js +49 -0
- package/dist/core/model-discovery-shared.d.ts +25 -1
- package/dist/core/model-discovery-shared.js +47 -0
- package/dist/defs/aider.d.ts +1 -0
- package/dist/defs/aider.js +1 -0
- package/dist/defs/claude.d.ts +1 -0
- package/dist/defs/claude.js +1 -0
- package/dist/defs/codex.js +6 -4
- package/dist/defs/pi.d.ts +1 -0
- package/dist/defs/pi.js +1 -0
- package/dist/defs/shared.d.ts +2 -3
- package/dist/defs/shared.js +2 -23
- package/dist/detection.d.ts +11 -2
- package/dist/detection.js +35 -5
- package/dist/diagnostics.d.ts +16 -1
- package/dist/diagnostics.js +44 -1
- package/dist/json-event-stream.js +8 -14
- package/dist/model-discovery-native.d.ts +1 -0
- package/dist/model-discovery.d.ts +6 -3
- package/dist/model-discovery.js +8 -3
- package/dist/models.js +2 -27
- package/dist/native-tool-policy.d.ts +59 -3
- package/dist/native-tool-policy.js +47 -11
- package/dist/providers/google-messages.d.ts +2 -1
- package/dist/providers/google-messages.js +10 -5
- package/dist/providers/google-schema.js +18 -0
- package/dist/providers/model-catalog.js +8 -4
- package/dist/qoder-stream.js +8 -15
- package/dist/types.d.ts +7 -1
- package/package.json +9 -9
package/dist/detection.d.ts
CHANGED
|
@@ -79,6 +79,7 @@ export interface AgentDetectionModelOptions {
|
|
|
79
79
|
}
|
|
80
80
|
/** Options accepted by {@link detectAgents} and {@link detectAgentsStream}. */
|
|
81
81
|
type DetectAgentsOptions = {
|
|
82
|
+
signal?: AbortSignal;
|
|
82
83
|
state?: AgentRuntimeState;
|
|
83
84
|
env?: NodeJS.ProcessEnv;
|
|
84
85
|
configuredEnvByAgent?: Record<string, Record<string, string>>;
|
|
@@ -88,7 +89,13 @@ type DetectAgentsOptions = {
|
|
|
88
89
|
force?: boolean;
|
|
89
90
|
probeAgent?: AgentDetectionModelOptions['probeAgent'];
|
|
90
91
|
};
|
|
91
|
-
|
|
92
|
+
/** Probe the selected inventory (all agents when omitted), reusing the existing host cache.
|
|
93
|
+
* Cancellation stops waiting, without cancelling a probe another caller may share.
|
|
94
|
+
* @complexity O(registered agents + selected probes); no additional cache or polling.
|
|
95
|
+
*/
|
|
96
|
+
export declare function detectAgents({ agentIds }: {
|
|
97
|
+
agentIds?: readonly string[];
|
|
98
|
+
}, optional?: DetectAgentsOptions): Promise<(Omit<RuntimeAgentDef, "discoverModels" | "resolveDefaultModel" | "buildArgs" | "listModels" | "fetchModels" | "deriveReasoningOptions" | "fallbackModels" | "fallbackModelsAssertedAt" | "helpArgs" | "capabilityFlags" | "fallbackBins" | "versionProbeTimeoutMs" | "maxPromptArgBytes" | "env" | "inactivityTimeoutMs" | "authProbe" | "needsAgentLogFile" | "stdoutPolicy" | "runtimeLock"> & {
|
|
92
99
|
models: RuntimeModelOption[];
|
|
93
100
|
modelsSource: RuntimeModelSource;
|
|
94
101
|
modelCatalog?: ModelCatalogSnapshot;
|
|
@@ -100,6 +107,8 @@ export declare function detectAgents({}: {}, optional?: DetectAgentsOptions): Pr
|
|
|
100
107
|
version?: string | null;
|
|
101
108
|
diagnostics?: AgentDiagnostic[];
|
|
102
109
|
})[]>;
|
|
103
|
-
export declare function detectAgentsStream({}: {
|
|
110
|
+
export declare function detectAgentsStream({ agentIds }: {
|
|
111
|
+
agentIds?: readonly string[];
|
|
112
|
+
}, optional?: DetectAgentsOptions): AsyncGenerator<DetectedAgent>;
|
|
104
113
|
export {};
|
|
105
114
|
//# sourceMappingURL=detection.d.ts.map
|
package/dist/detection.js
CHANGED
|
@@ -402,9 +402,38 @@ async function detectOne(def, { configuredEnvByAgent, amrProfileResolver, modelC
|
|
|
402
402
|
rememberDetectedModelList({ def, configuredEnv, models: agent.models, amrProfileResolver }, { state: base.state, env: base.env });
|
|
403
403
|
return agent;
|
|
404
404
|
}
|
|
405
|
-
|
|
405
|
+
/** Select existing registry entries; an empty or unknown-only list does no work. */
|
|
406
|
+
function selectedDefs(agentIds) {
|
|
407
|
+
if (!agentIds)
|
|
408
|
+
return AGENT_DEFS;
|
|
409
|
+
const selected = new Set(agentIds);
|
|
410
|
+
return AGENT_DEFS.filter(def => selected.has(def.id));
|
|
411
|
+
}
|
|
412
|
+
/** Cancellation detaches this observer; a coalesced probe still serves other callers and the cache. */
|
|
413
|
+
async function observeDetection(pending, signal) {
|
|
414
|
+
if (!signal)
|
|
415
|
+
return pending;
|
|
416
|
+
signal.throwIfAborted();
|
|
417
|
+
let abort;
|
|
418
|
+
const stopped = new Promise((_resolve, reject) => {
|
|
419
|
+
abort = () => reject(signal.reason);
|
|
420
|
+
signal.addEventListener('abort', abort, { once: true });
|
|
421
|
+
});
|
|
422
|
+
try {
|
|
423
|
+
return await Promise.race([pending, stopped]);
|
|
424
|
+
}
|
|
425
|
+
finally {
|
|
426
|
+
signal.removeEventListener('abort', abort);
|
|
427
|
+
}
|
|
428
|
+
}
|
|
429
|
+
/** Probe the selected inventory (all agents when omitted), reusing the existing host cache.
|
|
430
|
+
* Cancellation stops waiting, without cancelling a probe another caller may share.
|
|
431
|
+
* @complexity O(registered agents + selected probes); no additional cache or polling.
|
|
432
|
+
*/
|
|
433
|
+
export async function detectAgents({ agentIds }, optional = {}) {
|
|
434
|
+
optional.signal?.throwIfAborted();
|
|
406
435
|
const settings = detectionSettings(optional);
|
|
407
|
-
return Promise.all(
|
|
436
|
+
return observeDetection(Promise.all(selectedDefs(agentIds).map(def => detectOne(def, settings))), optional.signal);
|
|
408
437
|
}
|
|
409
438
|
// Streaming variant: yields each agent the moment its probe settles, in
|
|
410
439
|
// completion order rather than registry order, so the UI can paint a card
|
|
@@ -412,12 +441,13 @@ export async function detectAgents({}, optional = {}) {
|
|
|
412
441
|
// validation cache is refreshed per-agent (same effect as the batch path,
|
|
413
442
|
// just incrementally). `detectAgents` keeps the array contract for callers
|
|
414
443
|
// that don't care about incremental delivery.
|
|
415
|
-
export async function* detectAgentsStream({}, optional = {}) {
|
|
444
|
+
export async function* detectAgentsStream({ agentIds }, optional = {}) {
|
|
416
445
|
const settings = detectionSettings(optional);
|
|
417
|
-
|
|
446
|
+
optional.signal?.throwIfAborted();
|
|
447
|
+
const tagged = selectedDefs(agentIds).map((def, index) => detectOne(def, settings).then((agent) => ({ index, agent })));
|
|
418
448
|
const pending = new Set(tagged.keys());
|
|
419
449
|
while (pending.size > 0) {
|
|
420
|
-
const { index, agent } = await Promise.race(tagged.filter((_, i) => pending.has(i)));
|
|
450
|
+
const { index, agent } = await observeDetection(Promise.race(tagged.filter((_, i) => pending.has(i))), optional.signal);
|
|
421
451
|
pending.delete(index);
|
|
422
452
|
yield agent;
|
|
423
453
|
}
|
package/dist/diagnostics.d.ts
CHANGED
|
@@ -1,11 +1,26 @@
|
|
|
1
1
|
/**
|
|
2
2
|
* @module diagnostics
|
|
3
|
-
* Explain
|
|
3
|
+
* Explain executable/authentication detection failures and preserve safe startup evidence.
|
|
4
4
|
*/
|
|
5
5
|
import { type ExecutableResolutionOptions } from './executables.js';
|
|
6
6
|
import type { AgentLaunchResolution } from './launch.js';
|
|
7
7
|
import type { AgentAuthProbeResult } from './auth.js';
|
|
8
8
|
import type { AgentDiagnostic, RuntimeAgentDef } from './types.js';
|
|
9
|
+
/** Pasteable startup evidence, redacted before a UTF-8 byte cap is applied. No stack or input
|
|
10
|
+
* envelope is copied; deepest causes come first so a long wrapper cannot hide the cause.
|
|
11
|
+
* @param required Stage owned by the caller and the thrown startup value.
|
|
12
|
+
* @param options Exact host secrets and caller wording for an unconfirmed start response.
|
|
13
|
+
* @returns At most 2 KiB of actionable text; hostile diagnostic getters never escape.
|
|
14
|
+
* @complexity O(n) time/space in the messages read, with at most four causes; no I/O.
|
|
15
|
+
* @example startupFailureMessage({ stage: 'session binding', error }, {});
|
|
16
|
+
*/
|
|
17
|
+
export declare function startupFailureMessage({ stage, error }: {
|
|
18
|
+
stage: string;
|
|
19
|
+
error: unknown;
|
|
20
|
+
}, { exactSecrets, notice }?: {
|
|
21
|
+
exactSecrets?: readonly string[];
|
|
22
|
+
notice?: string;
|
|
23
|
+
}): string;
|
|
9
24
|
export declare function buildExecutableDiagnostic({ def }: {
|
|
10
25
|
def: Pick<RuntimeAgentDef, 'id' | 'name' | 'bin'>;
|
|
11
26
|
}, { configuredEnv, ...options }?: ExecutableResolutionOptions & {
|
package/dist/diagnostics.js
CHANGED
|
@@ -1,8 +1,51 @@
|
|
|
1
1
|
/**
|
|
2
2
|
* @module diagnostics
|
|
3
|
-
* Explain
|
|
3
|
+
* Explain executable/authentication detection failures and preserve safe startup evidence.
|
|
4
4
|
*/
|
|
5
5
|
import { agentBinEnvKey, agentSearchDirs } from './executables.js';
|
|
6
|
+
import { formatErrorForLog } from '@jini-ai/core';
|
|
7
|
+
/** Pasteable startup evidence, redacted before a UTF-8 byte cap is applied. No stack or input
|
|
8
|
+
* envelope is copied; deepest causes come first so a long wrapper cannot hide the cause.
|
|
9
|
+
* @param required Stage owned by the caller and the thrown startup value.
|
|
10
|
+
* @param options Exact host secrets and caller wording for an unconfirmed start response.
|
|
11
|
+
* @returns At most 2 KiB of actionable text; hostile diagnostic getters never escape.
|
|
12
|
+
* @complexity O(n) time/space in the messages read, with at most four causes; no I/O.
|
|
13
|
+
* @example startupFailureMessage({ stage: 'session binding', error }, {});
|
|
14
|
+
*/
|
|
15
|
+
export function startupFailureMessage({ stage, error }, { exactSecrets = [], notice = 'The assistant could not start. Correct the reported cause, then send again.' } = {}) {
|
|
16
|
+
let cause;
|
|
17
|
+
try {
|
|
18
|
+
cause = startupCauseText({ error });
|
|
19
|
+
}
|
|
20
|
+
catch {
|
|
21
|
+
cause = 'The error details could not be read.';
|
|
22
|
+
}
|
|
23
|
+
const safe = formatErrorForLog({ error: `${notice}\nStartup stage: ${stage}\nCause: ${cause}` }, { exactSecrets });
|
|
24
|
+
const bytes = new TextEncoder().encode(safe);
|
|
25
|
+
if (bytes.length <= 2048)
|
|
26
|
+
return safe;
|
|
27
|
+
// Streaming decode drops an incomplete trailing code point rather than inserting U+FFFD.
|
|
28
|
+
return new TextDecoder().decode(bytes.subarray(0, 2045), { stream: true }) + '…';
|
|
29
|
+
}
|
|
30
|
+
/** Bound cause traversal (including cycles); copy diagnostic fields only, never environment data. */
|
|
31
|
+
function startupCauseText({ error }) {
|
|
32
|
+
const parts = [];
|
|
33
|
+
const seen = new Set();
|
|
34
|
+
let current = error;
|
|
35
|
+
while (current != null && !seen.has(current) && parts.length < 4) {
|
|
36
|
+
seen.add(current);
|
|
37
|
+
parts.push(startupErrorPart({ error: current }));
|
|
38
|
+
current = typeof current === 'object' ? current.cause : undefined;
|
|
39
|
+
}
|
|
40
|
+
return parts.reverse().join('\nCaused by: ') || 'No startup cause was supplied.';
|
|
41
|
+
}
|
|
42
|
+
/** Retain plain messages and OS/provider codes without serializing arbitrary object fields. */
|
|
43
|
+
function startupErrorPart({ error }) {
|
|
44
|
+
if (typeof error !== 'object' || error === null)
|
|
45
|
+
return String(error);
|
|
46
|
+
const { message, code } = error;
|
|
47
|
+
return [code, message].filter(value => typeof value === 'string' || typeof value === 'number').join(': ') || 'Startup error without a message';
|
|
48
|
+
}
|
|
6
49
|
// Cap on how many searched dirs we attach to a `not-on-path` diagnostic.
|
|
7
50
|
// The resolver walks PATH + the user-toolchain whitelist, which can run to
|
|
8
51
|
// dozens of entries; the UI only needs enough to make "we looked here"
|
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
/** @module json-event-stream
|
|
2
2
|
* Multi-CLI JSON event parsing with per-handler stream state. */
|
|
3
|
+
import { createBoundedLineStream } from './core/bounded-line-stream.js';
|
|
3
4
|
import { sanitizeUntrustedText } from '@jini-ai/core/text';
|
|
4
5
|
import { handleAntigravityEvent } from './defs/antigravity/event-stream.js';
|
|
5
6
|
function isRecord(value) {
|
|
@@ -947,7 +948,11 @@ const PARSERS_BY_KIND = new Map([
|
|
|
947
948
|
['codex', handleCodexEvent],
|
|
948
949
|
]);
|
|
949
950
|
export function createJsonEventStreamHandler({ kind, onEvent }) {
|
|
950
|
-
|
|
951
|
+
const lines = createBoundedLineStream({
|
|
952
|
+
onLine: line => { const trimmed = line.trim(); if (trimmed)
|
|
953
|
+
handleLine(trimmed); },
|
|
954
|
+
onOverflow: error => onEvent({ type: 'error', message: error.message, raw: '' }),
|
|
955
|
+
});
|
|
951
956
|
const state = {
|
|
952
957
|
antigravity: { textEmitted: false, toolUses: new Set(), toolResults: new Set() },
|
|
953
958
|
cursorTextSoFar: '',
|
|
@@ -978,21 +983,10 @@ export function createJsonEventStreamHandler({ kind, onEvent }) {
|
|
|
978
983
|
onEvent({ type: 'raw', line });
|
|
979
984
|
}
|
|
980
985
|
function feed({ chunk }) {
|
|
981
|
-
|
|
982
|
-
let nl;
|
|
983
|
-
while ((nl = buffer.indexOf('\n')) !== -1) {
|
|
984
|
-
const line = buffer.slice(0, nl).trim();
|
|
985
|
-
buffer = buffer.slice(nl + 1);
|
|
986
|
-
if (!line)
|
|
987
|
-
continue;
|
|
988
|
-
handleLine(line);
|
|
989
|
-
}
|
|
986
|
+
lines.feed({ chunk: chunk });
|
|
990
987
|
}
|
|
991
988
|
function flush() {
|
|
992
|
-
|
|
993
|
-
buffer = '';
|
|
994
|
-
if (rem)
|
|
995
|
-
handleLine(rem);
|
|
989
|
+
lines.flush();
|
|
996
990
|
flushPendingArtifactText(state, onEvent);
|
|
997
991
|
}
|
|
998
992
|
return { feed, flush };
|
|
@@ -7,6 +7,7 @@ export declare function modelDiscoveryForDef(def: ModelDiscoveryDefinition): Age
|
|
|
7
7
|
export declare function resolveModelForLaunch(required: {
|
|
8
8
|
def: ModelDiscoveryDefinition;
|
|
9
9
|
context: ModelDiscoveryContext;
|
|
10
|
+
effort?: string | undefined;
|
|
10
11
|
}, { deps, ...optional }?: {
|
|
11
12
|
deps?: ModelDiscoveryDeps;
|
|
12
13
|
signal?: AbortSignal;
|
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
import type { RuntimeModelOption } from './types.js';
|
|
1
|
+
import type { RuntimeModelOption, RuntimeReasoningOption, RuntimeAgentDef } from './types.js';
|
|
2
2
|
import type { AgentModelDiscoveryPort, AgentDiscoveryConfiguration, DefaultModelResolution, ModelCatalogSnapshot, ModelDiscoveryContext, ModelDiscoveryDeps, ModelDiscoveryProbes } from './model-discovery-types.js';
|
|
3
|
-
export { ModelProbeError, modelIdentityKind, normalizeDiscoveredModels, withModelProbeTimeout } from './core/model-discovery-shared.js';
|
|
3
|
+
export { RuntimeSelectionError, ModelProbeError, modelIdentityKind, normalizeDiscoveredModels, withModelProbeTimeout } from './core/model-discovery-shared.js';
|
|
4
4
|
export type * from './model-discovery-types.js';
|
|
5
5
|
export declare const MODEL_CATALOG_TTL_MS: number;
|
|
6
6
|
export declare const MODEL_NEGATIVE_TTL_MS = 30000;
|
|
@@ -21,16 +21,19 @@ export type ModelDiscoveryDefinition = Partial<AgentModelDiscoveryPort> & {
|
|
|
21
21
|
defaultModelEnvVar?: string;
|
|
22
22
|
supportsCustomModel?: boolean;
|
|
23
23
|
supportsConcreteModelSelection?: boolean;
|
|
24
|
+
reasoningOptions?: RuntimeReasoningOption[];
|
|
25
|
+
reasoningInModelId?: NonNullable<RuntimeAgentDef['reasoningInModelId']>;
|
|
24
26
|
};
|
|
25
27
|
export declare function modelDiscoveryForDef({ def, deps: suppliedDeps }: {
|
|
26
28
|
def: ModelDiscoveryDefinition;
|
|
27
29
|
deps: ModelDiscoveryDeps;
|
|
28
30
|
}, _optional?: Record<string, never>): AgentModelDiscoveryPort;
|
|
29
31
|
/** Resolve against the actual launch scope, pinning the same ID shown by the picker. */
|
|
30
|
-
export declare function resolveModelForLaunch({ def, context, deps }: {
|
|
32
|
+
export declare function resolveModelForLaunch({ def, context, deps, effort }: {
|
|
31
33
|
def: ModelDiscoveryDefinition;
|
|
32
34
|
context: ModelDiscoveryContext;
|
|
33
35
|
deps: ModelDiscoveryDeps;
|
|
36
|
+
effort?: string | undefined;
|
|
34
37
|
}, optional?: {
|
|
35
38
|
signal?: AbortSignal;
|
|
36
39
|
}): Promise<{
|
package/dist/model-discovery.js
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { createHash } from 'node:crypto';
|
|
2
2
|
import { readModelConfiguration } from './model-discovery-config.js';
|
|
3
|
-
import { ModelProbeError, ProbeTimeout, modelIdentityKind, normalizeDiscoveredModels, withModelProbeTimeout } from './core/model-discovery-shared.js';
|
|
4
|
-
export { ModelProbeError, modelIdentityKind, normalizeDiscoveredModels, withModelProbeTimeout } from './core/model-discovery-shared.js';
|
|
3
|
+
import { ModelProbeError, ProbeTimeout, RuntimeSelectionError, validateRuntimeModelSelection, modelIdentityKind, normalizeDiscoveredModels, withModelProbeTimeout } from './core/model-discovery-shared.js';
|
|
4
|
+
export { RuntimeSelectionError, ModelProbeError, modelIdentityKind, normalizeDiscoveredModels, withModelProbeTimeout } from './core/model-discovery-shared.js';
|
|
5
5
|
export const MODEL_CATALOG_TTL_MS = 15 * 60_000;
|
|
6
6
|
export const MODEL_NEGATIVE_TTL_MS = 30_000;
|
|
7
7
|
const MAX_CATALOG_SCOPES = 128;
|
|
@@ -299,7 +299,7 @@ export function modelDiscoveryForDef({ def, deps: suppliedDeps }, _optional = {}
|
|
|
299
299
|
};
|
|
300
300
|
}
|
|
301
301
|
/** Resolve against the actual launch scope, pinning the same ID shown by the picker. */
|
|
302
|
-
export async function resolveModelForLaunch({ def, context, deps }, optional = {}) {
|
|
302
|
+
export async function resolveModelForLaunch({ def, context, deps, effort }, optional = {}) {
|
|
303
303
|
if (def.supportsConcreteModelSelection === false)
|
|
304
304
|
throw new Error('This CLI cannot pin a concrete starting model.');
|
|
305
305
|
const discovery = modelDiscoveryForDef({ def, deps });
|
|
@@ -311,6 +311,11 @@ export async function resolveModelForLaunch({ def, context, deps }, optional = {
|
|
|
311
311
|
: await discovery.resolveDefaultModel({ context, catalog }, { ...optional, deps });
|
|
312
312
|
if (resolution.status !== 'resolved')
|
|
313
313
|
throw new Error(resolution.reason);
|
|
314
|
+
if (effort) {
|
|
315
|
+
const refusal = validateRuntimeModelSelection({ agent: { ...def, models: catalog.models, defaultModelResolution: resolution }, agentId: def.id ?? 'runtime', modelId: resolution.id, effort });
|
|
316
|
+
if (refusal)
|
|
317
|
+
throw new RuntimeSelectionError(refusal);
|
|
318
|
+
}
|
|
314
319
|
return { model: resolution.id, catalog, resolution };
|
|
315
320
|
}
|
|
316
321
|
//# sourceMappingURL=model-discovery.js.map
|
package/dist/models.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { validateRuntimeModelSelection } from './core/model-discovery-shared.js';
|
|
2
2
|
import { defaultRuntimeState } from './runtime-state.js';
|
|
3
3
|
/** Refusal for an agent that cannot take this pick at all, before any model lookup. */
|
|
4
4
|
function agentReadinessRefusal({ agent, agentId, modelId, effort }) {
|
|
@@ -12,31 +12,6 @@ function agentReadinessRefusal({ agent, agentId, modelId, effort }) {
|
|
|
12
12
|
return `Live model catalog for '${agentId}' is unavailable. Rescan the chat picker before choosing a model or effort.`;
|
|
13
13
|
return null;
|
|
14
14
|
}
|
|
15
|
-
/** The concrete id a pick launches: the explicit model, else the resolved default (if any). */
|
|
16
|
-
function selectedModelId({ agent, modelId }) {
|
|
17
|
-
if (modelId && modelId !== 'default')
|
|
18
|
-
return modelId;
|
|
19
|
-
const resolution = agent.defaultModelResolution;
|
|
20
|
-
return resolution?.status === 'resolved' ? resolution.id : undefined;
|
|
21
|
-
}
|
|
22
|
-
/** Refusal for an unknown model, or an effort the selected model does not offer. */
|
|
23
|
-
function modelAndEffortRefusal({ agent, agentId, modelId, effort }) {
|
|
24
|
-
const choices = concreteModelOptions(agent);
|
|
25
|
-
const resolvedId = selectedModelId({ agent, modelId });
|
|
26
|
-
const model = choices.find(candidate => candidate.id === resolvedId);
|
|
27
|
-
if (modelId && modelId !== 'default' && !model)
|
|
28
|
-
return `Unknown model '${modelId}' for '${agentId}'. Available models: ${choices.map(candidate => candidate.id).join(', ')}.`;
|
|
29
|
-
if (!effort)
|
|
30
|
-
return null;
|
|
31
|
-
// Default must resolve before checking model-specific effort; agent-wide levels can differ.
|
|
32
|
-
if (!model)
|
|
33
|
-
return `Default model for '${agentId}' is unresolved. Pick a concrete model before choosing effort.`;
|
|
34
|
-
// Suffix-based runtimes own effort in the model id; a second effort setting would disagree.
|
|
35
|
-
const levels = agent.reasoningInModelId ? [] : model.reasoning ?? agent.reasoningOptions ?? [];
|
|
36
|
-
if (!levels.some(candidate => candidate.id === effort))
|
|
37
|
-
return `Unknown effort '${effort}' for '${agentId}'. Available effort levels: ${levels.map(candidate => candidate.id).join(', ')} (empty means Default).`;
|
|
38
|
-
return null;
|
|
39
|
-
}
|
|
40
15
|
/** Validate an explicit selection against the same discovered inventory the picker displays.
|
|
41
16
|
* Empty model/effort means the runtime default. Refusals include the current choices rather
|
|
42
17
|
* than silently substituting a different model. Pure; O(agents + models + effort options).
|
|
@@ -47,7 +22,7 @@ export function validateRuntimeSelection({ agents, agentId, modelId, effort }, _
|
|
|
47
22
|
if (!agent)
|
|
48
23
|
return `Unknown or unavailable agent '${agentId}'. Available agents: ${agents.filter(candidate => candidate.available).map(candidate => candidate.id).join(', ')}.`;
|
|
49
24
|
const request = { agent, agentId, modelId, effort };
|
|
50
|
-
return agentReadinessRefusal(request) ??
|
|
25
|
+
return agentReadinessRefusal(request) ?? validateRuntimeModelSelection(request);
|
|
51
26
|
}
|
|
52
27
|
export const DEFAULT_MODEL_OPTION = {
|
|
53
28
|
id: 'default',
|
|
@@ -33,10 +33,10 @@ export interface NativeToolPolicyInput {
|
|
|
33
33
|
cliParity?: boolean;
|
|
34
34
|
permissionMode?: 'bypass' | 'restricted';
|
|
35
35
|
}
|
|
36
|
-
/**
|
|
37
|
-
*
|
|
36
|
+
/** Resolve without granting authority: runtimes requiring full access need explicit host consent.
|
|
37
|
+
* Pure O(1); a definition is never an authorization decision.
|
|
38
38
|
*/
|
|
39
|
-
export declare function resolveNativeToolPolicy({
|
|
39
|
+
export declare function resolveNativeToolPolicy({ policy }: {
|
|
40
40
|
def: {
|
|
41
41
|
name?: string;
|
|
42
42
|
fullCliAccessOnly?: boolean;
|
|
@@ -54,4 +54,60 @@ export declare function assessNativeToolPolicy({ def, policy }: {
|
|
|
54
54
|
};
|
|
55
55
|
policy: NativeToolPolicyInput;
|
|
56
56
|
}, _options?: Record<string, never>): string | null;
|
|
57
|
+
/** Consent keys are the existing master switch and independently stored native capabilities. */
|
|
58
|
+
export type RunConsentKey = 'enabled' | keyof NativeCapabilities;
|
|
59
|
+
export type RunPlan = {
|
|
60
|
+
verdict: 'RUN';
|
|
61
|
+
loadsOwn: boolean;
|
|
62
|
+
bridged: boolean;
|
|
63
|
+
} | {
|
|
64
|
+
verdict: 'ASK';
|
|
65
|
+
keys: RunConsentKey[];
|
|
66
|
+
why?: 'isolation_blocked';
|
|
67
|
+
} | {
|
|
68
|
+
verdict: 'SETUP';
|
|
69
|
+
reason: 'not_installed' | 'not_signed_in' | 'host_locked';
|
|
70
|
+
keys?: RunConsentKey[];
|
|
71
|
+
lock?: string;
|
|
72
|
+
};
|
|
73
|
+
type PlanningDef = {
|
|
74
|
+
name: string;
|
|
75
|
+
supportsNativeToolAccess?: boolean;
|
|
76
|
+
mcpIsolation?: 'none' | 'no-client' | {
|
|
77
|
+
readonly perRun: string;
|
|
78
|
+
};
|
|
79
|
+
externalMcpInjection?: string;
|
|
80
|
+
mcpHttp?: boolean;
|
|
81
|
+
};
|
|
82
|
+
export interface RunPlanHost {
|
|
83
|
+
installed?: boolean;
|
|
84
|
+
auth?: 'ok' | 'missing' | 'unknown';
|
|
85
|
+
locked?: string;
|
|
86
|
+
isolationBlocked?: boolean;
|
|
87
|
+
}
|
|
88
|
+
/** Pure launch decision, before credentials, config repair or spawn. Unknown auth proceeds;
|
|
89
|
+
* unknown isolation requires consent. Fixed capability work, no filesystem or credential reads.
|
|
90
|
+
*/
|
|
91
|
+
export declare function planRun({ def, policy, host }: {
|
|
92
|
+
def: PlanningDef;
|
|
93
|
+
policy: NativeToolPolicyInput;
|
|
94
|
+
host?: RunPlanHost;
|
|
95
|
+
}, _optional?: Record<string, never>): RunPlan;
|
|
96
|
+
/** Shared consumer contract for a fresh local owner: provided tools stay available;
|
|
97
|
+
* the agent's personal MCP sources require an explicit grant. No persisted settings or I/O.
|
|
98
|
+
*/
|
|
99
|
+
export declare const LOCAL_HOST_DEFAULT_PERMISSIONS: Readonly<{
|
|
100
|
+
enabled: true;
|
|
101
|
+
capabilities: Readonly<{
|
|
102
|
+
shell: true;
|
|
103
|
+
fileWrite: true;
|
|
104
|
+
userMcp: false;
|
|
105
|
+
subagents: true;
|
|
106
|
+
userSettings: true;
|
|
107
|
+
web: true;
|
|
108
|
+
workflows: true;
|
|
109
|
+
loginEnvironment: true;
|
|
110
|
+
}>;
|
|
111
|
+
}>;
|
|
112
|
+
export {};
|
|
57
113
|
//# sourceMappingURL=native-tool-policy.d.ts.map
|
|
@@ -33,15 +33,11 @@ export function resolveNativeToolDenies(required, _optional = {}) {
|
|
|
33
33
|
return denied.filter(tool => !NATIVE_FALLBACK_TOOLS.includes(tool));
|
|
34
34
|
return [...new Set([...denied, ...NATIVE_FALLBACK_TOOLS])];
|
|
35
35
|
}
|
|
36
|
-
/**
|
|
37
|
-
*
|
|
36
|
+
/** Resolve without granting authority: runtimes requiring full access need explicit host consent.
|
|
37
|
+
* Pure O(1); a definition is never an authorization decision.
|
|
38
38
|
*/
|
|
39
|
-
export function resolveNativeToolPolicy({
|
|
40
|
-
|
|
41
|
-
return policy;
|
|
42
|
-
return { ...policy, nativeToolAccess: true, cliParity: true, permissionMode: 'bypass',
|
|
43
|
-
nativeCapabilities: { shell: true, fileWrite: true, userMcp: true, subagents: true,
|
|
44
|
-
userSettings: true, web: true, workflows: true, loginEnvironment: true } };
|
|
39
|
+
export function resolveNativeToolPolicy({ policy }, _options = {}) {
|
|
40
|
+
return policy;
|
|
45
41
|
}
|
|
46
42
|
/** Switch names a person sees for each native capability (the host's settings use the same words). */
|
|
47
43
|
const NATIVE_CAPABILITY_LABELS = {
|
|
@@ -58,14 +54,12 @@ function nativeToolPolicyRefusal({ cliName, offSwitches }, _options = {}) {
|
|
|
58
54
|
const blocked = switches.length > 0 ? `with ${new Intl.ListFormat('en', { type: 'conjunction' }).format(switches)} off` : `with this chat's CLI tool limits`;
|
|
59
55
|
const pronoun = switches.length === 1 ? 'it' : 'them';
|
|
60
56
|
const action = switches.length === 0 ? `Turn on 'Full CLI access'` : `Turn ${pronoun} on`;
|
|
61
|
-
return `${cliName} can't run ${blocked}. ${action} in
|
|
57
|
+
return `${cliName} can't run ${blocked}. ${action} in gear → More settings → Agent permissions, or choose an available agent that supports these limits.`;
|
|
62
58
|
}
|
|
63
59
|
/** The same fail-closed assessment at selection and spawn; no CLI-name allowlist.
|
|
64
60
|
* Unknown explicit OFF switches stay blocked. O(c) over declared limits, without effects.
|
|
65
61
|
*/
|
|
66
62
|
export function assessNativeToolPolicy({ def, policy }, _options = {}) {
|
|
67
|
-
if (def.fullCliAccessOnly)
|
|
68
|
-
return null;
|
|
69
63
|
if (def.supportsNativeToolAccess === true)
|
|
70
64
|
return null;
|
|
71
65
|
const parity = policy.cliParity === true && policy.permissionMode === 'bypass' && policy.nativeToolAccess !== false;
|
|
@@ -75,4 +69,46 @@ export function assessNativeToolPolicy({ def, policy }, _options = {}) {
|
|
|
75
69
|
}
|
|
76
70
|
return null;
|
|
77
71
|
}
|
|
72
|
+
function loadsOwnSources(def, policy, blocked) {
|
|
73
|
+
const isolation = blocked ? 'none' : def.mcpIsolation;
|
|
74
|
+
if (isolation === 'no-client')
|
|
75
|
+
return false;
|
|
76
|
+
if (typeof isolation === 'object' && typeof isolation.perRun === 'string' && isolation.perRun.length > 0) {
|
|
77
|
+
return policy.nativeCapabilities?.userMcp === true;
|
|
78
|
+
}
|
|
79
|
+
return true;
|
|
80
|
+
}
|
|
81
|
+
function consentKeys(def, policy, loadsOwn) {
|
|
82
|
+
const keys = def.supportsNativeToolAccess === true ? [] :
|
|
83
|
+
Object.entries(policy.nativeCapabilities ?? {}).filter(([key, value]) => key !== 'userMcp' && value === false).map(([key]) => key);
|
|
84
|
+
if (def.supportsNativeToolAccess !== true && policy.nativeToolAccess === false)
|
|
85
|
+
keys.unshift('enabled');
|
|
86
|
+
if (loadsOwn && policy.nativeCapabilities?.userMcp !== true)
|
|
87
|
+
keys.push('userMcp');
|
|
88
|
+
return keys;
|
|
89
|
+
}
|
|
90
|
+
/** Pure launch decision, before credentials, config repair or spawn. Unknown auth proceeds;
|
|
91
|
+
* unknown isolation requires consent. Fixed capability work, no filesystem or credential reads.
|
|
92
|
+
*/
|
|
93
|
+
export function planRun({ def, policy, host = {} }, _optional = {}) {
|
|
94
|
+
if (host.installed === false)
|
|
95
|
+
return { verdict: 'SETUP', reason: 'not_installed' };
|
|
96
|
+
if (host.auth === 'missing')
|
|
97
|
+
return { verdict: 'SETUP', reason: 'not_signed_in' };
|
|
98
|
+
const loadsOwn = loadsOwnSources(def, policy, host.isolationBlocked === true);
|
|
99
|
+
const keys = consentKeys(def, policy, loadsOwn);
|
|
100
|
+
if (keys.length > 0 && host.locked)
|
|
101
|
+
return { verdict: 'SETUP', reason: 'host_locked', keys, lock: host.locked };
|
|
102
|
+
if (keys.length > 0)
|
|
103
|
+
return { verdict: 'ASK', keys, ...(host.isolationBlocked ? { why: 'isolation_blocked' } : {}) };
|
|
104
|
+
return { verdict: 'RUN', loadsOwn, bridged: Boolean(def.externalMcpInjection || def.mcpHttp) };
|
|
105
|
+
}
|
|
106
|
+
/** Shared consumer contract for a fresh local owner: provided tools stay available;
|
|
107
|
+
* the agent's personal MCP sources require an explicit grant. No persisted settings or I/O.
|
|
108
|
+
*/
|
|
109
|
+
export const LOCAL_HOST_DEFAULT_PERMISSIONS = Object.freeze({
|
|
110
|
+
enabled: true,
|
|
111
|
+
capabilities: Object.freeze({ shell: true, fileWrite: true, userMcp: false, subagents: true,
|
|
112
|
+
userSettings: true, web: true, workflows: true, loginEnvironment: true }),
|
|
113
|
+
});
|
|
78
114
|
//# sourceMappingURL=native-tool-policy.js.map
|
|
@@ -343,7 +343,8 @@ export declare function executeGoogleToolCalls({ executeTool, calls, onEvent }:
|
|
|
343
343
|
* requests a function call. See `anthropic-messages.ts#runAnthropicToolTurn`'s
|
|
344
344
|
* doc for the shared event-stream/`ended`-flag contract this mirrors.
|
|
345
345
|
* An initial response without text or calls emits an error with its provider finish reason,
|
|
346
|
-
* not a successful stop.
|
|
346
|
+
* not a successful stop. So does a later empty response with a reason other than STOP. Tool-only
|
|
347
|
+
* turns ending in STOP remain valid: the host may already have acted on them.
|
|
347
348
|
*/
|
|
348
349
|
export declare function runGoogleToolTurn(requiredArgs: Pick<GoogleTurnOptions, "apiKey" | "model" | "contents" | "onEvent">, optionalArgs?: Omit<GoogleTurnOptions, "apiKey" | "model" | "contents" | "onEvent">): Promise<GoogleTurnResult>;
|
|
349
350
|
export {};
|
|
@@ -497,8 +497,12 @@ export async function executeGoogleToolCalls({ executeTool, calls, onEvent }) {
|
|
|
497
497
|
}
|
|
498
498
|
return { functionResponseParts, followUpParts };
|
|
499
499
|
}
|
|
500
|
-
|
|
501
|
-
|
|
500
|
+
/** A content-free response fails on the first request; after tools, only with a provider reason
|
|
501
|
+
* other than STOP, because a STOP there can be a valid tool-only turn. O(text) for the trim; no effects. */
|
|
502
|
+
function isFailedEmptyGoogleTurn({ toolTurns, outcome }, _options = {}) {
|
|
503
|
+
if (outcome.toolCalls.length > 0 || outcome.text.trim())
|
|
504
|
+
return false;
|
|
505
|
+
return toolTurns === 0 || (outcome.finishReason !== null && outcome.finishReason !== 'STOP');
|
|
502
506
|
}
|
|
503
507
|
/**
|
|
504
508
|
* Runs a full Gemini `streamGenerateContent` turn, including the
|
|
@@ -506,7 +510,8 @@ function isEmptyInitialGoogleTurn({ toolTurns, outcome }, _options = {}) {
|
|
|
506
510
|
* requests a function call. See `anthropic-messages.ts#runAnthropicToolTurn`'s
|
|
507
511
|
* doc for the shared event-stream/`ended`-flag contract this mirrors.
|
|
508
512
|
* An initial response without text or calls emits an error with its provider finish reason,
|
|
509
|
-
* not a successful stop.
|
|
513
|
+
* not a successful stop. So does a later empty response with a reason other than STOP. Tool-only
|
|
514
|
+
* turns ending in STOP remain valid: the host may already have acted on them.
|
|
510
515
|
*/
|
|
511
516
|
export async function runGoogleToolTurn(requiredArgs, optionalArgs = {}) {
|
|
512
517
|
const options = { ...optionalArgs, ...requiredArgs };
|
|
@@ -518,9 +523,9 @@ export async function runGoogleToolTurn(requiredArgs, optionalArgs = {}) {
|
|
|
518
523
|
let contents = options.contents.slice();
|
|
519
524
|
let toolTurns = 0;
|
|
520
525
|
let lastFinishReason = null;
|
|
521
|
-
/** `'error'` (after reporting it) for a content-free
|
|
526
|
+
/** `'error'` (after reporting it) for a failed content-free turn, else the regular loop exit reason. */
|
|
522
527
|
const turnExitReason = (outcome, turns) => {
|
|
523
|
-
if (!
|
|
528
|
+
if (!isFailedEmptyGoogleTurn({ toolTurns: turns, outcome })) {
|
|
524
529
|
return googleLoopExitReason({ outcome: outcome, toolTurns: turns, maxToolTurns: maxToolTurns });
|
|
525
530
|
}
|
|
526
531
|
// Thinking can consume the entire output budget without producing any answer. Preserve
|
|
@@ -62,6 +62,12 @@ function enforceGoogleSchemaShape(node) {
|
|
|
62
62
|
if (node.type === "array" && !isRecord(node.items)) {
|
|
63
63
|
node.items = { type: "string", description: "Contents simplified for Gemini compatibility." };
|
|
64
64
|
}
|
|
65
|
+
// Gemini 400s the whole request on array keywords outside an array, which a collapsed union leaves behind.
|
|
66
|
+
if (typeof node.type === "string" && node.type !== "array") {
|
|
67
|
+
delete node.items;
|
|
68
|
+
delete node.minItems;
|
|
69
|
+
delete node.maxItems;
|
|
70
|
+
}
|
|
65
71
|
return node;
|
|
66
72
|
}
|
|
67
73
|
function isGoogleIgnoredSchemaKey(key) {
|
|
@@ -158,6 +164,17 @@ function applyGoogleNumericEnumStringification(schema, result) {
|
|
|
158
164
|
result.enum = schema.enum.map((member) => String(member));
|
|
159
165
|
result.type = "string";
|
|
160
166
|
}
|
|
167
|
+
/** Gemini accepts string enums only. Keep native scalar types and describe unsupported literal
|
|
168
|
+
* constraints; the original host schema still validates the returned input.
|
|
169
|
+
* @complexity O(e) time and space for the existing enum's e serialized values. */
|
|
170
|
+
function applyGoogleLiteralGuidance(result) {
|
|
171
|
+
const values = result.enum;
|
|
172
|
+
if (!Array.isArray(values) || values.every(member => typeof member === "string"))
|
|
173
|
+
return;
|
|
174
|
+
const description = typeof result.description === "string" ? `${result.description} ` : "";
|
|
175
|
+
result.description = `${description}Allowed values: ${values.map(member => JSON.stringify(member)).join(", ")}.`;
|
|
176
|
+
delete result.enum;
|
|
177
|
+
}
|
|
161
178
|
function applyGoogleConstTypeInference(result, hasConst, constValue) {
|
|
162
179
|
if (!hasConst || result.type !== undefined)
|
|
163
180
|
return;
|
|
@@ -176,6 +193,7 @@ function sanitizeGoogleSchemaValue(schema, defs = {}, remainingRefDepth = MAX_GO
|
|
|
176
193
|
result.nullable = true;
|
|
177
194
|
applyGoogleConstTypeInference(result, hasConst, constValue);
|
|
178
195
|
applyGoogleNumericEnumStringification(schema, result);
|
|
196
|
+
applyGoogleLiteralGuidance(result);
|
|
179
197
|
return result;
|
|
180
198
|
}
|
|
181
199
|
function sanitizeGoogleSubschema(value, defs, depth) {
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { redactSecrets } from '@jini-ai/core';
|
|
2
|
-
import { defaultDnsLookup, validateBaseUrlResolved } from './connection-guard.js';
|
|
2
|
+
import { defaultDnsLookup, validateBaseUrl, validateBaseUrlResolved } from './connection-guard.js';
|
|
3
3
|
import { aihubmixCatalogUrl, aihubmixHeaders, parseAIHubMixCatalog } from './aihubmix.js';
|
|
4
4
|
import { googleProviderModelsUrl, normalizeGoogleModelId } from './google.js';
|
|
5
5
|
import { trimCharsEnd } from '@jini-ai/core/text';
|
|
@@ -294,7 +294,7 @@ export async function listProviderModels(requiredArgs, optionalArgs = {}) {
|
|
|
294
294
|
}
|
|
295
295
|
return result;
|
|
296
296
|
}
|
|
297
|
-
async function modelCatalogPreflight({ input, start }
|
|
297
|
+
async function modelCatalogPreflight({ input, start }) {
|
|
298
298
|
if (input.protocol === 'azure') {
|
|
299
299
|
return {
|
|
300
300
|
ok: false,
|
|
@@ -303,7 +303,11 @@ async function modelCatalogPreflight({ input, start }, _options = {}) {
|
|
|
303
303
|
detail: 'Azure OpenAI deployment discovery is not supported from the inference endpoint.',
|
|
304
304
|
};
|
|
305
305
|
}
|
|
306
|
-
const
|
|
306
|
+
const missingKey = PROTOCOLS_REQUIRING_API_KEY.has(input.protocol) && !input.apiKey.trim();
|
|
307
|
+
// Preserve syntax/host refusals, but a missing credential needs no DNS lookup that could mask it.
|
|
308
|
+
// Requests that can proceed, including anonymous public catalogs, retain resolved SSRF checks.
|
|
309
|
+
const validated = missingKey ? validateBaseUrl({ baseUrl: input.baseUrl })
|
|
310
|
+
: await validateBaseUrlResolved({ baseUrl: input.baseUrl, lookup: input.dnsLookup ?? defaultDnsLookup });
|
|
307
311
|
if (validated.error || !validated.parsed) {
|
|
308
312
|
return {
|
|
309
313
|
ok: false,
|
|
@@ -327,7 +331,7 @@ async function modelCatalogPreflight({ input, start }, _options = {}) {
|
|
|
327
331
|
detail: 'AWS Bedrock uses a static seed until AWS credential-backed discovery is available.',
|
|
328
332
|
};
|
|
329
333
|
}
|
|
330
|
-
if (
|
|
334
|
+
if (missingKey) {
|
|
331
335
|
return missingApiKeyResponse(start);
|
|
332
336
|
}
|
|
333
337
|
return undefined;
|