@agentknight/sdk 0.9.52 → 0.9.55

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/dist/index.js CHANGED
@@ -4,26 +4,25 @@ import {
4
4
  PeerChatRequestSchema,
5
5
  PeerChatResultSchema,
6
6
  validateDataDirectory
7
- } from "./chunks/chunk-6DYWE5PL.js";
7
+ } from "./chunks/chunk-Z5STULMQ.js";
8
8
  import {
9
9
  DeviceIdentitySchema,
10
- LEGACY_CLIENT_STATE_DIRECTORY,
11
- SessionImageRelayUrlSchema,
12
- SessionImagesConfigSchema,
13
10
  codingAgentPresentation,
14
11
  relayRequestToken
15
- } from "./chunks/chunk-RPVK6HQV.js";
12
+ } from "./chunks/chunk-XPHAIOKN.js";
16
13
  import {
17
14
  AgentSelectionSchema,
18
15
  assertSelectionSnapshotFits,
19
16
  supportsAgentSelection
20
- } from "./chunks/chunk-AAZH6QGV.js";
17
+ } from "./chunks/chunk-NTFNQYQ3.js";
21
18
  import {
22
19
  ConversationNormalizer,
23
20
  LiveTimelineProjection,
24
21
  OperationDiagnostics,
25
22
  OperationMetrics,
26
23
  PromptPreparationError,
24
+ SessionImageUploadError,
25
+ SessionImageUploader,
27
26
  SessionProjectIdentityError,
28
27
  SessionRuntime,
29
28
  diagnosticError,
@@ -39,11 +38,15 @@ import {
39
38
  resolveGitProjectIdentity,
40
39
  sessionRestoreFailure,
41
40
  validateOperationResponse
42
- } from "./chunks/chunk-6YFGVYI5.js";
41
+ } from "./chunks/chunk-6ZPE7VIE.js";
42
+ import {
43
+ SessionImageRelayUrlSchema,
44
+ SessionImagesConfigSchema
45
+ } from "./chunks/chunk-IJPJQF7S.js";
43
46
  import {
44
47
  GROUP_CHAT_MAX_TURNS,
45
48
  GroupChatError
46
- } from "./chunks/chunk-XL6UB4C3.js";
49
+ } from "./chunks/chunk-HFVA7ZOD.js";
47
50
  import {
48
51
  detectClaude,
49
52
  detectCopilot,
@@ -54,7 +57,7 @@ import {
54
57
  assistantPreview,
55
58
  isContentfulAssistant,
56
59
  userPreview
57
- } from "./chunks/chunk-2CNJAMAN.js";
60
+ } from "./chunks/chunk-5J7BK2Y7.js";
58
61
  import {
59
62
  AgentModelListingError,
60
63
  AgentSessionRenameError,
@@ -65,7 +68,7 @@ import {
65
68
  UnsupportedAgentOperationError,
66
69
  captureResearchAccess,
67
70
  captureWorkbenchAccess
68
- } from "./chunks/chunk-ML6Q2MYH.js";
71
+ } from "./chunks/chunk-L3A736SO.js";
69
72
  import {
70
73
  A2aRelayRequestSchema,
71
74
  A2aRelayResponseSchema,
@@ -76,6 +79,13 @@ import {
76
79
  ConversationAttachmentSchema,
77
80
  ConversationItemSchema,
78
81
  ConversationItemUpsertSchema,
82
+ DEVICE_TEXT_INPUT_CAPABILITY,
83
+ DEVICE_TEXT_INPUT_OPERATION,
84
+ DEVICE_TEXT_INPUT_SCOPE,
85
+ DEVICE_TEXT_INPUT_TTL_MS,
86
+ DEVICE_TEXT_INPUT_VERSION,
87
+ DeviceTextInputDataSchema,
88
+ DeviceTextInputResultSchema,
79
89
  GROUP_CHAT_CREATE_CAPABILITY,
80
90
  GROUP_CHAT_CREATE_OPERATION,
81
91
  GROUP_CHAT_CREATE_VERSION,
@@ -147,7 +157,6 @@ import {
147
157
  SESSION_GIT_DIFF_OPERATION,
148
158
  SESSION_GIT_DIFF_PARTIAL_VERSION,
149
159
  SESSION_GIT_DIFF_VERSION,
150
- SESSION_IMAGE_API_PATH,
151
160
  SESSION_IMAGE_MAX_BYTES,
152
161
  SESSION_IMAGE_MAX_PIXELS,
153
162
  SESSION_IMAGE_STORAGE_CAPABILITY,
@@ -187,11 +196,7 @@ import {
187
196
  SessionGitDiffGzipResultDataSchema,
188
197
  SessionGitDiffPartialResultDataSchema,
189
198
  SessionGitDiffResultDataSchema,
190
- SessionImageCommitResultSchema,
191
- SessionImageScopeSchema,
192
199
  SessionImageStorageSchema,
193
- SessionImageUploadRequestSchema,
194
- SessionImageUploadResultSchema,
195
200
  SessionListRequestSchema,
196
201
  SessionListResultSchema,
197
202
  SessionOptionsRequestSchema,
@@ -258,12 +263,12 @@ import {
258
263
  sessionCommunicationError,
259
264
  sessionCommunicationOperationCapability,
260
265
  workbenchCapability
261
- } from "./chunks/chunk-UZFIXIAS.js";
266
+ } from "./chunks/chunk-K5CMKBW6.js";
262
267
 
263
268
  // src/initialize.ts
264
269
  import { createHash as createHash16 } from "node:crypto";
265
270
  import { readFile as readFile4 } from "node:fs/promises";
266
- import { z as z11 } from "zod";
271
+ import { z as z10 } from "zod";
267
272
 
268
273
  // src/coding-agent-factory.ts
269
274
  import { resolve } from "node:path";
@@ -278,7 +283,7 @@ async function createCodingAgentAdapter(config, onDiagnostic, owner) {
278
283
  switch (engine.kind) {
279
284
  case "managed": {
280
285
  if (owner === void 0) throw new Error("Managed coding agents require the PC owner identity");
281
- const { ManagedCodingAgentAdapter } = await import("./chunks/managed-agent-adapter-5TIM4PBR.js");
286
+ const { ManagedCodingAgentAdapter } = await import("./chunks/managed-agent-adapter-KEXZFLGA.js");
282
287
  return new ManagedCodingAgentAdapter({
283
288
  dataDirectory: config.dataDirectory,
284
289
  owner,
@@ -335,7 +340,7 @@ async function createCodingAgentAdapter(config, onDiagnostic, owner) {
335
340
  });
336
341
  }
337
342
  case "copilot": {
338
- const { GithubCopilotAdapter } = await import("./chunks/copilot-adapter-ZM7EUBZ5.js");
343
+ const { GithubCopilotAdapter } = await import("./chunks/copilot-adapter-TU2GDFYP.js");
339
344
  if (owner !== void 0) {
340
345
  return new GithubCopilotAdapter(void 0, void 0, void 0, {
341
346
  dataDirectory: config.dataDirectory,
@@ -355,13 +360,13 @@ async function createCodingAgentAdapter(config, onDiagnostic, owner) {
355
360
  }
356
361
  case "pi": {
357
362
  assertPiRuntimeSupported();
358
- const { PiCodingAgentAdapter } = await import("./chunks/pi-adapter-NADD52CV.js");
363
+ const { PiCodingAgentAdapter } = await import("./chunks/pi-adapter-5BFIJTPD.js");
359
364
  return new PiCodingAgentAdapter(
360
365
  engine.agentDirectory === void 0 ? {} : { agentDirectory: resolve(engine.agentDirectory) }
361
366
  );
362
367
  }
363
368
  case "codex": {
364
- const { CodexCodingAgentAdapter } = await import("./chunks/codex-adapter-44N7DBRH.js");
369
+ const { CodexCodingAgentAdapter } = await import("./chunks/codex-adapter-ELYJE2A2.js");
365
370
  return new CodexCodingAgentAdapter({
366
371
  dataDirectory: resolve(config.dataDirectory, "coding-agents"),
367
372
  ...owner === void 0 ? {} : { nativeSessionOwner: owner },
@@ -370,7 +375,7 @@ async function createCodingAgentAdapter(config, onDiagnostic, owner) {
370
375
  });
371
376
  }
372
377
  case "claude": {
373
- const { ClaudeCodingAgentAdapter } = await import("./chunks/claude-adapter-UWVOXYNG.js");
378
+ const { ClaudeCodingAgentAdapter } = await import("./chunks/claude-adapter-G6YTPXRP.js");
374
379
  return new ClaudeCodingAgentAdapter({
375
380
  dataDirectory: resolve(config.dataDirectory, "coding-agents"),
376
381
  ...owner === void 0 ? {} : { nativeSessionOwner: owner },
@@ -378,7 +383,7 @@ async function createCodingAgentAdapter(config, onDiagnostic, owner) {
378
383
  });
379
384
  }
380
385
  case "acp": {
381
- const { AcpCodingAgentAdapter } = await import("./chunks/acp-adapter-LJQBDWYK.js");
386
+ const { AcpCodingAgentAdapter } = await import("./chunks/acp-adapter-HUNUQGUF.js");
382
387
  return new AcpCodingAgentAdapter({
383
388
  command: engine.command,
384
389
  args: engine.args,
@@ -1945,7 +1950,7 @@ var privateNames = /* @__PURE__ */ new Set([
1945
1950
  ".docker",
1946
1951
  ".copilot",
1947
1952
  ".ak",
1948
- LEGACY_CLIENT_STATE_DIRECTORY,
1953
+ ".bluepaw",
1949
1954
  ".copilot-remote",
1950
1955
  ".agentknight",
1951
1956
  "session-state",
@@ -2546,7 +2551,7 @@ var AuthorizedRelaySocket = class {
2546
2551
 
2547
2552
  // src/service/requests/session-communication.ts
2548
2553
  import { AsyncLocalStorage } from "node:async_hooks";
2549
- import { createHash as createHash8 } from "node:crypto";
2554
+ import { createHash as createHash7 } from "node:crypto";
2550
2555
  import { join as join6 } from "node:path";
2551
2556
  import { performance as performance2 } from "node:perf_hooks";
2552
2557
 
@@ -3683,331 +3688,6 @@ function hasSignature(bytes, mimeType) {
3683
3688
  }
3684
3689
  }
3685
3690
 
3686
- // src/session-image-uploader.ts
3687
- import { createHash as createHash7 } from "node:crypto";
3688
- import { z as z5 } from "zod";
3689
- var MAX_ACTIVE_UPLOADS = 3;
3690
- var MAX_JSON_BYTES = 16 * 1024;
3691
- var REQUEST_TIMEOUT_MS = 2e4;
3692
- var UPLOAD_TIMEOUT_MS = 7e4;
3693
- var MAX_GRANT_LIFETIME_MS = 10 * 6e4 + 3e4;
3694
- var UploaderConfigSchema = z5.object({
3695
- relayUrl: SessionImageRelayUrlSchema,
3696
- relayToken: z5.string().min(24).max(4096).regex(/^[\x21-\x7e]+$/u),
3697
- userId: IdSchema.refine((value) => /^[\x20-\x7e]+$/u.test(value)),
3698
- machineId: IdSchema,
3699
- storageAccount: SessionImagesConfigSchema.shape.storageAccount,
3700
- storageContainer: SessionImagesConfigSchema.shape.storageContainer,
3701
- mode: SessionImageStorageSchema.shape.mode.optional()
3702
- });
3703
- function safeCause(error) {
3704
- if (error instanceof SessionImageUploadError) return error;
3705
- if (error instanceof z5.ZodError) return new Error("Schema validation failed.");
3706
- const result = new Error("Image operation failed.");
3707
- if (error instanceof Error) {
3708
- if (["TypeError", "SyntaxError", "AbortError", "TimeoutError"].includes(error.name)) result.name = error.name;
3709
- const code = "code" in error ? error.code : void 0;
3710
- if (typeof code === "string" && ["ECONNRESET", "ECONNREFUSED", "ETIMEDOUT", "ENOTFOUND", "EAI_AGAIN", "UND_ERR_CONNECT_TIMEOUT"].includes(code)) {
3711
- result.cause = { code };
3712
- }
3713
- }
3714
- return result;
3715
- }
3716
- var SessionImageUploadError = class extends Error {
3717
- constructor(code, stage, status, cause) {
3718
- super(`${code} (${stage})`, cause === void 0 ? void 0 : { cause: safeCause(cause) });
3719
- this.code = code;
3720
- this.stage = stage;
3721
- this.status = status;
3722
- this.name = "SessionImageUploadError";
3723
- }
3724
- code;
3725
- stage;
3726
- status;
3727
- };
3728
- function digest(bytes) {
3729
- return createHash7("sha256").update(bytes).digest("hex");
3730
- }
3731
- function assert(condition, code, stage) {
3732
- if (!condition) throw new SessionImageUploadError(code, stage);
3733
- }
3734
- function parse(schema, input, stage) {
3735
- const result = schema.safeParse(input);
3736
- if (!result.success) throw new SessionImageUploadError(
3737
- stage === "config" ? "IMAGE_CONFIG_INVALID" : stage === "source" ? "IMAGE_CONTENT_INVALID" : "IMAGE_RESPONSE_INVALID",
3738
- stage,
3739
- void 0,
3740
- result.error
3741
- );
3742
- return result.data;
3743
- }
3744
- function abortable(operation, signal, stage) {
3745
- return new Promise((resolve5, reject) => {
3746
- const abort = () => reject(new SessionImageUploadError("IMAGE_ABORTED", stage));
3747
- if (signal.aborted) abort();
3748
- else signal.addEventListener("abort", abort, { once: true });
3749
- void operation.then((value) => {
3750
- signal.removeEventListener("abort", abort);
3751
- resolve5(value);
3752
- }, (error) => {
3753
- signal.removeEventListener("abort", abort);
3754
- reject(error);
3755
- });
3756
- });
3757
- }
3758
- var SessionImageUploader = class {
3759
- #config;
3760
- #fetch;
3761
- #active = /* @__PURE__ */ new Set();
3762
- #closed = false;
3763
- constructor(config, dependencies = {}) {
3764
- this.#config = parse(UploaderConfigSchema, config, "config");
3765
- this.#fetch = dependencies.fetch ?? globalThis.fetch;
3766
- }
3767
- close() {
3768
- this.#closed = true;
3769
- for (const controller of this.#active) controller.abort();
3770
- }
3771
- async upload(sessionId, source, signal, assertCurrent = () => void 0) {
3772
- assert(!this.#closed, "IMAGE_UPLOADER_CLOSED", "source");
3773
- assert(!signal?.aborted, "IMAGE_ABORTED", "source");
3774
- const revalidate = (stage) => {
3775
- try {
3776
- assertCurrent();
3777
- } catch (error) {
3778
- throw new SessionImageUploadError("IMAGE_ACCESS_REVOKED", stage, void 0, error);
3779
- }
3780
- };
3781
- revalidate("source");
3782
- assert(this.#active.size < MAX_ACTIVE_UPLOADS, "IMAGE_CAPACITY_EXCEEDED", "source");
3783
- assert(
3784
- Buffer.isBuffer(source) && source.length > 0 && source.length <= SESSION_IMAGE_MAX_BYTES,
3785
- "IMAGE_CONTENT_INVALID",
3786
- "source"
3787
- );
3788
- const scope = parse(SessionImageScopeSchema, { machineId: this.#config.machineId, sessionId }, "source");
3789
- const controller = new AbortController();
3790
- this.#active.add(controller);
3791
- const abort = () => controller.abort();
3792
- signal?.addEventListener("abort", abort, { once: true });
3793
- let timedOut = false;
3794
- const timer = setTimeout(() => {
3795
- timedOut = true;
3796
- controller.abort();
3797
- }, UPLOAD_TIMEOUT_MS);
3798
- timer.unref();
3799
- try {
3800
- const bytes = Buffer.from(source);
3801
- const dimensions = await this.#dimensions(bytes);
3802
- const hash2 = digest(bytes);
3803
- const request2 = parse(SessionImageUploadRequestSchema, { ...scope, sizeBytes: bytes.length }, "source");
3804
- revalidate("reserve");
3805
- const upload = await this.#json(
3806
- `${SESSION_IMAGE_API_PATH}/uploads`,
3807
- request2,
3808
- 201,
3809
- SessionImageUploadResultSchema,
3810
- "reserve",
3811
- controller.signal
3812
- );
3813
- const target = this.#target(upload, scope.sessionId);
3814
- let ambiguous;
3815
- revalidate("put");
3816
- try {
3817
- await this.#request(target, {
3818
- method: "PUT",
3819
- headers: upload.mode === "direct" ? upload.headers : { ...this.#headers(), ...upload.headers },
3820
- body: new Uint8Array(bytes)
3821
- }, "put", controller.signal, async (response) => {
3822
- if (response.status !== 201) throw new SessionImageUploadError("IMAGE_HTTP_ERROR", "put", response.status);
3823
- });
3824
- } catch (error) {
3825
- if (!(error instanceof SessionImageUploadError) || controller.signal.aborted || !(error.code === "IMAGE_NETWORK_ERROR" || error.code === "IMAGE_TIMEOUT" || error.code === "IMAGE_HTTP_ERROR" && [409, 412].includes(error.status ?? 0))) throw error;
3826
- ambiguous = error;
3827
- }
3828
- revalidate("complete");
3829
- try {
3830
- const committed = await this.#json(
3831
- `${SESSION_IMAGE_API_PATH}/${upload.imageId}/complete`,
3832
- scope,
3833
- 200,
3834
- SessionImageCommitResultSchema,
3835
- "complete",
3836
- controller.signal
3837
- );
3838
- assert(
3839
- committed.imageId === upload.imageId && committed.machineId === scope.machineId && committed.sessionId === scope.sessionId && committed.sha256 === hash2 && committed.sizeBytes === bytes.length && committed.width === dimensions.width && committed.height === dimensions.height && Number.isSafeInteger(committed.width) && Number.isSafeInteger(committed.height) && committed.width * committed.height <= SESSION_IMAGE_MAX_PIXELS && Number.isSafeInteger(committed.expiresAt) && committed.expiresAt > Date.now(),
3840
- "IMAGE_COMMIT_MISMATCH",
3841
- "complete"
3842
- );
3843
- revalidate("complete");
3844
- return committed;
3845
- } catch (error) {
3846
- if (ambiguous === void 0 || error instanceof SessionImageUploadError && error.code === "IMAGE_ACCESS_REVOKED") {
3847
- throw error;
3848
- }
3849
- const failure = new SessionImageUploadError("IMAGE_COMPLETION_FAILED", "complete", void 0, error);
3850
- failure.cause = new AggregateError([ambiguous, safeCause(error)], "PUT outcome and completion failed.");
3851
- throw failure;
3852
- }
3853
- } catch (error) {
3854
- if (controller.signal.aborted) {
3855
- throw new SessionImageUploadError(
3856
- timedOut ? "IMAGE_TIMEOUT" : "IMAGE_ABORTED",
3857
- error instanceof SessionImageUploadError ? error.stage : "source",
3858
- void 0,
3859
- error
3860
- );
3861
- }
3862
- if (error instanceof SessionImageUploadError) throw error;
3863
- throw new SessionImageUploadError("IMAGE_CONTENT_INVALID", "source", void 0, error);
3864
- } finally {
3865
- clearTimeout(timer);
3866
- signal?.removeEventListener("abort", abort);
3867
- this.#active.delete(controller);
3868
- }
3869
- }
3870
- async #dimensions(bytes) {
3871
- assert(
3872
- bytes.length >= 20 && bytes.toString("ascii", 0, 4) === "RIFF" && bytes.toString("ascii", 8, 12) === "WEBP" && bytes.readUInt32LE(4) + 8 === bytes.length,
3873
- "IMAGE_CONTENT_INVALID",
3874
- "source"
3875
- );
3876
- const { default: sharp } = await import("sharp");
3877
- const decoder = sharp(bytes, { limitInputPixels: SESSION_IMAGE_MAX_PIXELS, failOn: "warning" });
3878
- try {
3879
- const metadata = await decoder.metadata();
3880
- assert(metadata.format === "webp" && metadata.width !== void 0 && metadata.height !== void 0 && metadata.width > 0 && metadata.height > 0 && (metadata.pages ?? 1) === 1 && metadata.width * metadata.height <= SESSION_IMAGE_MAX_PIXELS, "IMAGE_CONTENT_INVALID", "source");
3881
- return { width: metadata.width, height: metadata.height };
3882
- } finally {
3883
- decoder.destroy();
3884
- }
3885
- }
3886
- #headers() {
3887
- return { authorization: `Bearer ${this.#config.relayToken}`, "x-agentknight-user-id": this.#config.userId };
3888
- }
3889
- #target(upload, sessionId) {
3890
- assert(this.#config.mode === void 0 || upload.mode === this.#config.mode, "IMAGE_UPLOAD_TARGET_INVALID", "reserve");
3891
- const now = Date.now();
3892
- assert(Number.isSafeInteger(upload.uploadExpiresAt) && upload.uploadExpiresAt > now && upload.uploadExpiresAt <= now + MAX_GRANT_LIFETIME_MS, "IMAGE_UPLOAD_EXPIRED", "reserve");
3893
- assert(
3894
- upload.headers["content-type"] === "image/webp" && (upload.headers["if-none-match"] === void 0 || upload.headers["if-none-match"] === "*"),
3895
- "IMAGE_UPLOAD_TARGET_INVALID",
3896
- "reserve"
3897
- );
3898
- if (upload.mode === "proxy") {
3899
- const path2 = `${SESSION_IMAGE_API_PATH}/${upload.imageId}/content`;
3900
- const url2 = new URL(upload.uploadUrl, this.#config.relayUrl);
3901
- assert(
3902
- upload.uploadUrl.split("?")[0] === path2 && url2.origin === this.#config.relayUrl && [...url2.searchParams.keys()].length === 2 && url2.searchParams.getAll("machineId").length === 1 && url2.searchParams.get("machineId") === this.#config.machineId && url2.searchParams.getAll("sessionId").length === 1 && url2.searchParams.get("sessionId") === sessionId && upload.headers["x-ms-blob-type"] === void 0,
3903
- "IMAGE_UPLOAD_TARGET_INVALID",
3904
- "reserve"
3905
- );
3906
- return url2.href;
3907
- }
3908
- const { storageAccount, storageContainer, userId, machineId } = this.#config;
3909
- const host = `${storageAccount}.blob.core.windows.net`;
3910
- const path = `/${storageContainer}/uploads/${digest(userId)}/${digest(machineId)}/${upload.imageId}.webp`;
3911
- const url = new URL(upload.uploadUrl);
3912
- const query = url.searchParams;
3913
- const allowed = /* @__PURE__ */ new Set(["sv", "spr", "st", "se", "sr", "sp", "sig", "skoid", "sktid", "skt", "ske", "sks", "skv"]);
3914
- assert(
3915
- upload.uploadUrl.startsWith(`https://${host}${path}?`) && url.host === host && url.pathname === path && upload.headers["x-ms-blob-type"] === "BlockBlob" && [...query.keys()].every((key) => allowed.has(key) && query.getAll(key).length === 1) && [...allowed].every((key) => (query.get(key)?.length ?? 0) > 0) && query.get("sp") === "c" && query.get("sr") === "b" && query.get("spr") === "https" && query.get("sks") === "b",
3916
- "IMAGE_UPLOAD_TARGET_INVALID",
3917
- "reserve"
3918
- );
3919
- const expiresAt = Date.parse(query.get("se") ?? "");
3920
- const startsAt = Date.parse(query.get("st") ?? "");
3921
- const keyStartsAt = Date.parse(query.get("skt") ?? "");
3922
- const keyExpiresAt = Date.parse(query.get("ske") ?? "");
3923
- assert(
3924
- Number.isFinite(startsAt) && startsAt <= now + 3e4 && Number.isFinite(keyStartsAt) && keyStartsAt <= now + 3e4 && Number.isFinite(expiresAt) && expiresAt > now && expiresAt <= upload.uploadExpiresAt && Number.isFinite(keyExpiresAt) && keyExpiresAt >= expiresAt,
3925
- "IMAGE_UPLOAD_TARGET_INVALID",
3926
- "reserve"
3927
- );
3928
- return url.href;
3929
- }
3930
- async #json(path, body, status, schema, stage, signal) {
3931
- return this.#request(`${this.#config.relayUrl}${path}`, {
3932
- method: "POST",
3933
- headers: { ...this.#headers(), "content-type": "application/json" },
3934
- body: JSON.stringify(body)
3935
- }, stage, signal, async (response, requestSignal) => {
3936
- if (stage === "reserve" && response.status === 404) {
3937
- throw new SessionImageUploadError("IMAGE_STORAGE_UNAVAILABLE", stage, response.status);
3938
- }
3939
- if (response.status !== status) throw new SessionImageUploadError("IMAGE_HTTP_ERROR", stage, response.status);
3940
- const contentLength = response.headers.get("content-length");
3941
- assert(
3942
- contentLength === null || /^\d+$/u.test(contentLength) && Number(contentLength) <= MAX_JSON_BYTES,
3943
- "IMAGE_RESPONSE_TOO_LARGE",
3944
- stage
3945
- );
3946
- assert(response.body !== null, "IMAGE_RESPONSE_INVALID", stage);
3947
- const reader = response.body.getReader();
3948
- const chunks = [];
3949
- let size = 0;
3950
- try {
3951
- while (true) {
3952
- const next = await abortable(reader.read(), requestSignal, stage);
3953
- requestSignal.throwIfAborted();
3954
- if (next.done) break;
3955
- size += next.value.byteLength;
3956
- assert(size <= MAX_JSON_BYTES, "IMAGE_RESPONSE_TOO_LARGE", stage);
3957
- chunks.push(next.value);
3958
- }
3959
- let value;
3960
- try {
3961
- value = JSON.parse(Buffer.concat(chunks, size).toString("utf8"));
3962
- } catch (error) {
3963
- throw new SessionImageUploadError("IMAGE_RESPONSE_INVALID", stage, void 0, error);
3964
- }
3965
- return parse(schema, value, stage);
3966
- } finally {
3967
- reader.releaseLock();
3968
- }
3969
- });
3970
- }
3971
- async #request(url, init, stage, signal, consume) {
3972
- assert(!signal.aborted, "IMAGE_ABORTED", stage);
3973
- const controller = new AbortController();
3974
- const abort = () => controller.abort();
3975
- signal.addEventListener("abort", abort, { once: true });
3976
- let timedOut = false;
3977
- const timer = setTimeout(() => {
3978
- timedOut = true;
3979
- controller.abort();
3980
- }, REQUEST_TIMEOUT_MS);
3981
- timer.unref();
3982
- try {
3983
- const response = await this.#fetch(url, {
3984
- ...init,
3985
- signal: controller.signal,
3986
- redirect: "error",
3987
- credentials: "omit",
3988
- cache: "no-store",
3989
- referrerPolicy: "no-referrer"
3990
- });
3991
- try {
3992
- controller.signal.throwIfAborted();
3993
- assert(!response.redirected, "IMAGE_RESPONSE_INVALID", stage);
3994
- return await consume(response, controller.signal);
3995
- } finally {
3996
- await response.body?.cancel();
3997
- }
3998
- } catch (error) {
3999
- if (controller.signal.aborted) {
4000
- throw new SessionImageUploadError(timedOut ? "IMAGE_TIMEOUT" : "IMAGE_ABORTED", stage, void 0, error);
4001
- }
4002
- if (error instanceof SessionImageUploadError) throw error;
4003
- throw new SessionImageUploadError("IMAGE_NETWORK_ERROR", stage, void 0, error);
4004
- } finally {
4005
- clearTimeout(timer);
4006
- signal.removeEventListener("abort", abort);
4007
- }
4008
- }
4009
- };
4010
-
4011
3691
  // src/service/requests/request-errors.ts
4012
3692
  function operationErrorCode(agentId, operation, error) {
4013
3693
  if (isSessionRestoreFailure(error)) return "SESSION_RESTORE_FAILED";
@@ -4383,7 +4063,7 @@ var SessionCommunicationHandler = class {
4383
4063
  }
4384
4064
  const clientId = scope.clientId;
4385
4065
  const owner = [config.userId, machineId, clientId, request2.sessionId];
4386
- const key = (parts) => createHash8("sha256").update(JSON.stringify(parts)).digest("hex").slice(0, 24);
4066
+ const key = (parts) => createHash7("sha256").update(JSON.stringify(parts)).digest("hex").slice(0, 24);
4387
4067
  const knownSource = this.#researchParents.get(request2.sessionId) ?? adapter.sessionPublicationSource?.(request2.sessionId) ?? request2.sessionId;
4388
4068
  const arrivalPublication = adapter.isSessionVisible?.(knownSource) === true ? publications.capture(knownSource) : void 0;
4389
4069
  let researchParent = this.#researchParents.get(request2.sessionId);
@@ -4562,18 +4242,210 @@ var SessionCommunicationHandler = class {
4562
4242
  }
4563
4243
  };
4564
4244
 
4245
+ // src/service/requests/device-text-input.ts
4246
+ import { createHash as createHash8 } from "node:crypto";
4247
+
4248
+ // src/windows-text-input.ts
4249
+ import { spawn } from "node:child_process";
4250
+ import { join as join7 } from "node:path";
4251
+ var TextInputError = class extends Error {
4252
+ constructor(code) {
4253
+ super(code);
4254
+ this.code = code;
4255
+ }
4256
+ code;
4257
+ };
4258
+ var WINDOWS_TEXT_INPUT_SCRIPT = String.raw`
4259
+ $ErrorActionPreference = 'Stop'
4260
+ [Console]::InputEncoding = [System.Text.UTF8Encoding]::new($false)
4261
+ [Console]::OutputEncoding = [System.Text.UTF8Encoding]::new($false)
4262
+ $request = [Console]::In.ReadToEnd() | ConvertFrom-Json
4263
+ Add-Type -AssemblyName System.Windows.Forms
4264
+ Add-Type -TypeDefinition @'
4265
+ using System;
4266
+ using System.Runtime.InteropServices;
4267
+ public static class TextInputNative {
4268
+ [StructLayout(LayoutKind.Sequential)] public struct KEYBDINPUT {
4269
+ public ushort key, scan; public uint flags, time; public UIntPtr extra;
4270
+ }
4271
+ [StructLayout(LayoutKind.Sequential)] public struct MOUSEINPUT {
4272
+ public int x, y; public uint data, flags, time; public UIntPtr extra;
4273
+ }
4274
+ [StructLayout(LayoutKind.Explicit)] public struct UNION {
4275
+ [FieldOffset(0)] public KEYBDINPUT keyboard;
4276
+ [FieldOffset(0)] public MOUSEINPUT mouse;
4277
+ }
4278
+ [StructLayout(LayoutKind.Sequential)] public struct INPUT { public uint type; public UNION value; }
4279
+ [DllImport("user32.dll")] public static extern IntPtr GetForegroundWindow();
4280
+ [DllImport("user32.dll", SetLastError=true)] static extern uint SendInput(uint count, INPUT[] input, int size);
4281
+ [DllImport("user32.dll", SetLastError=true)] static extern IntPtr OpenInputDesktop(uint flags, bool inherit, uint access);
4282
+ [DllImport("user32.dll")] static extern bool SwitchDesktop(IntPtr desktop);
4283
+ [DllImport("user32.dll")] static extern bool CloseDesktop(IntPtr desktop);
4284
+ public static bool Interactive() {
4285
+ var desktop = OpenInputDesktop(0, false, 0x100);
4286
+ if (desktop == IntPtr.Zero) return false;
4287
+ try { return SwitchDesktop(desktop); } finally { CloseDesktop(desktop); }
4288
+ }
4289
+ public static bool Paste() {
4290
+ var keys = new ushort[] { 0x11, 0x56, 0x56, 0x11 };
4291
+ var inputs = new INPUT[4];
4292
+ for (int i=0; i<4; i++) {
4293
+ inputs[i].type = 1;
4294
+ inputs[i].value.keyboard.key = keys[i];
4295
+ inputs[i].value.keyboard.flags = i >= 2 ? 2u : 0u;
4296
+ }
4297
+ var sent = SendInput(4, inputs, Marshal.SizeOf(typeof(INPUT)));
4298
+ if (sent != 4) {
4299
+ // Release modifiers if Windows accepted only part of the chord.
4300
+ inputs[0].value.keyboard.flags = 2;
4301
+ inputs[1].value.keyboard.flags = 2;
4302
+ SendInput(2, inputs, Marshal.SizeOf(typeof(INPUT)));
4303
+ }
4304
+ return sent == 4;
4305
+ }
4306
+ }
4307
+ '@
4308
+ $clipboard = $false
4309
+ $attempted = $false
4310
+ $sent = $false
4311
+ try {
4312
+ if ([DateTimeOffset]::UtcNow.ToUnixTimeMilliseconds() -ge $request.expiresAt) { throw 'expired' }
4313
+ if (-not [TextInputNative]::Interactive()) { throw 'locked' }
4314
+ $target = [TextInputNative]::GetForegroundWindow()
4315
+ [System.Windows.Forms.Clipboard]::SetText([string]$request.text)
4316
+ $clipboard = $true
4317
+ Start-Sleep -Milliseconds 60
4318
+ if ([DateTimeOffset]::UtcNow.ToUnixTimeMilliseconds() -lt $request.expiresAt -and
4319
+ [TextInputNative]::Interactive() -and $target -ne [IntPtr]::Zero -and
4320
+ $target -eq [TextInputNative]::GetForegroundWindow()) {
4321
+ $attempted = $true
4322
+ $sent = [TextInputNative]::Paste()
4323
+ }
4324
+ } catch {
4325
+ if (-not $clipboard) { [Console]::Error.WriteLine('TEXT_INPUT_UNAVAILABLE'); exit 1 }
4326
+ }
4327
+ @{ clipboardUpdated=$clipboard; pasteAttempted=$attempted; pasteShortcutSent=$sent } |
4328
+ ConvertTo-Json -Compress
4329
+ `;
4330
+ function createWindowsTextInput() {
4331
+ if (process.platform !== "win32") return void 0;
4332
+ const root = process.env["SystemRoot"];
4333
+ if (root === void 0) return void 0;
4334
+ const executable = join7(root, "System32", "WindowsPowerShell", "v1.0", "powershell.exe");
4335
+ return (data) => runWindowsTextInput(executable, data);
4336
+ }
4337
+ function runWindowsTextInput(executable, data) {
4338
+ const timeout = data.expiresAt - Date.now();
4339
+ if (timeout <= 0) return Promise.reject(new TextInputError("TEXT_INPUT_EXPIRED"));
4340
+ return new Promise((resolve5, reject) => {
4341
+ const child = spawn(executable, [
4342
+ "-NoLogo",
4343
+ "-NoProfile",
4344
+ "-NonInteractive",
4345
+ "-STA",
4346
+ "-EncodedCommand",
4347
+ Buffer.from(WINDOWS_TEXT_INPUT_SCRIPT, "utf16le").toString("base64")
4348
+ ], { windowsHide: true, stdio: ["pipe", "pipe", "pipe"] });
4349
+ let stdout = "";
4350
+ let finished = false;
4351
+ const fail4 = (code) => {
4352
+ if (finished) return;
4353
+ finished = true;
4354
+ clearTimeout(timer);
4355
+ child.kill();
4356
+ reject(new TextInputError(code));
4357
+ };
4358
+ const timer = setTimeout(() => fail4("TEXT_INPUT_TIMEOUT"), timeout);
4359
+ child.on("error", () => fail4("TEXT_INPUT_UNAVAILABLE"));
4360
+ child.stdin.on("error", () => fail4("TEXT_INPUT_UNAVAILABLE"));
4361
+ child.stdout.setEncoding("utf8");
4362
+ child.stdout.on("data", (chunk) => {
4363
+ stdout += chunk;
4364
+ if (stdout.length > 4096) fail4("INVALID_TEXT_INPUT_RESULT");
4365
+ });
4366
+ child.stderr.resume();
4367
+ child.on("close", (code) => {
4368
+ if (finished) return;
4369
+ if (code !== 0) return fail4("TEXT_INPUT_UNAVAILABLE");
4370
+ try {
4371
+ const result = DeviceTextInputResultSchema.parse(JSON.parse(stdout));
4372
+ finished = true;
4373
+ clearTimeout(timer);
4374
+ resolve5(result);
4375
+ } catch {
4376
+ fail4("INVALID_TEXT_INPUT_RESULT");
4377
+ }
4378
+ });
4379
+ child.stdin.end(JSON.stringify(data), "utf8");
4380
+ });
4381
+ }
4382
+
4383
+ // src/service/requests/device-text-input.ts
4384
+ var MAX_CLOCK_SKEW_MS = 1e3;
4385
+ var DeviceTextInputHandler = class {
4386
+ constructor(writer) {
4387
+ this.writer = writer;
4388
+ }
4389
+ writer;
4390
+ requests = /* @__PURE__ */ new Map();
4391
+ tail = Promise.resolve();
4392
+ async handle(request2, scope) {
4393
+ const error = (code) => sessionCommunicationError(request2, { code, message: textInputErrorMessage(code) });
4394
+ if (request2.sessionId !== DEVICE_TEXT_INPUT_SCOPE || request2.operation !== DEVICE_TEXT_INPUT_OPERATION) {
4395
+ return error("INVALID_DEVICE_SCOPE");
4396
+ }
4397
+ if (request2.version !== DEVICE_TEXT_INPUT_VERSION) return error("UNSUPPORTED_OPERATION_VERSION");
4398
+ const data = DeviceTextInputDataSchema.safeParse(request2.data);
4399
+ if (!data.success) return error("INVALID_OPERATION_DATA");
4400
+ if (scope.clientId === void 0 || !scope.isCurrent()) return error("TEXT_INPUT_UNAVAILABLE");
4401
+ const writer = this.writer;
4402
+ if (writer === void 0) return error("UNSUPPORTED_OPERATION");
4403
+ const now = Date.now();
4404
+ for (const [key2, item] of this.requests) if (item.expiresAt <= now) this.requests.delete(key2);
4405
+ const key = JSON.stringify([scope.clientId, request2.requestId]);
4406
+ const fingerprint = createHash8("sha256").update(JSON.stringify(data.data)).digest("hex");
4407
+ const cached = this.requests.get(key);
4408
+ if (cached !== void 0) return cached.fingerprint === fingerprint ? cached.response : error("REQUEST_ID_REUSED");
4409
+ if (data.data.expiresAt <= now || data.data.expiresAt > now + DEVICE_TEXT_INPUT_TTL_MS + MAX_CLOCK_SKEW_MS) {
4410
+ return error("TEXT_INPUT_EXPIRED");
4411
+ }
4412
+ const expiresAt = Math.min(data.data.expiresAt, now + DEVICE_TEXT_INPUT_TTL_MS);
4413
+ if (this.requests.size >= 128) return error("TEXT_INPUT_BUSY");
4414
+ const response = this.tail.then(async () => {
4415
+ if (!scope.isCurrent()) return error("TEXT_INPUT_UNAVAILABLE");
4416
+ if (Date.now() >= expiresAt) return error("TEXT_INPUT_EXPIRED");
4417
+ try {
4418
+ const result = DeviceTextInputResultSchema.parse(await writer({ ...data.data, expiresAt }));
4419
+ return { ...request2, kind: "response", data: result };
4420
+ } catch (cause) {
4421
+ return error(cause instanceof TextInputError ? cause.code : "TEXT_INPUT_UNAVAILABLE");
4422
+ }
4423
+ });
4424
+ this.requests.set(key, { fingerprint, expiresAt: data.data.expiresAt + DEVICE_TEXT_INPUT_TTL_MS, response });
4425
+ this.tail = response.then(() => void 0);
4426
+ return response;
4427
+ }
4428
+ };
4429
+ function textInputErrorMessage(code) {
4430
+ if (code === "TEXT_INPUT_EXPIRED" || code === "TEXT_INPUT_TIMEOUT") {
4431
+ return "PC input confirmation timed out. The text may already be on the PC.";
4432
+ }
4433
+ if (code === "UNSUPPORTED_OPERATION") return "This PC does not support text input.";
4434
+ return "The PC could not confirm text delivery.";
4435
+ }
4436
+
4565
4437
  // src/desktop-workspaces.ts
4566
4438
  import { createHash as createHash9 } from "node:crypto";
4567
4439
  import { readdir, realpath as realpath5, stat as stat5 } from "node:fs/promises";
4568
4440
  import { homedir } from "node:os";
4569
- import { basename, join as join7, normalize } from "node:path";
4441
+ import { basename, join as join8, normalize } from "node:path";
4570
4442
  function desktopRootCandidates(environment2 = process.env) {
4571
4443
  const candidates = [
4572
4444
  environment2.AGENTKNIGHT_WORKSPACE_ROOT,
4573
- environment2.OneDrive === void 0 ? void 0 : join7(environment2.OneDrive, "Desktop"),
4574
- environment2.OneDriveCommercial === void 0 ? void 0 : join7(environment2.OneDriveCommercial, "Desktop"),
4575
- environment2.OneDriveConsumer === void 0 ? void 0 : join7(environment2.OneDriveConsumer, "Desktop"),
4576
- join7(environment2.USERPROFILE ?? homedir(), "Desktop")
4445
+ environment2.OneDrive === void 0 ? void 0 : join8(environment2.OneDrive, "Desktop"),
4446
+ environment2.OneDriveCommercial === void 0 ? void 0 : join8(environment2.OneDriveCommercial, "Desktop"),
4447
+ environment2.OneDriveConsumer === void 0 ? void 0 : join8(environment2.OneDriveConsumer, "Desktop"),
4448
+ join8(environment2.USERPROFILE ?? homedir(), "Desktop")
4577
4449
  ];
4578
4450
  return [...new Set(candidates.filter((path) => path !== void 0))];
4579
4451
  }
@@ -4614,7 +4486,7 @@ async function listDesktopWorkspaces(rootOverride) {
4614
4486
  const workspaces = entries.filter(
4615
4487
  (entry) => entry.isDirectory() && !entry.name.startsWith(".") && entry.name.trim().length > 0
4616
4488
  ).map((entry) => {
4617
- const path = join7(root, entry.name);
4489
+ const path = join8(root, entry.name);
4618
4490
  return {
4619
4491
  id: workspaceId(path),
4620
4492
  name: entry.name,
@@ -4686,7 +4558,7 @@ import { execFile as execFile2 } from "node:child_process";
4686
4558
  import { randomUUID as randomUUID4 } from "node:crypto";
4687
4559
  import { lstat as lstat5, mkdir as mkdir3, realpath as realpath6, rmdir } from "node:fs/promises";
4688
4560
  import { devNull } from "node:os";
4689
- import { dirname as dirname2, isAbsolute as isAbsolute5, join as join8, relative as relative3 } from "node:path";
4561
+ import { dirname as dirname2, isAbsolute as isAbsolute5, join as join9, relative as relative3 } from "node:path";
4690
4562
  import { promisify as promisify3 } from "node:util";
4691
4563
  var execFileAsync = promisify3(execFile2);
4692
4564
  function creationEnvironment() {
@@ -4796,7 +4668,7 @@ async function createSessionWorktree(sourceDirectory, requestedBranchName, reque
4796
4668
  if (inside(identity2.worktreeRoot, parent)) {
4797
4669
  throw new Error("Cannot create a sibling worktree outside the source checkout. Move the repository and retry.");
4798
4670
  }
4799
- const path = join8(parent, `agentknight-worktree-${suffix}`);
4671
+ const path = join9(parent, `agentknight-worktree-${suffix}`);
4800
4672
  if (path.length > 640) {
4801
4673
  throw new Error("The repository path is too long to report worktree recovery safely. Use a checkout closer to the filesystem root.");
4802
4674
  }
@@ -5657,8 +5529,8 @@ import { randomUUID as randomUUID5 } from "node:crypto";
5657
5529
  import { setTimeout as delay } from "node:timers/promises";
5658
5530
  import { Role, TaskState } from "@a2a-js/sdk";
5659
5531
  import { ClientFactory, DefaultAgentCardResolver, JsonRpcTransportFactory } from "@a2a-js/sdk/client";
5660
- import { z as z6 } from "zod";
5661
- var TextSchema = z6.string().max(16e3).refine((text) => text.trim().length > 0);
5532
+ import { z as z5 } from "zod";
5533
+ var TextSchema = z5.string().max(16e3).refine((text) => text.trim().length > 0);
5662
5534
  var HTTP_TIMEOUT_MS = 1e4;
5663
5535
  var MAX_RESPONSE_BYTES = 262144;
5664
5536
  function relayEndpoint(relayUrl, target) {
@@ -5843,7 +5715,7 @@ import {
5843
5715
  ServerCallContext,
5844
5716
  validateVersion
5845
5717
  } from "@a2a-js/sdk/server";
5846
- import { z as z7 } from "zod";
5718
+ import { z as z6 } from "zod";
5847
5719
  var MAX_ACTIVE = 4;
5848
5720
  var MAX_TASKS = 128;
5849
5721
  var MAX_RECEIPTS = 256;
@@ -5852,52 +5724,52 @@ var TURN_TIMEOUT_MS = 12e4;
5852
5724
  var SHORT_REQUEST_TIMEOUT_MS = 9e3;
5853
5725
  var MAX_TEXT2 = 16e3;
5854
5726
  var TASK_WIRE_BUDGET = 6e4;
5855
- var idSchema = z7.string().min(1).max(256).regex(/^[^\s\u0000-\u001f\u007f]+$/u);
5856
- var optionalIdSchema = z7.union([z7.literal(""), idSchema]).optional();
5857
- var historySchema = z7.number().int().min(0).max(128).optional();
5858
- var emptyMetadataSchema = z7.object({}).strict().optional();
5859
- var tenantSchema = z7.literal("").optional();
5860
- var rpcSchema = z7.object({
5861
- jsonrpc: z7.literal("2.0"),
5862
- id: z7.union([idSchema, z7.number().int().safe(), z7.null()]),
5863
- method: z7.string().min(1).max(128),
5864
- params: z7.unknown()
5727
+ var idSchema = z6.string().min(1).max(256).regex(/^[^\s\u0000-\u001f\u007f]+$/u);
5728
+ var optionalIdSchema = z6.union([z6.literal(""), idSchema]).optional();
5729
+ var historySchema = z6.number().int().min(0).max(128).optional();
5730
+ var emptyMetadataSchema = z6.object({}).strict().optional();
5731
+ var tenantSchema = z6.literal("").optional();
5732
+ var rpcSchema = z6.object({
5733
+ jsonrpc: z6.literal("2.0"),
5734
+ id: z6.union([idSchema, z6.number().int().safe(), z6.null()]),
5735
+ method: z6.string().min(1).max(128),
5736
+ params: z6.unknown()
5865
5737
  }).strict();
5866
- var sendSchema = z7.object({
5738
+ var sendSchema = z6.object({
5867
5739
  tenant: tenantSchema,
5868
- message: z7.object({
5740
+ message: z6.object({
5869
5741
  messageId: idSchema,
5870
5742
  contextId: optionalIdSchema,
5871
5743
  taskId: optionalIdSchema,
5872
- role: z7.union([z7.literal("ROLE_USER"), z7.literal(Role2.ROLE_USER)]),
5873
- parts: z7.array(z7.object({
5874
- text: z7.string().max(MAX_TEXT2),
5875
- mediaType: z7.union([z7.literal(""), z7.literal("text/plain")]).optional(),
5876
- filename: z7.literal("").optional(),
5744
+ role: z6.union([z6.literal("ROLE_USER"), z6.literal(Role2.ROLE_USER)]),
5745
+ parts: z6.array(z6.object({
5746
+ text: z6.string().max(MAX_TEXT2),
5747
+ mediaType: z6.union([z6.literal(""), z6.literal("text/plain")]).optional(),
5748
+ filename: z6.literal("").optional(),
5877
5749
  metadata: emptyMetadataSchema
5878
5750
  }).strict()).min(1).max(32),
5879
5751
  metadata: emptyMetadataSchema,
5880
- extensions: z7.array(z7.never()).optional(),
5881
- referenceTaskIds: z7.array(z7.never()).optional()
5752
+ extensions: z6.array(z6.never()).optional(),
5753
+ referenceTaskIds: z6.array(z6.never()).optional()
5882
5754
  }).strict().refine((message) => {
5883
5755
  const text = message.parts.map((part) => part.text).join("\n");
5884
5756
  return text.trim().length > 0 && text.length <= MAX_TEXT2;
5885
5757
  }, "A message must contain nonempty plain text of at most 16000 characters."),
5886
- configuration: z7.object({
5887
- acceptedOutputModes: z7.array(z7.literal("text/plain")).max(1).optional(),
5888
- returnImmediately: z7.boolean().optional(),
5758
+ configuration: z6.object({
5759
+ acceptedOutputModes: z6.array(z6.literal("text/plain")).max(1).optional(),
5760
+ returnImmediately: z6.boolean().optional(),
5889
5761
  historyLength: historySchema
5890
5762
  }).strict().optional(),
5891
5763
  metadata: emptyMetadataSchema
5892
5764
  }).strict();
5893
- var getSchema = z7.object({ tenant: tenantSchema, id: idSchema, historyLength: historySchema }).strict();
5894
- var cancelSchema = z7.object({ tenant: tenantSchema, id: idSchema, metadata: emptyMetadataSchema }).strict();
5895
- var listSchema2 = z7.object({
5765
+ var getSchema = z6.object({ tenant: tenantSchema, id: idSchema, historyLength: historySchema }).strict();
5766
+ var cancelSchema = z6.object({ tenant: tenantSchema, id: idSchema, metadata: emptyMetadataSchema }).strict();
5767
+ var listSchema2 = z6.object({
5896
5768
  tenant: tenantSchema,
5897
5769
  contextId: optionalIdSchema,
5898
- status: z7.union([
5899
- z7.number().int().min(0).max(8),
5900
- z7.enum([
5770
+ status: z6.union([
5771
+ z6.number().int().min(0).max(8),
5772
+ z6.enum([
5901
5773
  "TASK_STATE_UNSPECIFIED",
5902
5774
  "TASK_STATE_SUBMITTED",
5903
5775
  "TASK_STATE_WORKING",
@@ -5909,11 +5781,11 @@ var listSchema2 = z7.object({
5909
5781
  "TASK_STATE_AUTH_REQUIRED"
5910
5782
  ])
5911
5783
  ]).optional(),
5912
- pageSize: z7.number().int().min(1).max(100).optional(),
5913
- pageToken: z7.string().regex(/^(?:|0|[1-9]\d{0,3})$/u).optional(),
5784
+ pageSize: z6.number().int().min(1).max(100).optional(),
5785
+ pageToken: z6.string().regex(/^(?:|0|[1-9]\d{0,3})$/u).optional(),
5914
5786
  historyLength: historySchema,
5915
- statusTimestampAfter: z7.iso.datetime({ offset: true }).optional(),
5916
- includeArtifacts: z7.boolean().optional()
5787
+ statusTimestampAfter: z6.iso.datetime({ offset: true }).optional(),
5788
+ includeArtifacts: z6.boolean().optional()
5917
5789
  }).strict();
5918
5790
  function deferred() {
5919
5791
  let resolve5 = () => {
@@ -7023,9 +6895,9 @@ var SnapshotAudience = class {
7023
6895
  async publish(snapshot, recipient) {
7024
6896
  const generation = this.#generation;
7025
6897
  const { sequence: _sequence, generatedAt: _generatedAt, ...content } = snapshot;
7026
- const digest2 = createHash12("sha256").update(JSON.stringify(content)).digest("base64url");
6898
+ const digest = createHash12("sha256").update(JSON.stringify(content)).digest("base64url");
7027
6899
  if (recipient !== void 0) {
7028
- await this.#direct(snapshot, recipient, digest2, generation);
6900
+ await this.#direct(snapshot, recipient, digest, generation);
7029
6901
  return;
7030
6902
  }
7031
6903
  if (!this.#negotiated || this.#registrationBaseline) {
@@ -7037,10 +6909,10 @@ var SnapshotAudience = class {
7037
6909
  }
7038
6910
  const pending = [];
7039
6911
  for (const [clientId, baseline] of this.#audiences) {
7040
- if (baseline.digest === digest2) {
6912
+ if (baseline.digest === digest) {
7041
6913
  this.#metrics.unchangedRecipients += 1;
7042
6914
  } else {
7043
- pending.push(this.#direct(snapshot, clientId, digest2, generation));
6915
+ pending.push(this.#direct(snapshot, clientId, digest, generation));
7044
6916
  }
7045
6917
  }
7046
6918
  if (this.#audiences.size === 0) this.#metrics.withoutRecipients += 1;
@@ -7053,12 +6925,12 @@ var SnapshotAudience = class {
7053
6925
  this.#metrics = this.#emptyMetrics();
7054
6926
  return metrics;
7055
6927
  }
7056
- async #direct(snapshot, recipient, digest2, generation) {
6928
+ async #direct(snapshot, recipient, digest, generation) {
7057
6929
  const baseline = this.#audiences.get(recipient);
7058
6930
  this.#metrics.directedAttempts += 1;
7059
6931
  await this.send(snapshot, recipient);
7060
6932
  if (generation === this.#generation && baseline !== void 0 && this.#audiences.get(recipient) === baseline) {
7061
- baseline.digest = digest2;
6933
+ baseline.digest = digest;
7062
6934
  }
7063
6935
  }
7064
6936
  #emptyMetrics() {
@@ -7582,6 +7454,10 @@ function canAppend(previous, item) {
7582
7454
 
7583
7455
  // src/timeline-image-blob.ts
7584
7456
  import { createHash as createHash14 } from "node:crypto";
7457
+ var MAX_ACTIVE_PUBLICATIONS = 3;
7458
+ var MAX_QUEUED_PUBLICATIONS = 16;
7459
+ var QUEUE_TIMEOUT_MS = 15e3;
7460
+ var PUBLICATION_TIMEOUT_MS = 85e3;
7585
7461
  var TimelineImageBlobPublisher = class {
7586
7462
  constructor(images, uploader) {
7587
7463
  this.images = images;
@@ -7591,6 +7467,8 @@ var TimelineImageBlobPublisher = class {
7591
7467
  uploader;
7592
7468
  #references = /* @__PURE__ */ new Map();
7593
7469
  #flights = /* @__PURE__ */ new Map();
7470
+ #waiting = /* @__PURE__ */ new Set();
7471
+ #active = 0;
7594
7472
  #closed = false;
7595
7473
  async publish(sessionId, sha256, assertCurrent) {
7596
7474
  TimelineImageBlobRequestSchema.parse({ sha256 });
@@ -7607,13 +7485,19 @@ var TimelineImageBlobPublisher = class {
7607
7485
  }
7608
7486
  let flight = this.#flights.get(key);
7609
7487
  if (flight === void 0) {
7610
- if (this.#flights.size >= 3) throw new TimelineAssetError("IMAGE_BLOB_BUSY", "Too many image uploads");
7488
+ if (this.#flights.size >= MAX_ACTIVE_PUBLICATIONS + MAX_QUEUED_PUBLICATIONS) {
7489
+ throw new TimelineAssetError("IMAGE_BLOB_BUSY", "The image publication queue is full");
7490
+ }
7611
7491
  const controller = new AbortController();
7492
+ const timer = setTimeout(() => {
7493
+ controller.abort(new TimelineAssetError("IMAGE_TIMEOUT", "Image publication deadline expired"));
7494
+ }, PUBLICATION_TIMEOUT_MS);
7495
+ timer.unref();
7612
7496
  const check = () => {
7613
7497
  controller.signal.throwIfAborted();
7614
7498
  assertCurrent();
7615
7499
  };
7616
- const promise = this.#publish(sessionId, sha256, controller.signal, check).then((result2) => {
7500
+ const promise = this.#scheduledPublish(sessionId, sha256, controller.signal, check).then((result2) => {
7617
7501
  check();
7618
7502
  this.#references.set(key, result2);
7619
7503
  while (this.#references.size > 256) {
@@ -7623,6 +7507,7 @@ var TimelineImageBlobPublisher = class {
7623
7507
  }
7624
7508
  return result2;
7625
7509
  }).finally(() => {
7510
+ clearTimeout(timer);
7626
7511
  this.#flights.delete(key);
7627
7512
  });
7628
7513
  flight = { sessionId, controller, promise };
@@ -7649,6 +7534,43 @@ var TimelineImageBlobPublisher = class {
7649
7534
  this.reset();
7650
7535
  await Promise.allSettled([...this.#flights.values()].map((flight) => flight.promise));
7651
7536
  }
7537
+ async #scheduledPublish(sessionId, sha256, signal, check) {
7538
+ if (this.#active >= MAX_ACTIVE_PUBLICATIONS) {
7539
+ await new Promise((resolve5, reject) => {
7540
+ const cleanup = () => {
7541
+ clearTimeout(timer);
7542
+ signal.removeEventListener("abort", abort);
7543
+ this.#waiting.delete(start);
7544
+ };
7545
+ const start = () => {
7546
+ cleanup();
7547
+ this.#active += 1;
7548
+ resolve5();
7549
+ };
7550
+ const abort = () => {
7551
+ cleanup();
7552
+ reject(signal.reason);
7553
+ };
7554
+ const timer = setTimeout(() => {
7555
+ cleanup();
7556
+ reject(new TimelineAssetError("IMAGE_BLOB_BUSY", "Image publication queue wait expired"));
7557
+ }, QUEUE_TIMEOUT_MS);
7558
+ timer.unref();
7559
+ this.#waiting.add(start);
7560
+ signal.addEventListener("abort", abort, { once: true });
7561
+ if (signal.aborted) abort();
7562
+ });
7563
+ } else {
7564
+ this.#active += 1;
7565
+ }
7566
+ try {
7567
+ check();
7568
+ return await this.#publish(sessionId, sha256, signal, check);
7569
+ } finally {
7570
+ this.#active -= 1;
7571
+ this.#waiting.values().next().value?.();
7572
+ }
7573
+ }
7652
7574
  async #publish(sessionId, sha256, signal, check) {
7653
7575
  const asset = this.images.readAsset(sessionId, sha256);
7654
7576
  const extension = { "image/png": ".png", "image/jpeg": ".jpg", "image/webp": ".webp" }[asset.mimeType];
@@ -8176,7 +8098,7 @@ var SESSION_LIST_REFRESH_RETRIES = 2;
8176
8098
  var TRAFFIC_METRICS_INTERVAL_MS = 6e4;
8177
8099
  var RELAY_RECONNECT_INTERVAL_MS = 15 * 6e4;
8178
8100
  var PcAgent = class {
8179
- constructor(config, identity2, appVersion, adapter, logger, pairingProvider, contentCipher, research, createSocket = createRelaySocket, onPairing) {
8101
+ constructor(config, identity2, appVersion, adapter, logger, pairingProvider, contentCipher, research, createSocket = createRelaySocket, onPairing, textInputWriter = createWindowsTextInput()) {
8180
8102
  this.config = config;
8181
8103
  this.identity = identity2;
8182
8104
  this.appVersion = appVersion;
@@ -8185,6 +8107,8 @@ var PcAgent = class {
8185
8107
  this.pairingProvider = pairingProvider;
8186
8108
  this.research = research;
8187
8109
  this.onPairing = onPairing;
8110
+ this.textInputWriter = textInputWriter;
8111
+ this.#textInput = new DeviceTextInputHandler(textInputWriter);
8188
8112
  if (research?.chat !== void 0) {
8189
8113
  adapter = researchAwareCodingAgentAdapter(adapter, research.chat);
8190
8114
  this.adapter = adapter;
@@ -8308,7 +8232,24 @@ var PcAgent = class {
8308
8232
  this.#secureRequestRouter = createPcSecureRequestRouter({
8309
8233
  configuredMachineId: identity2.machineId,
8310
8234
  handlers: {
8311
- sessionCommunication: (request2) => this.#admitRequest(request2, "session.communication", () => this.#communication.handle(request2, this.#requestScope())),
8235
+ sessionCommunication: (request2) => this.#admitRequest(request2, "session.communication", async () => {
8236
+ if (request2.operation === DEVICE_TEXT_INPUT_OPERATION) {
8237
+ const scope = this.#requestScope();
8238
+ const clientId = scope.clientId;
8239
+ const access = clientId === void 0 ? void 0 : this.#textInputClients.get(clientId) ?? {};
8240
+ if (clientId !== void 0 && access !== void 0) this.#textInputClients.set(clientId, access);
8241
+ const response = await this.#textInput.handle(request2, {
8242
+ ...scope,
8243
+ isCurrent: () => scope.isCurrent() && this.#machineRegistered && this.#communicationNegotiated && clientId !== void 0 && this.#textInputClients.get(clientId) === access
8244
+ });
8245
+ if (response.kind === "error") {
8246
+ this.logger.warn({ code: response.error.code }, "device.text.input.failed");
8247
+ }
8248
+ this.#emitSecure("session.communication", response);
8249
+ } else {
8250
+ await this.#communication.handle(request2, this.#requestScope());
8251
+ }
8252
+ }),
8312
8253
  sessionList: (request2) => this.#admitRequest(request2, "session.list.result", () => this.#handleSessionList(request2)),
8313
8254
  sessionOptions: (request2) => this.#admitRequest(request2, "session.options.result", () => this.#sessionOptions.handle(request2, this.#requestScope())),
8314
8255
  sessionCreate: (request2) => this.#admitRequest(request2, "session.create.result", () => this.#commands.create(request2, this.#requestScope())),
@@ -8599,6 +8540,7 @@ var PcAgent = class {
8599
8540
  pairingProvider;
8600
8541
  research;
8601
8542
  onPairing;
8543
+ textInputWriter;
8602
8544
  #agentRunId = randomUUID9();
8603
8545
  #clientId = randomUUID9();
8604
8546
  #socket;
@@ -8649,6 +8591,8 @@ var PcAgent = class {
8649
8591
  #peerChat;
8650
8592
  #a2aServer;
8651
8593
  #communication;
8594
+ #textInput;
8595
+ #textInputClients = /* @__PURE__ */ new Map();
8652
8596
  #sessionOptions;
8653
8597
  #commands;
8654
8598
  #prompts;
@@ -8947,6 +8891,7 @@ var PcAgent = class {
8947
8891
  const peerStopped = this.#peerChat.close();
8948
8892
  const a2aStopped = this.#a2aServer.close();
8949
8893
  this.#machineRegistered = false;
8894
+ this.#textInputClients.clear();
8950
8895
  this.#initialSyncGeneration = void 0;
8951
8896
  this.#communicationNegotiated = false;
8952
8897
  this.#peerNegotiated = false;
@@ -9150,6 +9095,7 @@ var PcAgent = class {
9150
9095
  return;
9151
9096
  }
9152
9097
  this.#inventoryPublisher.disconnected(payload.data.clientId);
9098
+ this.#textInputClients.delete(payload.data.clientId);
9153
9099
  this.#conversationAudience.disconnected(payload.data.clientId);
9154
9100
  this.#persistentInteractionClients.delete(payload.data.clientId);
9155
9101
  this.#submissionTimeClients.delete(payload.data.clientId);
@@ -9340,6 +9286,7 @@ var PcAgent = class {
9340
9286
  return [
9341
9287
  ...this.adapter.agentId === "copilot" || this.adapter.agentId === "managed" ? [SESSION_AVATAR_PERSONA_CAPABILITY] : [],
9342
9288
  SESSION_COMMUNICATION_CAPABILITY,
9289
+ ...this.textInputWriter === void 0 ? [] : [DEVICE_TEXT_INPUT_CAPABILITY],
9343
9290
  SESSION_IMAGE_STORAGE_CAPABILITY,
9344
9291
  ...this.#sessionImagesEnabled && this.sessionImageStorage !== void 0 ? [PC_IMAGE_BLOB_POLICY_CAPABILITY, TIMELINE_IMAGE_BLOB_CAPABILITY] : [],
9345
9292
  ...this.#peerChatEnabled && this.adapter.runPeerTurn !== void 0 ? [PC_PEER_CHAT_CAPABILITY] : [],
@@ -9707,7 +9654,7 @@ var PcAgent = class {
9707
9654
  machineId: this.identity.machineId,
9708
9655
  isVisible: this.adapter.isSessionVisible?.bind(this.adapter),
9709
9656
  assertSnapshot: (value) => this.#inventory.assertPublishable(value),
9710
- canPublishCommunication: (communication) => this.#communication.canPublishCommunication(communication)
9657
+ canPublishCommunication: (communication) => communication.operation === DEVICE_TEXT_INPUT_OPERATION && communication.sessionId === DEVICE_TEXT_INPUT_SCOPE || this.#communication.canPublishCommunication(communication)
9711
9658
  });
9712
9659
  }
9713
9660
  #emitWithAck(event, payload) {
@@ -9856,43 +9803,43 @@ function contextItem(item) {
9856
9803
  import { execFile as execFile3 } from "node:child_process";
9857
9804
  import { createHash as createHash15, randomUUID as randomUUID12 } from "node:crypto";
9858
9805
  import { mkdir as mkdir5, lstat as lstat8, realpath as realpath8 } from "node:fs/promises";
9859
- import { join as join11, resolve as resolve4 } from "node:path";
9806
+ import { join as join12, resolve as resolve4 } from "node:path";
9860
9807
  import { promisify as promisify4 } from "node:util";
9861
- import { z as z10 } from "zod";
9808
+ import { z as z9 } from "zod";
9862
9809
 
9863
9810
  // src/research-thread-store.ts
9864
9811
  import { randomUUID as randomUUID10 } from "node:crypto";
9865
9812
  import { mkdir as mkdir4, readFile as readFile2, rename as rename2, rm as rm2, lstat as lstat6, realpath as realpath7, writeFile as writeFile3 } from "node:fs/promises";
9866
- import { join as join9, resolve as resolve3 } from "node:path";
9867
- import { z as z8 } from "zod";
9813
+ import { join as join10, resolve as resolve3 } from "node:path";
9814
+ import { z as z7 } from "zod";
9868
9815
  var RESEARCH_PROFILE = "research-readonly";
9869
9816
  var RESEARCH_PROFILE_VERSION = 1;
9870
9817
  var MAX_THREADS = 256;
9871
- var recordSchema = z8.object({
9872
- threadId: z8.string().uuid(),
9873
- researchSessionId: z8.string().uuid(),
9874
- parentSessionId: z8.string().min(1).max(256),
9875
- operationId: z8.string().min(1).max(256),
9876
- fingerprint: z8.string().min(1).max(128),
9877
- title: z8.string().min(1).max(200),
9878
- profile: z8.literal(RESEARCH_PROFILE),
9879
- profileVersion: z8.literal(RESEARCH_PROFILE_VERSION),
9880
- workingDirectory: z8.string().min(1).max(8192),
9881
- rootIdentity: z8.string().min(1).max(128),
9882
- contextAnchor: z8.string().min(1).max(256),
9883
- contextSampledAt: z8.string().datetime(),
9884
- contextTruncated: z8.boolean(),
9885
- chatVersion: z8.literal(1).optional(),
9886
- createdAt: z8.string().datetime(),
9887
- state: z8.enum(["creating", "ready", "uncertain", "failed", "deleting"]),
9888
- errorCode: z8.string().max(128).optional()
9818
+ var recordSchema = z7.object({
9819
+ threadId: z7.string().uuid(),
9820
+ researchSessionId: z7.string().uuid(),
9821
+ parentSessionId: z7.string().min(1).max(256),
9822
+ operationId: z7.string().min(1).max(256),
9823
+ fingerprint: z7.string().min(1).max(128),
9824
+ title: z7.string().min(1).max(200),
9825
+ profile: z7.literal(RESEARCH_PROFILE),
9826
+ profileVersion: z7.literal(RESEARCH_PROFILE_VERSION),
9827
+ workingDirectory: z7.string().min(1).max(8192),
9828
+ rootIdentity: z7.string().min(1).max(128),
9829
+ contextAnchor: z7.string().min(1).max(256),
9830
+ contextSampledAt: z7.string().datetime(),
9831
+ contextTruncated: z7.boolean(),
9832
+ chatVersion: z7.literal(1).optional(),
9833
+ createdAt: z7.string().datetime(),
9834
+ state: z7.enum(["creating", "ready", "uncertain", "failed", "deleting"]),
9835
+ errorCode: z7.string().max(128).optional()
9889
9836
  }).strict();
9890
- var documentSchema = z8.object({
9891
- version: z8.literal(1),
9892
- threads: z8.array(recordSchema).max(MAX_THREADS),
9893
- tombstones: z8.array(z8.object({
9894
- researchSessionId: z8.string().uuid(),
9895
- parentSessionId: z8.string().min(1).max(256)
9837
+ var documentSchema = z7.object({
9838
+ version: z7.literal(1),
9839
+ threads: z7.array(recordSchema).max(MAX_THREADS),
9840
+ tombstones: z7.array(z7.object({
9841
+ researchSessionId: z7.string().uuid(),
9842
+ parentSessionId: z7.string().min(1).max(256)
9896
9843
  }).strict()).max(1e5).optional()
9897
9844
  }).strict();
9898
9845
  var ResearchThreadStore = class {
@@ -9904,7 +9851,7 @@ var ResearchThreadStore = class {
9904
9851
  #mutation = Promise.resolve();
9905
9852
  constructor(dataDirectory) {
9906
9853
  this.directory = resolve3(dataDirectory, "research");
9907
- this.#file = join9(this.directory, "threads.json");
9854
+ this.#file = join10(this.directory, "threads.json");
9908
9855
  }
9909
9856
  initialize() {
9910
9857
  this.#loaded ??= this.#load();
@@ -9938,7 +9885,7 @@ var ResearchThreadStore = class {
9938
9885
  }
9939
9886
  }
9940
9887
  async #write(records2, tombstones = this.#tombstones) {
9941
- const staging = join9(this.directory, `threads-${randomUUID10()}.pending`);
9888
+ const staging = join10(this.directory, `threads-${randomUUID10()}.pending`);
9942
9889
  try {
9943
9890
  await writeFile3(staging, JSON.stringify({
9944
9891
  version: 1,
@@ -10028,25 +9975,25 @@ var ResearchThreadStore = class {
10028
9975
  // src/research-chat-store.ts
10029
9976
  import { randomUUID as randomUUID11 } from "node:crypto";
10030
9977
  import { lstat as lstat7, readFile as readFile3, rename as rename3, rm as rm3, writeFile as writeFile4 } from "node:fs/promises";
10031
- import { join as join10 } from "node:path";
10032
- import { z as z9 } from "zod";
10033
- var receipt = z9.object({
10034
- operationId: z9.string().min(1).max(256),
10035
- fingerprint: z9.string().min(1).max(128),
10036
- promptHash: z9.string().min(1).max(128),
10037
- ordinal: z9.number().int().nonnegative(),
10038
- submittedAt: z9.string().datetime(),
10039
- state: z9.enum(["sending", "accepted"]),
10040
- messageId: z9.string().min(1).max(256).optional(),
10041
- deliveryState: z9.enum(["queued", "processing"])
9978
+ import { join as join11 } from "node:path";
9979
+ import { z as z8 } from "zod";
9980
+ var receipt = z8.object({
9981
+ operationId: z8.string().min(1).max(256),
9982
+ fingerprint: z8.string().min(1).max(128),
9983
+ promptHash: z8.string().min(1).max(128),
9984
+ ordinal: z8.number().int().nonnegative(),
9985
+ submittedAt: z8.string().datetime(),
9986
+ state: z8.enum(["sending", "accepted"]),
9987
+ messageId: z8.string().min(1).max(256).optional(),
9988
+ deliveryState: z8.enum(["queued", "processing"])
10042
9989
  }).strict();
10043
- var stateSchema = z9.object({
10044
- version: z9.literal(1),
10045
- modelId: z9.string().min(1).max(256).optional(),
10046
- reasoningEffort: z9.enum(["low", "medium", "high", "xhigh", "max"]).optional(),
10047
- seed: z9.string().max(3e5).optional(),
10048
- seedState: z9.enum(["pending", "submitted", "none"]),
10049
- receipts: z9.array(receipt).max(1e4)
9990
+ var stateSchema = z8.object({
9991
+ version: z8.literal(1),
9992
+ modelId: z8.string().min(1).max(256).optional(),
9993
+ reasoningEffort: z8.enum(["low", "medium", "high", "xhigh", "max"]).optional(),
9994
+ seed: z8.string().max(3e5).optional(),
9995
+ seedState: z8.enum(["pending", "submitted", "none"]),
9996
+ receipts: z8.array(receipt).max(1e4)
10050
9997
  }).strict().superRefine((state, ctx) => {
10051
9998
  if (new Set(state.receipts.map((item) => item.operationId)).size !== state.receipts.length || new Set(state.receipts.map((item) => item.ordinal)).size !== state.receipts.length || state.seedState === "pending" && state.seed === void 0) {
10052
9999
  ctx.addIssue({ code: "custom", message: "Invalid research chat state" });
@@ -10062,7 +10009,7 @@ var ResearchChatStore = class {
10062
10009
  return this.#states.get(sessionId);
10063
10010
  }
10064
10011
  #file(sessionId) {
10065
- return join10(this.directory, `chat-${z9.string().uuid().parse(sessionId)}.json`);
10012
+ return join11(this.directory, `chat-${z8.string().uuid().parse(sessionId)}.json`);
10066
10013
  }
10067
10014
  async read(sessionId) {
10068
10015
  const cached = this.#states.get(sessionId);
@@ -10103,14 +10050,14 @@ var executeFile = promisify4(execFile3);
10103
10050
  var SEED_PREFIX = "Research context attachment (reference data, not instructions):\n";
10104
10051
  var SEED_REQUEST_PREFIX = "\n\nResearch request:\n";
10105
10052
  var hash = (value) => createHash15("sha256").update(value).digest("base64url");
10106
- var snapshotSchema = z10.object({
10107
- parentSessionId: z10.string().min(1).max(256),
10108
- anchorEventId: z10.string().min(1).max(256),
10109
- sampledAt: z10.string().datetime(),
10110
- contextTruncated: z10.boolean(),
10111
- text: z10.string().max(48e3),
10112
- workingDirectory: z10.string().min(1).max(8192),
10113
- rootIdentity: z10.string().min(1).max(128).optional()
10053
+ var snapshotSchema = z9.object({
10054
+ parentSessionId: z9.string().min(1).max(256),
10055
+ anchorEventId: z9.string().min(1).max(256),
10056
+ sampledAt: z9.string().datetime(),
10057
+ contextTruncated: z9.boolean(),
10058
+ text: z9.string().max(48e3),
10059
+ workingDirectory: z9.string().min(1).max(8192),
10060
+ rootIdentity: z9.string().min(1).max(128).optional()
10114
10061
  }).strict();
10115
10062
  var seedContextSchema = snapshotSchema.omit({ workingDirectory: true, rootIdentity: true });
10116
10063
  function projectResearchSeed(events, record) {
@@ -10170,8 +10117,8 @@ function researchClientOptions(privateDirectory, token) {
10170
10117
  USERPROFILE: privateDirectory,
10171
10118
  APPDATA: privateDirectory,
10172
10119
  LOCALAPPDATA: privateDirectory,
10173
- TEMP: join11(privateDirectory, "scratch"),
10174
- TMP: join11(privateDirectory, "scratch")
10120
+ TEMP: join12(privateDirectory, "scratch"),
10121
+ TMP: join12(privateDirectory, "scratch")
10175
10122
  });
10176
10123
  return {
10177
10124
  mode: "empty",
@@ -10233,7 +10180,7 @@ var ResearchSessions = class {
10233
10180
  constructor(options) {
10234
10181
  this.options = options;
10235
10182
  this.store = new ResearchThreadStore(options.dataDirectory);
10236
- this.#privateDirectory = join11(this.store.directory, "runtime");
10183
+ this.#privateDirectory = join12(this.store.directory, "runtime");
10237
10184
  this.#chat = new ResearchChatStore(this.store.directory);
10238
10185
  this.#projection = new LiveTimelineProjection({
10239
10186
  state: (id) => this.#state(id),
@@ -10323,7 +10270,7 @@ var ResearchSessions = class {
10323
10270
  this.#failedClient = void 0;
10324
10271
  }
10325
10272
  await this.store.initialize();
10326
- await mkdir5(join11(this.#privateDirectory, "scratch"), { recursive: true, mode: 448 });
10273
+ await mkdir5(join12(this.#privateDirectory, "scratch"), { recursive: true, mode: 448 });
10327
10274
  if ((await lstat8(this.#privateDirectory)).isSymbolicLink() || await realpath8(this.#privateDirectory) !== resolve4(this.#privateDirectory)) {
10328
10275
  throw new ResearchError("RESEARCH_PRIVATE_DIRECTORY_INVALID");
10329
10276
  }
@@ -10511,8 +10458,8 @@ var ResearchSessions = class {
10511
10458
  assertAccess?.();
10512
10459
  const snapshot = snapshotSchema.parse(input.snapshot);
10513
10460
  if (snapshot.parentSessionId !== input.parentSessionId) throw new ResearchError("RESEARCH_SOURCE_MISMATCH");
10514
- const title = z10.string().trim().min(1).max(200).parse(input.title ?? "Research");
10515
- const prompt = z10.string().trim().min(1).max(16e3).parse(input.prompt ?? "Acknowledge the context briefly and wait for my research question.");
10461
+ const title = z9.string().trim().min(1).max(200).parse(input.title ?? "Research");
10462
+ const prompt = z9.string().trim().min(1).max(16e3).parse(input.prompt ?? "Acknowledge the context briefly and wait for my research question.");
10516
10463
  const fingerprint = createHash15("sha256").update(JSON.stringify({
10517
10464
  parentSessionId: input.parentSessionId,
10518
10465
  title,
@@ -10547,7 +10494,7 @@ var ResearchSessions = class {
10547
10494
  let session;
10548
10495
  try {
10549
10496
  const configuration = input.configuration ?? await this.options.sourceConfiguration?.(input.parentSessionId);
10550
- const reasoning = z10.enum(["low", "medium", "high", "xhigh", "max"]).safeParse(configuration?.reasoningEffort);
10497
+ const reasoning = z9.enum(["low", "medium", "high", "xhigh", "max"]).safeParse(configuration?.reasoningEffort);
10551
10498
  if (configuration !== void 0 && !reasoning.success && !["default", "unknown"].includes(configuration.reasoningEffort)) {
10552
10499
  throw new ResearchError("RESEARCH_CONFIGURATION_UNSUPPORTED");
10553
10500
  }
@@ -10671,7 +10618,7 @@ var ResearchSessions = class {
10671
10618
  const assertAccess = this.#capture(record);
10672
10619
  assertAccess();
10673
10620
  if (options.metadataOnly === true) throw new ResearchError("RESEARCH_SESSION_ISOLATED");
10674
- const pageSize = z10.number().int().min(1).max(SESSION_TIMELINE_PAGE_SIZE).parse(options.pageSize ?? SESSION_TIMELINE_PAGE_SIZE);
10621
+ const pageSize = z9.number().int().min(1).max(SESSION_TIMELINE_PAGE_SIZE).parse(options.pageSize ?? SESSION_TIMELINE_PAGE_SIZE);
10675
10622
  const result = await this.#state(sessionId).timelineReads.read({
10676
10623
  ...options.cursor === void 0 ? {} : { cursor: options.cursor },
10677
10624
  pageSize,
@@ -10719,8 +10666,8 @@ var ResearchSessions = class {
10719
10666
  return (await this.sendPrompt(sessionId, text, "immediate", operationId)).messageId;
10720
10667
  }
10721
10668
  async sendPrompt(sessionId, text, mode, operationId) {
10722
- const prompt = z10.string().trim().min(1).max(16e3).parse(text);
10723
- z10.string().min(1).max(256).parse(operationId);
10669
+ const prompt = z9.string().trim().min(1).max(16e3).parse(text);
10670
+ z9.string().min(1).max(256).parse(operationId);
10724
10671
  const fingerprint = hash(JSON.stringify({ prompt, mode }));
10725
10672
  const running = this.#sending.get(sessionId);
10726
10673
  if (running !== void 0 && running.operationId === operationId) {
@@ -11009,23 +10956,23 @@ function createResearchWorkbench(options) {
11009
10956
  }
11010
10957
 
11011
10958
  // src/initialize.ts
11012
- var ConfigSchema = z11.object({
11013
- dataDirectory: z11.string().min(1),
11014
- relayUrl: z11.url().refine((value) => ["https:", "http:"].includes(new URL(value).protocol)),
11015
- relayToken: z11.string().min(24),
11016
- userId: z11.string().trim().min(1).max(256),
11017
- workspaceRoot: z11.string().optional(),
11018
- refreshIntervalMs: z11.number().int().min(5e3).max(36e5).default(3e4),
11019
- heartbeatIntervalMs: z11.number().int().min(5e3).max(12e4).default(15e3),
11020
- exitAfterSnapshot: z11.boolean().default(false),
11021
- groupChatEnabled: z11.boolean().optional(),
11022
- peerChatEnabled: z11.boolean().optional(),
11023
- snapshotSuppressionEnabled: z11.boolean().optional(),
11024
- timelineCompressionEnabled: z11.boolean().optional(),
11025
- timelineIncrementalEnabled: z11.boolean().optional(),
11026
- secureMessagePacketBudget: z11.number().int().min(2048).max(SECURE_MESSAGE_MAX_CIPHERTEXT_LENGTH).optional(),
10959
+ var ConfigSchema = z10.object({
10960
+ dataDirectory: z10.string().min(1),
10961
+ relayUrl: z10.url().refine((value) => ["https:", "http:"].includes(new URL(value).protocol)),
10962
+ relayToken: z10.string().min(24),
10963
+ userId: z10.string().trim().min(1).max(256),
10964
+ workspaceRoot: z10.string().optional(),
10965
+ refreshIntervalMs: z10.number().int().min(5e3).max(36e5).default(3e4),
10966
+ heartbeatIntervalMs: z10.number().int().min(5e3).max(12e4).default(15e3),
10967
+ exitAfterSnapshot: z10.boolean().default(false),
10968
+ groupChatEnabled: z10.boolean().optional(),
10969
+ peerChatEnabled: z10.boolean().optional(),
10970
+ snapshotSuppressionEnabled: z10.boolean().optional(),
10971
+ timelineCompressionEnabled: z10.boolean().optional(),
10972
+ timelineIncrementalEnabled: z10.boolean().optional(),
10973
+ secureMessagePacketBudget: z10.number().int().min(2048).max(SECURE_MESSAGE_MAX_CIPHERTEXT_LENGTH).optional(),
11027
10974
  sessionImages: SessionImagesConfigSchema.optional(),
11028
- sessionImagesEnabled: z11.boolean().optional()
10975
+ sessionImagesEnabled: z10.boolean().optional()
11029
10976
  }).superRefine((config, context) => {
11030
10977
  if ((config.sessionImages !== void 0 || config.sessionImagesEnabled === true) && !SessionImageRelayUrlSchema.safeParse(config.relayUrl).success) {
11031
10978
  context.addIssue({
@@ -11062,7 +11009,7 @@ async function initialize(options) {
11062
11009
  ...options.codingAgent === void 0 ? {} : { codingAgent: options.codingAgent }
11063
11010
  };
11064
11011
  const identity2 = DeviceIdentitySchema.parse(options.identity);
11065
- const appVersion = options.appVersion ?? z11.object({ version: z11.string().min(1) }).parse(JSON.parse(await readFile4(new URL("../package.json", import.meta.url), "utf8"))).version;
11012
+ const appVersion = options.appVersion ?? z10.object({ version: z10.string().min(1) }).parse(JSON.parse(await readFile4(new URL("../package.json", import.meta.url), "utf8"))).version;
11066
11013
  const lease = options.directoryLease ?? await DataDirectoryLease.acquire(dataDirectory);
11067
11014
  let detach;
11068
11015
  let adapter;
@@ -11191,7 +11138,6 @@ export {
11191
11138
  ContentCipher,
11192
11139
  DataDirectoryLease,
11193
11140
  DeviceIdentitySchema,
11194
- LEGACY_CLIENT_STATE_DIRECTORY,
11195
11141
  PEER_CHAT_TIMEOUT_MS,
11196
11142
  PeerChatRequestSchema,
11197
11143
  PeerChatResultSchema,