@inneranimalmedia/agentsam-sdk 2.5.0 → 2.6.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/AGENTSAM.md +55 -0
- package/README.md +12 -8
- package/bin/agentsam +2 -0
- package/docs/AGENTSAM_ASTRA_OPENAI_INTEGRATION.md +1363 -0
- package/docs/CLI_SHELL.md +163 -53
- package/docs/PLATFORM_RUNTIME_EVENTS.md +48 -0
- package/docs/RELEASES.md +16 -7
- package/docs/SOURCE_ARCHITECTURE.md +58 -0
- package/docs/TEST_TIERS.md +26 -0
- package/migrations/runtime/0001_cli_runtime.sql +298 -0
- package/package.json +45 -12
- package/packages/agentsam-repository/README.md +15 -0
- package/packages/agentsam-repository/package.json +25 -0
- package/packages/agentsam-repository/src/contracts.js +113 -0
- package/packages/agentsam-repository/src/index.js +3 -0
- package/{src/lib → packages/agentsam-repository/src}/merkle/cloudflare-persistence.js +14 -24
- package/{src/lib → packages/agentsam-repository/src}/merkle/index.js +1 -0
- package/{src/lib → packages/agentsam-repository/src}/merkle/persistence.js +6 -4
- package/{src/lib → packages/agentsam-repository/src}/merkle/policy.js +1 -0
- package/packages/agentsam-repository/test/contracts.test.mjs +40 -0
- package/packages/agentsam-repository/test/git-context.test.mjs +24 -0
- package/{test/merkle.test.mjs → packages/agentsam-repository/test/merkle-core.test.mjs} +2 -32
- package/{test → packages/agentsam-repository/test}/merkle-persistence.test.mjs +11 -6
- package/packages/connectors/cloudflare/package.json +10 -0
- package/packages/connectors/cloudflare/src/index.js +127 -0
- package/packages/connectors/cloudflare/src/owner.js +76 -0
- package/packages/connectors/cloudflare/src/routes.js +223 -0
- package/packages/connectors/cloudflare/src/vault.js +80 -0
- package/packages/connectors/cloudflare/tests/connector.test.mjs +44 -0
- package/packages/identity/package.json +2 -2
- package/packages/identity/src/contracts/auth-config.js +18 -7
- package/packages/identity/tests/auth-config.test.mjs +9 -5
- package/packages/identity/tests/oauth-credentials.test.mjs +4 -4
- package/protocol/COMPANY_REPOSITORY_GRAPH_V1.md +91 -0
- package/protocol/MERKLE_PERSISTENCE_V1.md +2 -0
- package/protocol/MERKLE_PERSISTENCE_V2.md +40 -0
- package/protocol/README.md +1 -0
- package/protocol/capabilities/cloudflare-cpu-audit-input.schema.json +19 -0
- package/protocol/capabilities/cloudflare-cpu-profile-input.schema.json +13 -0
- package/protocol/capabilities/cloudflare-wrangler-native-input.schema.json +19 -0
- package/protocol/capabilities/manifest.json +47 -0
- package/protocol/context/context-budget.schema.json +10 -15
- package/protocol/context/context-item.schema.json +4 -5
- package/protocol/context/resolved-context-pack.schema.json +19 -14
- package/protocol/models/README.md +373 -0
- package/protocol/models/model-inventory-v2.schema.json +212 -0
- package/protocol/repository/repository-contract.schema.json +24 -0
- package/protocol/repository/repository-dependency.schema.json +24 -0
- package/protocol/repository/repository-identity.schema.json +17 -0
- package/protocol/rpc/v1/common.proto +16 -0
- package/protocol/rpc/v1/errors.proto +35 -0
- package/protocol/rpc/v1/knowledge.proto +77 -0
- package/services/knowledge/package-lock.json +333 -0
- package/services/knowledge/package.json +5 -1
- package/skills/agentsam-cloudflare-workers/SKILL.md +53 -0
- package/skills/agentsam-cloudflare-workers/references/cpu-profiling.md +16 -0
- package/skills/agentsam-cloudflare-workers/references/errors-and-observability.md +29 -0
- package/skills/agentsam-cloudflare-workers/references/wrangler-native-map.md +28 -0
- package/skills/catalog.json +18 -0
- package/src/agent/capability-adapter.js +25 -13
- package/src/agent/index.js +1 -0
- package/src/agent/responses-runner.js +353 -0
- package/src/capabilities/repository-snapshot.js +3 -3
- package/src/cli.js +118 -31
- package/src/cloudflare/cpu-profile.js +115 -0
- package/src/cloudflare/index.js +14 -0
- package/src/cloudflare/wrangler.js +132 -0
- package/src/commands/account-auth.js +47 -0
- package/src/commands/cloudflare.js +58 -0
- package/src/commands/connections.js +93 -0
- package/src/commands/context-economics.js +129 -0
- package/src/commands/context.js +1 -1
- package/src/commands/db.js +20 -3
- package/src/commands/deploy.js +39 -3
- package/src/commands/env.js +90 -0
- package/src/commands/eval.js +63 -0
- package/src/commands/interactive.js +2 -5
- package/src/commands/knowledge.js +12 -4
- package/src/commands/merkle-persist.js +30 -11
- package/src/commands/merkle.js +1 -1
- package/src/commands/models.js +149 -46
- package/src/commands/ollama.js +26 -0
- package/src/commands/preferences.js +130 -61
- package/src/commands/resume.js +67 -0
- package/src/commands/security.js +5 -3
- package/src/commands/shell.js +568 -119
- package/src/commands/tunnel.js +2 -2
- package/src/commands/whoami.js +86 -0
- package/src/context/budget.js +68 -6
- package/src/context/index.js +3 -1
- package/src/context/rehydrate.js +35 -0
- package/src/context/resolve.js +44 -12
- package/src/errors/contract.js +236 -0
- package/src/errors/diagnostic.js +160 -0
- package/src/errors/index.js +23 -0
- package/src/eval/context.js +191 -0
- package/src/eval/index.js +1 -0
- package/src/index.js +68 -2
- package/src/knowledge/service/auth.js +13 -0
- package/src/knowledge/service/grpc-client.js +115 -0
- package/src/knowledge/service/grpc-codec.js +237 -0
- package/src/knowledge/service/grpc-server.js +83 -0
- package/src/knowledge/service/job-engine.js +248 -0
- package/src/knowledge/service/server.js +87 -135
- package/src/knowledge/source.js +1 -1
- package/src/lib/account-session.js +98 -0
- package/src/lib/agent-instructions.js +73 -0
- package/src/lib/auth.js +4 -0
- package/src/lib/cli-preferences.js +55 -24
- package/src/lib/deploy/git-guard.js +69 -0
- package/src/lib/deploy/health.js +57 -0
- package/src/lib/deploy/local-studio.js +283 -0
- package/src/lib/deploy/secret-scan.js +65 -0
- package/src/lib/deploy-receipt/index.js +2 -2
- package/src/lib/detect-context.js +2 -2
- package/src/lib/execution-approvals.js +59 -0
- package/src/lib/knowledge-docker.js +6 -3
- package/src/lib/local-sessions.js +148 -0
- package/src/lib/local-status.js +1 -1
- package/src/lib/project-config.js +1 -1
- package/src/lib/provider-credentials.js +183 -0
- package/src/lib/scaffold/templates/worker-api/index.js +101 -20
- package/src/lib/scaffold/wizards/worker-api.js +27 -11
- package/src/lib/slash-commands.js +23 -16
- package/src/local/migrations.js +93 -0
- package/src/local/runtime-store.js +141 -0
- package/src/local/sqlite.js +2 -0
- package/src/local-pty/server.js +113 -51
- package/src/models/catalog.js +135 -0
- package/src/models/discovery.js +292 -0
- package/src/models/index.js +7 -0
- package/src/providers/anthropic-messages.js +192 -0
- package/src/providers/cloudflare-chat.js +183 -0
- package/src/providers/factory.js +69 -0
- package/src/providers/gemini-generate-content.js +208 -0
- package/src/providers/index.js +10 -0
- package/src/providers/ollama-chat.js +148 -0
- package/src/providers/openai-responses.js +426 -0
- package/src/repository/index.js +14 -2
- package/src/rpc/generated/common_grpc_pb.js +1 -0
- package/src/rpc/generated/common_pb.js +536 -0
- package/src/rpc/generated/errors_grpc_pb.js +1 -0
- package/src/rpc/generated/errors_pb.js +482 -0
- package/src/rpc/generated/knowledge_grpc_pb.js +135 -0
- package/src/rpc/generated/knowledge_pb.js +2168 -0
- package/src/rpc/generated/package.json +3 -0
- package/src/security/process.js +35 -9
- package/src/security/trust-boundary.js +2 -2
- package/src/telemetry/contracts.js +203 -0
- package/src/telemetry/events.js +51 -0
- package/src/telemetry/index.js +8 -0
- package/src/tools/hydrate.js +35 -0
- package/src/tools/index.js +1 -0
- package/src/ui/boot.js +15 -17
- package/src/ui/cli/activity.js +76 -0
- package/src/ui/cli/compaction.js +15 -0
- package/src/ui/cli/footer.js +39 -0
- package/src/ui/cli/help.js +192 -0
- package/src/ui/cli/plan.js +20 -0
- package/src/ui/cli/runtime-events.js +110 -0
- package/src/ui/cli/waiting.js +16 -0
- package/src/ui/merkle/render.js +1 -1
- package/test/account-session.test.mjs +36 -0
- package/test/cli/preferences-runtime.test.mjs +11 -0
- package/test/cli/runtime-ui.test.mjs +74 -0
- package/test/cli-preferences.test.mjs +26 -5
- package/test/cloudflare-connector.test.mjs +96 -0
- package/test/cloudflare-runtime.test.mjs +75 -0
- package/test/context.test.mjs +61 -12
- package/test/deploy-health-scan.test.mjs +67 -0
- package/test/error-diagnostics.test.mjs +115 -0
- package/test/eval-context.test.mjs +37 -0
- package/test/execution-approvals.test.mjs +27 -0
- package/test/fixtures/knowledge-rpc-worker.mjs +16 -0
- package/test/integration/cli-help.test.mjs +37 -0
- package/test/integration/knowledge-rpc.test.mjs +112 -0
- package/test/integration/merkle-cli.test.mjs +61 -0
- package/test/integration/merkle-persistence-identity.test.mjs +48 -0
- package/test/integration/provider-env-cli.test.mjs +49 -0
- package/test/integration/provider-factory.test.mjs +197 -0
- package/test/integration/repository-company-graph.test.mjs +90 -0
- package/test/integration/runtime-migrations.test.mjs +82 -0
- package/test/knowledge-service.test.mjs +5 -0
- package/test/knowledge.test.mjs +16 -0
- package/test/live/terminal-transport.live.test.mjs +24 -0
- package/test/local-sessions.test.mjs +48 -0
- package/test/local-studio-deploy.test.mjs +83 -0
- package/test/model-catalog.test.mjs +43 -0
- package/test/models.test.mjs +127 -16
- package/test/npm10-lock.test.mjs +29 -0
- package/test/ollama.test.mjs +21 -0
- package/test/openai-responses.test.mjs +95 -0
- package/test/portable-context.test.mjs +1 -1
- package/test/provider-credentials.test.mjs +96 -0
- package/test/rehydrate.test.mjs +25 -0
- package/test/release-hygiene.test.mjs +13 -5
- package/test/responses-runner.test.mjs +150 -0
- package/test/shell.test.mjs +92 -23
- package/test/smoke.mjs +4 -1
- package/test/telemetry.test.mjs +79 -0
- package/test/terminal/local-pty.mock.test.mjs +151 -0
- package/test/tools-search.test.mjs +14 -1
- package/test/whoami-resume.test.mjs +56 -0
- /package/{src/lib → packages/agentsam-repository/src}/git-context.js +0 -0
- /package/{src/lib → packages/agentsam-repository/src}/merkle/diff.js +0 -0
- /package/{src/lib → packages/agentsam-repository/src}/merkle/filemeta.js +0 -0
- /package/{src/lib → packages/agentsam-repository/src}/merkle/git-ignore.js +0 -0
- /package/{src/lib → packages/agentsam-repository/src}/merkle/hash.js +0 -0
- /package/{src/lib → packages/agentsam-repository/src}/merkle/semantic.js +0 -0
- /package/{src/lib → packages/agentsam-repository/src}/merkle/snapshot.js +0 -0
- /package/{src/lib → packages/agentsam-repository/src}/merkle/tree.js +0 -0
|
@@ -0,0 +1,353 @@
|
|
|
1
|
+
import { createHash } from 'node:crypto';
|
|
2
|
+
import path from 'node:path';
|
|
3
|
+
import { assessContextUsage, compileAgentInstructions, createContextBudget, estimateContextTokens, truncateResultText } from '../context/index.js';
|
|
4
|
+
import { getModelRecord, calculateModelCost } from '../models/index.js';
|
|
5
|
+
import { searchToolCards, hydrateToolSchemas } from '../tools/index.js';
|
|
6
|
+
import { createAgentEvent } from '../telemetry/index.js';
|
|
7
|
+
import { diagnosticFromError } from '../errors/index.js';
|
|
8
|
+
|
|
9
|
+
const RUNTIME_OWNED_KEYS = new Set(['account_id', 'user_id', 'tenant_id', 'workspace_id', 'connection_id', 'runtime_lease_id', 'execution_id']);
|
|
10
|
+
|
|
11
|
+
function clean(value) { return value == null ? '' : String(value).trim(); }
|
|
12
|
+
function hash(value) { return `sha256:${createHash('sha256').update(String(value)).digest('hex')}`; }
|
|
13
|
+
function event(emit, type, payload, runId) { if (typeof emit === 'function') emit(createAgentEvent(type, payload, { runId })); }
|
|
14
|
+
|
|
15
|
+
export function capabilityFunctionName(id) {
|
|
16
|
+
const source = clean(id).replace(/[^A-Za-z0-9_-]+/g, '_').replace(/^_+|_+$/g, '') || 'capability';
|
|
17
|
+
if (source.length <= 58) return `as_${source}`;
|
|
18
|
+
return `as_${source.slice(0, 45)}_${createHash('sha256').update(source).digest('hex').slice(0, 10)}`;
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
function userMessage(text) {
|
|
22
|
+
return { role: 'user', content: [{ type: 'input_text', text: String(text) }] };
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
function modelBudget(record) {
|
|
26
|
+
const windowTokens = Number(record?.context_window);
|
|
27
|
+
if (!Number.isFinite(windowTokens) || windowTokens <= 0) return null;
|
|
28
|
+
const policy = record.context_policy || {};
|
|
29
|
+
return createContextBudget({
|
|
30
|
+
windowTokens,
|
|
31
|
+
targetInputTokens: policy.target_input_tokens,
|
|
32
|
+
compactAtTokens: policy.compact_at_tokens,
|
|
33
|
+
interveneAtTokens: policy.intervene_at_tokens,
|
|
34
|
+
maxNormalInputTokens: policy.max_normal_input_tokens,
|
|
35
|
+
pricingThresholdTokens: policy.pricing_threshold_tokens,
|
|
36
|
+
safetyMarginTokens: policy.safety_margin_tokens,
|
|
37
|
+
});
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
export function buildAgentToolSurface(capabilityAdapter, objective, options = {}) {
|
|
41
|
+
if (!capabilityAdapter?.toolDescriptors) throw new TypeError('capabilityAdapter.toolDescriptors is required');
|
|
42
|
+
const catalog = capabilityAdapter.toolDescriptors({ includeUnavailable: false });
|
|
43
|
+
const searched = searchToolCards(catalog, objective, { maxItems: options.maxTools ?? 8, maxChars: options.maxCardChars ?? 24_000 });
|
|
44
|
+
const selected = searched.cards.map((card) => card.tool);
|
|
45
|
+
const hydrated = hydrateToolSchemas(catalog, selected, { maxTools: options.maxTools ?? 8, maxChars: options.maxSchemaChars ?? 40_000 });
|
|
46
|
+
const aliases = new Map();
|
|
47
|
+
const tools = hydrated.tools.map((descriptor) => {
|
|
48
|
+
const alias = capabilityFunctionName(descriptor.name);
|
|
49
|
+
aliases.set(alias, descriptor.name);
|
|
50
|
+
return Object.freeze({
|
|
51
|
+
type: 'function',
|
|
52
|
+
name: alias,
|
|
53
|
+
description: descriptor.description,
|
|
54
|
+
parameters: descriptor.input_schema || { type: 'object', properties: {} },
|
|
55
|
+
strict: true,
|
|
56
|
+
});
|
|
57
|
+
});
|
|
58
|
+
return Object.freeze({
|
|
59
|
+
tools: Object.freeze(tools),
|
|
60
|
+
aliases,
|
|
61
|
+
descriptors: Object.freeze(hydrated.tools),
|
|
62
|
+
receipt: Object.freeze({
|
|
63
|
+
catalog_tools: catalog.length,
|
|
64
|
+
cards_returned: searched.receipt.returned_items,
|
|
65
|
+
card_chars: searched.receipt.chars,
|
|
66
|
+
hydrated_tools: hydrated.receipt.hydrated_tools,
|
|
67
|
+
hydrated_schema_chars: hydrated.receipt.schema_chars,
|
|
68
|
+
deferred_tools: Object.freeze(hydrated.receipt.deferred_tools),
|
|
69
|
+
}),
|
|
70
|
+
});
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
function sanitizeToolInput(value, descriptor, cwd) {
|
|
74
|
+
const parsed = value && typeof value === 'object' && !Array.isArray(value) ? { ...value } : {};
|
|
75
|
+
for (const key of RUNTIME_OWNED_KEYS) delete parsed[key];
|
|
76
|
+
const properties = descriptor?.input_schema?.properties || {};
|
|
77
|
+
if (Object.hasOwn(properties, 'cwd')) parsed.cwd = cwd;
|
|
78
|
+
return parsed;
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
function parseArguments(value) {
|
|
82
|
+
if (!clean(value)) return {};
|
|
83
|
+
try {
|
|
84
|
+
const parsed = JSON.parse(value);
|
|
85
|
+
if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) throw new Error('arguments must be an object');
|
|
86
|
+
return parsed;
|
|
87
|
+
} catch (error) { throw new Error(`invalid_tool_arguments:${error?.message || error}`); }
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
function boundedToolOutput(value, callId, maxChars) {
|
|
91
|
+
const serialized = typeof value === 'string' ? value : JSON.stringify(value);
|
|
92
|
+
const ref = `tool:${callId}`;
|
|
93
|
+
const digest = hash(serialized);
|
|
94
|
+
if (serialized.length <= maxChars) return Object.freeze({ ref, hash: digest, source_chars: serialized.length, chars: serialized.length, truncated: false, output: serialized });
|
|
95
|
+
const bounded = truncateResultText(serialized, maxChars);
|
|
96
|
+
return Object.freeze({
|
|
97
|
+
ref,
|
|
98
|
+
hash: digest,
|
|
99
|
+
source_chars: serialized.length,
|
|
100
|
+
chars: bounded.chars,
|
|
101
|
+
truncated: true,
|
|
102
|
+
output: JSON.stringify({ ref, hash: digest, truncated: true, source_chars: serialized.length, excerpt: bounded.text }),
|
|
103
|
+
});
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
function toolResultCharBudget(activeTokens, budget) {
|
|
107
|
+
if (!budget) return 48_000;
|
|
108
|
+
if (!Number.isFinite(activeTokens) || activeTokens < 0) return budget.maxToolResultChars;
|
|
109
|
+
const reserveTokens = 4_000;
|
|
110
|
+
const headroomTokens = Math.max(256, budget.maxNormalInputTokens - Math.ceil(activeTokens) - reserveTokens);
|
|
111
|
+
return Math.max(1_024, Math.min(budget.maxToolResultChars, Math.floor(headroomTokens * budget.charsPerToken)));
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
function projectedInputTokens({ instructions, input, toolSurface, priorActiveTokens, budget }) {
|
|
115
|
+
const inputChars = typeof input === 'string' ? input.length : JSON.stringify(input ?? '').length;
|
|
116
|
+
const charsPerToken = budget?.charsPerToken || 4;
|
|
117
|
+
const newTokens = estimateContextTokens(String(instructions || '').length + inputChars + toolSurface.receipt.hydrated_schema_chars, charsPerToken);
|
|
118
|
+
return Math.max(newTokens, Number.isFinite(priorActiveTokens) ? Math.ceil(priorActiveTokens) + newTokens : newTokens);
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
function assertEconomicPreflight(projectedTokens, budget, allowOverride) {
|
|
122
|
+
if (!budget || allowOverride) return;
|
|
123
|
+
if (budget.pricingThresholdTokens != null && projectedTokens > budget.pricingThresholdTokens) {
|
|
124
|
+
throw new Error(`context_preflight_pricing_threshold:${projectedTokens}>${budget.pricingThresholdTokens}`);
|
|
125
|
+
}
|
|
126
|
+
if (projectedTokens >= budget.maxNormalInputTokens) throw new Error(`context_preflight_max_normal:${projectedTokens}>=${budget.maxNormalInputTokens}`);
|
|
127
|
+
if (projectedTokens >= budget.compactAtTokens) throw new Error(`context_preflight_compaction_required:${projectedTokens}>=${budget.compactAtTokens}`);
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
export async function runResponsesAgent(options = {}) {
|
|
131
|
+
const provider = options.provider;
|
|
132
|
+
if (!provider?.create || !provider?.continueWithToolOutputs) throw new TypeError('Responses provider adapter is required');
|
|
133
|
+
if (!options.capabilityAdapter) throw new TypeError('capabilityAdapter is required');
|
|
134
|
+
const cwd = path.resolve(options.cwd || process.cwd());
|
|
135
|
+
const objective = clean(options.prompt);
|
|
136
|
+
if (!objective) throw new TypeError('prompt is required');
|
|
137
|
+
const record = options.modelRecord || getModelRecord(options.model);
|
|
138
|
+
if (!record) throw new RangeError(`unknown model: ${options.model}`);
|
|
139
|
+
const reasoningEffort = clean(options.reasoningEffort || 'auto');
|
|
140
|
+
const serviceTier = clean(options.serviceTier || 'default');
|
|
141
|
+
const budget = modelBudget(record);
|
|
142
|
+
const instructionSet = options.instructions == null ? compileAgentInstructions(cwd, { maxChars: budget?.maxSystemChars || 48_000 }) : null;
|
|
143
|
+
const instructions = options.instructions == null ? instructionSet.content : String(options.instructions);
|
|
144
|
+
const toolSurface = buildAgentToolSurface(options.capabilityAdapter, objective, options);
|
|
145
|
+
const emit = options.emit;
|
|
146
|
+
const runId = options.runId;
|
|
147
|
+
event(emit, 'tool.search', toolSurface.receipt, runId);
|
|
148
|
+
|
|
149
|
+
let previousResponseId = clean(options.previousResponseId || options.previousProviderState?.previous_response_id) || null;
|
|
150
|
+
let providerState = options.previousProviderState && typeof options.previousProviderState === 'object'
|
|
151
|
+
? structuredClone(options.previousProviderState)
|
|
152
|
+
: previousResponseId ? { previous_response_id: previousResponseId } : null;
|
|
153
|
+
let priorActiveTokens = options.previousUsageSnapshot?.current_context?.input_tokens;
|
|
154
|
+
let input = objective;
|
|
155
|
+
let compacted = null;
|
|
156
|
+
let projected = projectedInputTokens({ instructions, input, toolSurface, priorActiveTokens, budget });
|
|
157
|
+
|
|
158
|
+
if (budget && projected >= budget.compactAtTokens && providerState && options.autoCompact !== false && typeof provider.compact === 'function') {
|
|
159
|
+
compacted = await provider.compact({
|
|
160
|
+
model: record.provider_model_id,
|
|
161
|
+
modelRecord: record,
|
|
162
|
+
previousResponseId,
|
|
163
|
+
providerState,
|
|
164
|
+
instructions,
|
|
165
|
+
promptCacheKey: options.promptCacheKey,
|
|
166
|
+
tokensBefore: Number.isFinite(priorActiveTokens) ? priorActiveTokens : projected,
|
|
167
|
+
emit,
|
|
168
|
+
runId,
|
|
169
|
+
});
|
|
170
|
+
if (Array.isArray(compacted.output) && compacted.output.length) input = [...compacted.output, userMessage(objective)];
|
|
171
|
+
providerState = compacted.provider_state || null;
|
|
172
|
+
previousResponseId = clean(providerState?.previous_response_id) || null;
|
|
173
|
+
priorActiveTokens = null;
|
|
174
|
+
projected = projectedInputTokens({ instructions, input, toolSurface, priorActiveTokens, budget });
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
assertEconomicPreflight(projected, budget, options.allowEconomicOverride === true);
|
|
178
|
+
const pressure = budget ? assessContextUsage(projected, budget) : null;
|
|
179
|
+
const declaredMaxOutput = Number(record.max_output_tokens);
|
|
180
|
+
const maxOutputTokens = Number.isInteger(options.maxOutputTokens) && options.maxOutputTokens > 0
|
|
181
|
+
? (Number.isFinite(declaredMaxOutput) && declaredMaxOutput > 0 ? Math.min(options.maxOutputTokens, declaredMaxOutput) : options.maxOutputTokens)
|
|
182
|
+
: (Number.isFinite(declaredMaxOutput) && declaredMaxOutput > 0 ? Math.min(32_768, declaredMaxOutput) : 16_384);
|
|
183
|
+
const projectedCost = record.pricing
|
|
184
|
+
? calculateModelCost(record, { input_tokens: projected, output_tokens: maxOutputTokens }, { serviceTier })
|
|
185
|
+
: null;
|
|
186
|
+
if (Number.isFinite(options.maxCallCostUsd) && projectedCost && projectedCost.total_usd > options.maxCallCostUsd) {
|
|
187
|
+
throw new Error(`projected_call_cost_exceeds_budget:${projectedCost.total_usd.toFixed(6)}>${Number(options.maxCallCostUsd).toFixed(6)}`);
|
|
188
|
+
}
|
|
189
|
+
const preflight = Object.freeze({
|
|
190
|
+
model: record.provider_model_id,
|
|
191
|
+
reasoning_effort: reasoningEffort,
|
|
192
|
+
service_tier: serviceTier,
|
|
193
|
+
estimated_input_tokens: projected,
|
|
194
|
+
max_output_tokens: maxOutputTokens,
|
|
195
|
+
projected_max_call_cost_usd: projectedCost?.total_usd ?? null,
|
|
196
|
+
pricing_threshold_tokens: budget?.pricingThresholdTokens ?? null,
|
|
197
|
+
tokens_until_pricing_threshold: pressure?.tokensUntilPricingThreshold ?? null,
|
|
198
|
+
compacted_before_turn: Boolean(compacted),
|
|
199
|
+
estimate_kind: 'local',
|
|
200
|
+
});
|
|
201
|
+
if (typeof options.beforeRequest === 'function') {
|
|
202
|
+
const approved = await options.beforeRequest(preflight);
|
|
203
|
+
if (approved === false) throw new Error('model_request_not_approved');
|
|
204
|
+
}
|
|
205
|
+
event(emit, 'context.snapshot', {
|
|
206
|
+
estimate_kind: 'local',
|
|
207
|
+
estimated_input_tokens: projected,
|
|
208
|
+
window_tokens: budget?.windowTokens ?? null,
|
|
209
|
+
utilization_ratio: pressure?.utilizationRatio ?? null,
|
|
210
|
+
pricing_threshold_tokens: budget?.pricingThresholdTokens ?? null,
|
|
211
|
+
tokens_until_pricing_threshold: pressure?.tokensUntilPricingThreshold ?? null,
|
|
212
|
+
pressure: pressure?.stage ?? 'unknown',
|
|
213
|
+
projected_max_call_cost_usd: projectedCost?.total_usd ?? null,
|
|
214
|
+
tool_surface: toolSurface.receipt,
|
|
215
|
+
}, runId);
|
|
216
|
+
|
|
217
|
+
let cumulativeUsage = options.cumulativeUsage || null;
|
|
218
|
+
let totalCostUsd = 0;
|
|
219
|
+
const costBreakdownUsd = { input: 0, cached_input: 0, cache_write: 0, output: 0 };
|
|
220
|
+
const accumulateCost = (cost) => {
|
|
221
|
+
totalCostUsd += Number(cost?.total_usd || 0);
|
|
222
|
+
for (const key of Object.keys(costBreakdownUsd)) costBreakdownUsd[key] += Number(cost?.components_usd?.[key] || 0);
|
|
223
|
+
};
|
|
224
|
+
let response = await provider.create({
|
|
225
|
+
model: record.provider_model_id,
|
|
226
|
+
modelRecord: record,
|
|
227
|
+
input,
|
|
228
|
+
instructions,
|
|
229
|
+
reasoningEffort,
|
|
230
|
+
serviceTier,
|
|
231
|
+
tools: toolSurface.tools,
|
|
232
|
+
previousResponseId: previousResponseId || undefined,
|
|
233
|
+
providerState,
|
|
234
|
+
maxOutputTokens,
|
|
235
|
+
promptCacheKey: options.promptCacheKey,
|
|
236
|
+
cumulativeUsage,
|
|
237
|
+
emit,
|
|
238
|
+
runId,
|
|
239
|
+
});
|
|
240
|
+
accumulateCost(response.cost);
|
|
241
|
+
providerState = response.provider_state || (response.response_id ? { previous_response_id: response.response_id } : providerState);
|
|
242
|
+
cumulativeUsage = response.usage_snapshot?.cumulative || cumulativeUsage;
|
|
243
|
+
|
|
244
|
+
const toolReceipts = [];
|
|
245
|
+
const maxToolRounds = Number.isInteger(options.maxToolRounds) && options.maxToolRounds > 0 ? options.maxToolRounds : 8;
|
|
246
|
+
let rounds = 0;
|
|
247
|
+
while (response.tool_calls?.length) {
|
|
248
|
+
rounds += 1;
|
|
249
|
+
if (rounds > maxToolRounds) throw new Error(`tool_round_limit_exceeded:${maxToolRounds}`);
|
|
250
|
+
const outputs = [];
|
|
251
|
+
const activeTokens = response.usage_snapshot?.current_context?.input_tokens;
|
|
252
|
+
const maxToolChars = toolResultCharBudget(activeTokens, budget);
|
|
253
|
+
for (const call of response.tool_calls) {
|
|
254
|
+
const capabilityId = toolSurface.aliases.get(call.name);
|
|
255
|
+
if (!capabilityId) throw new Error(`unrecognized_tool_call:${call.name}`);
|
|
256
|
+
const descriptor = toolSurface.descriptors.find((row) => row.name === capabilityId);
|
|
257
|
+
const args = sanitizeToolInput(parseArguments(call.arguments), descriptor, cwd);
|
|
258
|
+
if (typeof options.beforeTool === 'function') {
|
|
259
|
+
const approved = await options.beforeTool({
|
|
260
|
+
call_id: call.call_id,
|
|
261
|
+
capability_id: capabilityId,
|
|
262
|
+
descriptor: descriptor ? { ...descriptor, input_schema: undefined } : null,
|
|
263
|
+
input: args,
|
|
264
|
+
cwd,
|
|
265
|
+
});
|
|
266
|
+
if (approved === false) {
|
|
267
|
+
const denied = new Error(`tool_execution_not_approved:${capabilityId}`);
|
|
268
|
+
denied.code = 'AGENTSAM_TOOL_NOT_APPROVED';
|
|
269
|
+
const diagnostic = diagnosticFromError(denied, { source: 'tool', kind: 'tool_execution_denied' });
|
|
270
|
+
event(emit, 'tool.failed', { call_id: call.call_id, capability_id: capabilityId, error: diagnostic }, runId);
|
|
271
|
+
event(emit, 'error.observed', { ...diagnostic, call_id: call.call_id, capability_id: capabilityId }, runId);
|
|
272
|
+
throw denied;
|
|
273
|
+
}
|
|
274
|
+
}
|
|
275
|
+
event(emit, 'tool.started', { call_id: call.call_id, capability_id: capabilityId }, runId);
|
|
276
|
+
try {
|
|
277
|
+
const value = await options.capabilityAdapter.invoke(capabilityId, args);
|
|
278
|
+
const bounded = boundedToolOutput(value, call.call_id, maxToolChars);
|
|
279
|
+
toolReceipts.push(Object.freeze({ call_id: call.call_id, capability_id: capabilityId, ...bounded, output: undefined }));
|
|
280
|
+
outputs.push({ call_id: call.call_id, output: bounded.output });
|
|
281
|
+
event(emit, 'tool.completed', {
|
|
282
|
+
call_id: call.call_id,
|
|
283
|
+
capability_id: capabilityId,
|
|
284
|
+
result_ref: bounded.ref,
|
|
285
|
+
result_hash: bounded.hash,
|
|
286
|
+
result_chars: bounded.chars,
|
|
287
|
+
source_chars: bounded.source_chars,
|
|
288
|
+
truncated: bounded.truncated,
|
|
289
|
+
}, runId);
|
|
290
|
+
} catch (error) {
|
|
291
|
+
const diagnostic = diagnosticFromError(error, { source: 'tool', kind: 'tool_execution_error' });
|
|
292
|
+
event(emit, 'tool.failed', { call_id: call.call_id, capability_id: capabilityId, error: diagnostic }, runId);
|
|
293
|
+
event(emit, 'error.observed', { ...diagnostic, call_id: call.call_id, capability_id: capabilityId }, runId);
|
|
294
|
+
outputs.push({ call_id: call.call_id, output: JSON.stringify({ ok: false, error: diagnostic }) });
|
|
295
|
+
}
|
|
296
|
+
}
|
|
297
|
+
response = await provider.continueWithToolOutputs({
|
|
298
|
+
model: record.provider_model_id,
|
|
299
|
+
previousResponseId: response.response_id,
|
|
300
|
+
providerState: response.provider_state || providerState,
|
|
301
|
+
modelRecord: record,
|
|
302
|
+
toolOutputs: outputs,
|
|
303
|
+
instructions,
|
|
304
|
+
reasoningEffort,
|
|
305
|
+
serviceTier,
|
|
306
|
+
tools: toolSurface.tools,
|
|
307
|
+
maxOutputTokens,
|
|
308
|
+
promptCacheKey: options.promptCacheKey,
|
|
309
|
+
cumulativeUsage,
|
|
310
|
+
emit,
|
|
311
|
+
runId,
|
|
312
|
+
});
|
|
313
|
+
accumulateCost(response.cost);
|
|
314
|
+
providerState = response.provider_state || (response.response_id ? { previous_response_id: response.response_id } : providerState);
|
|
315
|
+
cumulativeUsage = response.usage_snapshot?.cumulative || cumulativeUsage;
|
|
316
|
+
}
|
|
317
|
+
|
|
318
|
+
const active = response.usage_snapshot?.current_context?.input_tokens ?? 0;
|
|
319
|
+
const finalPressure = budget ? assessContextUsage(active, budget) : null;
|
|
320
|
+
event(emit, 'context.snapshot', {
|
|
321
|
+
estimate_kind: 'provider',
|
|
322
|
+
active_input_tokens: active,
|
|
323
|
+
window_tokens: budget?.windowTokens ?? null,
|
|
324
|
+
utilization_ratio: finalPressure?.utilizationRatio ?? null,
|
|
325
|
+
pricing_threshold_tokens: budget?.pricingThresholdTokens ?? null,
|
|
326
|
+
tokens_until_pricing_threshold: finalPressure?.tokensUntilPricingThreshold ?? null,
|
|
327
|
+
pressure: finalPressure?.stage ?? 'unknown',
|
|
328
|
+
compact_before_next_turn: finalPressure?.shouldCompact ?? false,
|
|
329
|
+
}, runId);
|
|
330
|
+
|
|
331
|
+
return Object.freeze({
|
|
332
|
+
output_text: response.output_text || '',
|
|
333
|
+
response_id: response.response_id,
|
|
334
|
+
model: record.provider_model_id,
|
|
335
|
+
reasoning_effort: reasoningEffort,
|
|
336
|
+
requested_service_tier: serviceTier,
|
|
337
|
+
actual_service_tier: response.actual_service_tier,
|
|
338
|
+
usage_snapshot: response.usage_snapshot,
|
|
339
|
+
cumulative_usage: cumulativeUsage,
|
|
340
|
+
total_cost_usd: totalCostUsd,
|
|
341
|
+
cost_breakdown_usd: Object.freeze({ ...costBreakdownUsd }),
|
|
342
|
+
tool_surface: toolSurface.receipt,
|
|
343
|
+
tool_receipts: Object.freeze(toolReceipts),
|
|
344
|
+
compacted_before_turn: Boolean(compacted),
|
|
345
|
+
provider_state: providerState,
|
|
346
|
+
continuation: Object.freeze({
|
|
347
|
+
previous_response_id: response.response_id || providerState?.previous_response_id || null,
|
|
348
|
+
provider_state: providerState,
|
|
349
|
+
usage_snapshot: response.usage_snapshot,
|
|
350
|
+
compact_before_next_turn: finalPressure?.shouldCompact ?? false,
|
|
351
|
+
}),
|
|
352
|
+
});
|
|
353
|
+
}
|
|
@@ -4,10 +4,10 @@ import { execFile } from 'node:child_process';
|
|
|
4
4
|
import { promisify } from 'node:util';
|
|
5
5
|
import { fileURLToPath } from 'node:url';
|
|
6
6
|
import { createHash } from 'node:crypto';
|
|
7
|
-
import { resolveGitContext } from '
|
|
7
|
+
import { resolveGitContext } from '../../packages/agentsam-repository/src/git-context.js';
|
|
8
8
|
import { getRepositoryId, tryReadProjectConfig } from '../lib/project-config.js';
|
|
9
|
-
import { buildMerkleTree } from '
|
|
10
|
-
import { gitIgnoredPaths } from '
|
|
9
|
+
import { buildMerkleTree } from '../../packages/agentsam-repository/src/merkle/index.js';
|
|
10
|
+
import { gitIgnoredPaths } from '../../packages/agentsam-repository/src/merkle/git-ignore.js';
|
|
11
11
|
import { analyzeExecutionBoundaries } from '../indexing/execution-boundary.js';
|
|
12
12
|
import { showLatestDeployReceipt } from '../lib/deploy-receipt/index.js';
|
|
13
13
|
import { CONFIG_PATH, canonical, readConfig, scopeKey } from '../knowledge/config.js';
|