@kosuke-ai/kosuke 1.0.81 → 1.0.83

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 (33) hide show
  1. package/CHANGELOG.md +12 -0
  2. package/dist/generated/commands/crons/create--personal.js +1 -1
  3. package/dist/generated/commands/crons/update--personal.js +1 -1
  4. package/dist/generated/commands/index.js +124 -118
  5. package/dist/generated/commands/projects/batch-merging-members-delete.js +7 -0
  6. package/dist/generated/commands/prototypes/create.js +32 -0
  7. package/dist/generated/commands/providers/default-model-set--personal.js +2 -9
  8. package/dist/generated/commands/providers/get--personal.js +1 -1
  9. package/dist/generated/commands/sensei/reels-activity-list.js +1 -1
  10. package/dist/generated/commands/sensei/reels-later-holds-create.js +43 -0
  11. package/dist/generated/commands/sensei/reels-later-holds-delete.js +29 -0
  12. package/dist/generated/commands/sensei/reels-later-holds-list.js +17 -0
  13. package/dist/generated/commands/sensei/widgets-get.js +1 -1
  14. package/dist/generated/commands/sessions/create.js +0 -14
  15. package/dist/generated/commands/sessions/prompt-update.js +0 -11
  16. package/dist/generated/commands/sessions/send.js +0 -18
  17. package/dist/generated/commands/sessions/update.js +3 -10
  18. package/dist/generated/commands/tasks/create--personal.js +0 -14
  19. package/dist/generated/commands/tasks/create.js +0 -14
  20. package/dist/generated/commands/tasks/update--personal.js +2 -9
  21. package/dist/generated/commands/tasks/update.js +2 -9
  22. package/dist/runtime/arguments.js +2 -0
  23. package/dist/runtime/attach.js +6 -12
  24. package/dist/runtime/option-parsers.js +14 -0
  25. package/dist/runtime/prototype-create.js +47 -0
  26. package/dist/runtime/prototype-styles-scope.js +342 -0
  27. package/dist/runtime/prototype-styles.js +166 -0
  28. package/dist/runtime/prototype-visual-browser.js +87 -0
  29. package/dist/runtime/prototype-visual-check.js +388 -0
  30. package/dist/runtime/prototype-visual-preview.js +159 -0
  31. package/dist/runtime/prototype-visual-scripts.js +174 -0
  32. package/openapi.json +237 -88
  33. package/package.json +5 -6
@@ -0,0 +1,159 @@
1
+ import { existsSync, readFileSync } from 'node:fs';
2
+ import { request as httpRequest } from 'node:http';
3
+ import { request as httpsRequest } from 'node:https';
4
+ import { rootCertificates } from 'node:tls';
5
+ import { execute } from './invoke.js';
6
+ /**
7
+ * Where the real screen of the visual check is: the `--preview-url` flag, else this session
8
+ * sandbox's app preview, else the session's preview as `kosuke preview get` reads it. Inside a
9
+ * sandbox a preview host answers only through the sandbox's own HTTPS proxy, so the browser is
10
+ * launched with a resolver rule and the proxy's CA, and the reachability probe takes that route.
11
+ */
12
+ /** The sandbox's configuration; older images wrote the dotted name. */
13
+ const SANDBOX_CONFIGS = ['/tmp/kosuke.config.json', '/tmp/kosuke-config.json'];
14
+ const PROXY_MAP = '/tmp/kosuke-proxy-map.json';
15
+ const PROXY_CA = '/etc/kosuke/sandbox-proxy-certs/ca.crt';
16
+ const SYSTEM_CAS = ['/etc/ssl/certs/ca-certificates.crt', '/etc/pki/tls/certs/ca-bundle.crt'];
17
+ const PROBE_TIMEOUT_MS = 10_000;
18
+ const isRecord = (value) => typeof value === 'object' && value !== null && !Array.isArray(value);
19
+ function readJson(path) {
20
+ try {
21
+ const value = JSON.parse(readFileSync(path, 'utf8'));
22
+ return isRecord(value) ? value : null;
23
+ }
24
+ catch {
25
+ return null;
26
+ }
27
+ }
28
+ /**
29
+ * The app's web service route in the sandbox: the first service with an endpoint exposed as the
30
+ * preview, else one named `web` or `app`. A service's first endpoint routes by the service's
31
+ * name, a later one by `<service>-<endpoint>`.
32
+ */
33
+ function sandboxRoute(config) {
34
+ const services = isRecord(config.services) ? config.services : {};
35
+ const endpointsOf = (service) => isRecord(service) && Array.isArray(service.endpoints) ? service.endpoints.filter(isRecord) : [];
36
+ for (const [name, service] of Object.entries(services)) {
37
+ const endpoints = endpointsOf(service);
38
+ const index = endpoints.findIndex((endpoint) => endpoint.exposure === 'preview');
39
+ if (index === 0)
40
+ return name;
41
+ if (index > 0)
42
+ return `${name}-${String(endpoints[index].name)}`;
43
+ }
44
+ for (const name of ['web', 'app'])
45
+ if (endpointsOf(services[name]).length)
46
+ return name;
47
+ return null;
48
+ }
49
+ function sandboxProxyPort(config) {
50
+ const fromConfig = isRecord(config?.sandboxProxy) ? config.sandboxProxy.port : undefined;
51
+ const fromMap = readJson(PROXY_MAP)?.port;
52
+ const port = [fromConfig, fromMap].find((value) => typeof value === 'number');
53
+ return port ?? 443;
54
+ }
55
+ /**
56
+ * A preview host this sandbox serves (`local--<route>` or `<this sandbox>--<route>` under the
57
+ * preview domain) goes through the sandbox proxy; anything else is reached directly.
58
+ */
59
+ function previewOf(url, env, config) {
60
+ const origin = new URL(url);
61
+ const domain = env.KOSUKE_PREVIEW_DOMAIN;
62
+ const host = origin.hostname;
63
+ const local = !!domain &&
64
+ origin.protocol === 'https:' &&
65
+ host.endsWith(`.${domain}`) &&
66
+ existsSync(PROXY_CA) &&
67
+ (host.startsWith('local--') ||
68
+ (!!env.KOSUKE_SANDBOX_KEY && host.startsWith(`${env.KOSUKE_SANDBOX_KEY}--`)));
69
+ const base = `${origin.protocol}//${origin.host}${origin.pathname.replace(/\/+$/, '')}`;
70
+ if (!local)
71
+ return { url: base, launch: [], proxyPort: null };
72
+ const port = sandboxProxyPort(config);
73
+ const route = host.slice(0, -domain.length - 1).split('--')[1];
74
+ // One rule per switch: agent-browser splits `--args` on commas.
75
+ return {
76
+ url: base,
77
+ launch: [
78
+ '--ca-cert',
79
+ PROXY_CA,
80
+ '--args',
81
+ `--host-resolver-rules=MAP *--${route}.${domain} 127.0.0.1:${port}`,
82
+ ],
83
+ proxyPort: port,
84
+ };
85
+ }
86
+ /** The preview to compare with, or null when none is known. */
87
+ export async function findPreview(input) {
88
+ const env = input.env ?? process.env;
89
+ const config = SANDBOX_CONFIGS.map(readJson).find(Boolean) ?? null;
90
+ if (input.flag) {
91
+ try {
92
+ return previewOf(input.flag, env, config);
93
+ }
94
+ catch {
95
+ return null;
96
+ }
97
+ }
98
+ const route = config && sandboxRoute(config);
99
+ if (route && env.KOSUKE_PREVIEW_DOMAIN) {
100
+ return previewOf(`https://local--${route}.${env.KOSUKE_PREVIEW_DOMAIN}`, env, config);
101
+ }
102
+ if (!input.projectId)
103
+ return null;
104
+ const outcome = await execute(input.runtime.client(), {
105
+ method: 'get',
106
+ path: '/api/projects/{projectId}/preview',
107
+ pathParams: { projectId: input.projectId },
108
+ query: input.sessionId ? { sessionId: input.sessionId } : {},
109
+ body: null,
110
+ });
111
+ if (!outcome.ok || !isRecord(outcome.body))
112
+ return null;
113
+ const data = isRecord(outcome.body.data) ? outcome.body.data : outcome.body;
114
+ const urls = isRecord(data.frontendUrls) ? data.frontendUrls : {};
115
+ const url = urls.web ?? urls.app ?? Object.values(urls)[0];
116
+ if (typeof url !== 'string' || !url)
117
+ return null;
118
+ try {
119
+ return previewOf(url, env, config);
120
+ }
121
+ catch {
122
+ return null;
123
+ }
124
+ }
125
+ function trustedCas() {
126
+ const cas = [...rootCertificates];
127
+ for (const path of [...SYSTEM_CAS, PROXY_CA]) {
128
+ try {
129
+ cas.push(readFileSync(path, 'utf8'));
130
+ }
131
+ catch {
132
+ // Not on this machine.
133
+ }
134
+ }
135
+ return cas;
136
+ }
137
+ /** Whether the app answers at all within 10 s: any HTTP status counts, a redirect included. */
138
+ export function reachable(preview) {
139
+ const url = new URL(preview.url + '/');
140
+ const secure = url.protocol === 'https:';
141
+ const send = secure ? httpsRequest : httpRequest;
142
+ return new Promise((resolve) => {
143
+ const req = send({
144
+ host: preview.proxyPort ? '127.0.0.1' : url.hostname,
145
+ port: preview.proxyPort ?? (url.port || (secure ? 443 : 80)),
146
+ path: url.pathname,
147
+ method: 'GET',
148
+ headers: { host: url.host },
149
+ ...(secure ? { servername: url.hostname, ca: trustedCas() } : {}),
150
+ timeout: PROBE_TIMEOUT_MS,
151
+ }, (response) => {
152
+ response.resume();
153
+ resolve(true);
154
+ });
155
+ req.on('timeout', () => req.destroy(new Error('timeout')));
156
+ req.on('error', () => resolve(false));
157
+ req.end();
158
+ });
159
+ }
@@ -0,0 +1,174 @@
1
+ /**
2
+ * The scripts the visual check runs in the browser: one shows the baseline state on the
3
+ * prototype's page with nothing of the prototype's controls around the canvas, one compares the
4
+ * two screenshots in canvases and draws the side-by-side picture. The CLI adds no image library.
5
+ */
6
+ /** A colour channel further apart than this marks the pixel as different: anti-aliasing stays under it. */
7
+ const CHANNEL_TOLERANCE = 24;
8
+ const json = (value) => JSON.stringify(value);
9
+ /**
10
+ * Leaves the All states view a page opened on its own lands on, selects the theme through the
11
+ * shell's `#pt-theme` control, shows the state, then strips the prototype's header, footer and
12
+ * phone bar so the canvas is the page: `width` wide from the top left, at least `height` tall.
13
+ */
14
+ export function showStateScript(input) {
15
+ const css = [
16
+ '.pt-header,.pt-foot,.pt-phone,.pt-all-phone,[data-prototype-only]{display:none!important}',
17
+ '.pt-stage{padding:0!important;overflow:visible!important;height:auto!important}',
18
+ '.pt-fit{width:auto!important;height:auto!important;margin:0!important}',
19
+ `.pt-viewport{width:${input.width}px!important;min-height:${input.height}px!important;margin:0!important;border:0!important;border-radius:0!important;box-shadow:none!important;transform:none!important}`,
20
+ `.pt-canvas{min-height:${input.height}px!important}`,
21
+ 'body{margin:0!important}',
22
+ STILL_CSS,
23
+ ].join('\n');
24
+ return `(async () => {
25
+ // Stilled before the theme changes, so no colour is caught halfway through its transition.
26
+ const style = document.createElement('style');
27
+ style.id = 'pt-visual-check-style';
28
+ style.textContent = ${json(css)};
29
+ document.head.append(style);
30
+ const all = window.__kosukeAllStates;
31
+ if (all && all.isOpen()) all.close();
32
+ const theme = document.getElementById('pt-theme');
33
+ if (theme && theme.value !== ${json(input.theme)}) {
34
+ theme.value = ${json(input.theme)};
35
+ theme.dispatchEvent(new Event('change', { bubbles: true }));
36
+ }
37
+ const api = window.__kosukePrototype;
38
+ if (!api) throw new Error('the page has no window.__kosukePrototype');
39
+ const reached = api.showState(${json(input.state)}, ${json(input.variant ?? undefined)}) === true;
40
+ window.scrollTo(0, 0);
41
+ if (document.fonts) await document.fonts.ready;
42
+ await new Promise((done) => requestAnimationFrame(() => requestAnimationFrame(done)));
43
+ const rect = document.getElementById('pt-canvas').getBoundingClientRect();
44
+ const ratio = window.devicePixelRatio || 1;
45
+ return {
46
+ reached,
47
+ current: api.currentState(),
48
+ box: {
49
+ x: Math.round((rect.left + window.scrollX) * ratio),
50
+ y: Math.round((rect.top + window.scrollY) * ratio),
51
+ width: Math.round(rect.width * ratio),
52
+ height: Math.round(rect.height * ratio),
53
+ },
54
+ };
55
+ })()`;
56
+ }
57
+ /**
58
+ * Compares the real screen with the prototype's canvas, cropped to the common width and height
59
+ * (at most `maxHeight`), and draws real screen | prototype | difference under a label row, the
60
+ * differing pixels red over a faded copy of the real screen.
61
+ */
62
+ export function compareScript(input) {
63
+ return `(async () => {
64
+ const load = (src) => new Promise((done, fail) => {
65
+ const image = new Image();
66
+ image.onload = () => done(image);
67
+ image.onerror = () => fail(new Error('a screenshot did not load'));
68
+ image.src = src;
69
+ });
70
+ const [real, proto] = await Promise.all([load(${json(input.real)}), load(${json(input.prototype)})]);
71
+ const box = ${json(input.box)};
72
+ const width = Math.min(real.naturalWidth, box.width, proto.naturalWidth - box.x);
73
+ const height = Math.min(real.naturalHeight, box.height, proto.naturalHeight - box.y, ${input.maxHeight});
74
+ if (width < 1 || height < 1) throw new Error('a screenshot is empty');
75
+ const pixels = (image, x, y) => {
76
+ const canvas = document.createElement('canvas');
77
+ canvas.width = width;
78
+ canvas.height = height;
79
+ const context = canvas.getContext('2d');
80
+ context.drawImage(image, x, y, width, height, 0, 0, width, height);
81
+ return context.getImageData(0, 0, width, height);
82
+ };
83
+ const a = pixels(real, 0, 0);
84
+ const b = pixels(proto, box.x, box.y);
85
+ const diff = new ImageData(width, height);
86
+ let differing = 0;
87
+ for (let i = 0; i < a.data.length; i += 4) {
88
+ const apart = Math.abs(a.data[i] - b.data[i]) > ${CHANNEL_TOLERANCE} ||
89
+ Math.abs(a.data[i + 1] - b.data[i + 1]) > ${CHANNEL_TOLERANCE} ||
90
+ Math.abs(a.data[i + 2] - b.data[i + 2]) > ${CHANNEL_TOLERANCE};
91
+ if (apart) {
92
+ differing++;
93
+ diff.data[i] = 230; diff.data[i + 1] = 0; diff.data[i + 2] = 0;
94
+ } else {
95
+ const grey = (a.data[i] * 0.3 + a.data[i + 1] * 0.59 + a.data[i + 2] * 0.11);
96
+ const faded = Math.round(255 - (255 - grey) * 0.25);
97
+ diff.data[i] = faded; diff.data[i + 1] = faded; diff.data[i + 2] = faded;
98
+ }
99
+ diff.data[i + 3] = 255;
100
+ }
101
+ const diffPercent = Math.round((differing / (width * height)) * 10000) / 100;
102
+ const gap = 16, label = 36;
103
+ const out = document.createElement('canvas');
104
+ out.width = width * 3 + gap * 4;
105
+ out.height = height + label + gap;
106
+ const context = out.getContext('2d');
107
+ context.fillStyle = '#ffffff';
108
+ context.fillRect(0, 0, out.width, out.height);
109
+ context.putImageData(a, gap, label);
110
+ context.putImageData(b, gap * 2 + width, label);
111
+ context.putImageData(diff, gap * 3 + width * 2, label);
112
+ context.fillStyle = '#1d1d1f';
113
+ context.font = '600 14px ui-sans-serif, system-ui, -apple-system, "Segoe UI", sans-serif';
114
+ context.textBaseline = 'middle';
115
+ const labels = ${json(input.labels)};
116
+ labels[2] = labels[2] + ': ' + diffPercent + '%';
117
+ labels.forEach((text, index) => {
118
+ const x = gap + index * (width + gap);
119
+ context.save();
120
+ context.beginPath();
121
+ context.rect(x, 0, width, label);
122
+ context.clip();
123
+ context.fillText(text, x, label / 2);
124
+ context.restore();
125
+ });
126
+ return { diffPercent, png: out.toDataURL('image/png') };
127
+ })()`;
128
+ }
129
+ /**
130
+ * Waits in the page until it has loaded and no resource has finished for 750 ms, at most
131
+ * `mostMs`: an app with a socket or polling never goes network-idle, and a wait the browser
132
+ * holds would outlive a client that gives up on it. Answers the page's address.
133
+ */
134
+ /** Turns off transitions, animations and the caret, so a screenshot shows settled colours. */
135
+ const STILL_CSS = '*,*::before,*::after{transition:none!important;animation:none!important;caret-color:transparent!important}';
136
+ /**
137
+ * Puts the real screen in a theme the way the app keeps one: the stored choice next-themes and
138
+ * its like read (`theme` in localStorage), the `dark` class Tailwind's dark variant reads, and
139
+ * the colour scheme; then stills it and waits two frames. A fresh browser has no stored choice,
140
+ * so an app whose default theme is dark would otherwise stay dark under a light media query.
141
+ */
142
+ export function realThemeScript(scheme) {
143
+ return `(async () => {
144
+ const scheme = ${json(scheme)};
145
+ try { localStorage.setItem('theme', scheme); } catch (error) {}
146
+ const root = document.documentElement;
147
+ root.classList.toggle('dark', scheme === 'dark');
148
+ root.classList.toggle('light', scheme === 'light');
149
+ root.style.colorScheme = scheme;
150
+ const style = document.createElement('style');
151
+ style.textContent = ${json(STILL_CSS)};
152
+ document.head.append(style);
153
+ if (document.fonts) await document.fonts.ready;
154
+ await new Promise((done) => requestAnimationFrame(() => requestAnimationFrame(done)));
155
+ await new Promise((done) => setTimeout(done, 300));
156
+ return root.classList.contains('dark') ? 'dark' : 'light';
157
+ })()`;
158
+ }
159
+ export function settleScript(mostMs) {
160
+ return `new Promise((done) => {
161
+ const start = Date.now();
162
+ let seen = -1;
163
+ let quiet = 0;
164
+ const tick = () => {
165
+ const count = performance.getEntriesByType('resource').length;
166
+ if (document.readyState === 'complete' && count === seen) quiet += 250;
167
+ else quiet = 0;
168
+ seen = count;
169
+ if (quiet >= 750 || Date.now() - start > ${mostMs}) done(location.href);
170
+ else setTimeout(tick, 250);
171
+ };
172
+ tick();
173
+ })`;
174
+ }