@celljs/ta-host 4.14.0 → 4.15.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (55) hide show
  1. package/README.en.md +2 -1
  2. package/README.md +2 -1
  3. package/esm/node/auth-server-impl.d.ts +12 -2
  4. package/esm/node/auth-server-impl.js +102 -3
  5. package/esm/node/custom-providers.d.ts +50 -0
  6. package/esm/node/custom-providers.js +335 -0
  7. package/esm/node/extension-data.js +7 -3
  8. package/esm/node/index.d.ts +1 -0
  9. package/esm/node/index.js +1 -0
  10. package/esm/node/jpeg-encoder.d.ts +7 -0
  11. package/esm/node/jpeg-encoder.js +268 -0
  12. package/esm/node/png-thumbnail.d.ts +40 -0
  13. package/esm/node/png-thumbnail.js +384 -0
  14. package/esm/node/serve-updates.d.ts +38 -0
  15. package/esm/node/serve-updates.js +89 -0
  16. package/esm/node/sign-in/sign-in-provider.d.ts +44 -0
  17. package/esm/node/sign-in/sign-in-provider.js +74 -7
  18. package/esm/node/sign-in/ta-sign-in.d.ts +4 -1
  19. package/esm/node/sign-in/ta-sign-in.js +6 -2
  20. package/esm/node/ta-server-impl.d.ts +3 -0
  21. package/esm/node/ta-server-impl.js +33 -9
  22. package/esm/node/team/host-team.js +1 -0
  23. package/esm/node/team/member-accounts.d.ts +25 -8
  24. package/esm/node/team/member-accounts.js +84 -4
  25. package/esm/node/team/team-calls.js +5 -0
  26. package/esm/node/web-extension-util.js +1 -0
  27. package/esm/node/workspace-files.d.ts +23 -0
  28. package/esm/node/workspace-files.js +86 -0
  29. package/lib/node/auth-server-impl.d.ts +12 -2
  30. package/lib/node/auth-server-impl.js +101 -2
  31. package/lib/node/custom-providers.d.ts +51 -0
  32. package/lib/node/custom-providers.js +338 -0
  33. package/lib/node/extension-data.js +6 -2
  34. package/lib/node/index.d.ts +1 -0
  35. package/lib/node/index.js +1 -0
  36. package/lib/node/jpeg-encoder.d.ts +8 -0
  37. package/lib/node/jpeg-encoder.js +271 -0
  38. package/lib/node/png-thumbnail.d.ts +41 -0
  39. package/lib/node/png-thumbnail.js +387 -0
  40. package/lib/node/serve-updates.d.ts +39 -0
  41. package/lib/node/serve-updates.js +92 -0
  42. package/lib/node/sign-in/sign-in-provider.d.ts +44 -0
  43. package/lib/node/sign-in/sign-in-provider.js +77 -9
  44. package/lib/node/sign-in/ta-sign-in.d.ts +4 -1
  45. package/lib/node/sign-in/ta-sign-in.js +6 -2
  46. package/lib/node/ta-server-impl.d.ts +3 -0
  47. package/lib/node/ta-server-impl.js +33 -9
  48. package/lib/node/team/host-team.js +1 -0
  49. package/lib/node/team/member-accounts.d.ts +25 -8
  50. package/lib/node/team/member-accounts.js +84 -4
  51. package/lib/node/team/team-calls.js +5 -0
  52. package/lib/node/web-extension-util.js +1 -0
  53. package/lib/node/workspace-files.d.ts +23 -0
  54. package/lib/node/workspace-files.js +86 -0
  55. package/package.json +10 -10
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.SignInProviders = exports.WeChatSignIn = exports.OidcSignIn = exports.GitHubSignIn = exports.SignInHttp = exports.SignInError = void 0;
3
+ exports.SignInProviders = exports.WeChatSignIn = exports.OidcSignIn = exports.GitHubDeviceSignIn = exports.GitHubSignIn = exports.SignInHttp = exports.SignInError = void 0;
4
4
  /** A sign-in that failed with the provider (a code refused, an account without what it needs). */
5
5
  class SignInError extends Error {
6
6
  }
@@ -48,7 +48,22 @@ class GitHubSignIn {
48
48
  static endpoints(url = 'https://github.com') {
49
49
  const base = url.replace(/\/+$/, '');
50
50
  const api = base === 'https://github.com' ? 'https://api.github.com' : `${base}/api/v3`;
51
- return { authorize: `${base}/login/oauth/authorize`, token: `${base}/login/oauth/access_token`, user: `${api}/user` };
51
+ return {
52
+ authorize: `${base}/login/oauth/authorize`,
53
+ token: `${base}/login/oauth/access_token`,
54
+ user: `${api}/user`,
55
+ device: `${base}/login/device/code`,
56
+ };
57
+ }
58
+ /** Who a token of GitHub is. */
59
+ static async user(endpoints, token) {
60
+ const user = await SignInHttp.json(endpoints.user, {
61
+ headers: { Authorization: `Bearer ${token}`, Accept: 'application/vnd.github+json', 'User-Agent': 'Ta' },
62
+ });
63
+ if (!user.login) {
64
+ throw new SignInError('GitHub: the user has no login');
65
+ }
66
+ return { id: `github:${user.login.toLowerCase()}`, name: user.name || user.login, avatar: user.avatar_url };
52
67
  }
53
68
  constructor(clientId, clientSecret, endpoints = GitHubSignIn.endpoints()) {
54
69
  this.clientId = clientId;
@@ -74,16 +89,51 @@ class GitHubSignIn {
74
89
  if (!token.access_token) {
75
90
  throw new SignInError(`GitHub: ${(_b = (_a = token.error_description) !== null && _a !== void 0 ? _a : token.error) !== null && _b !== void 0 ? _b : 'no access token'}`);
76
91
  }
77
- const user = await SignInHttp.json(this.endpoints.user, {
78
- headers: { Authorization: `Bearer ${token.access_token}`, Accept: 'application/vnd.github+json', 'User-Agent': 'Ta' },
79
- });
80
- if (!user.login) {
81
- throw new SignInError('GitHub: the user has no login');
82
- }
83
- return { id: `github:${user.login.toLowerCase()}`, name: user.name || user.login, avatar: user.avatar_url };
92
+ return GitHubSignIn.user(this.endpoints, token.access_token);
84
93
  }
85
94
  }
86
95
  exports.GitHubSignIn = GitHubSignIn;
96
+ /** GitHub's device flow, with Ta's own OAuth app by default; the account is `github:<login>`, as GitHubSignIn's. */
97
+ class GitHubDeviceSignIn {
98
+ constructor(clientId = GitHubDeviceSignIn.CLIENT_ID, endpoints = GitHubSignIn.endpoints()) {
99
+ this.clientId = clientId;
100
+ this.endpoints = endpoints;
101
+ this.id = 'github';
102
+ this.name = 'GitHub';
103
+ this.device = true;
104
+ }
105
+ async code() {
106
+ var _a, _b, _c, _d;
107
+ const answer = await SignInHttp.json(this.endpoints.device, SignInHttp.form({ client_id: this.clientId, scope: 'read:user' }));
108
+ if (!answer.device_code || !answer.user_code || !answer.verification_uri || !/^https?:\/\//.test(answer.verification_uri)) {
109
+ throw new SignInError(`GitHub: ${(_b = (_a = answer.error_description) !== null && _a !== void 0 ? _a : answer.error) !== null && _b !== void 0 ? _b : 'no code'}`);
110
+ }
111
+ return {
112
+ deviceCode: answer.device_code,
113
+ userCode: answer.user_code,
114
+ uri: answer.verification_uri,
115
+ interval: Number((_c = answer.interval) !== null && _c !== void 0 ? _c : 5),
116
+ expiresIn: Number((_d = answer.expires_in) !== null && _d !== void 0 ? _d : 900),
117
+ };
118
+ }
119
+ async poll(deviceCode) {
120
+ var _a, _b;
121
+ const token = await SignInHttp.json(this.endpoints.token, SignInHttp.form({ client_id: this.clientId, device_code: deviceCode, grant_type: 'urn:ietf:params:oauth:grant-type:device_code' }));
122
+ if (token.access_token) {
123
+ return GitHubSignIn.user(this.endpoints, token.access_token);
124
+ }
125
+ if (token.error === 'authorization_pending') {
126
+ return 'pending';
127
+ }
128
+ if (token.error === 'slow_down') {
129
+ return 'slowDown';
130
+ }
131
+ throw new SignInError(`GitHub: ${(_b = (_a = token.error_description) !== null && _a !== void 0 ? _a : token.error) !== null && _b !== void 0 ? _b : 'no access token'}`);
132
+ }
133
+ }
134
+ exports.GitHubDeviceSignIn = GitHubDeviceSignIn;
135
+ /** Ta's own OAuth app on GitHub.com, its device flow on: a client id is public, and the device flow needs no secret. */
136
+ GitHubDeviceSignIn.CLIENT_ID = 'Ov23lip46sRQDlDM1xt7';
87
137
  /**
88
138
  * OpenID Connect, found from the issuer (`/.well-known/openid-configuration`): Google, and the provider of
89
139
  * the operator (Microsoft Entra, Okta, Keycloak, Authing...). The account is `<id>:<email>` when the
@@ -322,6 +372,24 @@ var SignInProviders;
322
372
  return merged;
323
373
  }
324
374
  SignInProviders.withConfig = withConfig;
375
+ /**
376
+ * GitHub by a code, for those asking to come in, when GitHub is not set up with its secret (which goes there and back
377
+ * instead): `TA_GITHUB_DEVICE` is `off`, or `<client id>` or `<client id>@<address of GitHub>` of an OAuth app of
378
+ * one's own with its device flow on; by default Ta's own, on GitHub.com.
379
+ */
380
+ function device(env) {
381
+ var _a;
382
+ var _b;
383
+ const value = (_b = (_a = env.TA_GITHUB_DEVICE) === null || _a === void 0 ? void 0 : _a.trim()) !== null && _b !== void 0 ? _b : '';
384
+ if (value === 'off' || (env.TA_GITHUB_CLIENT_ID && env.TA_GITHUB_CLIENT_SECRET)) {
385
+ return undefined;
386
+ }
387
+ const at = value.indexOf('@');
388
+ const clientId = at < 0 ? value : value.slice(0, at);
389
+ const url = at < 0 ? undefined : value.slice(at + 1);
390
+ return new GitHubDeviceSignIn(clientId || GitHubDeviceSignIn.CLIENT_ID, GitHubSignIn.endpoints(url || undefined));
391
+ }
392
+ SignInProviders.device = device;
325
393
  /**
326
394
  * The providers the operator configured in the environment of ta serve: a provider is offered when it
327
395
  * has its id and its secret.
@@ -1,14 +1,17 @@
1
1
  import type { TaSignInKind, TaSignInSetup } from '@celljs/ta-protocol';
2
2
  import { SignInFlow } from './sign-in-flow';
3
+ import { type DeviceSignInProvider } from './sign-in-provider';
3
4
  export declare const TA_SIGN_IN: unique symbol;
4
5
  /**
5
6
  * Signing in to ta serve with an account, besides its token. The providers come from the environment, then
6
7
  * sign-in.json of the agent directory (SignInProviders.withConfig), which Settings, Access writes (setProvider) and
7
8
  * which is read again then; who may sign in from TA_ALLOWED_USERS and the accounts added in the web client
8
9
  * (AccessStore). Someone else who signs in is told to wait, and shows up as a request. Those asking to come in by a
9
- * link sign in with the same providers to say who they are (TaHostAccounts), which lets them into nothing.
10
+ * link sign in with the same providers to say who they are (TaHostAccounts), which lets them into nothing, or, when GitHub
11
+ * is not set up, with GitHub by a code, Ta's own app (`device`, SignInProviders.device).
10
12
  */
11
13
  export declare class TaSignIn extends SignInFlow {
14
+ device: DeviceSignInProvider | undefined;
12
15
  constructor();
13
16
  setups(): TaSignInSetup[];
14
17
  /** Sets a kind up in sign-in.json (readable by the user alone), offered at once; not one the environment sets. */
@@ -35,14 +35,17 @@ function config() {
35
35
  * sign-in.json of the agent directory (SignInProviders.withConfig), which Settings, Access writes (setProvider) and
36
36
  * which is read again then; who may sign in from TA_ALLOWED_USERS and the accounts added in the web client
37
37
  * (AccessStore). Someone else who signs in is told to wait, and shows up as a request. Those asking to come in by a
38
- * link sign in with the same providers to say who they are (TaHostAccounts), which lets them into nothing.
38
+ * link sign in with the same providers to say who they are (TaHostAccounts), which lets them into nothing, or, when GitHub
39
+ * is not set up, with GitHub by a code, Ta's own app (`device`, SignInProviders.device).
39
40
  */
40
41
  let TaSignIn = class TaSignIn extends sign_in_flow_1.SignInFlow {
41
42
  constructor() {
42
43
  super(sign_in_provider_1.SignInProviders.fromEnv(sign_in_provider_1.SignInProviders.withConfig(process.env, config())), new access_store_1.AccessStore((0, node_path_1.join)(ta_brand_1.TaBrand.agentDir(), 'access.json'), access_store_1.AccessUtil.parseList(process.env.TA_ALLOWED_USERS)), sign_in_provider_1.SignInProviders.publicUrl(process.env));
44
+ this.device = sign_in_provider_1.SignInProviders.device(sign_in_provider_1.SignInProviders.withConfig(process.env, config()));
43
45
  }
44
46
  setups() {
45
- return sign_in_provider_1.SignInProviders.setups(process.env, config());
47
+ const device = this.device;
48
+ return sign_in_provider_1.SignInProviders.setups(process.env, config()).map(setup => ((device === null || device === void 0 ? void 0 : device.id) === setup.id && !setup.configured ? { ...setup, device: true } : setup));
46
49
  }
47
50
  /** Sets a kind up in sign-in.json (readable by the user alone), offered at once; not one the environment sets. */
48
51
  setProvider(id, fields) {
@@ -53,6 +56,7 @@ let TaSignIn = class TaSignIn extends sign_in_flow_1.SignInFlow {
53
56
  const next = sign_in_provider_1.SignInProviders.withProvider(config(), id, fields);
54
57
  (0, node_fs_1.writeFileSync)(file(), `${JSON.stringify(next, null, 2)}\n`, { mode: 0o600 });
55
58
  this.providers = sign_in_provider_1.SignInProviders.fromEnv(sign_in_provider_1.SignInProviders.withConfig(process.env, next));
59
+ this.device = sign_in_provider_1.SignInProviders.device(sign_in_provider_1.SignInProviders.withConfig(process.env, next));
56
60
  }
57
61
  };
58
62
  exports.TaSignIn = TaSignIn;
@@ -1,6 +1,7 @@
1
1
  import { ExecEnvironmentFactory } from '@celljs/ta-exec';
2
2
  import { type ImageContent, type RpcExtensionUIResponse, type TaAttachOptions, type TaAttachResult, type TaClientToolResult, type TaCommandResult, type TaForkFileResult, type TaMessagePage, type TaNavigateResult, type TaOpenedSession, type TaOpenSessionOptions, type TaPromptInput, type TaPromptReceipt, type TaSavedSessionInfo, type TaSavedSessionQuery, TaServer, type TaServerInfo, type TaSessionInfo, type TaSlashCommand, type ThinkingLevel } from '@celljs/ta-protocol';
3
3
  import { TaSessionCatalog, TaSessionFactory, TaSessionRegistry } from './host-protocol';
4
+ import { TaServeUpdates } from './serve-updates';
4
5
  import type { TaSession } from './ta-session';
5
6
  import { TaAuthority, TaPrincipals, TaRunActors, TaVisibility } from './team/team-protocol';
6
7
  import { TaWorkingDirectory } from './working-directory';
@@ -19,7 +20,9 @@ export declare class TaServerImpl implements TaServer {
19
20
  protected readonly principals: TaPrincipals;
20
21
  protected readonly authority: TaAuthority;
21
22
  protected readonly visibility: TaVisibility;
23
+ protected readonly updates: TaServeUpdates;
22
24
  getServerInfo(): Promise<TaServerInfo>;
25
+ restartServer(): Promise<void>;
23
26
  setWorkingDirectory(cwd: string): Promise<TaServerInfo>;
24
27
  openSession({ attach, ...options }: TaOpenSessionOptions): Promise<TaOpenedSession>;
25
28
  closeSession(sessionId: string): Promise<void>;
@@ -17,14 +17,17 @@ const core_1 = require("@celljs/core");
17
17
  const rpc_1 = require("@celljs/rpc");
18
18
  const node_1 = require("@celljs/rpc/lib/node");
19
19
  const ta_exec_1 = require("@celljs/ta-exec");
20
- const ta_brand_1 = require("@celljs/ta-harness/lib/node/ta-brand");
20
+ const serve_restart_1 = require("@celljs/ta-harness/lib/node/serve-restart");
21
21
  const ta_protocol_1 = require("@celljs/ta-protocol");
22
22
  const host_protocol_1 = require("./host-protocol");
23
+ const serve_updates_1 = require("./serve-updates");
23
24
  const session_info_util_1 = require("./session-info-util");
24
25
  const slash_command_util_1 = require("./slash-command-util");
25
26
  const ta_errors_1 = require("./ta-errors");
26
27
  const team_protocol_1 = require("./team/team-protocol");
27
28
  const working_directory_1 = require("./working-directory");
29
+ /** How long restartServer leaves its answer to go out before ta serve stops. */
30
+ const RESTART_DELAY_MS = 200;
28
31
  /**
29
32
  * The sessions of ta serve. Each command of pi's RPC mode does here what it does in pi's `rpc-mode`, which
30
33
  * pi exports only bound to stdio: when pi changes one, change it here too (the spec of TaServer in
@@ -32,14 +35,31 @@ const working_directory_1 = require("./working-directory");
32
35
  */
33
36
  let TaServerImpl = class TaServerImpl {
34
37
  async getServerInfo() {
35
- return this.guard(async () => ({
36
- version: ta_brand_1.TaBrand.version(),
37
- cwd: await this.environments.defaultCwd(),
38
- user: (0, node_os_1.userInfo)().username,
39
- host: (0, node_os_1.hostname)().replace(/\.local$/, ''),
40
- home: (0, node_os_1.homedir)(),
41
- ...(this.member() ? { member: this.member() } : {}),
42
- }));
38
+ return this.guard(async () => {
39
+ const { version, build } = this.updates.running();
40
+ const member = this.member();
41
+ // Restarting is the owner's: one let in is not told of it.
42
+ const update = member ? undefined : this.updates.update();
43
+ return {
44
+ version,
45
+ ...(build ? { build } : {}),
46
+ cwd: await this.environments.defaultCwd(),
47
+ user: (0, node_os_1.userInfo)().username,
48
+ host: (0, node_os_1.hostname)().replace(/\.local$/, ''),
49
+ home: (0, node_os_1.homedir)(),
50
+ ...(member ? { member } : { restartable: serve_restart_1.TaServeRestart.supported() }),
51
+ ...(update ? { update } : {}),
52
+ };
53
+ });
54
+ }
55
+ async restartServer() {
56
+ return this.guard(async () => {
57
+ if (!serve_restart_1.TaServeRestart.supported()) {
58
+ throw ta_errors_1.TaErrors.invalidArgument('This Ta service was not started as ta serve, and cannot restart itself.', 'Stop it and start it again where it was started.');
59
+ }
60
+ // Once the answer went out: then the connections close, and connect again to the new one.
61
+ setTimeout(() => serve_restart_1.TaServeRestart.request(), RESTART_DELAY_MS);
62
+ });
43
63
  }
44
64
  async setWorkingDirectory(cwd) {
45
65
  return this.guard(async () => {
@@ -415,6 +435,10 @@ __decorate([
415
435
  (0, core_1.Autowired)(team_protocol_1.TaVisibility),
416
436
  __metadata("design:type", Object)
417
437
  ], TaServerImpl.prototype, "visibility", void 0);
438
+ __decorate([
439
+ (0, core_1.Autowired)(serve_updates_1.TaServeUpdates),
440
+ __metadata("design:type", Object)
441
+ ], TaServerImpl.prototype, "updates", void 0);
418
442
  exports.TaServerImpl = TaServerImpl = __decorate([
419
443
  (0, rpc_1.Rpc)(ta_protocol_1.TaServer)
420
444
  ], TaServerImpl);
@@ -38,6 +38,7 @@ let DefaultTaHostTeamProvider = class DefaultTaHostTeamProvider {
38
38
  providers: () => this.accounts.providers(),
39
39
  start: (provider, redirectUri) => this.accounts.start(provider, redirectUri),
40
40
  verify: (state, code) => this.accounts.verify(state, code),
41
+ typed: (state, waitMs) => this.accounts.typed(state, waitMs),
41
42
  },
42
43
  };
43
44
  }
@@ -1,14 +1,31 @@
1
- import type { TaAccount, TaSignInProvider } from '@celljs/ta-protocol';
2
- import type { SignInFlow } from '../sign-in/sign-in-flow';
1
+ import type { TaAccount, TaAccountStart, TaSignInProvider } from '@celljs/ta-protocol';
2
+ import { type DeviceSignInProvider, type SignInAccount } from '../sign-in/sign-in-provider';
3
+ import { type TaSignIn } from '../sign-in/ta-sign-in';
3
4
  import { TaMemberAccounts } from './team-protocol';
4
- /** Who one asking to come in is, by an account of the providers ta serve signs in with (TaSignIn): nothing let in by it. */
5
+ /** A sign-in by a code, its device code kept here: who types the code sees it alone. */
6
+ interface Typing {
7
+ provider: DeviceSignInProvider;
8
+ deviceCode: string;
9
+ interval: number;
10
+ next: number;
11
+ expiresAt: number;
12
+ account?: TaAccount;
13
+ }
14
+ /**
15
+ * Who one asking to come in is, by an account of the providers ta serve signs in with (TaSignIn), or by a code typed at
16
+ * GitHub with Ta's own app when GitHub is not set up (TaSignIn.device): nothing let in by it.
17
+ */
5
18
  export declare class DefaultTaMemberAccounts implements TaMemberAccounts {
6
- protected readonly flow: SignInFlow;
19
+ protected readonly flow: TaSignIn;
20
+ protected readonly typing: Map<string, Typing>;
7
21
  providers(): TaSignInProvider[];
8
- start(provider: string, redirectUri: string): Promise<{
9
- url: string;
10
- state: string;
11
- }>;
22
+ start(provider: string, redirectUri: string): Promise<TaAccountStart>;
12
23
  verify(state: string, code: string): Promise<TaAccount>;
24
+ typed(state: string, waitMs?: number): Promise<TaAccount | undefined>;
25
+ /** GitHub by a code, when ta serve has no GitHub of its own. */
26
+ protected device(): DeviceSignInProvider | undefined;
27
+ protected startTyping(device: DeviceSignInProvider): Promise<TaAccountStart>;
28
+ protected of({ id, name, avatar }: SignInAccount): TaAccount;
13
29
  }
30
+ export {};
14
31
  //# sourceMappingURL=member-accounts.d.ts.map
@@ -10,22 +10,102 @@ var __metadata = (this && this.__metadata) || function (k, v) {
10
10
  };
11
11
  Object.defineProperty(exports, "__esModule", { value: true });
12
12
  exports.DefaultTaMemberAccounts = void 0;
13
+ const node_crypto_1 = require("node:crypto");
13
14
  const core_1 = require("@celljs/core");
15
+ const sign_in_provider_1 = require("../sign-in/sign-in-provider");
14
16
  const ta_sign_in_1 = require("../sign-in/ta-sign-in");
15
17
  const team_protocol_1 = require("./team-protocol");
16
- /** Who one asking to come in is, by an account of the providers ta serve signs in with (TaSignIn): nothing let in by it. */
18
+ /** Sign-ins by a code under way at once: anyone holding a link may start one. */
19
+ const MAX_TYPING = 200;
20
+ const WAIT_MS = 25000;
21
+ /**
22
+ * Who one asking to come in is, by an account of the providers ta serve signs in with (TaSignIn), or by a code typed at
23
+ * GitHub with Ta's own app when GitHub is not set up (TaSignIn.device): nothing let in by it.
24
+ */
17
25
  let DefaultTaMemberAccounts = class DefaultTaMemberAccounts {
26
+ constructor() {
27
+ this.typing = new Map();
28
+ }
18
29
  providers() {
19
- return this.flow.providers.map(({ id, name }) => ({ id, name }));
30
+ const own = this.flow.providers.map(({ id, name }) => ({ id, name }));
31
+ const device = this.device();
32
+ return device ? [...own, { id: device.id, name: device.name, device: true }] : own;
20
33
  }
21
- start(provider, redirectUri) {
34
+ async start(provider, redirectUri) {
35
+ const device = this.device();
36
+ if ((device === null || device === void 0 ? void 0 : device.id) === provider) {
37
+ return this.startTyping(device);
38
+ }
22
39
  if (!/^https?:\/\/[^/?#]+\/[^?#]*$/.test(redirectUri)) {
23
40
  throw new Error(`Not an address to come back to: ${redirectUri}`);
24
41
  }
25
42
  return this.flow.startVerify(provider, redirectUri);
26
43
  }
27
44
  async verify(state, code) {
28
- const { id, name, avatar } = await this.flow.verify(state, code);
45
+ return this.of(await this.flow.verify(state, code));
46
+ }
47
+ async typed(state, waitMs = WAIT_MS) {
48
+ const typing = this.typing.get(state);
49
+ if (!typing) {
50
+ throw new sign_in_provider_1.SignInError('The sign-in expired or was not started here');
51
+ }
52
+ const until = Date.now() + Math.min(Math.max(0, waitMs), WAIT_MS);
53
+ // Asked no more often than the provider says; one waiting already asks for both.
54
+ while (!typing.account) {
55
+ if (Date.now() >= typing.expiresAt) {
56
+ this.typing.delete(state);
57
+ throw new sign_in_provider_1.SignInError('The code ran out: sign in again');
58
+ }
59
+ const sleep = typing.next - Date.now();
60
+ if (Date.now() + Math.max(0, sleep) > until) {
61
+ return undefined;
62
+ }
63
+ if (sleep > 0) {
64
+ await new Promise(resolve => setTimeout(resolve, sleep));
65
+ continue;
66
+ }
67
+ typing.next = Date.now() + typing.interval;
68
+ let answer;
69
+ try {
70
+ answer = await typing.provider.poll(typing.deviceCode);
71
+ }
72
+ catch (failure) {
73
+ // Refused, or the code is no good: over. The network failing is not, and is asked again.
74
+ if (failure instanceof sign_in_provider_1.SignInError) {
75
+ this.typing.delete(state);
76
+ }
77
+ throw failure;
78
+ }
79
+ if (answer === 'slowDown') {
80
+ typing.interval += 5000;
81
+ typing.next = Date.now() + typing.interval;
82
+ }
83
+ else if (answer !== 'pending') {
84
+ typing.account = this.of(answer);
85
+ }
86
+ }
87
+ return typing.account;
88
+ }
89
+ /** GitHub by a code, when ta serve has no GitHub of its own. */
90
+ device() {
91
+ const device = this.flow.device;
92
+ return device && !this.flow.providers.some(one => one.id === device.id) ? device : undefined;
93
+ }
94
+ async startTyping(device) {
95
+ const now = Date.now();
96
+ for (const [state, typing] of this.typing) {
97
+ if (now >= typing.expiresAt || this.typing.size >= MAX_TYPING) {
98
+ this.typing.delete(state);
99
+ }
100
+ }
101
+ const code = await device.code();
102
+ const state = (0, node_crypto_1.randomBytes)(18).toString('base64url');
103
+ const interval = Math.max(0, code.interval) * 1000;
104
+ const expiresAt = now + code.expiresIn * 1000;
105
+ this.typing.set(state, { provider: device, deviceCode: code.deviceCode, interval, next: now + interval, expiresAt });
106
+ return { state, device: { code: code.userCode, uri: code.uri, expiresAt } };
107
+ }
108
+ of({ id, name, avatar }) {
29
109
  return { id, ...(name ? { name } : {}), ...(avatar ? { avatar } : {}) };
30
110
  }
31
111
  };
@@ -60,6 +60,7 @@ const RULES = {
60
60
  TaServer: {
61
61
  getServerInfo: anyone,
62
62
  setWorkingDirectory: fixed('settings.manage'),
63
+ restartServer: owner,
63
64
  openSession: (params, lookup) => {
64
65
  var _a;
65
66
  const options = ((_a = params[0]) !== null && _a !== void 0 ? _a : {});
@@ -233,6 +234,10 @@ const RULES = {
233
234
  answer: fixed('models.manage'),
234
235
  cancel: fixed('models.manage'),
235
236
  logout: fixed('models.manage'),
237
+ listCustomProviders: fixed('models.manage'),
238
+ saveCustomProvider: fixed('models.manage'),
239
+ removeCustomProvider: fixed('models.manage'),
240
+ fetchCustomModels: fixed('models.manage'),
236
241
  },
237
242
  TaAccessServer: {
238
243
  getSignInConfig: owner,
@@ -25,6 +25,7 @@ var WebExtensionUtil;
25
25
  origin: pkg.origin,
26
26
  enabled: (_e = pkg.enabled) !== null && _e !== void 0 ? _e : true,
27
27
  source: pkg.source,
28
+ root: pkg.root,
28
29
  entry,
29
30
  hash: hash((0, node_fs_1.readFileSync)((0, node_path_1.join)(pkg.root, entry), 'utf8')),
30
31
  title: text((_a = manifest === null || manifest === void 0 ? void 0 : manifest.pi) === null || _a === void 0 ? void 0 : _a.title),
@@ -1,6 +1,7 @@
1
1
  import type { IncomingMessage, ServerResponse } from 'node:http';
2
2
  import { type ExecEnvironment, ExecEnvironmentFactory, type FileStat } from '@celljs/ta-exec';
3
3
  import { type Context, Middleware } from '@celljs/web/lib/node';
4
+ import { type ThumbnailBox } from './png-thumbnail';
4
5
  import { WorkspaceFiles } from './workspace-protocol';
5
6
  interface ServedDirectory {
6
7
  root: string;
@@ -24,6 +25,11 @@ export declare namespace WorkspaceFilesUtil {
24
25
  start: number;
25
26
  end: number;
26
27
  } | false | undefined;
28
+ /**
29
+ * The box of `?w=<px>&h=<px>&fit=cover`, which asks for a smaller picture, as the page shows one it has not
30
+ * enlarged (contain without `fit`); undefined for a URL without both sides, or sides out of bounds.
31
+ */
32
+ function thumbnail(url: string | undefined): ThumbnailBox | undefined;
27
33
  function etag(stat: FileStat): string;
28
34
  }
29
35
  /**
@@ -45,9 +51,26 @@ export declare class DefaultWorkspaceFiles implements WorkspaceFiles, Middleware
45
51
  */
46
52
  protected readonly directories: Map<string, ServedDirectory>;
47
53
  protected readonly ids: Map<string, string>;
54
+ /** Smaller pictures made, by file, version and box, the last used last; `null` for one sent as it is. */
55
+ protected readonly thumbnails: Map<string, {
56
+ bytes: Uint8Array;
57
+ type: string;
58
+ } | null>;
59
+ protected thumbnailBytes: number;
60
+ /** Made one at a time: each takes the event loop in turns, and many at once would hold many large pictures. */
61
+ protected making: Promise<unknown>;
48
62
  url(cwd: string, path: string): string;
49
63
  handle(ctx: Context, next: () => Promise<void>): Promise<void>;
50
64
  protected send(request: IncomingMessage, response: ServerResponse, directory: ServedDirectory, path: string): Promise<void>;
65
+ /**
66
+ * A smaller picture of a PNG for `box` (PngThumbnail), with an ETag of its own; false when the picture itself is
67
+ * to be sent (not much larger than the box, or a PNG it does not read).
68
+ */
69
+ protected sendThumbnail(request: IncomingMessage, response: ServerResponse, env: ExecEnvironment, absolute: string, etag: string, box: ThumbnailBox): Promise<boolean>;
70
+ protected keepThumbnail(key: string, made: {
71
+ bytes: Uint8Array;
72
+ type: string;
73
+ } | null): void;
51
74
  /** The file at `path` of `root`, or the `index.html` of the directory there. */
52
75
  protected find(env: ExecEnvironment, root: string, path: string): Promise<{
53
76
  absolute: string;
@@ -17,6 +17,7 @@ const core_1 = require("@celljs/core");
17
17
  const ta_exec_1 = require("@celljs/ta-exec");
18
18
  const ta_protocol_1 = require("@celljs/ta-protocol");
19
19
  const node_1 = require("@celljs/web/lib/node");
20
+ const png_thumbnail_1 = require("./png-thumbnail");
20
21
  const ta_access_1 = require("./ta-access");
21
22
  const workspace_protocol_1 = require("./workspace-protocol");
22
23
  const workspace_util_1 = require("./workspace-util");
@@ -68,6 +69,13 @@ const TYPES = {
68
69
  */
69
70
  const SANDBOX = 'sandbox allow-scripts allow-forms allow-popups allow-modals allow-downloads';
70
71
  const ID_BYTES = 16;
72
+ /** The smallest and largest sides of the box a smaller picture is asked for. */
73
+ const THUMB_MIN = 16;
74
+ const THUMB_MAX = 4096;
75
+ /** Smaller pictures kept, made once for every page that shows them, up to this many bytes. */
76
+ const THUMB_CACHE_BYTES = 32 * 1024 * 1024;
77
+ /** Pictures larger than this are sent as they are, never read whole to make a smaller one. */
78
+ const THUMB_SOURCE_BYTES = 48 * 1024 * 1024;
71
79
  /** Read whole from another machine: a part of a larger file is read with `tail` and `head`. */
72
80
  const REMOTE_WHOLE_BYTES = 8 * 1024 * 1024;
73
81
  var WorkspaceFilesUtil;
@@ -113,6 +121,25 @@ var WorkspaceFilesUtil;
113
121
  return start <= end && start < size ? { start, end } : false;
114
122
  }
115
123
  WorkspaceFilesUtil.range = range;
124
+ /**
125
+ * The box of `?w=<px>&h=<px>&fit=cover`, which asks for a smaller picture, as the page shows one it has not
126
+ * enlarged (contain without `fit`); undefined for a URL without both sides, or sides out of bounds.
127
+ */
128
+ function thumbnail(url) {
129
+ const query = (url !== null && url !== void 0 ? url : '').split('#')[0].split('?')[1];
130
+ if (!query) {
131
+ return undefined;
132
+ }
133
+ const params = new URLSearchParams(query);
134
+ const side = (name) => {
135
+ const value = Number(params.get(name));
136
+ return Number.isInteger(value) && value >= THUMB_MIN && value <= THUMB_MAX ? value : undefined;
137
+ };
138
+ const width = side('w');
139
+ const height = side('h');
140
+ return width && height ? { width, height, fit: params.get('fit') === 'cover' ? 'cover' : 'contain' } : undefined;
141
+ }
142
+ WorkspaceFilesUtil.thumbnail = thumbnail;
116
143
  function etag(stat) {
117
144
  return `"${stat.size.toString(36)}-${Math.floor(stat.mtimeMs).toString(36)}"`;
118
145
  }
@@ -136,6 +163,11 @@ let DefaultWorkspaceFiles = class DefaultWorkspaceFiles {
136
163
  */
137
164
  this.directories = new Map();
138
165
  this.ids = new Map();
166
+ /** Smaller pictures made, by file, version and box, the last used last; `null` for one sent as it is. */
167
+ this.thumbnails = new Map();
168
+ this.thumbnailBytes = 0;
169
+ /** Made one at a time: each takes the event loop in turns, and many at once would hold many large pictures. */
170
+ this.making = Promise.resolve();
139
171
  }
140
172
  url(cwd, path) {
141
173
  const absolute = (0, node_path_1.resolve)(cwd, path || '.');
@@ -196,6 +228,10 @@ let DefaultWorkspaceFiles = class DefaultWorkspaceFiles {
196
228
  response.end();
197
229
  return;
198
230
  }
231
+ const box = type === 'image/png' && !request.headers.range && stat.size <= THUMB_SOURCE_BYTES ? WorkspaceFilesUtil.thumbnail(request.url) : undefined;
232
+ if (box && (await this.sendThumbnail(request, response, env, absolute, etag, box))) {
233
+ return;
234
+ }
199
235
  const range = WorkspaceFilesUtil.range(request.headers.range, stat.size);
200
236
  if (range === false) {
201
237
  response.setHeader('Content-Range', `bytes */${stat.size}`);
@@ -219,6 +255,56 @@ let DefaultWorkspaceFiles = class DefaultWorkspaceFiles {
219
255
  response.end(await this.read(env, absolute, stat.size, start, end));
220
256
  }
221
257
  }
258
+ /**
259
+ * A smaller picture of a PNG for `box` (PngThumbnail), with an ETag of its own; false when the picture itself is
260
+ * to be sent (not much larger than the box, or a PNG it does not read).
261
+ */
262
+ async sendThumbnail(request, response, env, absolute, etag, box) {
263
+ var _a;
264
+ const own = `${etag.slice(0, -1)}-${box.width}x${box.height}${box.fit === 'cover' ? 'c' : ''}"`;
265
+ // Made from this version of the file before: what the page has is still right.
266
+ if (request.headers['if-none-match'] === own) {
267
+ response.setHeader('ETag', own);
268
+ response.removeHeader('Accept-Ranges');
269
+ response.statusCode = 304;
270
+ response.end();
271
+ return true;
272
+ }
273
+ const key = `${absolute}\0${own}`;
274
+ let made = this.thumbnails.get(key);
275
+ if (made === undefined) {
276
+ const making = this.making.then(async () => png_thumbnail_1.PngThumbnail.make(await env.readFile(absolute), box).catch(() => undefined));
277
+ this.making = making.catch(() => undefined);
278
+ made = (_a = (await making.catch(() => undefined))) !== null && _a !== void 0 ? _a : null;
279
+ this.keepThumbnail(key, made);
280
+ }
281
+ else {
282
+ this.thumbnails.delete(key);
283
+ this.thumbnails.set(key, made);
284
+ }
285
+ if (!made) {
286
+ return false;
287
+ }
288
+ response.setHeader('ETag', own);
289
+ response.setHeader('Content-Type', made.type);
290
+ response.removeHeader('Accept-Ranges');
291
+ response.statusCode = 200;
292
+ response.setHeader('Content-Length', made.bytes.length);
293
+ response.end(request.method === 'HEAD' ? undefined : made.bytes);
294
+ return true;
295
+ }
296
+ keepThumbnail(key, made) {
297
+ var _a, _b;
298
+ this.thumbnails.set(key, made);
299
+ this.thumbnailBytes += (_a = made === null || made === void 0 ? void 0 : made.bytes.length) !== null && _a !== void 0 ? _a : 0;
300
+ for (const [old, bytes] of this.thumbnails) {
301
+ if (this.thumbnailBytes <= THUMB_CACHE_BYTES && this.thumbnails.size <= 4096) {
302
+ break;
303
+ }
304
+ this.thumbnails.delete(old);
305
+ this.thumbnailBytes -= (_b = bytes === null || bytes === void 0 ? void 0 : bytes.bytes.length) !== null && _b !== void 0 ? _b : 0;
306
+ }
307
+ }
222
308
  /** The file at `path` of `root`, or the `index.html` of the directory there. */
223
309
  async find(env, root, path) {
224
310
  let absolute;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@celljs/ta-host",
3
- "version": "4.14.0",
3
+ "version": "4.15.1",
4
4
  "description": "ta serve: pi sessions for many clients over WebSocket",
5
5
  "keywords": [
6
6
  "cell-component"
@@ -34,15 +34,15 @@
34
34
  "watch": "tsc -b -w --preserveWatchOutput"
35
35
  },
36
36
  "dependencies": {
37
- "@celljs/ai-agent": "4.14.0",
38
- "@celljs/ai-coding-agent": "4.14.0",
39
- "@celljs/core": "4.14.0",
40
- "@celljs/rpc": "4.14.0",
41
- "@celljs/ta-exec": "4.14.0",
42
- "@celljs/ta-harness": "4.14.0",
43
- "@celljs/ta-protocol": "4.14.0",
44
- "@celljs/ta-relay": "4.14.0",
45
- "@celljs/web": "4.14.0",
37
+ "@celljs/ai-agent": "4.15.1",
38
+ "@celljs/ai-coding-agent": "4.15.1",
39
+ "@celljs/core": "4.15.1",
40
+ "@celljs/rpc": "4.15.1",
41
+ "@celljs/ta-exec": "4.15.1",
42
+ "@celljs/ta-harness": "4.15.1",
43
+ "@celljs/ta-protocol": "4.15.1",
44
+ "@celljs/ta-relay": "4.15.1",
45
+ "@celljs/web": "4.15.1",
46
46
  "@earendil-works/pi-coding-agent": "^1.5.2"
47
47
  },
48
48
  "devDependencies": {