askimo 0.0.2

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.
@@ -0,0 +1,12 @@
1
+ <?xml version="1.0" encoding="UTF-8"?>
2
+ <module type="WEB_MODULE" version="4">
3
+ <component name="NewModuleRootManager">
4
+ <content url="file://$MODULE_DIR$">
5
+ <excludeFolder url="file://$MODULE_DIR$/.tmp" />
6
+ <excludeFolder url="file://$MODULE_DIR$/temp" />
7
+ <excludeFolder url="file://$MODULE_DIR$/tmp" />
8
+ </content>
9
+ <orderEntry type="inheritedJdk" />
10
+ <orderEntry type="sourceFolder" forTests="false" />
11
+ </component>
12
+ </module>
@@ -0,0 +1,9 @@
1
+ <?xml version="1.0" encoding="UTF-8"?>
2
+ <project version="4">
3
+ <component name="BiomeSettings">
4
+ <option name="applySafeFixesOnSave" value="true" />
5
+ <option name="enableLspFormat" value="true" />
6
+ <option name="formatOnSave" value="true" />
7
+ <option name="sortImportOnSave" value="true" />
8
+ </component>
9
+ </project>
@@ -0,0 +1,6 @@
1
+ <?xml version="1.0" encoding="UTF-8"?>
2
+ <project version="4">
3
+ <component name="AgentMigrationStateService">
4
+ <option name="migrationStatus" value="COMPLETED" />
5
+ </component>
6
+ </project>
@@ -0,0 +1,6 @@
1
+ <?xml version="1.0" encoding="UTF-8"?>
2
+ <project version="4">
3
+ <component name="AskMigrationStateService">
4
+ <option name="migrationStatus" value="COMPLETED" />
5
+ </component>
6
+ </project>
@@ -0,0 +1,6 @@
1
+ <?xml version="1.0" encoding="UTF-8"?>
2
+ <project version="4">
3
+ <component name="Ask2AgentMigrationStateService">
4
+ <option name="migrationStatus" value="COMPLETED" />
5
+ </component>
6
+ </project>
@@ -0,0 +1,6 @@
1
+ <?xml version="1.0" encoding="UTF-8"?>
2
+ <project version="4">
3
+ <component name="EditMigrationStateService">
4
+ <option name="migrationStatus" value="COMPLETED" />
5
+ </component>
6
+ </project>
@@ -0,0 +1,6 @@
1
+ <?xml version="1.0" encoding="UTF-8"?>
2
+ <project version="4">
3
+ <component name="JavaScriptLibraryMappings">
4
+ <includedPredefinedLibrary name="Node.js Core" />
5
+ </component>
6
+ </project>
@@ -0,0 +1,8 @@
1
+ <?xml version="1.0" encoding="UTF-8"?>
2
+ <project version="4">
3
+ <component name="ProjectModuleManager">
4
+ <modules>
5
+ <module fileurl="file://$PROJECT_DIR$/.idea/askimo.iml" filepath="$PROJECT_DIR$/.idea/askimo.iml" />
6
+ </modules>
7
+ </component>
8
+ </project>
package/.idea/vcs.xml ADDED
@@ -0,0 +1,6 @@
1
+ <?xml version="1.0" encoding="UTF-8"?>
2
+ <project version="4">
3
+ <component name="VcsDirectoryMappings">
4
+ <mapping directory="$PROJECT_DIR$" vcs="Git" />
5
+ </component>
6
+ </project>
@@ -0,0 +1,55 @@
1
+ {
2
+ "biome.enabled": true,
3
+ "[javascript]": {
4
+ "editor.defaultFormatter": "biomejs.biome",
5
+ "editor.formatOnSave": true,
6
+ "editor.codeActionsOnSave": {
7
+ "source.organizeImports.biome": "explicit",
8
+ "source.fixAll.biome": "explicit"
9
+ }
10
+ },
11
+ "[json]": {
12
+ "editor.defaultFormatter": "biomejs.biome",
13
+ "editor.formatOnSave": true
14
+ },
15
+ "[jsonc]": {
16
+ "editor.defaultFormatter": "biomejs.biome",
17
+ "editor.formatOnSave": true
18
+ },
19
+ "[javascriptreact]": {
20
+ "editor.defaultFormatter": "biomejs.biome",
21
+ "editor.formatOnSave": true,
22
+ "editor.codeActionsOnSave": {
23
+ "source.organizeImports.biome": "explicit",
24
+ "source.fixAll.biome": "explicit"
25
+ }
26
+ },
27
+ "[typescript]": {
28
+ "editor.defaultFormatter": "biomejs.biome",
29
+ "editor.formatOnSave": true,
30
+ "editor.codeActionsOnSave": {
31
+ "source.organizeImports.biome": "explicit",
32
+ "source.fixAll.biome": "explicit"
33
+ }
34
+ },
35
+ "[typescriptreact]": {
36
+ "editor.defaultFormatter": "biomejs.biome",
37
+ "editor.formatOnSave": true,
38
+ "editor.codeActionsOnSave": {
39
+ "source.organizeImports.biome": "explicit",
40
+ "source.fixAll.biome": "explicit"
41
+ }
42
+ },
43
+ "[css]": {
44
+ "editor.defaultFormatter": "biomejs.biome",
45
+ "editor.formatOnSave": true
46
+ },
47
+ "[graphql]": {
48
+ "editor.defaultFormatter": "biomejs.biome",
49
+ "editor.formatOnSave": true
50
+ },
51
+ "[svelte]": {
52
+ "editor.defaultFormatter": "biomejs.biome",
53
+ "editor.formatOnSave": true
54
+ }
55
+ }
package/LICENSE.md ADDED
@@ -0,0 +1,53 @@
1
+ Apache License
2
+
3
+ Version 2.0, January 2004
4
+
5
+ <http://www.apache.org/licenses/>
6
+
7
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
8
+
9
+ 1. Definitions.
10
+
11
+ "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity.
16
+
17
+ "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License.
18
+
19
+ "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files.
20
+
21
+ "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types.
22
+
23
+ "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below).
24
+
25
+ "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof.
26
+
27
+ "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution."
28
+
29
+ "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work.
30
+
31
+ 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form.
32
+
33
+ 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed.
34
+
35
+ 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions:
36
+
37
+ You must give any other recipients of the Work or Derivative Works a copy of this License; and
38
+ You must cause any modified files to carry prominent notices stating that You changed the files; and
39
+ You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and
40
+ If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License.
41
+
42
+ You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License.
43
+ 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions.
44
+
45
+ 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file.
46
+
47
+ 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License.
48
+
49
+ 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages.
50
+
51
+ 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability.
52
+
53
+ END OF TERMS AND CONDITIONS
package/README.md ADDED
@@ -0,0 +1,102 @@
1
+ # Askimo
2
+
3
+ A CLI tool for communicating with AI providers (Perplexity, OpenAI, Anthropic).
4
+
5
+ ## Installation
6
+
7
+ ```bash
8
+ npm install -g .
9
+ ```
10
+
11
+ ## Configuration
12
+
13
+ Create a config file at `~/.askimo/config`:
14
+
15
+ ```
16
+ # API Keys (at least one required)
17
+ PERPLEXITY_API_KEY=your-perplexity-key
18
+ OPENAI_API_KEY=your-openai-key
19
+ ANTHROPIC_API_KEY=your-anthropic-key
20
+
21
+ # Optional settings
22
+ DEFAULT_PROVIDER=perplexity
23
+ PERPLEXITY_MODEL=sonar
24
+ OPENAI_MODEL=gpt-4o
25
+ ANTHROPIC_MODEL=claude-sonnet-4-20250514
26
+ ```
27
+
28
+ ## Usage
29
+
30
+ ### Ask a single question
31
+
32
+ ```bash
33
+ askimo "What is the capital of France?"
34
+ ```
35
+
36
+ The `ask` command is the default, so you can omit it:
37
+
38
+ ```bash
39
+ askimo ask "What is the capital of France?"
40
+ ```
41
+
42
+ ### Provider flags
43
+
44
+ ```bash
45
+ askimo "question" -p # Use Perplexity (default)
46
+ askimo "question" -o # Use OpenAI
47
+ askimo "question" -a # Use Anthropic
48
+ ```
49
+
50
+ ### Continue a conversation
51
+
52
+ ```bash
53
+ askimo "follow up question" -c 1 # Continue last conversation
54
+ askimo "follow up question" -c 2 # Continue second-to-last
55
+ ```
56
+
57
+ ### JSON output
58
+
59
+ ```bash
60
+ askimo "question" --json
61
+ ```
62
+
63
+ Returns structured JSON with provider, model, question, response, and sources (for Perplexity).
64
+
65
+ ### Interactive chat
66
+
67
+ ```bash
68
+ askimo chat
69
+ askimo chat -o # Chat with OpenAI
70
+ askimo chat -c 1 # Continue last conversation
71
+ ```
72
+
73
+ Type `exit` or press `Ctrl+C` to quit.
74
+
75
+ ### List available models
76
+
77
+ ```bash
78
+ askimo models # List all providers
79
+ askimo models -p # Perplexity only
80
+ askimo models -o # OpenAI only
81
+ askimo models -a # Anthropic only
82
+ ```
83
+
84
+ ## Features
85
+
86
+ - Streaming responses
87
+ - Conversation history (saved to `~/.askimo/conversations/`)
88
+ - Source citations (Perplexity)
89
+ - Multiple AI providers
90
+ - Configurable default models
91
+
92
+ ## Development
93
+
94
+ ```bash
95
+ npm install
96
+ npm test
97
+ npm run lint
98
+ ```
99
+
100
+ ## License
101
+
102
+ Apache-2.0
package/biome.json ADDED
@@ -0,0 +1,65 @@
1
+ {
2
+ "$schema": "./node_modules/@biomejs/biome/configuration_schema.json",
3
+ "files": {
4
+ "includes": ["**", "!node_modules", "!.next", "!dist", "!build"],
5
+ "ignoreUnknown": true
6
+ },
7
+ "linter": {
8
+ "rules": {
9
+ "complexity": {
10
+ "useOptionalChain": "off",
11
+ "noExcessiveCognitiveComplexity": {
12
+ "level": "info",
13
+ "options": { "maxAllowedComplexity": 50 }
14
+ }
15
+ },
16
+ "suspicious": {
17
+ "noConsole": "off"
18
+ },
19
+ "style": {
20
+ "useBlockStatements": "off",
21
+ "noCommonJs": "error",
22
+ "useNamingConvention": "warn",
23
+ "useFilenamingConvention": {
24
+ "level": "warn",
25
+ "options": {
26
+ "strictCase": false,
27
+ "requireAscii": true,
28
+ "filenameCases": ["camelCase", "PascalCase"]
29
+ }
30
+ },
31
+ "noParameterAssign": "warn",
32
+ "noDefaultExport": "warn",
33
+ "useAsConstAssertion": "error",
34
+ "useDefaultParameterLast": "error",
35
+ "useEnumInitializers": "error",
36
+ "useSelfClosingElements": "error",
37
+ "useSingleVarDeclarator": "error",
38
+ "noUnusedTemplateLiteral": "error",
39
+ "useNumberNamespace": "error",
40
+ "noInferrableTypes": "error",
41
+ "noUselessElse": "error"
42
+ },
43
+ "correctness": {
44
+ "noNodejsModules": "off",
45
+ "useImportExtensions": "error",
46
+ "noUndeclaredVariables": "error"
47
+ }
48
+ },
49
+ "domains": {
50
+ "test": "recommended"
51
+ }
52
+ },
53
+ "formatter": {
54
+ "formatWithErrors": true,
55
+ "lineWidth": 120,
56
+ "indentStyle": "space"
57
+ },
58
+ "javascript": {
59
+ "formatter": {
60
+ "semicolons": "asNeeded",
61
+ "quoteStyle": "single",
62
+ "trailingCommas": "none"
63
+ }
64
+ }
65
+ }
package/index.mjs ADDED
@@ -0,0 +1,144 @@
1
+ #!/usr/bin/env node
2
+
3
+ import { Command } from 'commander'
4
+ import { startChat } from './lib/chat.mjs'
5
+ import { ensureDirectories, loadConfig } from './lib/config.mjs'
6
+ import { createConversation, loadConversation, saveConversation } from './lib/conversation.mjs'
7
+ import { DEFAULT_MODELS, determineProvider, getProvider, listModels } from './lib/providers.mjs'
8
+ import { generateResponse, outputJson, streamResponse } from './lib/stream.mjs'
9
+ import pkg from './package.json' with { type: 'json' }
10
+
11
+ const program = new Command()
12
+
13
+ program.name('askimo').description('CLI tool for communicating with AI providers').version(pkg.version)
14
+
15
+ program
16
+ .command('ask', { isDefault: true })
17
+ .description('Ask a single question')
18
+ .argument('<question>', 'The question to ask')
19
+ .option('-p, --perplexity', 'Use Perplexity AI (default)')
20
+ .option('-o, --openai', 'Use OpenAI')
21
+ .option('-a, --anthropic', 'Use Anthropic Claude')
22
+ .option('-j, --json', 'Output as JSON instead of streaming')
23
+ .option('-c, --continue <n>', 'Continue conversation N (1=last, 2=second-to-last)', Number.parseInt)
24
+ .action(async (question, options) => {
25
+ try {
26
+ const config = await loadConfig()
27
+ await ensureDirectories()
28
+
29
+ const providerName = determineProvider(options, config)
30
+ const { model, name, modelName } = getProvider(providerName, config)
31
+
32
+ let conversation
33
+ let existingPath = null
34
+
35
+ if (options.continue) {
36
+ const loaded = await loadConversation(options.continue)
37
+ conversation = loaded.conversation
38
+ existingPath = loaded.filePath
39
+
40
+ if (conversation.provider !== name) {
41
+ console.error(`Warning: Continuing ${conversation.provider} conversation with ${name}`)
42
+ }
43
+ } else {
44
+ conversation = createConversation(name, modelName)
45
+ }
46
+
47
+ conversation.messages.push({
48
+ role: 'user',
49
+ content: question
50
+ })
51
+
52
+ let responseText
53
+
54
+ if (options.json) {
55
+ const { text, sources } = await generateResponse(model, conversation.messages)
56
+ responseText = text
57
+ conversation.messages.push({
58
+ role: 'assistant',
59
+ content: responseText
60
+ })
61
+ await saveConversation(conversation, existingPath)
62
+ outputJson(conversation, responseText, sources)
63
+ } else {
64
+ responseText = await streamResponse(model, conversation.messages)
65
+ conversation.messages.push({
66
+ role: 'assistant',
67
+ content: responseText
68
+ })
69
+ await saveConversation(conversation, existingPath)
70
+ }
71
+ } catch (err) {
72
+ console.error('Error:', err.message)
73
+ process.exit(1)
74
+ }
75
+ })
76
+
77
+ program
78
+ .command('chat')
79
+ .description('Start an interactive chat session')
80
+ .option('-p, --perplexity', 'Use Perplexity AI (default)')
81
+ .option('-o, --openai', 'Use OpenAI')
82
+ .option('-a, --anthropic', 'Use Anthropic Claude')
83
+ .option('-c, --continue <n>', 'Continue conversation N (1=last, 2=second-to-last)', Number.parseInt)
84
+ .action(async (options) => {
85
+ try {
86
+ const config = await loadConfig()
87
+ await ensureDirectories()
88
+
89
+ const providerName = determineProvider(options, config)
90
+ const { model, name, modelName } = getProvider(providerName, config)
91
+
92
+ await startChat(model, name, modelName, options.continue)
93
+ } catch (err) {
94
+ console.error('Error:', err.message)
95
+ process.exit(1)
96
+ }
97
+ })
98
+
99
+ program
100
+ .command('models')
101
+ .description('List available models for each provider')
102
+ .option('-p, --perplexity', 'Show only Perplexity models')
103
+ .option('-o, --openai', 'Show only OpenAI models')
104
+ .option('-a, --anthropic', 'Show only Anthropic models')
105
+ .action(async (options) => {
106
+ try {
107
+ const config = await loadConfig()
108
+
109
+ const providers = []
110
+ if (options.perplexity) providers.push('perplexity')
111
+ if (options.openai) providers.push('openai')
112
+ if (options.anthropic) providers.push('anthropic')
113
+
114
+ const toShow = providers.length === 0 ? ['perplexity', 'openai', 'anthropic'] : providers
115
+
116
+ const results = await Promise.all(
117
+ toShow.map(async (provider) => ({
118
+ provider,
119
+ models: await listModels(provider, config)
120
+ }))
121
+ )
122
+
123
+ for (const { provider, models } of results) {
124
+ const defaultModel = DEFAULT_MODELS[provider]
125
+ console.log(`\n${provider.toUpperCase()}`)
126
+ console.log('─'.repeat(40))
127
+
128
+ for (const model of models) {
129
+ const isDefault = model.id === defaultModel ? ' (default)' : ''
130
+ const description = model.description || model.displayName || ''
131
+ console.log(` ${model.id}${isDefault}`)
132
+ if (description) {
133
+ console.log(` ${description}`)
134
+ }
135
+ }
136
+ }
137
+ console.log('')
138
+ } catch (err) {
139
+ console.error('Error:', err.message)
140
+ process.exit(1)
141
+ }
142
+ })
143
+
144
+ program.parse()
package/lib/chat.mjs ADDED
@@ -0,0 +1,64 @@
1
+ import input from '@inquirer/input'
2
+ import { createConversation, loadConversation, saveConversation } from './conversation.mjs'
3
+ import { streamResponse } from './stream.mjs'
4
+
5
+ async function startChat(model, providerName, modelName, continueN = null) {
6
+ let conversation
7
+ let existingPath = null
8
+
9
+ if (continueN) {
10
+ const loaded = await loadConversation(continueN)
11
+ conversation = loaded.conversation
12
+ existingPath = loaded.filePath
13
+
14
+ if (conversation.provider !== providerName) {
15
+ console.error(`Warning: Continuing ${conversation.provider} conversation with ${providerName}`)
16
+ }
17
+
18
+ console.log(`Continuing conversation ${conversation.id} (${conversation.messages.length} messages)`)
19
+ } else {
20
+ conversation = createConversation(providerName, modelName)
21
+ console.log(`Starting new chat with ${providerName} (${modelName})`)
22
+ }
23
+
24
+ console.log('Type "exit" or press Ctrl+C to quit\n')
25
+
26
+ while (true) {
27
+ let question
28
+ try {
29
+ question = await input({ message: 'You:' })
30
+ } catch {
31
+ // User pressed Ctrl+C
32
+ break
33
+ }
34
+
35
+ const trimmed = question.trim()
36
+ if (!trimmed) continue
37
+ if (trimmed.toLowerCase() === 'exit') break
38
+
39
+ conversation.messages.push({
40
+ role: 'user',
41
+ content: trimmed
42
+ })
43
+
44
+ console.log('')
45
+ const responseText = await streamResponse(model, conversation.messages)
46
+
47
+ conversation.messages.push({
48
+ role: 'assistant',
49
+ content: responseText
50
+ })
51
+
52
+ await saveConversation(conversation, existingPath)
53
+ if (!existingPath) {
54
+ const timestamp = conversation.createdAt.replace(/:/g, '-')
55
+ const { join } = await import('node:path')
56
+ const { CONVERSATIONS_DIR } = await import('./config.mjs')
57
+ existingPath = join(CONVERSATIONS_DIR, `${timestamp}-${conversation.id}.json`)
58
+ }
59
+ }
60
+
61
+ console.log('\nChat ended. Conversation saved.')
62
+ }
63
+
64
+ export { startChat }
package/lib/config.mjs ADDED
@@ -0,0 +1,54 @@
1
+ import { mkdir, readFile } from 'node:fs/promises'
2
+ import { homedir } from 'node:os'
3
+ import { join } from 'node:path'
4
+
5
+ const ASKIMO_DIR = join(homedir(), '.askimo')
6
+ const CONFIG_FILE = join(ASKIMO_DIR, 'config')
7
+ const CONVERSATIONS_DIR = join(ASKIMO_DIR, 'conversations')
8
+
9
+ function parseConfig(content) {
10
+ const config = {}
11
+
12
+ for (const line of content.split('\n')) {
13
+ const trimmed = line.trim()
14
+ if (!trimmed || trimmed.startsWith('#')) continue
15
+
16
+ const eqIndex = trimmed.indexOf('=')
17
+ if (eqIndex === -1) continue
18
+
19
+ const key = trimmed.slice(0, eqIndex).trim()
20
+ config[key] = trimmed.slice(eqIndex + 1).trim()
21
+ }
22
+
23
+ return config
24
+ }
25
+
26
+ async function loadConfig() {
27
+ try {
28
+ const content = await readFile(CONFIG_FILE, 'utf8')
29
+ return parseConfig(content)
30
+ } catch (err) {
31
+ if (err.code !== 'ENOENT') {
32
+ throw err
33
+ }
34
+ console.error(`Config file not found: ${CONFIG_FILE}`)
35
+ console.error('Create the file with your API keys:')
36
+ console.error(' PERPLEXITY_API_KEY=your-key')
37
+ console.error(' OPENAI_API_KEY=your-key')
38
+ console.error(' ANTHROPIC_API_KEY=your-key')
39
+ console.error('')
40
+ console.error('Optional settings:')
41
+ console.error(' DEFAULT_PROVIDER=perplexity # perplexity, openai, or anthropic')
42
+ console.error(' PERPLEXITY_MODEL=sonar # default model for Perplexity')
43
+ console.error(' OPENAI_MODEL=gpt-4o # default model for OpenAI')
44
+ console.error(' ANTHROPIC_MODEL=claude-sonnet-4-20250514 # default model for Anthropic')
45
+ process.exit(1)
46
+ }
47
+ }
48
+
49
+ async function ensureDirectories() {
50
+ await mkdir(ASKIMO_DIR, { recursive: true })
51
+ await mkdir(CONVERSATIONS_DIR, { recursive: true })
52
+ }
53
+
54
+ export { loadConfig, ensureDirectories, parseConfig, ASKIMO_DIR, CONVERSATIONS_DIR }
@@ -0,0 +1,71 @@
1
+ import { randomUUID } from 'node:crypto'
2
+ import { readdir, readFile, writeFile } from 'node:fs/promises'
3
+ import { join } from 'node:path'
4
+ import { CONVERSATIONS_DIR, ensureDirectories } from './config.mjs'
5
+
6
+ function createConversation(provider, model) {
7
+ const id = randomUUID().slice(0, 8)
8
+ const now = new Date().toISOString()
9
+ return {
10
+ id,
11
+ createdAt: now,
12
+ updatedAt: now,
13
+ provider,
14
+ model,
15
+ messages: []
16
+ }
17
+ }
18
+
19
+ async function loadConversation(n) {
20
+ await ensureDirectories()
21
+
22
+ try {
23
+ const files = await readdir(CONVERSATIONS_DIR)
24
+ const jsonFiles = files
25
+ .filter((f) => f.endsWith('.json'))
26
+ .sort()
27
+ .reverse()
28
+
29
+ if (jsonFiles.length === 0) {
30
+ console.error('No previous conversations found')
31
+ process.exit(1)
32
+ }
33
+
34
+ const index = n - 1
35
+ if (index >= jsonFiles.length) {
36
+ console.error(`Only ${jsonFiles.length} conversation(s) available`)
37
+ process.exit(1)
38
+ }
39
+
40
+ const filePath = join(CONVERSATIONS_DIR, jsonFiles[index])
41
+ const content = await readFile(filePath, 'utf8')
42
+ return {
43
+ conversation: JSON.parse(content),
44
+ filePath
45
+ }
46
+ } catch (err) {
47
+ if (err.code !== 'ENOENT') {
48
+ throw err
49
+ }
50
+ console.error('No conversations directory found')
51
+ process.exit(1)
52
+ }
53
+ }
54
+
55
+ async function saveConversation(conversation, existingPath = null) {
56
+ await ensureDirectories()
57
+
58
+ conversation.updatedAt = new Date().toISOString()
59
+
60
+ let filePath = existingPath
61
+ if (!filePath) {
62
+ const timestamp = conversation.createdAt.replace(/:/g, '-')
63
+ const filename = `${timestamp}-${conversation.id}.json`
64
+ filePath = join(CONVERSATIONS_DIR, filename)
65
+ }
66
+
67
+ await writeFile(filePath, JSON.stringify(conversation, null, 2))
68
+ return filePath
69
+ }
70
+
71
+ export { createConversation, loadConversation, saveConversation }
@@ -0,0 +1,138 @@
1
+ import { createAnthropic } from '@ai-sdk/anthropic'
2
+ import { createOpenAI } from '@ai-sdk/openai'
3
+ import { createPerplexity } from '@ai-sdk/perplexity'
4
+
5
+ const DEFAULT_MODELS = {
6
+ perplexity: 'sonar',
7
+ openai: 'gpt-4o',
8
+ anthropic: 'claude-sonnet-4-20250514'
9
+ }
10
+
11
+ // Perplexity doesn't have a models list API, so we hardcode these
12
+ const PERPLEXITY_MODELS = [
13
+ { id: 'sonar', description: 'Lightweight, cost-effective search model' },
14
+ { id: 'sonar-pro', description: 'Advanced search for complex queries' },
15
+ { id: 'sonar-reasoning', description: 'Chain-of-thought problem solving' },
16
+ { id: 'sonar-reasoning-pro', description: 'Advanced reasoning (DeepSeek-R1)' },
17
+ { id: 'sonar-deep-research', description: 'Deep research sessions' }
18
+ ]
19
+
20
+ async function fetchOpenAiModels(apiKey) {
21
+ const response = await fetch('https://api.openai.com/v1/models', {
22
+ // biome-ignore lint/style/useNamingConvention: headers use standard capitalization
23
+ headers: { Authorization: `Bearer ${apiKey}` }
24
+ })
25
+
26
+ if (!response.ok) {
27
+ throw new Error(`OpenAI API error: ${response.status}`)
28
+ }
29
+
30
+ const data = await response.json()
31
+ return data.data.map((m) => ({ id: m.id, created: m.created })).sort((a, b) => b.created - a.created)
32
+ }
33
+
34
+ async function fetchAnthropicModels(apiKey) {
35
+ const response = await fetch('https://api.anthropic.com/v1/models', {
36
+ headers: {
37
+ 'x-api-key': apiKey,
38
+ 'anthropic-version': '2023-06-01'
39
+ }
40
+ })
41
+
42
+ if (!response.ok) {
43
+ throw new Error(`Anthropic API error: ${response.status}`)
44
+ }
45
+
46
+ const data = await response.json()
47
+ return data.data.map((m) => ({
48
+ id: m.id,
49
+ displayName: m.display_name
50
+ }))
51
+ }
52
+
53
+ async function listModels(provider, config) {
54
+ switch (provider) {
55
+ case 'perplexity':
56
+ return PERPLEXITY_MODELS
57
+
58
+ case 'openai': {
59
+ const apiKey = config.OPENAI_API_KEY
60
+ if (!apiKey) {
61
+ throw new Error('OPENAI_API_KEY not found in config')
62
+ }
63
+ return fetchOpenAiModels(apiKey)
64
+ }
65
+
66
+ case 'anthropic': {
67
+ const apiKey = config.ANTHROPIC_API_KEY
68
+ if (!apiKey) {
69
+ throw new Error('ANTHROPIC_API_KEY not found in config')
70
+ }
71
+ return fetchAnthropicModels(apiKey)
72
+ }
73
+
74
+ default:
75
+ throw new Error(`Unknown provider: ${provider}`)
76
+ }
77
+ }
78
+
79
+ function getProvider(providerName, config) {
80
+ switch (providerName) {
81
+ case 'perplexity': {
82
+ const apiKey = config.PERPLEXITY_API_KEY
83
+ if (!apiKey) {
84
+ throw new Error('PERPLEXITY_API_KEY not found in config')
85
+ }
86
+ const modelName = config.PERPLEXITY_MODEL || DEFAULT_MODELS.perplexity
87
+ const perplexity = createPerplexity({ apiKey })
88
+ return {
89
+ model: perplexity(modelName),
90
+ name: 'perplexity',
91
+ modelName
92
+ }
93
+ }
94
+ case 'openai': {
95
+ const apiKey = config.OPENAI_API_KEY
96
+ if (!apiKey) {
97
+ throw new Error('OPENAI_API_KEY not found in config')
98
+ }
99
+ const modelName = config.OPENAI_MODEL || DEFAULT_MODELS.openai
100
+ const openai = createOpenAI({ apiKey })
101
+ return {
102
+ model: openai(modelName),
103
+ name: 'openai',
104
+ modelName
105
+ }
106
+ }
107
+ case 'anthropic': {
108
+ const apiKey = config.ANTHROPIC_API_KEY
109
+ if (!apiKey) {
110
+ throw new Error('ANTHROPIC_API_KEY not found in config')
111
+ }
112
+ const modelName = config.ANTHROPIC_MODEL || DEFAULT_MODELS.anthropic
113
+ const anthropic = createAnthropic({ apiKey })
114
+ return {
115
+ model: anthropic(modelName),
116
+ name: 'anthropic',
117
+ modelName
118
+ }
119
+ }
120
+ default:
121
+ throw new Error(`Unknown provider: ${providerName}`)
122
+ }
123
+ }
124
+
125
+ function determineProvider(options, config = {}) {
126
+ if (options.openai) return 'openai'
127
+ if (options.anthropic) return 'anthropic'
128
+ if (options.perplexity) return 'perplexity'
129
+
130
+ const defaultProvider = config.DEFAULT_PROVIDER?.toLowerCase()
131
+ if (defaultProvider && ['perplexity', 'openai', 'anthropic'].includes(defaultProvider)) {
132
+ return defaultProvider
133
+ }
134
+
135
+ return 'perplexity'
136
+ }
137
+
138
+ export { getProvider, determineProvider, DEFAULT_MODELS, listModels }
package/lib/stream.mjs ADDED
@@ -0,0 +1,67 @@
1
+ import { generateText, streamText } from 'ai'
2
+
3
+ async function streamResponse(model, messages) {
4
+ const result = streamText({
5
+ model,
6
+ messages
7
+ })
8
+
9
+ let fullText = ''
10
+
11
+ for await (const textPart of result.textStream) {
12
+ process.stdout.write(textPart)
13
+ fullText += textPart
14
+ }
15
+
16
+ process.stdout.write('\n')
17
+
18
+ // Display sources/citations if available (Perplexity)
19
+ const sources = await result.sources
20
+ if (sources?.length > 0) {
21
+ process.stdout.write('\n\x1b[2m─── Sources ───\x1b[0m\n')
22
+ sources.forEach((source, index) => {
23
+ const num = index + 1
24
+ const title = source.title || source.url
25
+ process.stdout.write(`\x1b[2m[${num}] ${title}\x1b[0m\n`)
26
+ if (source.url && source.title) {
27
+ process.stdout.write(`\x1b[2m ${source.url}\x1b[0m\n`)
28
+ }
29
+ })
30
+ }
31
+
32
+ return fullText
33
+ }
34
+
35
+ async function generateResponse(model, messages) {
36
+ const { text, sources } = await generateText({
37
+ model,
38
+ messages
39
+ })
40
+
41
+ return { text, sources }
42
+ }
43
+
44
+ function buildJsonOutput(conversation, response, sources) {
45
+ const lastUserMessage = conversation.messages[conversation.messages.length - 1]
46
+ const output = {
47
+ provider: conversation.provider,
48
+ model: conversation.model,
49
+ question: lastUserMessage?.content || '',
50
+ response,
51
+ conversationId: conversation.id,
52
+ messageCount: conversation.messages.length + 1
53
+ }
54
+
55
+ if (sources?.length > 0) {
56
+ output.sources = sources
57
+ }
58
+
59
+ return output
60
+ }
61
+
62
+ function outputJson(conversation, response, sources) {
63
+ const output = buildJsonOutput(conversation, response, sources)
64
+ console.log(JSON.stringify(output, null, 2))
65
+ }
66
+
67
+ export { streamResponse, generateResponse, outputJson, buildJsonOutput }
package/package.json ADDED
@@ -0,0 +1,34 @@
1
+ {
2
+ "name": "askimo",
3
+ "version": "0.0.2",
4
+ "description": "A CLI tool for communicating with AI providers (Perplexity, OpenAI, Anthropic)",
5
+ "license": "Apache-2.0",
6
+ "author": "Amit Tal",
7
+ "type": "module",
8
+ "bin": {
9
+ "askimo": "./index.mjs"
10
+ },
11
+ "scripts": {
12
+ "test": "ava",
13
+ "lint": "biome check --write"
14
+ },
15
+ "ava": {
16
+ "files": [
17
+ "test/**/*.mjs"
18
+ ]
19
+ },
20
+ "repository": "https://github.com/amitosdev/askimo.git",
21
+ "homepage": "https://github.com/amitosdev/askimo#readme",
22
+ "devDependencies": {
23
+ "@biomejs/biome": "^2.3.8",
24
+ "ava": "^6.4.1"
25
+ },
26
+ "dependencies": {
27
+ "@ai-sdk/anthropic": "^2.0.53",
28
+ "@ai-sdk/openai": "^2.0.76",
29
+ "@ai-sdk/perplexity": "^2.0.21",
30
+ "@inquirer/input": "^5.0.2",
31
+ "ai": "^5.0.106",
32
+ "commander": "^14.0.2"
33
+ }
34
+ }
@@ -0,0 +1,76 @@
1
+ // biome-ignore-all lint/style/useNamingConvention: values in configs are often upper case with underscores
2
+ import test from 'ava'
3
+ import { parseConfig } from '../lib/config.mjs'
4
+
5
+ test('parseConfig parses simple key=value pairs', (t) => {
6
+ const content = 'FOO=bar\nBAZ=qux'
7
+ const result = parseConfig(content)
8
+ t.deepEqual(result, { FOO: 'bar', BAZ: 'qux' })
9
+ })
10
+
11
+ test('parseConfig ignores empty lines', (t) => {
12
+ const content = 'FOO=bar\n\nBAZ=qux\n'
13
+ const result = parseConfig(content)
14
+ t.deepEqual(result, { FOO: 'bar', BAZ: 'qux' })
15
+ })
16
+
17
+ test('parseConfig ignores comment lines', (t) => {
18
+ const content = '# This is a comment\nFOO=bar\n# Another comment\nBAZ=qux'
19
+ const result = parseConfig(content)
20
+ t.deepEqual(result, { FOO: 'bar', BAZ: 'qux' })
21
+ })
22
+
23
+ test('parseConfig ignores lines without equals sign', (t) => {
24
+ const content = 'FOO=bar\ninvalid line\nBAZ=qux'
25
+ const result = parseConfig(content)
26
+ t.deepEqual(result, { FOO: 'bar', BAZ: 'qux' })
27
+ })
28
+
29
+ test('parseConfig trims whitespace around keys and values', (t) => {
30
+ const content = ' FOO = bar \n BAZ = qux '
31
+ const result = parseConfig(content)
32
+ t.deepEqual(result, { FOO: 'bar', BAZ: 'qux' })
33
+ })
34
+
35
+ test('parseConfig handles values with equals signs', (t) => {
36
+ const content = 'API_KEY=abc=def=ghi'
37
+ const result = parseConfig(content)
38
+ t.deepEqual(result, { API_KEY: 'abc=def=ghi' })
39
+ })
40
+
41
+ test('parseConfig handles empty values', (t) => {
42
+ const content = 'EMPTY_KEY='
43
+ const result = parseConfig(content)
44
+ t.deepEqual(result, { EMPTY_KEY: '' })
45
+ })
46
+
47
+ test('parseConfig returns empty object for empty content', (t) => {
48
+ const result = parseConfig('')
49
+ t.deepEqual(result, {})
50
+ })
51
+
52
+ test('parseConfig returns empty object for only comments', (t) => {
53
+ const content = '# comment 1\n# comment 2'
54
+ const result = parseConfig(content)
55
+ t.deepEqual(result, {})
56
+ })
57
+
58
+ test('parseConfig handles typical config file', (t) => {
59
+ const content = `# API Keys
60
+ PERPLEXITY_API_KEY=pplx-123
61
+ OPENAI_API_KEY=sk-456
62
+ ANTHROPIC_API_KEY=ant-789
63
+
64
+ # Optional settings
65
+ DEFAULT_PROVIDER=openai
66
+ OPENAI_MODEL=gpt-4-turbo`
67
+
68
+ const result = parseConfig(content)
69
+ t.deepEqual(result, {
70
+ PERPLEXITY_API_KEY: 'pplx-123',
71
+ OPENAI_API_KEY: 'sk-456',
72
+ ANTHROPIC_API_KEY: 'ant-789',
73
+ DEFAULT_PROVIDER: 'openai',
74
+ OPENAI_MODEL: 'gpt-4-turbo'
75
+ })
76
+ })
@@ -0,0 +1,57 @@
1
+ import test from 'ava'
2
+ import { createConversation } from '../lib/conversation.mjs'
3
+
4
+ test('createConversation creates a conversation with correct provider', (t) => {
5
+ const conversation = createConversation('openai', 'gpt-4o')
6
+ t.is(conversation.provider, 'openai')
7
+ })
8
+
9
+ test('createConversation creates a conversation with correct model', (t) => {
10
+ const conversation = createConversation('openai', 'gpt-4o')
11
+ t.is(conversation.model, 'gpt-4o')
12
+ })
13
+
14
+ test('createConversation creates empty messages array', (t) => {
15
+ const conversation = createConversation('openai', 'gpt-4o')
16
+ t.deepEqual(conversation.messages, [])
17
+ })
18
+
19
+ test('createConversation generates 8-character id', (t) => {
20
+ const conversation = createConversation('openai', 'gpt-4o')
21
+ t.is(conversation.id.length, 8)
22
+ })
23
+
24
+ test('createConversation sets createdAt timestamp', (t) => {
25
+ const before = new Date().toISOString()
26
+ const conversation = createConversation('openai', 'gpt-4o')
27
+ const after = new Date().toISOString()
28
+
29
+ t.true(conversation.createdAt >= before)
30
+ t.true(conversation.createdAt <= after)
31
+ })
32
+
33
+ test('createConversation sets updatedAt equal to createdAt', (t) => {
34
+ const conversation = createConversation('openai', 'gpt-4o')
35
+ t.is(conversation.updatedAt, conversation.createdAt)
36
+ })
37
+
38
+ test('createConversation generates unique ids', (t) => {
39
+ const ids = new Set()
40
+ for (let i = 0; i < 100; i++) {
41
+ const conversation = createConversation('openai', 'gpt-4o')
42
+ ids.add(conversation.id)
43
+ }
44
+ t.is(ids.size, 100)
45
+ })
46
+
47
+ test('createConversation works with perplexity provider', (t) => {
48
+ const conversation = createConversation('perplexity', 'sonar')
49
+ t.is(conversation.provider, 'perplexity')
50
+ t.is(conversation.model, 'sonar')
51
+ })
52
+
53
+ test('createConversation works with anthropic provider', (t) => {
54
+ const conversation = createConversation('anthropic', 'claude-sonnet-4-20250514')
55
+ t.is(conversation.provider, 'anthropic')
56
+ t.is(conversation.model, 'claude-sonnet-4-20250514')
57
+ })
@@ -0,0 +1,59 @@
1
+ // biome-ignore-all lint/style/useNamingConvention: values in configs are often upper case with underscores
2
+ import test from 'ava'
3
+ import { DEFAULT_MODELS, determineProvider } from '../lib/providers.mjs'
4
+
5
+ // determineProvider tests
6
+
7
+ test('determineProvider returns perplexity when --perplexity flag is set', (t) => {
8
+ const result = determineProvider({ perplexity: true })
9
+ t.is(result, 'perplexity')
10
+ })
11
+
12
+ test('determineProvider returns openai when --openai flag is set', (t) => {
13
+ const result = determineProvider({ openai: true })
14
+ t.is(result, 'openai')
15
+ })
16
+
17
+ test('determineProvider returns anthropic when --anthropic flag is set', (t) => {
18
+ const result = determineProvider({ anthropic: true })
19
+ t.is(result, 'anthropic')
20
+ })
21
+
22
+ test('determineProvider prefers flag over config', (t) => {
23
+ const result = determineProvider({ openai: true }, { DEFAULT_PROVIDER: 'anthropic' })
24
+ t.is(result, 'openai')
25
+ })
26
+
27
+ test('determineProvider uses DEFAULT_PROVIDER from config when no flag', (t) => {
28
+ const result = determineProvider({}, { DEFAULT_PROVIDER: 'openai' })
29
+ t.is(result, 'openai')
30
+ })
31
+
32
+ test('determineProvider handles case-insensitive DEFAULT_PROVIDER', (t) => {
33
+ const result = determineProvider({}, { DEFAULT_PROVIDER: 'ANTHROPIC' })
34
+ t.is(result, 'anthropic')
35
+ })
36
+
37
+ test('determineProvider defaults to perplexity when no flag or config', (t) => {
38
+ const result = determineProvider({})
39
+ t.is(result, 'perplexity')
40
+ })
41
+
42
+ test('determineProvider defaults to perplexity with invalid DEFAULT_PROVIDER', (t) => {
43
+ const result = determineProvider({}, { DEFAULT_PROVIDER: 'invalid' })
44
+ t.is(result, 'perplexity')
45
+ })
46
+
47
+ // DEFAULT_MODELS tests
48
+
49
+ test('DEFAULT_MODELS contains perplexity model', (t) => {
50
+ t.is(DEFAULT_MODELS.perplexity, 'sonar')
51
+ })
52
+
53
+ test('DEFAULT_MODELS contains openai model', (t) => {
54
+ t.is(DEFAULT_MODELS.openai, 'gpt-4o')
55
+ })
56
+
57
+ test('DEFAULT_MODELS contains anthropic model', (t) => {
58
+ t.is(DEFAULT_MODELS.anthropic, 'claude-sonnet-4-20250514')
59
+ })
@@ -0,0 +1,92 @@
1
+ import test from 'ava'
2
+ import { buildJsonOutput } from '../lib/stream.mjs'
3
+
4
+ const createMockConversation = (overrides = {}) => ({
5
+ id: 'test-123',
6
+ provider: 'openai',
7
+ model: 'gpt-4o',
8
+ messages: [],
9
+ ...overrides
10
+ })
11
+
12
+ test('buildJsonOutput includes provider from conversation', (t) => {
13
+ const conversation = createMockConversation({ provider: 'anthropic' })
14
+ const output = buildJsonOutput(conversation, 'response text')
15
+ t.is(output.provider, 'anthropic')
16
+ })
17
+
18
+ test('buildJsonOutput includes model from conversation', (t) => {
19
+ const conversation = createMockConversation({ model: 'gpt-4-turbo' })
20
+ const output = buildJsonOutput(conversation, 'response text')
21
+ t.is(output.model, 'gpt-4-turbo')
22
+ })
23
+
24
+ test('buildJsonOutput includes conversationId', (t) => {
25
+ const conversation = createMockConversation({ id: 'abc-456' })
26
+ const output = buildJsonOutput(conversation, 'response text')
27
+ t.is(output.conversationId, 'abc-456')
28
+ })
29
+
30
+ test('buildJsonOutput includes response', (t) => {
31
+ const conversation = createMockConversation()
32
+ const output = buildJsonOutput(conversation, 'Hello, world!')
33
+ t.is(output.response, 'Hello, world!')
34
+ })
35
+
36
+ test('buildJsonOutput extracts question from last user message', (t) => {
37
+ const conversation = createMockConversation({
38
+ messages: [
39
+ { role: 'user', content: 'First question' },
40
+ { role: 'assistant', content: 'First answer' },
41
+ { role: 'user', content: 'Second question' }
42
+ ]
43
+ })
44
+ const output = buildJsonOutput(conversation, 'response')
45
+ t.is(output.question, 'Second question')
46
+ })
47
+
48
+ test('buildJsonOutput returns empty question when no messages', (t) => {
49
+ const conversation = createMockConversation({ messages: [] })
50
+ const output = buildJsonOutput(conversation, 'response')
51
+ t.is(output.question, '')
52
+ })
53
+
54
+ test('buildJsonOutput calculates messageCount correctly', (t) => {
55
+ const conversation = createMockConversation({
56
+ messages: [
57
+ { role: 'user', content: 'Q1' },
58
+ { role: 'assistant', content: 'A1' },
59
+ { role: 'user', content: 'Q2' }
60
+ ]
61
+ })
62
+ const output = buildJsonOutput(conversation, 'response')
63
+ t.is(output.messageCount, 4) // 3 existing + 1 for new response
64
+ })
65
+
66
+ test('buildJsonOutput includes sources when provided', (t) => {
67
+ const conversation = createMockConversation()
68
+ const sources = [
69
+ { title: 'Source 1', url: 'https://example.com/1' },
70
+ { title: 'Source 2', url: 'https://example.com/2' }
71
+ ]
72
+ const output = buildJsonOutput(conversation, 'response', sources)
73
+ t.deepEqual(output.sources, sources)
74
+ })
75
+
76
+ test('buildJsonOutput excludes sources when empty array', (t) => {
77
+ const conversation = createMockConversation()
78
+ const output = buildJsonOutput(conversation, 'response', [])
79
+ t.false('sources' in output)
80
+ })
81
+
82
+ test('buildJsonOutput excludes sources when undefined', (t) => {
83
+ const conversation = createMockConversation()
84
+ const output = buildJsonOutput(conversation, 'response', undefined)
85
+ t.false('sources' in output)
86
+ })
87
+
88
+ test('buildJsonOutput excludes sources when null', (t) => {
89
+ const conversation = createMockConversation()
90
+ const output = buildJsonOutput(conversation, 'response', null)
91
+ t.false('sources' in output)
92
+ })