tinker-agent 1.9.0 → 1.11.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.
Files changed (52) hide show
  1. package/CHANGELOG.md +36 -1
  2. package/README.md +64 -6
  3. package/package.json +1 -1
  4. package/src/agent/loop.ts +17 -0
  5. package/src/agent/runtime-session.ts +341 -1
  6. package/src/agent/session-ledger.ts +100 -3
  7. package/src/cli/config.ts +11 -2
  8. package/src/cli/model-profiles.ts +58 -0
  9. package/src/cli/public-config-contract.ts +73 -7
  10. package/src/cli/run-runner.ts +4 -1
  11. package/src/cli/runner-dependencies.ts +28 -4
  12. package/src/cli/tui-memory.ts +4 -0
  13. package/src/cli/tui-runner.tsx +8 -1
  14. package/src/context/context-automation-policy.ts +22 -21
  15. package/src/context/context-manager.ts +91 -15
  16. package/src/context/context-policy.ts +0 -2
  17. package/src/context/context-swap-renderer.ts +1 -1
  18. package/src/context/prefix-retirement-planner.ts +58 -8
  19. package/src/context/recall-retirement-contract.ts +5 -4
  20. package/src/context/swap-planner.ts +33 -27
  21. package/src/events/observation-text-log.ts +4 -0
  22. package/src/events/stdout-event-printer.ts +5 -0
  23. package/src/events/types.ts +5 -1
  24. package/src/model/fake-model-client.ts +55 -16
  25. package/src/model/model-api.ts +12 -0
  26. package/src/model/model-client.ts +9 -1
  27. package/src/model/moonshot-input-token-estimator.ts +5 -1
  28. package/src/model/openai-chat-mapping.ts +2 -24
  29. package/src/model/openai-chat-model-client.ts +18 -294
  30. package/src/model/openai-image-mapping.ts +20 -0
  31. package/src/model/openai-model-utils.ts +304 -0
  32. package/src/model/openai-responses-mapping.ts +532 -0
  33. package/src/model/openai-responses-model-client.ts +295 -0
  34. package/src/model/openai-responses-stream.ts +96 -0
  35. package/src/model/openai-responses-token-estimator.ts +155 -0
  36. package/src/model/reasoning-effort.ts +60 -0
  37. package/src/session/session-catalog.ts +2 -2
  38. package/src/session/session-history-reader.ts +6 -1
  39. package/src/session/session-schema.ts +268 -4
  40. package/src/session/session-store.ts +134 -26
  41. package/src/skills/skill-context.ts +2 -2
  42. package/src/tools/bounded-output-preview.ts +276 -0
  43. package/src/tools/recall.ts +67 -36
  44. package/src/tools/registry.ts +7 -2
  45. package/src/tools/task-output-snapshot.ts +6 -22
  46. package/src/tools/task-output.ts +23 -27
  47. package/src/tui/app.tsx +153 -11
  48. package/src/tui/components/footer.tsx +6 -1
  49. package/src/tui/components/prompt-input.tsx +9 -1
  50. package/src/tui/event-store.ts +15 -0
  51. package/src/tui/slash-commands.ts +20 -0
  52. package/src/tui/tui-session-controller.ts +14 -0
@@ -0,0 +1,20 @@
1
+ import { parseImageAssetId, type ImageAssetId } from "../image/image-types";
2
+
3
+ const IMAGE_ASSET_URL_MARKER = Symbol("tinker.image-asset-url-marker");
4
+
5
+ export type ImageAssetUrlMarker = {
6
+ readonly [IMAGE_ASSET_URL_MARKER]: ImageAssetId;
7
+ };
8
+
9
+ export function imageAssetUrlMarker(assetId: ImageAssetId): ImageAssetUrlMarker {
10
+ parseImageAssetId(assetId);
11
+ return Object.freeze({ [IMAGE_ASSET_URL_MARKER]: assetId });
12
+ }
13
+
14
+ export function parseImageAssetUrlMarker(value: unknown): ImageAssetId | undefined {
15
+ if (typeof value !== "object" || value === null) {
16
+ return undefined;
17
+ }
18
+ const assetId = (value as Partial<ImageAssetUrlMarker>)[IMAGE_ASSET_URL_MARKER];
19
+ return typeof assetId === "string" ? parseImageAssetId(assetId) : undefined;
20
+ }
@@ -0,0 +1,304 @@
1
+ import OpenAI from "openai";
2
+ import type { UserMessage } from "../agent/types";
3
+ import { IMAGE_INPUT_POLICY } from "../image/image-input-policy";
4
+ import type { ImageAssetId, ImageAssetRef } from "../image/image-types";
5
+ import {
6
+ ModelRequestMediaAggregateError,
7
+ ProviderResponseError,
8
+ type MaterializedModelRequest,
9
+ type ModelMaterializeOptions,
10
+ type ModelRequestInput,
11
+ type PreparedMediaDescriptor,
12
+ type PreparedModelRequest,
13
+ type PreparedPromptSegment,
14
+ type ProviderResponseErrorCode,
15
+ } from "./model-client";
16
+ import { parseImageAssetUrlMarker } from "./openai-image-mapping";
17
+ import { stableJsonStringify } from "./model-request-preflight";
18
+
19
+ export async function materializeOpenAIRequest(
20
+ prepared: PreparedModelRequest,
21
+ options: ModelMaterializeOptions,
22
+ ): Promise<MaterializedModelRequest> {
23
+ options.signal.throwIfAborted();
24
+ if (prepared.mediaOccurrenceCount > IMAGE_INPUT_POLICY.maxImagesPerRequest) {
25
+ throw new ModelRequestMediaAggregateError(
26
+ `Model request has ${prepared.mediaOccurrenceCount} images; maximum is ${IMAGE_INPUT_POLICY.maxImagesPerRequest}.`,
27
+ );
28
+ }
29
+
30
+ const assets = distinctPreparedAssets(prepared.promptSegments);
31
+ const lowerLengths = new Map<ImageAssetId, number>();
32
+ for (const asset of assets.values()) {
33
+ lowerLengths.set(asset.assetId, dataUrlLength(asset));
34
+ }
35
+ const markerCount = countImageMarkers(prepared.payload);
36
+ if (markerCount !== prepared.mediaOccurrenceCount) {
37
+ throw new Error("Prepared image marker count does not match media descriptors.");
38
+ }
39
+ const lowerBodyBytes = exactJsonBodyBytes(prepared.payload, lowerLengths);
40
+ assertBodyLimit(lowerBodyBytes, prepared.mediaOccurrenceCount);
41
+
42
+ const dataUrls = new Map<ImageAssetId, string>();
43
+ for (const asset of assets.values()) {
44
+ options.signal.throwIfAborted();
45
+ const bytes = await options.assetStore.readVerified(asset, {
46
+ signal: options.signal,
47
+ });
48
+ dataUrls.set(
49
+ asset.assetId,
50
+ `data:${asset.mimeType};base64,${bytes.toString("base64")}`,
51
+ );
52
+ await yieldToEventLoop();
53
+ }
54
+ options.signal.throwIfAborted();
55
+ const exactLengths = new Map(
56
+ [...dataUrls].map(([assetId, value]) => [assetId, value.length] as const),
57
+ );
58
+ const bodyBytes = exactJsonBodyBytes(prepared.payload, exactLengths);
59
+ assertBodyLimit(bodyBytes, prepared.mediaOccurrenceCount);
60
+ const payload = deepFreeze(materializePayload(prepared.payload, dataUrls));
61
+ return Object.freeze({ ...prepared, payload, bodyBytes });
62
+ }
63
+
64
+ export function exactJsonBodyBytes(
65
+ value: unknown,
66
+ imageDataUrlLengths: ReadonlyMap<ImageAssetId, number>,
67
+ ): number {
68
+ const assetId = parseImageAssetUrlMarker(value);
69
+ if (assetId !== undefined) {
70
+ const length = imageDataUrlLengths.get(assetId);
71
+ if (!Number.isSafeInteger(length) || length === undefined || length < 1) {
72
+ throw new Error(
73
+ `Missing materialized length for image ${assetId.slice(0, 12)}….`,
74
+ );
75
+ }
76
+ return length + 2;
77
+ }
78
+ if (
79
+ value === null ||
80
+ typeof value === "string" ||
81
+ typeof value === "number" ||
82
+ typeof value === "boolean"
83
+ ) {
84
+ const serialized: unknown = JSON.stringify(value);
85
+ if (typeof serialized !== "string") {
86
+ throw new Error("JSON primitive did not serialize to a string.");
87
+ }
88
+ return Buffer.byteLength(serialized, "utf8");
89
+ }
90
+ if (Array.isArray(value)) {
91
+ const entries: readonly unknown[] = value;
92
+ return (
93
+ 2 +
94
+ Math.max(0, entries.length - 1) +
95
+ entries.reduce<number>(
96
+ (total, entry) => total + exactJsonBodyBytes(entry, imageDataUrlLengths),
97
+ 0,
98
+ )
99
+ );
100
+ }
101
+ if (typeof value !== "object" || value === undefined) {
102
+ throw new Error(`Cannot size non-JSON value of type ${typeof value}.`);
103
+ }
104
+ const entries = Object.entries(value as Record<string, unknown>).filter(
105
+ ([, entry]) => entry !== undefined,
106
+ );
107
+ return (
108
+ 2 +
109
+ Math.max(0, entries.length - 1) +
110
+ entries.reduce(
111
+ (total, [key, entry]) =>
112
+ total +
113
+ Buffer.byteLength(JSON.stringify(key), "utf8") +
114
+ 1 +
115
+ exactJsonBodyBytes(entry, imageDataUrlLengths),
116
+ 0,
117
+ )
118
+ );
119
+ }
120
+
121
+ export function imageUserSegment(message: UserMessage): PreparedPromptSegment {
122
+ const media = message.attachments!.map(
123
+ (attachment): PreparedMediaDescriptor =>
124
+ Object.freeze({
125
+ assetId: attachment.assetId,
126
+ label: attachment.label,
127
+ range: Object.freeze({ ...attachment.range }),
128
+ mimeType: attachment.mimeType,
129
+ byteLength: attachment.byteLength,
130
+ width: attachment.width,
131
+ height: attachment.height,
132
+ planningTokens: IMAGE_INPUT_POLICY.planningTokensPerImage,
133
+ }),
134
+ );
135
+ return Object.freeze({
136
+ kind: "user",
137
+ normalizedText: message.content,
138
+ media: Object.freeze(media),
139
+ });
140
+ }
141
+
142
+ export function normalizedEndpointPolicy(baseURL: string | undefined): string {
143
+ const url = new URL(baseURL ?? "https://api.openai.com/v1");
144
+ url.username = "";
145
+ url.password = "";
146
+ url.search = "";
147
+ url.hash = "";
148
+ const pathname = url.pathname.replace(/\/+$/, "") || "/";
149
+ return `${url.protocol}//${url.host}${pathname}`;
150
+ }
151
+
152
+ export function segmentKind(
153
+ role: ModelRequestInput["messages"][number]["role"],
154
+ ): PreparedPromptSegment["kind"] {
155
+ switch (role) {
156
+ case "system":
157
+ return "kernel";
158
+ case "user":
159
+ return "user";
160
+ case "assistant":
161
+ return "assistant";
162
+ case "tool":
163
+ return "tool";
164
+ }
165
+ }
166
+
167
+ export function deepFreeze<T>(value: T): T {
168
+ if (typeof value !== "object" || value === null || Object.isFrozen(value)) {
169
+ return value;
170
+ }
171
+ for (const child of Object.values(value)) {
172
+ deepFreeze(child);
173
+ }
174
+ return Object.freeze(value);
175
+ }
176
+
177
+ export function sanitizedProviderError(
178
+ error: unknown,
179
+ provider: string,
180
+ model: string,
181
+ ): ProviderResponseError {
182
+ const message = error instanceof Error ? error.message : String(error);
183
+ const sanitized = message
184
+ .replace(
185
+ /data:image\/(?:png|jpeg|webp);base64,[A-Za-z0-9+/=]+/gu,
186
+ "[redacted image data]",
187
+ )
188
+ .replace(/Bearer\s+[A-Za-z0-9._~+/-]+/giu, "Bearer [redacted]");
189
+ return new ProviderResponseError(
190
+ providerErrorCode(error),
191
+ sanitized,
192
+ { provider, model },
193
+ { cause: error },
194
+ );
195
+ }
196
+
197
+ function distinctPreparedAssets(
198
+ segments: readonly PreparedPromptSegment[],
199
+ ): Map<ImageAssetId, ImageAssetRef> {
200
+ const assets = new Map<ImageAssetId, ImageAssetRef>();
201
+ for (const segment of segments) {
202
+ for (const media of segment.media ?? []) {
203
+ const asset = Object.freeze({
204
+ assetId: media.assetId,
205
+ mimeType: media.mimeType,
206
+ byteLength: media.byteLength,
207
+ width: media.width,
208
+ height: media.height,
209
+ });
210
+ const existing = assets.get(media.assetId);
211
+ if (
212
+ existing !== undefined &&
213
+ stableJsonStringify(existing) !== stableJsonStringify(asset)
214
+ ) {
215
+ throw new Error(`Conflicting descriptors for image ${media.assetId}.`);
216
+ }
217
+ assets.set(media.assetId, asset);
218
+ }
219
+ }
220
+ return assets;
221
+ }
222
+
223
+ function materializePayload(
224
+ value: unknown,
225
+ dataUrls: ReadonlyMap<ImageAssetId, string>,
226
+ ): unknown {
227
+ const assetId = parseImageAssetUrlMarker(value);
228
+ if (assetId !== undefined) {
229
+ const dataUrl = dataUrls.get(assetId);
230
+ if (dataUrl === undefined) {
231
+ throw new Error(`Image ${assetId.slice(0, 12)}… was not materialized.`);
232
+ }
233
+ return dataUrl;
234
+ }
235
+ if (Array.isArray(value)) {
236
+ return value.map((entry) => materializePayload(entry, dataUrls));
237
+ }
238
+ if (typeof value === "object" && value !== null) {
239
+ return Object.fromEntries(
240
+ Object.entries(value)
241
+ .filter(([, entry]) => entry !== undefined)
242
+ .map(([key, entry]) => [key, materializePayload(entry, dataUrls)]),
243
+ );
244
+ }
245
+ return value;
246
+ }
247
+
248
+ function countImageMarkers(value: unknown): number {
249
+ if (parseImageAssetUrlMarker(value) !== undefined) {
250
+ return 1;
251
+ }
252
+ if (Array.isArray(value)) {
253
+ const entries: readonly unknown[] = value;
254
+ return entries.reduce<number>(
255
+ (total, entry) => total + countImageMarkers(entry),
256
+ 0,
257
+ );
258
+ }
259
+ if (typeof value === "object" && value !== null) {
260
+ return Object.values(value as Record<string, unknown>).reduce<number>(
261
+ (total, entry) => total + countImageMarkers(entry),
262
+ 0,
263
+ );
264
+ }
265
+ return 0;
266
+ }
267
+
268
+ function dataUrlLength(asset: ImageAssetRef): number {
269
+ return `data:${asset.mimeType};base64,`.length + 4 * Math.ceil(asset.byteLength / 3);
270
+ }
271
+
272
+ function assertBodyLimit(bodyBytes: number, imageCount: number): void {
273
+ if (bodyBytes > IMAGE_INPUT_POLICY.maxRequestBodyBytes) {
274
+ throw new ModelRequestMediaAggregateError(
275
+ `Model request is ${bodyBytes} UTF-8 bytes with ${imageCount} images; maximum is ${IMAGE_INPUT_POLICY.maxRequestBodyBytes}.`,
276
+ );
277
+ }
278
+ }
279
+
280
+ function yieldToEventLoop(): Promise<void> {
281
+ return new Promise((resolve) => setTimeout(resolve, 0));
282
+ }
283
+
284
+ function providerErrorCode(error: unknown): ProviderResponseErrorCode {
285
+ const status = providerErrorStatus(error);
286
+ if (status === 429) {
287
+ return "provider_rate_limited";
288
+ }
289
+ if (status === 500 || status === 502 || status === 503 || status === 504) {
290
+ return "provider_unavailable";
291
+ }
292
+ if (status === undefined && error instanceof OpenAI.APIConnectionError) {
293
+ return "provider_unavailable";
294
+ }
295
+ return "provider_request_error";
296
+ }
297
+
298
+ function providerErrorStatus(error: unknown): number | undefined {
299
+ if (typeof error !== "object" || error === null || !("status" in error)) {
300
+ return undefined;
301
+ }
302
+ const status = (error as { status?: unknown }).status;
303
+ return typeof status === "number" ? status : undefined;
304
+ }