@agentknight/sdk 0.9.53 → 0.9.56

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,25 +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
- SessionImageRelayUrlSchema,
11
- SessionImagesConfigSchema,
12
10
  codingAgentPresentation,
13
11
  relayRequestToken
14
- } from "./chunks/chunk-EFRYPUKX.js";
12
+ } from "./chunks/chunk-XPHAIOKN.js";
15
13
  import {
16
14
  AgentSelectionSchema,
17
15
  assertSelectionSnapshotFits,
18
16
  supportsAgentSelection
19
- } from "./chunks/chunk-AAZH6QGV.js";
17
+ } from "./chunks/chunk-NTFNQYQ3.js";
20
18
  import {
21
19
  ConversationNormalizer,
22
20
  LiveTimelineProjection,
23
21
  OperationDiagnostics,
24
22
  OperationMetrics,
25
23
  PromptPreparationError,
24
+ SessionImageUploadError,
25
+ SessionImageUploader,
26
26
  SessionProjectIdentityError,
27
27
  SessionRuntime,
28
28
  diagnosticError,
@@ -38,11 +38,15 @@ import {
38
38
  resolveGitProjectIdentity,
39
39
  sessionRestoreFailure,
40
40
  validateOperationResponse
41
- } from "./chunks/chunk-6YFGVYI5.js";
41
+ } from "./chunks/chunk-6ZPE7VIE.js";
42
+ import {
43
+ SessionImageRelayUrlSchema,
44
+ SessionImagesConfigSchema
45
+ } from "./chunks/chunk-IJPJQF7S.js";
42
46
  import {
43
47
  GROUP_CHAT_MAX_TURNS,
44
48
  GroupChatError
45
- } from "./chunks/chunk-XL6UB4C3.js";
49
+ } from "./chunks/chunk-HFVA7ZOD.js";
46
50
  import {
47
51
  detectClaude,
48
52
  detectCopilot,
@@ -53,7 +57,7 @@ import {
53
57
  assistantPreview,
54
58
  isContentfulAssistant,
55
59
  userPreview
56
- } from "./chunks/chunk-2CNJAMAN.js";
60
+ } from "./chunks/chunk-5J7BK2Y7.js";
57
61
  import {
58
62
  AgentModelListingError,
59
63
  AgentSessionRenameError,
@@ -64,7 +68,7 @@ import {
64
68
  UnsupportedAgentOperationError,
65
69
  captureResearchAccess,
66
70
  captureWorkbenchAccess
67
- } from "./chunks/chunk-ML6Q2MYH.js";
71
+ } from "./chunks/chunk-L3A736SO.js";
68
72
  import {
69
73
  A2aRelayRequestSchema,
70
74
  A2aRelayResponseSchema,
@@ -75,6 +79,13 @@ import {
75
79
  ConversationAttachmentSchema,
76
80
  ConversationItemSchema,
77
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,
78
89
  GROUP_CHAT_CREATE_CAPABILITY,
79
90
  GROUP_CHAT_CREATE_OPERATION,
80
91
  GROUP_CHAT_CREATE_VERSION,
@@ -146,7 +157,6 @@ import {
146
157
  SESSION_GIT_DIFF_OPERATION,
147
158
  SESSION_GIT_DIFF_PARTIAL_VERSION,
148
159
  SESSION_GIT_DIFF_VERSION,
149
- SESSION_IMAGE_API_PATH,
150
160
  SESSION_IMAGE_MAX_BYTES,
151
161
  SESSION_IMAGE_MAX_PIXELS,
152
162
  SESSION_IMAGE_STORAGE_CAPABILITY,
@@ -186,11 +196,7 @@ import {
186
196
  SessionGitDiffGzipResultDataSchema,
187
197
  SessionGitDiffPartialResultDataSchema,
188
198
  SessionGitDiffResultDataSchema,
189
- SessionImageCommitResultSchema,
190
- SessionImageScopeSchema,
191
199
  SessionImageStorageSchema,
192
- SessionImageUploadRequestSchema,
193
- SessionImageUploadResultSchema,
194
200
  SessionListRequestSchema,
195
201
  SessionListResultSchema,
196
202
  SessionOptionsRequestSchema,
@@ -257,12 +263,12 @@ import {
257
263
  sessionCommunicationError,
258
264
  sessionCommunicationOperationCapability,
259
265
  workbenchCapability
260
- } from "./chunks/chunk-UZFIXIAS.js";
266
+ } from "./chunks/chunk-K5CMKBW6.js";
261
267
 
262
268
  // src/initialize.ts
263
269
  import { createHash as createHash16 } from "node:crypto";
264
270
  import { readFile as readFile4 } from "node:fs/promises";
265
- import { z as z11 } from "zod";
271
+ import { z as z10 } from "zod";
266
272
 
267
273
  // src/coding-agent-factory.ts
268
274
  import { resolve } from "node:path";
@@ -277,7 +283,7 @@ async function createCodingAgentAdapter(config, onDiagnostic, owner) {
277
283
  switch (engine.kind) {
278
284
  case "managed": {
279
285
  if (owner === void 0) throw new Error("Managed coding agents require the PC owner identity");
280
- const { ManagedCodingAgentAdapter } = await import("./chunks/managed-agent-adapter-5TIM4PBR.js");
286
+ const { ManagedCodingAgentAdapter } = await import("./chunks/managed-agent-adapter-KEXZFLGA.js");
281
287
  return new ManagedCodingAgentAdapter({
282
288
  dataDirectory: config.dataDirectory,
283
289
  owner,
@@ -334,7 +340,7 @@ async function createCodingAgentAdapter(config, onDiagnostic, owner) {
334
340
  });
335
341
  }
336
342
  case "copilot": {
337
- const { GithubCopilotAdapter } = await import("./chunks/copilot-adapter-ZM7EUBZ5.js");
343
+ const { GithubCopilotAdapter } = await import("./chunks/copilot-adapter-2QAIOSEK.js");
338
344
  if (owner !== void 0) {
339
345
  return new GithubCopilotAdapter(void 0, void 0, void 0, {
340
346
  dataDirectory: config.dataDirectory,
@@ -354,13 +360,13 @@ async function createCodingAgentAdapter(config, onDiagnostic, owner) {
354
360
  }
355
361
  case "pi": {
356
362
  assertPiRuntimeSupported();
357
- const { PiCodingAgentAdapter } = await import("./chunks/pi-adapter-NADD52CV.js");
363
+ const { PiCodingAgentAdapter } = await import("./chunks/pi-adapter-5BFIJTPD.js");
358
364
  return new PiCodingAgentAdapter(
359
365
  engine.agentDirectory === void 0 ? {} : { agentDirectory: resolve(engine.agentDirectory) }
360
366
  );
361
367
  }
362
368
  case "codex": {
363
- const { CodexCodingAgentAdapter } = await import("./chunks/codex-adapter-44N7DBRH.js");
369
+ const { CodexCodingAgentAdapter } = await import("./chunks/codex-adapter-ELYJE2A2.js");
364
370
  return new CodexCodingAgentAdapter({
365
371
  dataDirectory: resolve(config.dataDirectory, "coding-agents"),
366
372
  ...owner === void 0 ? {} : { nativeSessionOwner: owner },
@@ -369,7 +375,7 @@ async function createCodingAgentAdapter(config, onDiagnostic, owner) {
369
375
  });
370
376
  }
371
377
  case "claude": {
372
- const { ClaudeCodingAgentAdapter } = await import("./chunks/claude-adapter-UWVOXYNG.js");
378
+ const { ClaudeCodingAgentAdapter } = await import("./chunks/claude-adapter-G6YTPXRP.js");
373
379
  return new ClaudeCodingAgentAdapter({
374
380
  dataDirectory: resolve(config.dataDirectory, "coding-agents"),
375
381
  ...owner === void 0 ? {} : { nativeSessionOwner: owner },
@@ -377,7 +383,7 @@ async function createCodingAgentAdapter(config, onDiagnostic, owner) {
377
383
  });
378
384
  }
379
385
  case "acp": {
380
- const { AcpCodingAgentAdapter } = await import("./chunks/acp-adapter-LJQBDWYK.js");
386
+ const { AcpCodingAgentAdapter } = await import("./chunks/acp-adapter-HUNUQGUF.js");
381
387
  return new AcpCodingAgentAdapter({
382
388
  command: engine.command,
383
389
  args: engine.args,
@@ -2545,7 +2551,7 @@ var AuthorizedRelaySocket = class {
2545
2551
 
2546
2552
  // src/service/requests/session-communication.ts
2547
2553
  import { AsyncLocalStorage } from "node:async_hooks";
2548
- import { createHash as createHash8 } from "node:crypto";
2554
+ import { createHash as createHash7 } from "node:crypto";
2549
2555
  import { join as join6 } from "node:path";
2550
2556
  import { performance as performance2 } from "node:perf_hooks";
2551
2557
 
@@ -3682,331 +3688,6 @@ function hasSignature(bytes, mimeType) {
3682
3688
  }
3683
3689
  }
3684
3690
 
3685
- // src/session-image-uploader.ts
3686
- import { createHash as createHash7 } from "node:crypto";
3687
- import { z as z5 } from "zod";
3688
- var MAX_ACTIVE_UPLOADS = 3;
3689
- var MAX_JSON_BYTES = 16 * 1024;
3690
- var REQUEST_TIMEOUT_MS = 2e4;
3691
- var UPLOAD_TIMEOUT_MS = 7e4;
3692
- var MAX_GRANT_LIFETIME_MS = 10 * 6e4 + 3e4;
3693
- var UploaderConfigSchema = z5.object({
3694
- relayUrl: SessionImageRelayUrlSchema,
3695
- relayToken: z5.string().min(24).max(4096).regex(/^[\x21-\x7e]+$/u),
3696
- userId: IdSchema.refine((value) => /^[\x20-\x7e]+$/u.test(value)),
3697
- machineId: IdSchema,
3698
- storageAccount: SessionImagesConfigSchema.shape.storageAccount,
3699
- storageContainer: SessionImagesConfigSchema.shape.storageContainer,
3700
- mode: SessionImageStorageSchema.shape.mode.optional()
3701
- });
3702
- function safeCause(error) {
3703
- if (error instanceof SessionImageUploadError) return error;
3704
- if (error instanceof z5.ZodError) return new Error("Schema validation failed.");
3705
- const result = new Error("Image operation failed.");
3706
- if (error instanceof Error) {
3707
- if (["TypeError", "SyntaxError", "AbortError", "TimeoutError"].includes(error.name)) result.name = error.name;
3708
- const code = "code" in error ? error.code : void 0;
3709
- if (typeof code === "string" && ["ECONNRESET", "ECONNREFUSED", "ETIMEDOUT", "ENOTFOUND", "EAI_AGAIN", "UND_ERR_CONNECT_TIMEOUT"].includes(code)) {
3710
- result.cause = { code };
3711
- }
3712
- }
3713
- return result;
3714
- }
3715
- var SessionImageUploadError = class extends Error {
3716
- constructor(code, stage, status, cause) {
3717
- super(`${code} (${stage})`, cause === void 0 ? void 0 : { cause: safeCause(cause) });
3718
- this.code = code;
3719
- this.stage = stage;
3720
- this.status = status;
3721
- this.name = "SessionImageUploadError";
3722
- }
3723
- code;
3724
- stage;
3725
- status;
3726
- };
3727
- function digest(bytes) {
3728
- return createHash7("sha256").update(bytes).digest("hex");
3729
- }
3730
- function assert(condition, code, stage) {
3731
- if (!condition) throw new SessionImageUploadError(code, stage);
3732
- }
3733
- function parse(schema, input, stage) {
3734
- const result = schema.safeParse(input);
3735
- if (!result.success) throw new SessionImageUploadError(
3736
- stage === "config" ? "IMAGE_CONFIG_INVALID" : stage === "source" ? "IMAGE_CONTENT_INVALID" : "IMAGE_RESPONSE_INVALID",
3737
- stage,
3738
- void 0,
3739
- result.error
3740
- );
3741
- return result.data;
3742
- }
3743
- function abortable(operation, signal, stage) {
3744
- return new Promise((resolve5, reject) => {
3745
- const abort = () => reject(new SessionImageUploadError("IMAGE_ABORTED", stage));
3746
- if (signal.aborted) abort();
3747
- else signal.addEventListener("abort", abort, { once: true });
3748
- void operation.then((value) => {
3749
- signal.removeEventListener("abort", abort);
3750
- resolve5(value);
3751
- }, (error) => {
3752
- signal.removeEventListener("abort", abort);
3753
- reject(error);
3754
- });
3755
- });
3756
- }
3757
- var SessionImageUploader = class {
3758
- #config;
3759
- #fetch;
3760
- #active = /* @__PURE__ */ new Set();
3761
- #closed = false;
3762
- constructor(config, dependencies = {}) {
3763
- this.#config = parse(UploaderConfigSchema, config, "config");
3764
- this.#fetch = dependencies.fetch ?? globalThis.fetch;
3765
- }
3766
- close() {
3767
- this.#closed = true;
3768
- for (const controller of this.#active) controller.abort();
3769
- }
3770
- async upload(sessionId, source, signal, assertCurrent = () => void 0) {
3771
- assert(!this.#closed, "IMAGE_UPLOADER_CLOSED", "source");
3772
- assert(!signal?.aborted, "IMAGE_ABORTED", "source");
3773
- const revalidate = (stage) => {
3774
- try {
3775
- assertCurrent();
3776
- } catch (error) {
3777
- throw new SessionImageUploadError("IMAGE_ACCESS_REVOKED", stage, void 0, error);
3778
- }
3779
- };
3780
- revalidate("source");
3781
- assert(this.#active.size < MAX_ACTIVE_UPLOADS, "IMAGE_CAPACITY_EXCEEDED", "source");
3782
- assert(
3783
- Buffer.isBuffer(source) && source.length > 0 && source.length <= SESSION_IMAGE_MAX_BYTES,
3784
- "IMAGE_CONTENT_INVALID",
3785
- "source"
3786
- );
3787
- const scope = parse(SessionImageScopeSchema, { machineId: this.#config.machineId, sessionId }, "source");
3788
- const controller = new AbortController();
3789
- this.#active.add(controller);
3790
- const abort = () => controller.abort();
3791
- signal?.addEventListener("abort", abort, { once: true });
3792
- let timedOut = false;
3793
- const timer = setTimeout(() => {
3794
- timedOut = true;
3795
- controller.abort();
3796
- }, UPLOAD_TIMEOUT_MS);
3797
- timer.unref();
3798
- try {
3799
- const bytes = Buffer.from(source);
3800
- const dimensions = await this.#dimensions(bytes);
3801
- const hash2 = digest(bytes);
3802
- const request2 = parse(SessionImageUploadRequestSchema, { ...scope, sizeBytes: bytes.length }, "source");
3803
- revalidate("reserve");
3804
- const upload = await this.#json(
3805
- `${SESSION_IMAGE_API_PATH}/uploads`,
3806
- request2,
3807
- 201,
3808
- SessionImageUploadResultSchema,
3809
- "reserve",
3810
- controller.signal
3811
- );
3812
- const target = this.#target(upload, scope.sessionId);
3813
- let ambiguous;
3814
- revalidate("put");
3815
- try {
3816
- await this.#request(target, {
3817
- method: "PUT",
3818
- headers: upload.mode === "direct" ? upload.headers : { ...this.#headers(), ...upload.headers },
3819
- body: new Uint8Array(bytes)
3820
- }, "put", controller.signal, async (response) => {
3821
- if (response.status !== 201) throw new SessionImageUploadError("IMAGE_HTTP_ERROR", "put", response.status);
3822
- });
3823
- } catch (error) {
3824
- 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;
3825
- ambiguous = error;
3826
- }
3827
- revalidate("complete");
3828
- try {
3829
- const committed = await this.#json(
3830
- `${SESSION_IMAGE_API_PATH}/${upload.imageId}/complete`,
3831
- scope,
3832
- 200,
3833
- SessionImageCommitResultSchema,
3834
- "complete",
3835
- controller.signal
3836
- );
3837
- assert(
3838
- 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(),
3839
- "IMAGE_COMMIT_MISMATCH",
3840
- "complete"
3841
- );
3842
- revalidate("complete");
3843
- return committed;
3844
- } catch (error) {
3845
- if (ambiguous === void 0 || error instanceof SessionImageUploadError && error.code === "IMAGE_ACCESS_REVOKED") {
3846
- throw error;
3847
- }
3848
- const failure = new SessionImageUploadError("IMAGE_COMPLETION_FAILED", "complete", void 0, error);
3849
- failure.cause = new AggregateError([ambiguous, safeCause(error)], "PUT outcome and completion failed.");
3850
- throw failure;
3851
- }
3852
- } catch (error) {
3853
- if (controller.signal.aborted) {
3854
- throw new SessionImageUploadError(
3855
- timedOut ? "IMAGE_TIMEOUT" : "IMAGE_ABORTED",
3856
- error instanceof SessionImageUploadError ? error.stage : "source",
3857
- void 0,
3858
- error
3859
- );
3860
- }
3861
- if (error instanceof SessionImageUploadError) throw error;
3862
- throw new SessionImageUploadError("IMAGE_CONTENT_INVALID", "source", void 0, error);
3863
- } finally {
3864
- clearTimeout(timer);
3865
- signal?.removeEventListener("abort", abort);
3866
- this.#active.delete(controller);
3867
- }
3868
- }
3869
- async #dimensions(bytes) {
3870
- assert(
3871
- bytes.length >= 20 && bytes.toString("ascii", 0, 4) === "RIFF" && bytes.toString("ascii", 8, 12) === "WEBP" && bytes.readUInt32LE(4) + 8 === bytes.length,
3872
- "IMAGE_CONTENT_INVALID",
3873
- "source"
3874
- );
3875
- const { default: sharp } = await import("sharp");
3876
- const decoder = sharp(bytes, { limitInputPixels: SESSION_IMAGE_MAX_PIXELS, failOn: "warning" });
3877
- try {
3878
- const metadata = await decoder.metadata();
3879
- 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");
3880
- return { width: metadata.width, height: metadata.height };
3881
- } finally {
3882
- decoder.destroy();
3883
- }
3884
- }
3885
- #headers() {
3886
- return { authorization: `Bearer ${this.#config.relayToken}`, "x-agentknight-user-id": this.#config.userId };
3887
- }
3888
- #target(upload, sessionId) {
3889
- assert(this.#config.mode === void 0 || upload.mode === this.#config.mode, "IMAGE_UPLOAD_TARGET_INVALID", "reserve");
3890
- const now = Date.now();
3891
- assert(Number.isSafeInteger(upload.uploadExpiresAt) && upload.uploadExpiresAt > now && upload.uploadExpiresAt <= now + MAX_GRANT_LIFETIME_MS, "IMAGE_UPLOAD_EXPIRED", "reserve");
3892
- assert(
3893
- upload.headers["content-type"] === "image/webp" && (upload.headers["if-none-match"] === void 0 || upload.headers["if-none-match"] === "*"),
3894
- "IMAGE_UPLOAD_TARGET_INVALID",
3895
- "reserve"
3896
- );
3897
- if (upload.mode === "proxy") {
3898
- const path2 = `${SESSION_IMAGE_API_PATH}/${upload.imageId}/content`;
3899
- const url2 = new URL(upload.uploadUrl, this.#config.relayUrl);
3900
- assert(
3901
- 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,
3902
- "IMAGE_UPLOAD_TARGET_INVALID",
3903
- "reserve"
3904
- );
3905
- return url2.href;
3906
- }
3907
- const { storageAccount, storageContainer, userId, machineId } = this.#config;
3908
- const host = `${storageAccount}.blob.core.windows.net`;
3909
- const path = `/${storageContainer}/uploads/${digest(userId)}/${digest(machineId)}/${upload.imageId}.webp`;
3910
- const url = new URL(upload.uploadUrl);
3911
- const query = url.searchParams;
3912
- const allowed = /* @__PURE__ */ new Set(["sv", "spr", "st", "se", "sr", "sp", "sig", "skoid", "sktid", "skt", "ske", "sks", "skv"]);
3913
- assert(
3914
- 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",
3915
- "IMAGE_UPLOAD_TARGET_INVALID",
3916
- "reserve"
3917
- );
3918
- const expiresAt = Date.parse(query.get("se") ?? "");
3919
- const startsAt = Date.parse(query.get("st") ?? "");
3920
- const keyStartsAt = Date.parse(query.get("skt") ?? "");
3921
- const keyExpiresAt = Date.parse(query.get("ske") ?? "");
3922
- assert(
3923
- 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,
3924
- "IMAGE_UPLOAD_TARGET_INVALID",
3925
- "reserve"
3926
- );
3927
- return url.href;
3928
- }
3929
- async #json(path, body, status, schema, stage, signal) {
3930
- return this.#request(`${this.#config.relayUrl}${path}`, {
3931
- method: "POST",
3932
- headers: { ...this.#headers(), "content-type": "application/json" },
3933
- body: JSON.stringify(body)
3934
- }, stage, signal, async (response, requestSignal) => {
3935
- if (stage === "reserve" && response.status === 404) {
3936
- throw new SessionImageUploadError("IMAGE_STORAGE_UNAVAILABLE", stage, response.status);
3937
- }
3938
- if (response.status !== status) throw new SessionImageUploadError("IMAGE_HTTP_ERROR", stage, response.status);
3939
- const contentLength = response.headers.get("content-length");
3940
- assert(
3941
- contentLength === null || /^\d+$/u.test(contentLength) && Number(contentLength) <= MAX_JSON_BYTES,
3942
- "IMAGE_RESPONSE_TOO_LARGE",
3943
- stage
3944
- );
3945
- assert(response.body !== null, "IMAGE_RESPONSE_INVALID", stage);
3946
- const reader = response.body.getReader();
3947
- const chunks = [];
3948
- let size = 0;
3949
- try {
3950
- while (true) {
3951
- const next = await abortable(reader.read(), requestSignal, stage);
3952
- requestSignal.throwIfAborted();
3953
- if (next.done) break;
3954
- size += next.value.byteLength;
3955
- assert(size <= MAX_JSON_BYTES, "IMAGE_RESPONSE_TOO_LARGE", stage);
3956
- chunks.push(next.value);
3957
- }
3958
- let value;
3959
- try {
3960
- value = JSON.parse(Buffer.concat(chunks, size).toString("utf8"));
3961
- } catch (error) {
3962
- throw new SessionImageUploadError("IMAGE_RESPONSE_INVALID", stage, void 0, error);
3963
- }
3964
- return parse(schema, value, stage);
3965
- } finally {
3966
- reader.releaseLock();
3967
- }
3968
- });
3969
- }
3970
- async #request(url, init, stage, signal, consume) {
3971
- assert(!signal.aborted, "IMAGE_ABORTED", stage);
3972
- const controller = new AbortController();
3973
- const abort = () => controller.abort();
3974
- signal.addEventListener("abort", abort, { once: true });
3975
- let timedOut = false;
3976
- const timer = setTimeout(() => {
3977
- timedOut = true;
3978
- controller.abort();
3979
- }, REQUEST_TIMEOUT_MS);
3980
- timer.unref();
3981
- try {
3982
- const response = await this.#fetch(url, {
3983
- ...init,
3984
- signal: controller.signal,
3985
- redirect: "error",
3986
- credentials: "omit",
3987
- cache: "no-store",
3988
- referrerPolicy: "no-referrer"
3989
- });
3990
- try {
3991
- controller.signal.throwIfAborted();
3992
- assert(!response.redirected, "IMAGE_RESPONSE_INVALID", stage);
3993
- return await consume(response, controller.signal);
3994
- } finally {
3995
- await response.body?.cancel();
3996
- }
3997
- } catch (error) {
3998
- if (controller.signal.aborted) {
3999
- throw new SessionImageUploadError(timedOut ? "IMAGE_TIMEOUT" : "IMAGE_ABORTED", stage, void 0, error);
4000
- }
4001
- if (error instanceof SessionImageUploadError) throw error;
4002
- throw new SessionImageUploadError("IMAGE_NETWORK_ERROR", stage, void 0, error);
4003
- } finally {
4004
- clearTimeout(timer);
4005
- signal.removeEventListener("abort", abort);
4006
- }
4007
- }
4008
- };
4009
-
4010
3691
  // src/service/requests/request-errors.ts
4011
3692
  function operationErrorCode(agentId, operation, error) {
4012
3693
  if (isSessionRestoreFailure(error)) return "SESSION_RESTORE_FAILED";
@@ -4382,7 +4063,7 @@ var SessionCommunicationHandler = class {
4382
4063
  }
4383
4064
  const clientId = scope.clientId;
4384
4065
  const owner = [config.userId, machineId, clientId, request2.sessionId];
4385
- 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);
4386
4067
  const knownSource = this.#researchParents.get(request2.sessionId) ?? adapter.sessionPublicationSource?.(request2.sessionId) ?? request2.sessionId;
4387
4068
  const arrivalPublication = adapter.isSessionVisible?.(knownSource) === true ? publications.capture(knownSource) : void 0;
4388
4069
  let researchParent = this.#researchParents.get(request2.sessionId);
@@ -4561,18 +4242,210 @@ var SessionCommunicationHandler = class {
4561
4242
  }
4562
4243
  };
4563
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
+
4564
4437
  // src/desktop-workspaces.ts
4565
4438
  import { createHash as createHash9 } from "node:crypto";
4566
4439
  import { readdir, realpath as realpath5, stat as stat5 } from "node:fs/promises";
4567
4440
  import { homedir } from "node:os";
4568
- import { basename, join as join7, normalize } from "node:path";
4441
+ import { basename, join as join8, normalize } from "node:path";
4569
4442
  function desktopRootCandidates(environment2 = process.env) {
4570
4443
  const candidates = [
4571
4444
  environment2.AGENTKNIGHT_WORKSPACE_ROOT,
4572
- environment2.OneDrive === void 0 ? void 0 : join7(environment2.OneDrive, "Desktop"),
4573
- environment2.OneDriveCommercial === void 0 ? void 0 : join7(environment2.OneDriveCommercial, "Desktop"),
4574
- environment2.OneDriveConsumer === void 0 ? void 0 : join7(environment2.OneDriveConsumer, "Desktop"),
4575
- 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")
4576
4449
  ];
4577
4450
  return [...new Set(candidates.filter((path) => path !== void 0))];
4578
4451
  }
@@ -4613,7 +4486,7 @@ async function listDesktopWorkspaces(rootOverride) {
4613
4486
  const workspaces = entries.filter(
4614
4487
  (entry) => entry.isDirectory() && !entry.name.startsWith(".") && entry.name.trim().length > 0
4615
4488
  ).map((entry) => {
4616
- const path = join7(root, entry.name);
4489
+ const path = join8(root, entry.name);
4617
4490
  return {
4618
4491
  id: workspaceId(path),
4619
4492
  name: entry.name,
@@ -4685,7 +4558,7 @@ import { execFile as execFile2 } from "node:child_process";
4685
4558
  import { randomUUID as randomUUID4 } from "node:crypto";
4686
4559
  import { lstat as lstat5, mkdir as mkdir3, realpath as realpath6, rmdir } from "node:fs/promises";
4687
4560
  import { devNull } from "node:os";
4688
- 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";
4689
4562
  import { promisify as promisify3 } from "node:util";
4690
4563
  var execFileAsync = promisify3(execFile2);
4691
4564
  function creationEnvironment() {
@@ -4795,7 +4668,7 @@ async function createSessionWorktree(sourceDirectory, requestedBranchName, reque
4795
4668
  if (inside(identity2.worktreeRoot, parent)) {
4796
4669
  throw new Error("Cannot create a sibling worktree outside the source checkout. Move the repository and retry.");
4797
4670
  }
4798
- const path = join8(parent, `agentknight-worktree-${suffix}`);
4671
+ const path = join9(parent, `agentknight-worktree-${suffix}`);
4799
4672
  if (path.length > 640) {
4800
4673
  throw new Error("The repository path is too long to report worktree recovery safely. Use a checkout closer to the filesystem root.");
4801
4674
  }
@@ -5656,8 +5529,8 @@ import { randomUUID as randomUUID5 } from "node:crypto";
5656
5529
  import { setTimeout as delay } from "node:timers/promises";
5657
5530
  import { Role, TaskState } from "@a2a-js/sdk";
5658
5531
  import { ClientFactory, DefaultAgentCardResolver, JsonRpcTransportFactory } from "@a2a-js/sdk/client";
5659
- import { z as z6 } from "zod";
5660
- 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);
5661
5534
  var HTTP_TIMEOUT_MS = 1e4;
5662
5535
  var MAX_RESPONSE_BYTES = 262144;
5663
5536
  function relayEndpoint(relayUrl, target) {
@@ -5842,7 +5715,7 @@ import {
5842
5715
  ServerCallContext,
5843
5716
  validateVersion
5844
5717
  } from "@a2a-js/sdk/server";
5845
- import { z as z7 } from "zod";
5718
+ import { z as z6 } from "zod";
5846
5719
  var MAX_ACTIVE = 4;
5847
5720
  var MAX_TASKS = 128;
5848
5721
  var MAX_RECEIPTS = 256;
@@ -5851,52 +5724,52 @@ var TURN_TIMEOUT_MS = 12e4;
5851
5724
  var SHORT_REQUEST_TIMEOUT_MS = 9e3;
5852
5725
  var MAX_TEXT2 = 16e3;
5853
5726
  var TASK_WIRE_BUDGET = 6e4;
5854
- var idSchema = z7.string().min(1).max(256).regex(/^[^\s\u0000-\u001f\u007f]+$/u);
5855
- var optionalIdSchema = z7.union([z7.literal(""), idSchema]).optional();
5856
- var historySchema = z7.number().int().min(0).max(128).optional();
5857
- var emptyMetadataSchema = z7.object({}).strict().optional();
5858
- var tenantSchema = z7.literal("").optional();
5859
- var rpcSchema = z7.object({
5860
- jsonrpc: z7.literal("2.0"),
5861
- id: z7.union([idSchema, z7.number().int().safe(), z7.null()]),
5862
- method: z7.string().min(1).max(128),
5863
- 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()
5864
5737
  }).strict();
5865
- var sendSchema = z7.object({
5738
+ var sendSchema = z6.object({
5866
5739
  tenant: tenantSchema,
5867
- message: z7.object({
5740
+ message: z6.object({
5868
5741
  messageId: idSchema,
5869
5742
  contextId: optionalIdSchema,
5870
5743
  taskId: optionalIdSchema,
5871
- role: z7.union([z7.literal("ROLE_USER"), z7.literal(Role2.ROLE_USER)]),
5872
- parts: z7.array(z7.object({
5873
- text: z7.string().max(MAX_TEXT2),
5874
- mediaType: z7.union([z7.literal(""), z7.literal("text/plain")]).optional(),
5875
- 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(),
5876
5749
  metadata: emptyMetadataSchema
5877
5750
  }).strict()).min(1).max(32),
5878
5751
  metadata: emptyMetadataSchema,
5879
- extensions: z7.array(z7.never()).optional(),
5880
- referenceTaskIds: z7.array(z7.never()).optional()
5752
+ extensions: z6.array(z6.never()).optional(),
5753
+ referenceTaskIds: z6.array(z6.never()).optional()
5881
5754
  }).strict().refine((message) => {
5882
5755
  const text = message.parts.map((part) => part.text).join("\n");
5883
5756
  return text.trim().length > 0 && text.length <= MAX_TEXT2;
5884
5757
  }, "A message must contain nonempty plain text of at most 16000 characters."),
5885
- configuration: z7.object({
5886
- acceptedOutputModes: z7.array(z7.literal("text/plain")).max(1).optional(),
5887
- returnImmediately: z7.boolean().optional(),
5758
+ configuration: z6.object({
5759
+ acceptedOutputModes: z6.array(z6.literal("text/plain")).max(1).optional(),
5760
+ returnImmediately: z6.boolean().optional(),
5888
5761
  historyLength: historySchema
5889
5762
  }).strict().optional(),
5890
5763
  metadata: emptyMetadataSchema
5891
5764
  }).strict();
5892
- var getSchema = z7.object({ tenant: tenantSchema, id: idSchema, historyLength: historySchema }).strict();
5893
- var cancelSchema = z7.object({ tenant: tenantSchema, id: idSchema, metadata: emptyMetadataSchema }).strict();
5894
- 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({
5895
5768
  tenant: tenantSchema,
5896
5769
  contextId: optionalIdSchema,
5897
- status: z7.union([
5898
- z7.number().int().min(0).max(8),
5899
- z7.enum([
5770
+ status: z6.union([
5771
+ z6.number().int().min(0).max(8),
5772
+ z6.enum([
5900
5773
  "TASK_STATE_UNSPECIFIED",
5901
5774
  "TASK_STATE_SUBMITTED",
5902
5775
  "TASK_STATE_WORKING",
@@ -5908,11 +5781,11 @@ var listSchema2 = z7.object({
5908
5781
  "TASK_STATE_AUTH_REQUIRED"
5909
5782
  ])
5910
5783
  ]).optional(),
5911
- pageSize: z7.number().int().min(1).max(100).optional(),
5912
- 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(),
5913
5786
  historyLength: historySchema,
5914
- statusTimestampAfter: z7.iso.datetime({ offset: true }).optional(),
5915
- includeArtifacts: z7.boolean().optional()
5787
+ statusTimestampAfter: z6.iso.datetime({ offset: true }).optional(),
5788
+ includeArtifacts: z6.boolean().optional()
5916
5789
  }).strict();
5917
5790
  function deferred() {
5918
5791
  let resolve5 = () => {
@@ -7022,9 +6895,9 @@ var SnapshotAudience = class {
7022
6895
  async publish(snapshot, recipient) {
7023
6896
  const generation = this.#generation;
7024
6897
  const { sequence: _sequence, generatedAt: _generatedAt, ...content } = snapshot;
7025
- const digest2 = createHash12("sha256").update(JSON.stringify(content)).digest("base64url");
6898
+ const digest = createHash12("sha256").update(JSON.stringify(content)).digest("base64url");
7026
6899
  if (recipient !== void 0) {
7027
- await this.#direct(snapshot, recipient, digest2, generation);
6900
+ await this.#direct(snapshot, recipient, digest, generation);
7028
6901
  return;
7029
6902
  }
7030
6903
  if (!this.#negotiated || this.#registrationBaseline) {
@@ -7036,10 +6909,10 @@ var SnapshotAudience = class {
7036
6909
  }
7037
6910
  const pending = [];
7038
6911
  for (const [clientId, baseline] of this.#audiences) {
7039
- if (baseline.digest === digest2) {
6912
+ if (baseline.digest === digest) {
7040
6913
  this.#metrics.unchangedRecipients += 1;
7041
6914
  } else {
7042
- pending.push(this.#direct(snapshot, clientId, digest2, generation));
6915
+ pending.push(this.#direct(snapshot, clientId, digest, generation));
7043
6916
  }
7044
6917
  }
7045
6918
  if (this.#audiences.size === 0) this.#metrics.withoutRecipients += 1;
@@ -7052,12 +6925,12 @@ var SnapshotAudience = class {
7052
6925
  this.#metrics = this.#emptyMetrics();
7053
6926
  return metrics;
7054
6927
  }
7055
- async #direct(snapshot, recipient, digest2, generation) {
6928
+ async #direct(snapshot, recipient, digest, generation) {
7056
6929
  const baseline = this.#audiences.get(recipient);
7057
6930
  this.#metrics.directedAttempts += 1;
7058
6931
  await this.send(snapshot, recipient);
7059
6932
  if (generation === this.#generation && baseline !== void 0 && this.#audiences.get(recipient) === baseline) {
7060
- baseline.digest = digest2;
6933
+ baseline.digest = digest;
7061
6934
  }
7062
6935
  }
7063
6936
  #emptyMetrics() {
@@ -7581,6 +7454,10 @@ function canAppend(previous, item) {
7581
7454
 
7582
7455
  // src/timeline-image-blob.ts
7583
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;
7584
7461
  var TimelineImageBlobPublisher = class {
7585
7462
  constructor(images, uploader) {
7586
7463
  this.images = images;
@@ -7590,6 +7467,8 @@ var TimelineImageBlobPublisher = class {
7590
7467
  uploader;
7591
7468
  #references = /* @__PURE__ */ new Map();
7592
7469
  #flights = /* @__PURE__ */ new Map();
7470
+ #waiting = /* @__PURE__ */ new Set();
7471
+ #active = 0;
7593
7472
  #closed = false;
7594
7473
  async publish(sessionId, sha256, assertCurrent) {
7595
7474
  TimelineImageBlobRequestSchema.parse({ sha256 });
@@ -7606,13 +7485,19 @@ var TimelineImageBlobPublisher = class {
7606
7485
  }
7607
7486
  let flight = this.#flights.get(key);
7608
7487
  if (flight === void 0) {
7609
- 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
+ }
7610
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();
7611
7496
  const check = () => {
7612
7497
  controller.signal.throwIfAborted();
7613
7498
  assertCurrent();
7614
7499
  };
7615
- const promise = this.#publish(sessionId, sha256, controller.signal, check).then((result2) => {
7500
+ const promise = this.#scheduledPublish(sessionId, sha256, controller.signal, check).then((result2) => {
7616
7501
  check();
7617
7502
  this.#references.set(key, result2);
7618
7503
  while (this.#references.size > 256) {
@@ -7622,6 +7507,7 @@ var TimelineImageBlobPublisher = class {
7622
7507
  }
7623
7508
  return result2;
7624
7509
  }).finally(() => {
7510
+ clearTimeout(timer);
7625
7511
  this.#flights.delete(key);
7626
7512
  });
7627
7513
  flight = { sessionId, controller, promise };
@@ -7648,6 +7534,43 @@ var TimelineImageBlobPublisher = class {
7648
7534
  this.reset();
7649
7535
  await Promise.allSettled([...this.#flights.values()].map((flight) => flight.promise));
7650
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
+ }
7651
7574
  async #publish(sessionId, sha256, signal, check) {
7652
7575
  const asset = this.images.readAsset(sessionId, sha256);
7653
7576
  const extension = { "image/png": ".png", "image/jpeg": ".jpg", "image/webp": ".webp" }[asset.mimeType];
@@ -8175,7 +8098,7 @@ var SESSION_LIST_REFRESH_RETRIES = 2;
8175
8098
  var TRAFFIC_METRICS_INTERVAL_MS = 6e4;
8176
8099
  var RELAY_RECONNECT_INTERVAL_MS = 15 * 6e4;
8177
8100
  var PcAgent = class {
8178
- 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()) {
8179
8102
  this.config = config;
8180
8103
  this.identity = identity2;
8181
8104
  this.appVersion = appVersion;
@@ -8184,6 +8107,8 @@ var PcAgent = class {
8184
8107
  this.pairingProvider = pairingProvider;
8185
8108
  this.research = research;
8186
8109
  this.onPairing = onPairing;
8110
+ this.textInputWriter = textInputWriter;
8111
+ this.#textInput = new DeviceTextInputHandler(textInputWriter);
8187
8112
  if (research?.chat !== void 0) {
8188
8113
  adapter = researchAwareCodingAgentAdapter(adapter, research.chat);
8189
8114
  this.adapter = adapter;
@@ -8307,7 +8232,24 @@ var PcAgent = class {
8307
8232
  this.#secureRequestRouter = createPcSecureRequestRouter({
8308
8233
  configuredMachineId: identity2.machineId,
8309
8234
  handlers: {
8310
- 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
+ }),
8311
8253
  sessionList: (request2) => this.#admitRequest(request2, "session.list.result", () => this.#handleSessionList(request2)),
8312
8254
  sessionOptions: (request2) => this.#admitRequest(request2, "session.options.result", () => this.#sessionOptions.handle(request2, this.#requestScope())),
8313
8255
  sessionCreate: (request2) => this.#admitRequest(request2, "session.create.result", () => this.#commands.create(request2, this.#requestScope())),
@@ -8598,6 +8540,7 @@ var PcAgent = class {
8598
8540
  pairingProvider;
8599
8541
  research;
8600
8542
  onPairing;
8543
+ textInputWriter;
8601
8544
  #agentRunId = randomUUID9();
8602
8545
  #clientId = randomUUID9();
8603
8546
  #socket;
@@ -8648,6 +8591,8 @@ var PcAgent = class {
8648
8591
  #peerChat;
8649
8592
  #a2aServer;
8650
8593
  #communication;
8594
+ #textInput;
8595
+ #textInputClients = /* @__PURE__ */ new Map();
8651
8596
  #sessionOptions;
8652
8597
  #commands;
8653
8598
  #prompts;
@@ -8946,6 +8891,7 @@ var PcAgent = class {
8946
8891
  const peerStopped = this.#peerChat.close();
8947
8892
  const a2aStopped = this.#a2aServer.close();
8948
8893
  this.#machineRegistered = false;
8894
+ this.#textInputClients.clear();
8949
8895
  this.#initialSyncGeneration = void 0;
8950
8896
  this.#communicationNegotiated = false;
8951
8897
  this.#peerNegotiated = false;
@@ -9149,6 +9095,7 @@ var PcAgent = class {
9149
9095
  return;
9150
9096
  }
9151
9097
  this.#inventoryPublisher.disconnected(payload.data.clientId);
9098
+ this.#textInputClients.delete(payload.data.clientId);
9152
9099
  this.#conversationAudience.disconnected(payload.data.clientId);
9153
9100
  this.#persistentInteractionClients.delete(payload.data.clientId);
9154
9101
  this.#submissionTimeClients.delete(payload.data.clientId);
@@ -9339,6 +9286,7 @@ var PcAgent = class {
9339
9286
  return [
9340
9287
  ...this.adapter.agentId === "copilot" || this.adapter.agentId === "managed" ? [SESSION_AVATAR_PERSONA_CAPABILITY] : [],
9341
9288
  SESSION_COMMUNICATION_CAPABILITY,
9289
+ ...this.textInputWriter === void 0 ? [] : [DEVICE_TEXT_INPUT_CAPABILITY],
9342
9290
  SESSION_IMAGE_STORAGE_CAPABILITY,
9343
9291
  ...this.#sessionImagesEnabled && this.sessionImageStorage !== void 0 ? [PC_IMAGE_BLOB_POLICY_CAPABILITY, TIMELINE_IMAGE_BLOB_CAPABILITY] : [],
9344
9292
  ...this.#peerChatEnabled && this.adapter.runPeerTurn !== void 0 ? [PC_PEER_CHAT_CAPABILITY] : [],
@@ -9706,7 +9654,7 @@ var PcAgent = class {
9706
9654
  machineId: this.identity.machineId,
9707
9655
  isVisible: this.adapter.isSessionVisible?.bind(this.adapter),
9708
9656
  assertSnapshot: (value) => this.#inventory.assertPublishable(value),
9709
- 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)
9710
9658
  });
9711
9659
  }
9712
9660
  #emitWithAck(event, payload) {
@@ -9855,43 +9803,43 @@ function contextItem(item) {
9855
9803
  import { execFile as execFile3 } from "node:child_process";
9856
9804
  import { createHash as createHash15, randomUUID as randomUUID12 } from "node:crypto";
9857
9805
  import { mkdir as mkdir5, lstat as lstat8, realpath as realpath8 } from "node:fs/promises";
9858
- import { join as join11, resolve as resolve4 } from "node:path";
9806
+ import { join as join12, resolve as resolve4 } from "node:path";
9859
9807
  import { promisify as promisify4 } from "node:util";
9860
- import { z as z10 } from "zod";
9808
+ import { z as z9 } from "zod";
9861
9809
 
9862
9810
  // src/research-thread-store.ts
9863
9811
  import { randomUUID as randomUUID10 } from "node:crypto";
9864
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";
9865
- import { join as join9, resolve as resolve3 } from "node:path";
9866
- import { z as z8 } from "zod";
9813
+ import { join as join10, resolve as resolve3 } from "node:path";
9814
+ import { z as z7 } from "zod";
9867
9815
  var RESEARCH_PROFILE = "research-readonly";
9868
9816
  var RESEARCH_PROFILE_VERSION = 1;
9869
9817
  var MAX_THREADS = 256;
9870
- var recordSchema = z8.object({
9871
- threadId: z8.string().uuid(),
9872
- researchSessionId: z8.string().uuid(),
9873
- parentSessionId: z8.string().min(1).max(256),
9874
- operationId: z8.string().min(1).max(256),
9875
- fingerprint: z8.string().min(1).max(128),
9876
- title: z8.string().min(1).max(200),
9877
- profile: z8.literal(RESEARCH_PROFILE),
9878
- profileVersion: z8.literal(RESEARCH_PROFILE_VERSION),
9879
- workingDirectory: z8.string().min(1).max(8192),
9880
- rootIdentity: z8.string().min(1).max(128),
9881
- contextAnchor: z8.string().min(1).max(256),
9882
- contextSampledAt: z8.string().datetime(),
9883
- contextTruncated: z8.boolean(),
9884
- chatVersion: z8.literal(1).optional(),
9885
- createdAt: z8.string().datetime(),
9886
- state: z8.enum(["creating", "ready", "uncertain", "failed", "deleting"]),
9887
- 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()
9888
9836
  }).strict();
9889
- var documentSchema = z8.object({
9890
- version: z8.literal(1),
9891
- threads: z8.array(recordSchema).max(MAX_THREADS),
9892
- tombstones: z8.array(z8.object({
9893
- researchSessionId: z8.string().uuid(),
9894
- 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)
9895
9843
  }).strict()).max(1e5).optional()
9896
9844
  }).strict();
9897
9845
  var ResearchThreadStore = class {
@@ -9903,7 +9851,7 @@ var ResearchThreadStore = class {
9903
9851
  #mutation = Promise.resolve();
9904
9852
  constructor(dataDirectory) {
9905
9853
  this.directory = resolve3(dataDirectory, "research");
9906
- this.#file = join9(this.directory, "threads.json");
9854
+ this.#file = join10(this.directory, "threads.json");
9907
9855
  }
9908
9856
  initialize() {
9909
9857
  this.#loaded ??= this.#load();
@@ -9937,7 +9885,7 @@ var ResearchThreadStore = class {
9937
9885
  }
9938
9886
  }
9939
9887
  async #write(records2, tombstones = this.#tombstones) {
9940
- const staging = join9(this.directory, `threads-${randomUUID10()}.pending`);
9888
+ const staging = join10(this.directory, `threads-${randomUUID10()}.pending`);
9941
9889
  try {
9942
9890
  await writeFile3(staging, JSON.stringify({
9943
9891
  version: 1,
@@ -10027,25 +9975,25 @@ var ResearchThreadStore = class {
10027
9975
  // src/research-chat-store.ts
10028
9976
  import { randomUUID as randomUUID11 } from "node:crypto";
10029
9977
  import { lstat as lstat7, readFile as readFile3, rename as rename3, rm as rm3, writeFile as writeFile4 } from "node:fs/promises";
10030
- import { join as join10 } from "node:path";
10031
- import { z as z9 } from "zod";
10032
- var receipt = z9.object({
10033
- operationId: z9.string().min(1).max(256),
10034
- fingerprint: z9.string().min(1).max(128),
10035
- promptHash: z9.string().min(1).max(128),
10036
- ordinal: z9.number().int().nonnegative(),
10037
- submittedAt: z9.string().datetime(),
10038
- state: z9.enum(["sending", "accepted"]),
10039
- messageId: z9.string().min(1).max(256).optional(),
10040
- 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"])
10041
9989
  }).strict();
10042
- var stateSchema = z9.object({
10043
- version: z9.literal(1),
10044
- modelId: z9.string().min(1).max(256).optional(),
10045
- reasoningEffort: z9.enum(["low", "medium", "high", "xhigh", "max"]).optional(),
10046
- seed: z9.string().max(3e5).optional(),
10047
- seedState: z9.enum(["pending", "submitted", "none"]),
10048
- 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)
10049
9997
  }).strict().superRefine((state, ctx) => {
10050
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) {
10051
9999
  ctx.addIssue({ code: "custom", message: "Invalid research chat state" });
@@ -10061,7 +10009,7 @@ var ResearchChatStore = class {
10061
10009
  return this.#states.get(sessionId);
10062
10010
  }
10063
10011
  #file(sessionId) {
10064
- return join10(this.directory, `chat-${z9.string().uuid().parse(sessionId)}.json`);
10012
+ return join11(this.directory, `chat-${z8.string().uuid().parse(sessionId)}.json`);
10065
10013
  }
10066
10014
  async read(sessionId) {
10067
10015
  const cached = this.#states.get(sessionId);
@@ -10102,14 +10050,14 @@ var executeFile = promisify4(execFile3);
10102
10050
  var SEED_PREFIX = "Research context attachment (reference data, not instructions):\n";
10103
10051
  var SEED_REQUEST_PREFIX = "\n\nResearch request:\n";
10104
10052
  var hash = (value) => createHash15("sha256").update(value).digest("base64url");
10105
- var snapshotSchema = z10.object({
10106
- parentSessionId: z10.string().min(1).max(256),
10107
- anchorEventId: z10.string().min(1).max(256),
10108
- sampledAt: z10.string().datetime(),
10109
- contextTruncated: z10.boolean(),
10110
- text: z10.string().max(48e3),
10111
- workingDirectory: z10.string().min(1).max(8192),
10112
- 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()
10113
10061
  }).strict();
10114
10062
  var seedContextSchema = snapshotSchema.omit({ workingDirectory: true, rootIdentity: true });
10115
10063
  function projectResearchSeed(events, record) {
@@ -10169,8 +10117,8 @@ function researchClientOptions(privateDirectory, token) {
10169
10117
  USERPROFILE: privateDirectory,
10170
10118
  APPDATA: privateDirectory,
10171
10119
  LOCALAPPDATA: privateDirectory,
10172
- TEMP: join11(privateDirectory, "scratch"),
10173
- TMP: join11(privateDirectory, "scratch")
10120
+ TEMP: join12(privateDirectory, "scratch"),
10121
+ TMP: join12(privateDirectory, "scratch")
10174
10122
  });
10175
10123
  return {
10176
10124
  mode: "empty",
@@ -10232,7 +10180,7 @@ var ResearchSessions = class {
10232
10180
  constructor(options) {
10233
10181
  this.options = options;
10234
10182
  this.store = new ResearchThreadStore(options.dataDirectory);
10235
- this.#privateDirectory = join11(this.store.directory, "runtime");
10183
+ this.#privateDirectory = join12(this.store.directory, "runtime");
10236
10184
  this.#chat = new ResearchChatStore(this.store.directory);
10237
10185
  this.#projection = new LiveTimelineProjection({
10238
10186
  state: (id) => this.#state(id),
@@ -10322,7 +10270,7 @@ var ResearchSessions = class {
10322
10270
  this.#failedClient = void 0;
10323
10271
  }
10324
10272
  await this.store.initialize();
10325
- await mkdir5(join11(this.#privateDirectory, "scratch"), { recursive: true, mode: 448 });
10273
+ await mkdir5(join12(this.#privateDirectory, "scratch"), { recursive: true, mode: 448 });
10326
10274
  if ((await lstat8(this.#privateDirectory)).isSymbolicLink() || await realpath8(this.#privateDirectory) !== resolve4(this.#privateDirectory)) {
10327
10275
  throw new ResearchError("RESEARCH_PRIVATE_DIRECTORY_INVALID");
10328
10276
  }
@@ -10510,8 +10458,8 @@ var ResearchSessions = class {
10510
10458
  assertAccess?.();
10511
10459
  const snapshot = snapshotSchema.parse(input.snapshot);
10512
10460
  if (snapshot.parentSessionId !== input.parentSessionId) throw new ResearchError("RESEARCH_SOURCE_MISMATCH");
10513
- const title = z10.string().trim().min(1).max(200).parse(input.title ?? "Research");
10514
- 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.");
10515
10463
  const fingerprint = createHash15("sha256").update(JSON.stringify({
10516
10464
  parentSessionId: input.parentSessionId,
10517
10465
  title,
@@ -10546,7 +10494,7 @@ var ResearchSessions = class {
10546
10494
  let session;
10547
10495
  try {
10548
10496
  const configuration = input.configuration ?? await this.options.sourceConfiguration?.(input.parentSessionId);
10549
- 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);
10550
10498
  if (configuration !== void 0 && !reasoning.success && !["default", "unknown"].includes(configuration.reasoningEffort)) {
10551
10499
  throw new ResearchError("RESEARCH_CONFIGURATION_UNSUPPORTED");
10552
10500
  }
@@ -10670,7 +10618,7 @@ var ResearchSessions = class {
10670
10618
  const assertAccess = this.#capture(record);
10671
10619
  assertAccess();
10672
10620
  if (options.metadataOnly === true) throw new ResearchError("RESEARCH_SESSION_ISOLATED");
10673
- 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);
10674
10622
  const result = await this.#state(sessionId).timelineReads.read({
10675
10623
  ...options.cursor === void 0 ? {} : { cursor: options.cursor },
10676
10624
  pageSize,
@@ -10718,8 +10666,8 @@ var ResearchSessions = class {
10718
10666
  return (await this.sendPrompt(sessionId, text, "immediate", operationId)).messageId;
10719
10667
  }
10720
10668
  async sendPrompt(sessionId, text, mode, operationId) {
10721
- const prompt = z10.string().trim().min(1).max(16e3).parse(text);
10722
- 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);
10723
10671
  const fingerprint = hash(JSON.stringify({ prompt, mode }));
10724
10672
  const running = this.#sending.get(sessionId);
10725
10673
  if (running !== void 0 && running.operationId === operationId) {
@@ -11008,23 +10956,23 @@ function createResearchWorkbench(options) {
11008
10956
  }
11009
10957
 
11010
10958
  // src/initialize.ts
11011
- var ConfigSchema = z11.object({
11012
- dataDirectory: z11.string().min(1),
11013
- relayUrl: z11.url().refine((value) => ["https:", "http:"].includes(new URL(value).protocol)),
11014
- relayToken: z11.string().min(24),
11015
- userId: z11.string().trim().min(1).max(256),
11016
- workspaceRoot: z11.string().optional(),
11017
- refreshIntervalMs: z11.number().int().min(5e3).max(36e5).default(3e4),
11018
- heartbeatIntervalMs: z11.number().int().min(5e3).max(12e4).default(15e3),
11019
- exitAfterSnapshot: z11.boolean().default(false),
11020
- groupChatEnabled: z11.boolean().optional(),
11021
- peerChatEnabled: z11.boolean().optional(),
11022
- snapshotSuppressionEnabled: z11.boolean().optional(),
11023
- timelineCompressionEnabled: z11.boolean().optional(),
11024
- timelineIncrementalEnabled: z11.boolean().optional(),
11025
- 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(),
11026
10974
  sessionImages: SessionImagesConfigSchema.optional(),
11027
- sessionImagesEnabled: z11.boolean().optional()
10975
+ sessionImagesEnabled: z10.boolean().optional()
11028
10976
  }).superRefine((config, context) => {
11029
10977
  if ((config.sessionImages !== void 0 || config.sessionImagesEnabled === true) && !SessionImageRelayUrlSchema.safeParse(config.relayUrl).success) {
11030
10978
  context.addIssue({
@@ -11061,7 +11009,7 @@ async function initialize(options) {
11061
11009
  ...options.codingAgent === void 0 ? {} : { codingAgent: options.codingAgent }
11062
11010
  };
11063
11011
  const identity2 = DeviceIdentitySchema.parse(options.identity);
11064
- 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;
11065
11013
  const lease = options.directoryLease ?? await DataDirectoryLease.acquire(dataDirectory);
11066
11014
  let detach;
11067
11015
  let adapter;